Skip to content

feat(ai): one json repair seam that counts repairs per entry point #875

Closed

Description

@dan-petty

Context & Rationale

json-repair is called from three places:

  • src/devops_cli/ai/response_repair.py:139-143 (_repair_loads). It sits behind repair_json_string (:105), which fix_llm_response (:503) and tool-call parsing (:210, :224) use.
  • src/devops_cli/ai/client/structured.py:61-84 (_parse_json_payload, with calls at :69 and :72).
  • src/devops_cli/core/serialization.py:76-82, the fallback in extract_json_block. Seven call sites use it: ai/agents/pipeline.py:68, ai/review/runner.py:524 and :546, ai/review_schema.py:1349, ai/benchmark/runner.py:593, ai/analyze/outlines.py:124 and ai/review/verification.py:1995.

Only chat_structured counts repairs (structured.py:263-270).

  • Nothing in src calls it: rg -n '\.chat_structured\(' src finds nothing. Only tests/test_ai_client_structured.py and tests/test_schema_reflection.py do.
  • feat(cli): lossless structured error reflection for schema retries #437 shipped its reflection retry there in v0.2.23.
  • The reflection report also feeds fix_llm_response (response_repair.py:418-439, ai/schema_reflection.py).

So nobody can tell how often a model's JSON needs repair. json-repair's own log cannot tell either: a trailing-comma repair logs 0 entries.

The original #599 text excluded security/tflint.py:189. tflint no longer parses JSON this way (5d34541, #763).

Scope & Deliverables

  • Deliverable:
    • One repair_json(text, *, source) in ai/response_repair.py. It tries strict json.loads first and json-repair only when that fails. It returns the value and whether a repair happened.
    • The other two entry points call it, and json_repair is imported only in response_repair.py.
    • A counter, devops_cli_ai_json_repairs_total, with a source label naming the entry point. It is defined in telemetry/instruments.py and emitted on every repair. Label values are constants in config/constants.py.
    • chat_structured is deleted, together with its helpers, its metric constants (config/constants.py:547 and the constants beside it) and its tests. Its re-exports go with it, with no aliases.
  • Acceptance criteria:
    • For each entry point, a payload with a trailing comma returns the repaired value and emits one count with that entry point's label. Valid JSON emits no count. Verified by unit tests with an in-memory metric reader.
    • rg -n 'import json_repair' src finds only ai/response_repair.py.
    • rg -n chat_structured src tests finds nothing.
    • uv run devops ci passes, and the new tests take under 1 s.
  • Key questions:
    • Wire chat_structured in, or delete it? Delete it (proposed).
      • Nothing has called it since it shipped.
      • Review replies already keep their partial results through parse_review_response.
      • schema_reflection.py stays, because fix_llm_response uses it.
    • Label by entry point or by call site? By entry point (proposed). That already separates review parsing (fix_llm_response) from the extract_json_block callers. A per-call-site label is a small follow-up if one entry point dominates.
    • What counts as a repair? Strict json.loads failed and json-repair returned a value (proposed). json-repair's log misses some repairs.
  • Constraint:

Strategic Alignment

Split off #599 during the v0.2.25/v0.2.26 readiness review (2026-10-01): This was deliverable (4) of #599's original text. It shares no code with finish reasons or stream framing, so keeping it in #599 would push that PR beyond one reviewable change. Its premise also changed: the tflint exclusion is gone, and #437 has shipped, so the decision is now only whether to delete chat_structured.

Scope added 2026-10-03 from review session 20261003-005122 (S7, at b6847e9) (.data/review-evaluation-20261003-s7-s8.md, section 3, defect D3 and sketch D). Lines are at da50329. extract_json_block (src/devops_cli/core/serialization.py:23-88) loses a complete reply whose ```json fence is never closed. Its fence pattern (:9) needs a closing fence, so step 1 finds nothing. Step 3 slices from the first `{` to the last `}` before it tries `[` to `]` (`:57-74`), so a one-item list `[{…}]` comes back as the inner dict, and json-repair (`:76-84`) is never reached. `_parse_verifier_payload` (`src/devops_cli/ai/review/verification.py:2225-2233`) rejects a dict without `findings` or `items`, so every finding of the call ends `verifier-reply-unparsed`.

The case is S7's gpt-oss refutation of the non-literal-import finding on src/devops_cli/commands/workspace.py:43: cache llm_82417aa8…, ledger row 9985, finish reason stop, 1,034 completion tokens. It is INVALIDATED with citation_line 24, the static _LAZY_OBJECT_MAPPING table, and it is correct. The finding was reported UNVERIFIED. In S8, qwen3-coder VERIFIED the same false finding with a reason that refutes it (row 10050), and #948's ranking put it among the report's top rows.

The repair entry this item builds reads the reply right. repair_json_string (src/devops_cli/ai/response_repair.py:105-125) returns the one-item list through its whole-reply repair, and json_repair.loads on the whole reply returns the same list. Its own fence pattern (:49-52) also needs a closing fence, so #802's fenced-block rule plays no part. Over the 69 verifier cache entries of S5 to S8 (system hash 04f4c24c1b74873c), the two parsers return a different shape for this entry only. On 11 others both return the same one-item list, and repair_json_string only normalizes dashes and spaces in its text. The 10 entries S9 added at da50329 change nothing. The 79e1e93 parser behaves the same. #802 fixed bracketed prose around a fenced answer (#786) in repair_json_string only. extract_json_block keeps its own slicing, and 7 call sites pass it model replies (verification.py:2227, ai/agents/pipeline.py:68, ai/review_schema.py:1568, ai/analyze/outlines.py:124, ai/benchmark/runner.py:593, ai/review/runner.py:538 and :560). This item owns the fix because it already routes extract_json_block's repair through the one repair_json entry. #1003 builds on that entry and does not repeat this parse work. #1013 (v0.2.29) would stop caching a reply like this one. This fix makes it usable. Parsing is not the last step: replayed at da50329, the parsed verdict is still downgraded by the construct guard (_validate_citation_line), because line 24 holds none of the candidates (importlib.import_module, import_module, devops_cli, importlib, allows). #1021's criterion that a construct token on a line of the finding's own range counts would let it stand, since :43 holds importlib.import_module. The criteria below therefore stop at the parsed verdict.

  • extract_json_block never returns a value nested inside the reply's top-level value. A reply that opens a ```json fence, holds a one-item list of objects and never closes the fence returns the list. A test in tests/test_consolidation_serialization.py uses the `llm_82417aa8…` reply, trimmed to a fixture: `_parse_verifier_payload` returns one verdict, INVALIDATED with `citation_line` 24. It fails on the current code, which returns the inner dict and then None.
  • A reply that strict parsing rejects goes through the one repair_json entry, not through extract_json_block's own {…}-then-[…] slice. The existing tests in tests/test_consolidation_serialization.py:10-48 and fix(ai): keep a reply's structured output when its prose contains brackets (#786) #802's cases in tests/test_ai_fixer.py pass unchanged. A new test runs fix(ai): keep a reply's structured output when its prose contains brackets (#786) #802's bracketed-prose replies (tests/test_ai_fixer.py:215-228) and the unfenced list-after-prose and object-after-a-link replies (:281-282) through extract_json_block and gets each answer whole. They pass on the current code and guard against json-repair reading bracketed prose as values beside the answer.
  • (person-run) Replaying the 69 verifier cache entries of S5 to S8 with the new parser changes the parsed shape of llm_82417aa8… only. The PR gives the count.

Update 2026-10-08: refinement

Keep chat_structured: intake and refine call it (roadmap/intake_model.py:184, roadmap/refine.py:369). Drop its deletion and the rg criterion. Its _parse_json_payload (ai/client/structured.py:72-95) uses the one repair_json entry under its own source label, replacing CONST_METRIC_AI_STRUCTURED_REPAIR_SUCCESS. The S7 verifier assertion applies only until #1150. #1363 merged.

Activity

  1. added
    type/feature
    scope/ai
    priority/p2-medium
    on Oct 1, 2026
  2. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    This item's premise is out of date (checked 2026-10-08 at 910b823). chat_structured has had production callers since v0.2.26:

    Both PRs merged into release/v0.2.26 on 2026-10-04, and both callers run in the roadmap service. rg -n '\.chat_structured\(' src now lists those three calls. Applied as written, the deliverable "chat_structured is deleted" and the criterion "rg -n chat_structured src tests finds nothing" would break intake and refine.

    Suggested amendment:

    • Keep chat_structured.
    • Route its json_repair calls (_parse_json_payload in ai/client/structured.py) through the single repair_json entry, under their own source label.
    • Drop the deletion deliverable, that criterion and the "Delete it" answer.

    #1363 also changes chat_structured, so whichever lands second rebases.

  3. added this to the v0.2.36 milestone on Oct 14, 2026
  4. dan-petty commented on Oct 14, 2026

    @dan-petty
    OwnerAuthor

    Moved to v0.2.36: v0.2.36 started with fewer than its 16 items and was topped up to 16 from Ready items, critical fixes and P0 features first. (devops roadmap reprioritize)

  5. added
    status/in-progress
    on Oct 16, 2026
  6. dan-petty commented on Oct 16, 2026

    @dan-petty
    OwnerAuthor

    What changed

    #1594, merged into release/v0.2.36 as 08512a4.

    Summary

    • Add repair_json(text, *, source, max_length=None) -> tuple[Any, bool] in src/devops_cli/ai/response_repair.py that attempts strict json.loads first, falls back to fenced block decoding and json_repair.loads, and emits devops_cli_ai_json_repairs_total (AI_JSON_REPAIRS_TOTAL in src/devops_cli/telemetry/instruments.py) with {"source": source} whenever json-repair repairs a payload.
    • Route all three JSON repair entry points (repair_json_string, extract_json_block in src/devops_cli/core/serialization.py, and _parse_json_payload in src/devops_cli/ai/client/structured.py) through repair_json using constants CONST_JSON_REPAIR_SOURCE_REPAIR_JSON_STRING, CONST_JSON_REPAIR_SOURCE_EXTRACT_JSON_BLOCK, and CONST_JSON_REPAIR_SOURCE_CHAT_STRUCTURED in src/devops_cli/config/constants.py, replacing CONST_METRIC_AI_STRUCTURED_REPAIR_SUCCESS and leaving src/devops_cli/ai/response_repair.py as the only module in src/ importing json_repair.
    • Remove {...}-then-[...] substring slicing from extract_json_block so replies with unclosed ```json fences holding a one-item list of objects return the list rather than the inner dictionary.
    • Add unit tests in [tests/test_consolidation_serialization.py](tests/test_consolidation_serializa…

    11 file(s) changed.

    How it was verified

    Check runs at d7fad5d:

    • Audit Defect PR Hardening: skipping
    • Prune PR DevContainer Images: pass
    • devops-cli: pass
    • bandit: pass
    • Static Analysis: pass
    • CodeQL: pass
    • Analyze (python): pass
    • Changed-Test Independence: pass
    • Tests & Coverage: pass
    • Analyze (actions): pass
    • Dependency Freshness: skipping
    • Service Image: skipping
    • DevContainer Image: skipping

    Acceptance Criteria of docs/agent/tasks/task-875-json-repair-seam.md:

    No Acceptance Criteria section.

  7. added a commit that references this issue on Oct 17, 2026
  8. removed
    status/in-progress
    on Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p2-mediumscope/aitype/feature

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions