Skip to content
Prev Previous commit
Next Next commit
workflow: repair common LLM JSON malformations as a last resort
Stage outputs from weaker models fail strict JSON parsing on
unescaped double quotes inside string values (serde reports
'expected , or ]' right after an inner quote ends the string
early) and on trailing commas. Three validation retries cannot
fix what the model keeps rewriting the same way, so a parallel
stage dies under BestEffort and its findings are lost.

Add utils::repair_json_candidates: quotes are escaped as content
unless the next non-whitespace character is a structural token,
and commas directly before } or ] are dropped. A quote followed
by a comma or colon is ambiguous - it separates real elements
but also appears inside quoted prose - and no local rule tells
them apart, so two readings are produced. In the prose reading
the first syntax error localizes the derailment and comma- or
colon-preceded quotes at or after it are escaped as content,
while in the structural reading every such quote terminates its
string and keeps the fields after it intact; the prose reading
can swallow those fields into the derailed value, so the
structural reading is preferred whenever it strictly parses and
the prose reading covers the inputs where terminating quotes
cannot parse at all, such as prose that embeds key-colon pairs.
parse_json_from_text applies the variants only after the strict
parse, the raw text, and the brace-candidate extraction all
failed, and only accepts a variant when a strict parse of it
succeeds, so an unrepaired or still-broken output surfaces the
original error instead of silently misreading the input.

The repair runs on the raw text and clean_json_string escapes
control characters on each repaired variant: the cleaner tracks
string state by quote count, so an odd unescaped quote would
flip it and turn the structural newlines between fields into
literal \n sequences outside strings that survive no repair.

Signed-off-by: Denis Benato <denis.benato@linux.dev>
  • Loading branch information
NeroReflex committed Nov 7, 2026
commit 49b6e4145b02b780553a250b9de50d46995b9a3d
200 changes: 200 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,127 @@ pub fn clean_json_string(input: &str) -> String {
out
}

/// Best-effort repairs for common LLM JSON malformations that strict
/// parsing rejects: unescaped double quotes inside string literals and
/// trailing commas before `}` or `]`.
///
/// A quote inside a string is treated as the terminator only when the next
/// non-whitespace character is a structural token (`,` `:` `}` `]`) or the
/// input ends; any other quote is escaped as content. A quote followed by a
/// comma is ambiguous: it genuinely separates list elements but also shows
/// up inside quoted prose. Two readings are produced: the prose reading
/// localizes the derailment with the first syntax error and escapes
/// comma- or colon-preceded quotes at or after it as content, while quotes
/// in the region the parser already accepted stay terminators; the
/// structural reading terminates every such quote and keeps any later
/// fields and array elements intact. Because the prose reading can swallow
/// those fields into the derailed value, the structural reading is
/// preferred whenever it strictly parses, and the prose reading covers the
/// inputs where terminating the quotes cannot parse at all, such as prose
/// that embeds key-colon pairs. Callers re-parse each variant with a
/// strict parser and use the first that parses, keeping the original error
/// when none does. A quote directly followed by a closing brace or bracket
/// always terminates, so prose that embeds one right after a quote stays
/// unrecoverable.
pub fn repair_json_candidates(input: &str) -> Vec<String> {
let error_offset = serde_json::from_str::<serde_json::Value>(input)
.err()
.map(|e| error_byte_offset(input, e.line(), e.column()));
let mixed = repair_json_with(input, error_offset);
let pairs = repair_json_with(input, None);
if mixed == pairs {
return vec![mixed];
}
// A swallowed field is silent data loss, while a truncated prose tail
// stays visible content, so the structural reading wins when it
// strictly parses; candidates that fail the strict parse stay last,
// where callers only ever see them as error-reporting inputs.
if serde_json::from_str::<serde_json::Value>(&pairs).is_ok() {
vec![pairs, mixed]
} else {
vec![mixed, pairs]
}
}

/// Maps a serde_json 1-based line/column error position onto a byte offset
/// in `input`, clamped to the line and input lengths.
fn error_byte_offset(input: &str, line: usize, column: usize) -> usize {
let mut offset = 0;
for (i, line_text) in input.split('\n').enumerate() {
if i + 1 == line {
return offset + column.saturating_sub(1).min(line_text.len());
}
offset += line_text.len() + 1;
}
offset
}

/// Renders one repair reading of `input`. A comma-preceded in-string quote
/// terminates the string only when it lies before `error_offset` (or when
/// the position is unknown). See [`repair_json_candidates`].
fn repair_json_with(input: &str, error_offset: Option<usize>) -> String {
let chars: Vec<char> = input.chars().collect();
let mut out = String::with_capacity(input.len());
let mut in_string = false;
let mut escape = false;
let mut byte_pos = 0;
let mut i = 0;

while i < chars.len() {
let c = chars[i];
if in_string {
if escape {
out.push('\\');
out.push(c);
escape = false;
} else if c == '\\' {
escape = true;
} else if c == '"' {
let mut j = i + 1;
while j < chars.len() && chars[j].is_whitespace() {
j += 1;
}
let terminates = if j >= chars.len() {
true
} else {
match chars[j] {
'}' | ']' => true,
',' | ':' => {
error_offset.is_none() || byte_pos < error_offset.unwrap_or(usize::MAX)
}
_ => false,
}
};
if terminates {
in_string = false;
out.push(c);
} else {
out.push_str("\\\"");
}
} else {
out.push(c);
}
} else if c == '"' {
in_string = true;
out.push(c);
} else if c == ',' {
let mut j = i + 1;
while j < chars.len() && chars[j].is_whitespace() {
j += 1;
}
// Strict JSON forbids a comma directly before } or ].
if !matches!(chars.get(j), Some('}') | Some(']')) {
out.push(c);
}
} else {
out.push(c);
}
byte_pos += c.len_utf8();
i += 1;
}
out
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -132,6 +253,85 @@ mod tests {
assert_eq!(utf8_prefix("short", 100), "short");
}

#[test]
fn test_repair_json_candidates_pairs_reading_is_identity_on_valid_json() {
let valid = r#"{"a": "x \"y\" z", "b": [1, 2], "c": {"d": true}}"#;
assert_eq!(repair_json_candidates(valid), vec![valid.to_string()]);
}

#[test]
fn test_repair_json_candidates_prefers_structure_over_swallowed_fields() {
// The early-closed "say " string is where parsing derails, so the
// comma- and colon-preceded quotes after the error are read as
// prose in the first candidate - which swallows the later fields
// into the derailed value - while the structural reading
// terminates them and keeps every field. The structural reading
// wins whenever it strictly parses, because a swallowed field is
// silent data loss and only a lost prose tail is the price of
// the shift.
let broken = r#"{"b": [1, 2], "a": "say "hi", "c": "tail"}"#;
let candidates = repair_json_candidates(broken);
let parsed = candidates
.iter()
.find_map(|c| serde_json::from_str::<serde_json::Value>(c).ok())
.unwrap();
assert_eq!(parsed["b"], serde_json::json!([1, 2]));
assert_eq!(parsed["a"], "say \"hi");
assert_eq!(parsed["c"], "tail");
}

#[test]
fn test_repair_json_candidates_escapes_unescaped_inner_quotes() {
let broken = r#"{"description": "the flag turns "on" by default", "n": 3}"#;
let repaired = repair_json_candidates(broken);
let parsed = repaired
.iter()
.find_map(|c| serde_json::from_str::<serde_json::Value>(c).ok())
.unwrap();
assert_eq!(parsed["description"], "the flag turns \"on\" by default");
assert_eq!(parsed["n"], 3);
}

#[test]
fn test_repair_json_candidates_drops_trailing_commas() {
let broken = "{\n \"a\": [1, 2,],\n \"b\": \"x\",\n}\n";
let repaired = repair_json_candidates(broken);
let parsed = repaired
.iter()
.find_map(|c| serde_json::from_str::<serde_json::Value>(c).ok())
.unwrap();
assert_eq!(parsed["a"], serde_json::json!([1, 2]));
assert_eq!(parsed["b"], "x");
}

#[test]
fn test_repair_json_candidates_terminates_list_elements_before_the_error() {
// The trailing comma is the first syntax error, so the quotes the
// parser already accepted as element separators stay terminators.
let broken = r#"{"a": ["one", "two"], "c": [3,]}"#;
let repaired = repair_json_candidates(broken);
let parsed = repaired
.iter()
.find_map(|c| serde_json::from_str::<serde_json::Value>(c).ok())
.unwrap();
assert_eq!(parsed["a"], serde_json::json!(["one", "two"]));
assert_eq!(parsed["c"], serde_json::json!([3]));
}

#[test]
fn test_repair_json_candidates_recovers_embedded_key_colon_pairs() {
// In the prose reading, colon-preceded quotes after the first
// syntax error are content, so prose that itself embeds key-colon
// pairs is recovered instead of truncated at the embedded colon.
let broken = r#"{"a": "flag "b": 1"}"#;
let candidates = repair_json_candidates(broken);
let parsed = candidates
.iter()
.find_map(|c| serde_json::from_str::<serde_json::Value>(c).ok())
.unwrap();
assert_eq!(parsed["a"], "flag \"b\": 1");
}

#[test]
fn test_redact_gemini_key() {
let url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=AIzaSyD-12345";
Expand Down
94 changes: 91 additions & 3 deletions src/workflow/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,25 @@ pub fn parse_json_from_text<T: DeserializeOwned>(raw_text: &str) -> Result<T, St
}
}

// Last resort: repair common LLM malformations (unescaped inner quotes,
// trailing commas) and re-parse strictly. The repair runs on the raw
// text and control-character escaping runs on each repaired variant:
// clean_json_string tracks string state by quote count, so an odd
// unescaped quote would flip it and turn the structural newlines
// between fields into literal \n sequences outside strings, which no
// repair recovers. Variants arrive in preference order and any variant
// that still fails the strict parse is skipped, so the original error
// surfaces unchanged when no repair parses.
for repaired in crate::utils::repair_json_candidates(raw_text) {
let repaired = crate::utils::clean_json_string(&repaired);
if repaired == cleaned {
continue;
}
if let Ok(val) = serde_json::from_str::<T>(&repaired) {
return Ok(val);
}
}

Err(format!(
"Failed to parse JSON from output ({primary_err}): {}",
crate::utils::utf8_prefix(raw_text, 200)
Expand Down Expand Up @@ -245,9 +264,21 @@ fn find_json_candidates(text: &str) -> Vec<Value> {
{
let candidate: String = chars[i..=end].iter().collect();
let clean_candidate = crate::utils::clean_json_string(&candidate);
if let Ok(v) =
serde_json::from_str(&clean_candidate).or_else(|_| serde_json::from_str(&candidate))
{
let mut parsed = serde_json::from_str::<Value>(&clean_candidate)
.or_else(|_| serde_json::from_str::<Value>(&candidate));
if parsed.is_err() {
// Repair the raw candidate and escape control characters on
// each repaired variant: see parse_json_from_text for why
// the order matters.
for repaired in crate::utils::repair_json_candidates(&candidate) {
let repaired = crate::utils::clean_json_string(&repaired);
if let Ok(v) = serde_json::from_str::<Value>(&repaired) {
parsed = Ok(v);
break;
}
}
}
if let Ok(v) = parsed {
candidates.push(v);
i = end + 1;
continue;
Expand Down Expand Up @@ -297,6 +328,63 @@ mod tests {
count: u32,
}

#[test]
fn test_parse_recovers_unescaped_inner_quotes() {
let raw = r#"{"name": "the driver sets "on" mode", "count": 3}"#;
let out: DummyOutput = parse_json_from_text(raw).unwrap();
assert_eq!(
out,
DummyOutput {
name: "the driver sets \"on\" mode".to_string(),
count: 3,
}
);
}

#[test]
fn test_parse_recovers_trailing_commas() {
let raw = "{\n \"name\": \"x\",\n \"count\": 3,\n}\n";
let out: DummyOutput = parse_json_from_text(raw).unwrap();
assert_eq!(
out,
DummyOutput {
name: "x".to_string(),
count: 3,
}
);
}

#[test]
fn test_parse_repairs_quotes_before_escaping_control_characters() {
// One unescaped quote inside the value is an odd count: escaping
// control characters first would flip the string state for the rest
// of the payload and turn the structural newlines between fields
// into literal \n sequences outside strings, which no repair
// recovers. Repairing the quotes first keeps every field intact.
let raw = "{\n \"name\": \"a \"b c d\",\n \"count\": 7\n}";
let out: DummyOutput = parse_json_from_text(raw).unwrap();
assert_eq!(
out,
DummyOutput {
name: "a \"b c d".to_string(),
count: 7,
}
);
}

#[test]
fn test_parse_repairs_candidate_embedded_in_prose() {
let raw = r#"Verdict below.\n{"name": "handles "x" input", "count": 1}\nDone."#;
let out: DummyOutput = parse_json_from_text(raw).unwrap();
assert_eq!(
out,
DummyOutput {
name: "handles \"x\" input".to_string(),
count: 1,
}
);
}

#[test]
fn test_json_output_format_valid() {
let fmt = OutputFormat::<(), DummyOutput>::json();
Expand Down
Loading