Skip to main content

hyprstream_decision_stub/
render.rs

1//! Rendering: IR answers → the jev-1 wire answer shapes.
2//!
3//! Raw distributions come from the mock; everything else on the wire is derived through
4//! `hyprstream-decision`'s normative functions — argmax label (D6 tie-break), expected
5//! score (`Σ i·pᵢ`), confidence-from-peakedness (S6a formulas), the legend echo. The stub
6//! never hand-computes a derived statistic, so the facade cannot drift from the profile.
7//!
8//! Abstention on the facade (a superset concept — upstream has no abstain value) renders
9//! the value positions as JSON `null`: `{"type": "noul", "noul": null}` etc. Stock SDKs
10//! validate those fields as non-nullable and will reject an abstained answer — that is
11//! honest: abstention is only contract-stable on the Arrow surface in v1.
12
13use hyprstream_decision::answer::AnswerValue;
14use hyprstream_decision::arrow::AnswerRow;
15use hyprstream_decision::confidence;
16use hyprstream_decision::entry::Entry;
17use hyprstream_decision::spec::{QuestionBody, QuestionSet};
18use serde_json::{Map, Value};
19
20/// Convert an IR entry back to JSON (insertion order → sorted, matching serde_json's
21/// canonical map order; duplicate keys, already rejected at validation, collapse
22/// last-wins).
23pub fn entry_to_json(entry: &Entry) -> Value {
24    match entry {
25        Entry::Null => Value::Null,
26        Entry::Bool(value) => Value::Bool(*value),
27        Entry::Number(value) => {
28            serde_json::Number::from_f64(*value).map_or(Value::Null, Value::Number)
29        }
30        Entry::Str(text) => Value::String(text.clone()),
31        Entry::Seq(items) => Value::Array(items.iter().map(entry_to_json).collect()),
32        Entry::Map(pairs) => Value::Object(
33            pairs
34                .iter()
35                .map(|(key, value)| (key.clone(), entry_to_json(value)))
36                .collect(),
37        ),
38    }
39}
40
41fn probability_map(labels: &[String], probabilities: &[f32]) -> Value {
42    Value::Object(
43        labels
44            .iter()
45            .zip(probabilities)
46            .map(|(label, p)| {
47                (
48                    label.clone(),
49                    serde_json::Number::from_f64(f64::from(*p)).map_or(Value::Null, Value::Number),
50                )
51            })
52            .collect::<Map<String, Value>>(),
53    )
54}
55
56fn render_one(question: &hyprstream_decision::spec::QuestionSpec, row: &AnswerRow) -> Value {
57    let answer = row.answers.get(&question.id);
58    let value = answer.and_then(|a| a.value.as_ref());
59    let mut out = Map::new();
60    out.insert(
61        "type".to_owned(),
62        Value::String(question.kind.as_str().to_owned()),
63    );
64    match (&question.body, value) {
65        (QuestionBody::Noul { .. }, Some(AnswerValue::Noul { p_true })) => {
66            out.insert(
67                "noul".to_owned(),
68                serde_json::Number::from_f64(f64::from(*p_true)).map_or(Value::Null, Value::Number),
69            );
70        }
71        (QuestionBody::Noul { .. }, None) => {
72            out.insert("noul".to_owned(), Value::Null);
73        }
74        (QuestionBody::Choice { .. }, Some(value @ AnswerValue::Choice { .. })) => {
75            let labels = question.labels();
76            let probabilities = value.probabilities();
77            let argmax = confidence::argmax_index(&probabilities).unwrap_or(0);
78            out.insert("choice".to_owned(), Value::String(labels[argmax].clone()));
79            out.insert(
80                "probabilities".to_owned(),
81                probability_map(&labels, &probabilities),
82            );
83            out.insert(
84                "confidence".to_owned(),
85                serde_json::Number::from_f64(f64::from(confidence::choice_confidence(
86                    &probabilities,
87                )))
88                .map_or(Value::Null, Value::Number),
89            );
90        }
91        (QuestionBody::Choice { .. }, None) => {
92            out.insert("choice".to_owned(), Value::Null);
93            out.insert("probabilities".to_owned(), Value::Null);
94            out.insert("confidence".to_owned(), Value::Null);
95        }
96        (QuestionBody::Score { levels }, Some(value @ AnswerValue::Score { .. })) => {
97            let labels = question.labels();
98            let probabilities = value.probabilities();
99            out.insert(
100                "score".to_owned(),
101                serde_json::Number::from_f64(f64::from(confidence::expected_score(&probabilities)))
102                    .map_or(Value::Null, Value::Number),
103            );
104            out.insert(
105                "legend".to_owned(),
106                Value::Object(
107                    levels
108                        .iter()
109                        .enumerate()
110                        .map(|(index, level)| {
111                            (
112                                index.to_string(),
113                                level.as_ref().map_or(Value::Null, entry_to_json),
114                            )
115                        })
116                        .collect(),
117                ),
118            );
119            out.insert(
120                "probabilities".to_owned(),
121                probability_map(&labels, &probabilities),
122            );
123            out.insert(
124                "confidence".to_owned(),
125                serde_json::Number::from_f64(f64::from(confidence::score_confidence(
126                    &probabilities,
127                )))
128                .map_or(Value::Null, Value::Number),
129            );
130        }
131        (QuestionBody::Score { .. }, None) => {
132            out.insert("score".to_owned(), Value::Null);
133            out.insert("legend".to_owned(), Value::Null);
134            out.insert("probabilities".to_owned(), Value::Null);
135            out.insert("confidence".to_owned(), Value::Null);
136        }
137        // Kind mismatches are unreachable: answers are produced from the same IR.
138        _ => {
139            out.insert(
140                "error".to_owned(),
141                Value::String("kind mismatch".to_owned()),
142            );
143        }
144    }
145    Value::Object(out)
146}
147
148/// Render the full `answers` map for one facade request, keyed by question id.
149pub fn render_answers(set: &QuestionSet, row: &AnswerRow) -> Value {
150    Value::Object(
151        set.questions
152            .iter()
153            .map(|question| (question.id.clone(), render_one(question, row)))
154            .collect(),
155    )
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use crate::mock::MockDecisionModel;
162    use hyprstream_decision::author;
163    use hyprstream_decision::confidence::CONSUMER_SUM_TOLERANCE;
164
165    #[test]
166    fn rendered_answers_satisfy_consumer_tolerance_and_derivations() {
167        let set = author::parse_yaml(
168            r#"
169state: "The box was crushed."
170questions:
171  is_refund:
172    type: noul
173  tone:
174    type: choice
175    criteria:
176      angry: "Hostile"
177      calm: ~
178  severity:
179    type: score
180    criteria: ["cosmetic", "usable", "unusable"]
181"#,
182        )
183        .unwrap_or_else(|error| panic!("parses: {error}"));
184        let row = MockDecisionModel.answer_row(&set, "The box was crushed.", 0);
185        let answers = render_answers(&set, &row);
186
187        let noul = &answers["is_refund"];
188        assert_eq!(noul["type"], "noul");
189        assert!(noul["noul"].as_f64().unwrap_or_else(|| panic!("p")) >= 0.0);
190
191        let choice = &answers["tone"];
192        let probabilities = choice["probabilities"]
193            .as_object()
194            .unwrap_or_else(|| panic!("map"));
195        let sum: f64 = probabilities
196            .values()
197            .map(|v| v.as_f64().unwrap_or_else(|| panic!("p")))
198            .sum();
199        assert!((sum - 1.0).abs() <= f64::from(CONSUMER_SUM_TOLERANCE));
200        let argmax = probabilities
201            .iter()
202            .max_by(|(_, a), (_, b)| {
203                a.as_f64()
204                    .unwrap_or_else(|| panic!("p"))
205                    .partial_cmp(&b.as_f64().unwrap_or_else(|| panic!("p")))
206                    .unwrap_or_else(|| panic!("ordered"))
207            })
208            .map(|(label, _)| label);
209        assert_eq!(choice["choice"].as_str(), argmax.map(String::as_str));
210
211        let score = &answers["severity"];
212        let levels = score["probabilities"]
213            .as_object()
214            .unwrap_or_else(|| panic!("map"));
215        assert_eq!(levels.len(), 3);
216        let expected: f64 = levels
217            .iter()
218            .map(|(level, p)| {
219                level
220                    .parse::<f64>()
221                    .unwrap_or_else(|error| panic!("index: {error}"))
222                    * p.as_f64().unwrap_or_else(|| panic!("p"))
223            })
224            .sum();
225        let rendered = score["score"].as_f64().unwrap_or_else(|| panic!("score"));
226        assert!(
227            (expected - rendered).abs() < 1e-5,
228            "score == Σ i·pᵢ: {rendered} vs {expected}"
229        );
230        assert_eq!(score["legend"]["0"], "cosmetic", "legend echoes criteria");
231    }
232}