Skip to main content

spar/
jsonx.rs

1//! Getting structured data back out of a model, and hashing it stably.
2
3use serde_json::Value;
4use sha2::{Digest, Sha256};
5use std::sync::LazyLock;
6
7use regex::Regex;
8
9use crate::error::{Result, SparError};
10
11static FENCE: LazyLock<Regex> = LazyLock::new(|| {
12    Regex::new(r"(?s)```(?:json)?\s*(\{.*?\}|\[.*?\])\s*```").expect("fence pattern")
13});
14
15/// Pull the last JSON value out of a model response.
16///
17/// Models wrap JSON in prose or fences despite explicit instructions not to,
18/// and some emit a draft before the real answer, so the *last* well formed
19/// value wins: fenced blocks first, then brace matching backwards from the end.
20pub fn extract_json(text: &str) -> Result<Value> {
21    if text.trim().is_empty() {
22        return Err(SparError::new("empty response, expected JSON"));
23    }
24    candidates(text)
25        .into_iter()
26        .next()
27        .ok_or_else(|| SparError::new(format!("no JSON found in response:\n{}", head(text, 800))))
28}
29
30/// Every JSON value plausibly present in a model response, most likely first.
31///
32/// Fenced blocks come first because a model that fences its answer means it,
33/// then whole objects matched backwards from the end.
34pub fn candidates(text: &str) -> Vec<Value> {
35    let mut out = Vec::new();
36    let mut push = |value: Value| {
37        if !out.contains(&value) {
38            out.push(value);
39        }
40    };
41
42    let fenced: Vec<&str> = FENCE
43        .captures_iter(text)
44        .filter_map(|c| c.get(1).map(|m| m.as_str()))
45        .collect();
46    for blob in fenced.iter().rev() {
47        if let Ok(value) = serde_json::from_str::<Value>(blob) {
48            push(value);
49        }
50    }
51
52    let bytes = text.as_bytes();
53    for (opener, closer) in [(b'{', b'}'), (b'[', b']')] {
54        let mut end = rfind_byte(bytes, closer, bytes.len());
55        while let Some(e) = end {
56            let mut depth = 0i32;
57            let mut start = None;
58            for i in (0..=e).rev() {
59                if bytes[i] == closer {
60                    depth += 1;
61                } else if bytes[i] == opener {
62                    depth -= 1;
63                    if depth == 0 {
64                        start = Some(i);
65                        break;
66                    }
67                }
68            }
69            if let Some(s) = start {
70                if let Ok(value) = serde_json::from_str::<Value>(&text[s..=e]) {
71                    push(value);
72                }
73            }
74            end = rfind_byte(bytes, closer, e);
75        }
76    }
77    out
78}
79
80/// Whether a response looks cut off rather than merely malformed.
81///
82/// A model with an output limit stops mid-object on a long answer. The braces
83/// it opened outnumber the ones it closed, and every complete object left is
84/// something nested inside the one it was building.
85pub fn looks_truncated(text: &str) -> bool {
86    let mut opened = 0i64;
87    let mut in_string = false;
88    let mut escaped = false;
89    for c in text.chars() {
90        if escaped {
91            escaped = false;
92            continue;
93        }
94        match c {
95            '\\' if in_string => escaped = true,
96            '"' => in_string = !in_string,
97            '{' if !in_string => opened += 1,
98            '}' if !in_string => opened -= 1,
99            _ => {}
100        }
101    }
102    opened > 0
103}
104
105/// Parse a model response straight into a typed value.
106///
107/// Tries every candidate rather than only the last one found. A review cut off
108/// before its outer object closed used to yield the last *nested* finding,
109/// which parsed as JSON perfectly well and then failed to be a review, and the
110/// error blamed the shape rather than the truncation.
111pub fn extract_into<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
112    let found = candidates(text);
113    if found.is_empty() {
114        return Err(SparError::new(if looks_truncated(text) {
115            format!(
116                "the response was cut off before any complete JSON:\n{}",
117                head(text, 400)
118            )
119        } else {
120            format!("no JSON found in response:\n{}", head(text, 800))
121        }));
122    }
123
124    // Which failure to report is not the same question as which candidate to
125    // parse. Any candidate that parses wins, and a stray object never will,
126    // because every schema here requires fields it does not have. But when
127    // nothing parses, this error is handed straight back to the model on the
128    // retry, so it has to be about the answer the model meant.
129    //
130    // Neither end of the list is that. The order here is really last-closing
131    // first, so the last object a response happens to contain leads, and a
132    // model that wrote its answer and then a sentence with an object in it gets
133    // told about the sentence. The biggest candidate is the better guess: an
134    // answer is longer than the fragments around it.
135    let mut failures: Vec<(serde_json::Error, &Value)> = Vec::new();
136    for value in &found {
137        match serde_json::from_value::<T>(value.clone()) {
138            Ok(parsed) => return Ok(parsed),
139            Err(e) => failures.push((e, value)),
140        }
141    }
142    let (error, value) = failures
143        .into_iter()
144        .max_by_key(|(_, value)| value.to_string().len())
145        .expect("non-empty");
146    if looks_truncated(text) {
147        return Err(SparError::new(format!(
148            "the response was cut off before the answer was complete, so only fragments of it \
149             parsed ({error}). Ask for less in one go, or give this agent a CLI flag for native \
150             structured output."
151        )));
152    }
153    Err(SparError::new(format!(
154        "response did not match the expected shape ({error}).{}\nGot: {}",
155        envelope_hint(value),
156        head(&value.to_string(), 600)
157    )))
158}
159
160/// An extra sentence when serde's own message would send the model to the wrong
161/// place.
162///
163/// serde maps a JSON array onto a struct's fields by position, so a bare array
164/// of findings tried as a review fails on field zero: "invalid type: map,
165/// expected a string", where the string is `verdict`. A model told that goes
166/// looking at a field, and the field is not what is wrong. Every schema here
167/// asks for one object, so an array is always the envelope rather than the
168/// contents.
169fn envelope_hint(value: &Value) -> &'static str {
170    if value.is_array() {
171        " The answer was a JSON array, and the schema asks for a single object: \
172         the array belongs in a field of it."
173    } else {
174        ""
175    }
176}
177
178fn rfind_byte(haystack: &[u8], needle: u8, before: usize) -> Option<usize> {
179    haystack[..before.min(haystack.len())]
180        .iter()
181        .rposition(|b| *b == needle)
182}
183
184fn head(text: &str, max: usize) -> String {
185    text.chars().take(max).collect()
186}
187
188/// A stable identity for a review finding, so a refutation survives across
189/// rounds even when the reviewer rewords the point.
190///
191/// Wording noise, punctuation, and case are all discarded; the file is not,
192/// because the same complaint about two different files is two complaints.
193pub fn finding_key(title: &str, file: &str) -> String {
194    let basis: String = format!("{} {}", title.trim(), file.trim())
195        .to_lowercase()
196        .chars()
197        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '/' | '.' | '_' | '-'))
198        .collect();
199    let basis = basis.split_whitespace().collect::<Vec<_>>().join(" ");
200
201    let digest = Sha256::digest(basis.as_bytes());
202    let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
203    hex[..12].to_string()
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    #[test]
211    fn bare_object() {
212        assert_eq!(
213            serde_json::json!({"a": 1}),
214            extract_json(r#"{"a": 1}"#).unwrap()
215        );
216    }
217
218    #[test]
219    fn fenced_block() {
220        let out = extract_json("here you go:\n```json\n{\"a\": 1}\n```\n").unwrap();
221        assert_eq!(serde_json::json!({"a": 1}), out);
222    }
223
224    #[test]
225    fn trailing_prose() {
226        let out = extract_json("Thoughts...\n{\"verdict\": \"approve\"}\nDone.").unwrap();
227        assert_eq!(serde_json::json!({"verdict": "approve"}), out);
228    }
229
230    #[test]
231    fn picks_the_last_fenced_block() {
232        let text = "```json\n{\"n\": 1}\n```\nrevised:\n```json\n{\"n\": 2}\n```";
233        assert_eq!(serde_json::json!({"n": 2}), extract_json(text).unwrap());
234    }
235
236    #[test]
237    fn nested_braces() {
238        let payload = r#"{"findings": [{"severity": "nit", "d": {"x": [1, 2]}}]}"#;
239        let out = extract_json(&format!("blah {payload} blah")).unwrap();
240        assert_eq!(1, out["findings"].as_array().unwrap().len());
241    }
242
243    #[test]
244    fn top_level_array() {
245        let out = extract_json("result: [1, 2, 3]").unwrap();
246        assert_eq!(3, out.as_array().unwrap().len());
247    }
248
249    #[test]
250    fn multibyte_prose_around_the_payload_does_not_panic() {
251        let out = extract_json("\u{1f600}\u{1f600} {\"a\": 1} \u{1f600}").unwrap();
252        assert_eq!(serde_json::json!({"a": 1}), out);
253    }
254
255    #[test]
256    fn raises_when_there_is_none() {
257        assert!(extract_json("no json here at all").is_err());
258    }
259
260    #[test]
261    fn raises_on_empty() {
262        assert!(extract_json("   ").is_err());
263    }
264
265    #[test]
266    fn malformed_trailing_object_falls_back_to_an_earlier_one() {
267        let text = "{\"good\": true}\nthen: {\"bad\": ,}";
268        assert_eq!(
269            serde_json::json!({"good": true}),
270            extract_json(text).unwrap()
271        );
272    }
273
274    // -- finding_key -----------------------------------------------------
275
276    #[test]
277    fn key_is_stable_across_wording_noise() {
278        assert_eq!(
279            finding_key("Unbounded loop!", "src/x.rs"),
280            finding_key("unbounded loop", "src/x.rs")
281        );
282    }
283
284    #[test]
285    fn key_differs_by_file() {
286        assert_ne!(finding_key("t", "a.rs"), finding_key("t", "b.rs"));
287    }
288
289    #[test]
290    fn key_is_case_insensitive_in_the_path_too() {
291        assert_eq!(
292            finding_key("t", "src/Main.rs"),
293            finding_key("t", "src/main.rs")
294        );
295    }
296
297    #[test]
298    fn key_is_stable_across_whitespace() {
299        assert_eq!(finding_key("a  b", "x.rs"), finding_key(" a b ", "x.rs"));
300    }
301
302    #[test]
303    fn key_is_twelve_hex_characters() {
304        let key = finding_key("anything", "file.rs");
305        assert_eq!(12, key.len());
306        assert!(key.chars().all(|c| c.is_ascii_hexdigit()));
307    }
308}
309
310#[cfg(test)]
311mod truncation_tests {
312    use super::*;
313    use serde::Deserialize;
314
315    #[derive(Debug, Deserialize)]
316    struct Review {
317        verdict: String,
318        findings: Vec<Finding>,
319    }
320    #[derive(Debug, Deserialize)]
321    struct Finding {
322        title: String,
323    }
324
325    /// What actually happened on a real pull request. A long review hit the
326    /// model's output limit and stopped before its outer object closed, so the
327    /// last complete JSON in the response was a nested finding. It parsed, it
328    /// was not a review, and the error blamed the shape.
329    const TRUNCATED: &str = r#"Here is my review.
330{"verdict":"changes_requested","next_action":"hand_back","summary":"Two problems.",
331 "findings":[
332   {"severity":"blocking","title":"First","detail":"one","file":"a.ts","in_scope":true},
333   {"severity":"non-blocking","title":"Second","detail":"numbers unnamed keys by position"#;
334
335    #[test]
336    fn a_truncated_review_is_reported_as_truncated_not_as_the_wrong_shape() {
337        let err = extract_into::<Review>(TRUNCATED).unwrap_err().to_string();
338        assert!(err.contains("cut off"), "{err}");
339        assert!(!err.contains("did not match the expected shape"), "{err}");
340    }
341
342    #[test]
343    fn truncation_is_detected_from_the_unclosed_braces() {
344        assert!(looks_truncated(TRUNCATED));
345        assert!(!looks_truncated(r#"{"a":1}"#));
346        // A brace inside a string is not an open brace.
347        assert!(!looks_truncated(r#"{"a":"a { in a string"}"#));
348        assert!(!looks_truncated(r#"{"a":"an escaped \" quote { here"}"#));
349    }
350
351    /// The fix that matters: the right object is found even when it is not the
352    /// last one in the response.
353    #[test]
354    fn the_review_is_found_even_with_nested_objects_after_it() {
355        let text = r#"Thinking out loud first.
356{"verdict":"approve","next_action":"merge","summary":"Fine.","findings":[{"severity":"nit","title":"Wording","detail":"d","file":"a.ts","in_scope":true}]}
357And here is a stray object afterwards: {"title":"not the review"}"#;
358        let review: Review = extract_into(text).unwrap();
359        assert_eq!("approve", review.verdict);
360        assert_eq!(1, review.findings.len());
361        assert_eq!("Wording", review.findings[0].title);
362    }
363
364    #[test]
365    fn candidates_are_offered_most_likely_first() {
366        let text = "```json\n{\"verdict\":\"approve\",\"findings\":[]}\n```\ntrailing {\"x\":1}";
367        let review: Review = extract_into(text).unwrap();
368        assert_eq!("approve", review.verdict);
369    }
370
371    #[test]
372    fn a_genuinely_wrong_shape_still_says_so() {
373        let err = extract_into::<Review>(r#"{"colour":"blue"}"#)
374            .unwrap_err()
375            .to_string();
376        assert!(err.contains("did not match the expected shape"), "{err}");
377        assert!(!err.contains("cut off"), "{err}");
378    }
379
380    /// What a real round two review produced. The model wrote a review object
381    /// and a findings array, the object failed to parse, and the complaint that
382    /// went back to it described the array: "invalid type: map, expected a
383    /// string", which is field zero of a struct serde had mapped an array onto
384    /// by position. The model was sent to look at a field, and the field was
385    /// not what was wrong.
386    #[test]
387    fn the_complaint_is_about_the_answer_the_model_meant() {
388        let text = r#"Here is my review.
389{"verdict":"changes_requested","next_action":"hand_back","summary":"Two problems.","findings":"should have been a list"}
390Supporting detail: [{"detail":"The working tree bumps 0.5.9 to 0.5.10."}]"#;
391        let err = extract_into::<Review>(text).unwrap_err().to_string();
392        // The review object is what failed, and its own field is named.
393        assert!(err.contains("findings"), "{err}");
394        assert!(
395            err.contains("changes_requested"),
396            "the object is shown:\n{err}"
397        );
398        assert!(
399            !err.contains("The working tree"),
400            "the stray array leaked in:\n{err}"
401        );
402    }
403
404    /// serde maps a JSON array onto a struct by position, so a bare array of
405    /// findings fails on the first field and says "expected a string". Left at
406    /// that, the model reads it as a field problem.
407    #[test]
408    fn a_bare_array_is_named_as_the_envelope_problem() {
409        let err = extract_into::<Review>(r#"[{"title":"First"},{"title":"Second"}]"#)
410            .unwrap_err()
411            .to_string();
412        assert!(err.contains("JSON array"), "{err}");
413        assert!(err.contains("single object"), "{err}");
414    }
415
416    /// And an object that is merely the wrong shape says nothing about arrays.
417    #[test]
418    fn a_wrong_object_is_not_told_it_was_an_array() {
419        let err = extract_into::<Review>(r#"{"colour":"blue"}"#)
420            .unwrap_err()
421            .to_string();
422        assert!(!err.contains("JSON array"), "{err}");
423    }
424
425    #[test]
426    fn nothing_parseable_is_still_reported_plainly() {
427        let err = extract_into::<Review>("no json at all")
428            .unwrap_err()
429            .to_string();
430        assert!(err.contains("no JSON found"), "{err}");
431    }
432}