fix: retry invalid CLI review reports within timeout budget #31

Merged
nimmo merged 1 commit from fix/invalid-agent-review-retry into main 2026-10-08 07:29:35 +01:00
Owner

Completed Pi/agent-cli reviews can fail the action when a model response contains invalid JSON or violates the review schema. This change retries that response once with a fresh invocation and the remaining original timeout budget. A second invalid response still fails without publishing. Diagnostics identify JSON positions or schema requirements without exposing model output.

Execution failures, missing/oversized artifacts, and OpenCode event errors retain their existing failure behavior. README documents the retry and its limits.

Related to #30 and nixos-config MR #286. That MR's run #1116 attempt 2 failed artifact validation; its rejected output was deleted, so the exact defect remains unknown. Captured run #1126 succeeded on the same head and both responses passed JSON/schema validation.

Validation: 70 unit tests passed with one existing skip; git diff --check passed. Regression coverage includes successful recovery, fresh artifact directories, attempt and timeout limits, safe diagnostics, and non-retryable failures. Live recovery with this change remains to be verified before closing #30.

Completed Pi/agent-cli reviews can fail the action when a model response contains invalid JSON or violates the review schema. This change retries that response once with a fresh invocation and the remaining original timeout budget. A second invalid response still fails without publishing. Diagnostics identify JSON positions or schema requirements without exposing model output. Execution failures, missing/oversized artifacts, and OpenCode event errors retain their existing failure behavior. README documents the retry and its limits. Related to #30 and [nixos-config MR #286](https://git.nimmog.uk/nimmo/nixos-config/pulls/286). That MR's run #1116 attempt 2 failed artifact validation; its rejected output was deleted, so the exact defect remains unknown. Captured run #1126 succeeded on the same head and both responses passed JSON/schema validation. Validation: 70 unit tests passed with one existing skip; `git diff --check` passed. Regression coverage includes successful recovery, fresh artifact directories, attempt and timeout limits, safe diagnostics, and non-retryable failures. Live recovery with this change remains to be verified before closing #30.
fix: retry invalid CLI review reports within timeout budget
All checks were successful
Build and publish container image / prepare-tags (push) Successful in 1s
Build and publish container image / build-and-push (push) Successful in 23s
AI pull-request review / review (pull_request) Successful in 5m3s
28285599fa
clankbot left a comment

Automated code review

Reviewed commit: 28285599fa4d4be8e598cd45b56e6aa552bb8aa2

Verdict: Ready to merge

No blocking or important findings were retained, and deterministic checks passed. Suggestions remain advisory.

Overall assessment

The change adds a single retry for completed Pi/agent-cli responses that fail JSON parsing or report-schema validation. Verified from the checked-out code: InvalidAgentReport (reviewer.py:613-615) is raised only from the two new inner handlers in agent_cli_review (reviewer.py:730-741); review_with_provider (reviewer.py:750-766) catches it once, derives remaining from the original provider timeout_seconds (default 900, matching agent_cli_review's own default at reviewer.py:640), prints a diagnostic to stderr, deep-copies the config (so the caller's config is not mutated), and re-invokes agent_cli_review, which always allocates a fresh tempfile.TemporaryDirectory (reviewer.py:672), so the rejected artifact cannot be reused. The retry is bounded to one attempt (the retry call is outside any try), remaining < 1 suppresses it, and non-report failures (start failure, non-zero exit, timeout, missing/oversized artifact) still raise plain RuntimeError and are not caught. validate_agent_report (reviewer.py:550-573) raises only fixed messages, so the schema diagnostic cannot echo model output; the JSON diagnostic uses only exc.lineno/exc.colno. Two diagnostics-accuracy and classification gaps are noted; both are minor and do not affect the retry decision itself.

Blocking findings

None.

Important findings

None.

Suggestions

  • Reported JSON line/column are offsets into the extracted candidate, not the model response (reviewer.py:732; high confidence)
    The new handler reports exc.lineno, exc.colno verbatim. In stdout mode those values come from parse_model_json (reviewer.py:778-792), which parses strip_fences(text); strip_fences (reviewer.py:770-775) strips leading/trailing fences and re-anchors the string at text.find("{")/text.rfind("}"), and on a repair attempt the error can come from json.loads(repaired), whose offsets reflect the backslash-rewritten text. In artifact mode json.loads(content) is called on raw bytes (reviewer.py:726), so colno counts bytes. The README states the reviewer 'reports JSON line/column positions' without qualification.
    Impact: For the common malformed-report case (prose or a code fence before the object, or an invalid escape), the position quoted in the stderr diagnostic and re-sent in the retry prompt points into the stripped/repaired substring, so it can be several lines away from the location in the actual response. The retry decision is unaffected; only the human-facing diagnostic is misleading.
    Suggested fix: Either state in the README that positions are relative to the extracted JSON candidate, or recompute the offset against the original content (e.g. carry the strip_fences offset) before formatting the diagnostic.

  • Completed responses that fail with a non-JSONDecodeError decode error are still classified as non-retryable (reviewer.py:730; medium confidence)
    Only json.JSONDecodeError is converted to InvalidAgentReport (reviewer.py:733-736). The surrounding handler except (OSError, UnicodeError, ValueError) (reviewer.py:742) converts everything else to the generic RuntimeError("Agent CLI produced a missing, invalid, or oversized review artifact"), which review_with_provider does not catch. content.decode() (reviewer.py:731) and json.loads(content) on undecoded bytes (reviewer.py:725) both raise UnicodeDecodeError (a UnicodeError/ValueError) for non-UTF-8 output, so an otherwise-complete response with an encoding problem gets no retry. The README's non-retry list names only 'CLI failures, timeouts, missing artifacts, output-size limits, and OpenCode event errors', so this case is undocumented.
    Impact: The recovery path covers a narrower set of invalid completed responses than the README describes ('contains invalid JSON or fails the report schema'), and the one case that is neither listed as retried nor as non-retried (undecodable output) silently falls into the non-retryable artifact error. This is a classification gap, not a demonstrated defect in a known failure.
    Suggested fix: Decide explicitly whether an undecodable completed artifact/stdout is an invalid report (retryable) or an artifact failure; if retryable, move the decode/json.loads boundary inside the inner try so UnicodeDecodeError also raises InvalidAgentReport, and state the choice in the README's non-retry list.

Tests and validation

  • unit-tests: success

Questions

  • Should a completed OpenCode response whose final text fails the report schema also be retried? parse_opencode_events is called at reviewer.py:729, before the new handlers, so its ValueError/JSONDecodeError still becomes the non-retryable RuntimeError; the README scopes the retry to Pi/agent-cli but does not state the OpenCode report-schema case.
  • When remaining < 1, the first attempt's diagnostic is only re-raised, not printed to stderr. Should that diagnostic be logged before giving up, so the failing job still reports why the response was rejected?

Review limitations

  • I read the supplied diff plus the checked-out reviewer.py and tests/test_agent_cli.py; I did not run the unit tests, the deterministic analysis command, or any live Pi/agent-cli review, so the stated unit-test pass count and the recovered live case remain unverified here.
  • The exact defect in the referenced rejected run is unknown (its output was deleted), so I cannot confirm the new retry would have recovered that specific failure.
  • Files not supplied in the diff (Nix packaging, workflow YAML, other test modules) were not inspected.

Diff coverage

  • README.md: reviewed — included in a context-limited batch
  • reviewer.py: reviewed — included in a context-limited batch
  • tests/test_agent_cli.py: reviewed — included in a context-limited batch
Review metadata
  • Reviewer: forgejo-ai-review v1
  • Model: strata/strata
  • Guidance loaded: .forgejo/ai-review.yml, docs/pi-live-sample.md, README.md
  • Commits considered: 1
  • Previous automated review: none found
  • Findings: 2
<!-- forgejo-ai-review:v1 --> ## Automated code review Reviewed commit: `28285599fa4d4be8e598cd45b56e6aa552bb8aa2` ## Verdict: Ready to merge No blocking or important findings were retained, and deterministic checks passed. Suggestions remain advisory. ### Overall assessment The change adds a single retry for completed Pi/agent-cli responses that fail JSON parsing or report-schema validation. Verified from the checked-out code: InvalidAgentReport (reviewer.py:613-615) is raised only from the two new inner handlers in agent_cli_review (reviewer.py:730-741); review_with_provider (reviewer.py:750-766) catches it once, derives `remaining` from the original provider `timeout_seconds` (default 900, matching agent_cli_review's own default at reviewer.py:640), prints a diagnostic to stderr, deep-copies the config (so the caller's config is not mutated), and re-invokes agent_cli_review, which always allocates a fresh tempfile.TemporaryDirectory (reviewer.py:672), so the rejected artifact cannot be reused. The retry is bounded to one attempt (the retry call is outside any try), `remaining < 1` suppresses it, and non-report failures (start failure, non-zero exit, timeout, missing/oversized artifact) still raise plain RuntimeError and are not caught. validate_agent_report (reviewer.py:550-573) raises only fixed messages, so the schema diagnostic cannot echo model output; the JSON diagnostic uses only exc.lineno/exc.colno. Two diagnostics-accuracy and classification gaps are noted; both are minor and do not affect the retry decision itself. ### Blocking findings None. ### Important findings None. ### Suggestions - **Reported JSON line/column are offsets into the extracted candidate, not the model response** (reviewer.py:732; high confidence) The new handler reports `exc.lineno, exc.colno` verbatim. In stdout mode those values come from `parse_model_json` (reviewer.py:778-792), which parses `strip_fences(text)`; `strip_fences` (reviewer.py:770-775) strips leading/trailing fences and re-anchors the string at `text.find("{")`/`text.rfind("}")`, and on a repair attempt the error can come from `json.loads(repaired)`, whose offsets reflect the backslash-rewritten text. In artifact mode `json.loads(content)` is called on raw bytes (reviewer.py:726), so `colno` counts bytes. The README states the reviewer 'reports JSON line/column positions' without qualification. Impact: For the common malformed-report case (prose or a code fence before the object, or an invalid escape), the position quoted in the stderr diagnostic and re-sent in the retry prompt points into the stripped/repaired substring, so it can be several lines away from the location in the actual response. The retry decision is unaffected; only the human-facing diagnostic is misleading. Suggested fix: Either state in the README that positions are relative to the extracted JSON candidate, or recompute the offset against the original content (e.g. carry the strip_fences offset) before formatting the diagnostic. - **Completed responses that fail with a non-JSONDecodeError decode error are still classified as non-retryable** (reviewer.py:730; medium confidence) Only `json.JSONDecodeError` is converted to `InvalidAgentReport` (reviewer.py:733-736). The surrounding handler `except (OSError, UnicodeError, ValueError)` (reviewer.py:742) converts everything else to the generic `RuntimeError("Agent CLI produced a missing, invalid, or oversized review artifact")`, which review_with_provider does not catch. `content.decode()` (reviewer.py:731) and `json.loads(content)` on undecoded bytes (reviewer.py:725) both raise UnicodeDecodeError (a UnicodeError/ValueError) for non-UTF-8 output, so an otherwise-complete response with an encoding problem gets no retry. The README's non-retry list names only 'CLI failures, timeouts, missing artifacts, output-size limits, and OpenCode event errors', so this case is undocumented. Impact: The recovery path covers a narrower set of invalid completed responses than the README describes ('contains invalid JSON or fails the report schema'), and the one case that is neither listed as retried nor as non-retried (undecodable output) silently falls into the non-retryable artifact error. This is a classification gap, not a demonstrated defect in a known failure. Suggested fix: Decide explicitly whether an undecodable completed artifact/stdout is an invalid report (retryable) or an artifact failure; if retryable, move the decode/`json.loads` boundary inside the inner try so UnicodeDecodeError also raises InvalidAgentReport, and state the choice in the README's non-retry list. ### Tests and validation - unit-tests: **success** ### Questions - Should a completed OpenCode response whose final text fails the report schema also be retried? `parse_opencode_events` is called at reviewer.py:729, before the new handlers, so its ValueError/JSONDecodeError still becomes the non-retryable RuntimeError; the README scopes the retry to Pi/agent-cli but does not state the OpenCode report-schema case. - When `remaining < 1`, the first attempt's diagnostic is only re-raised, not printed to stderr. Should that diagnostic be logged before giving up, so the failing job still reports why the response was rejected? ### Review limitations - I read the supplied diff plus the checked-out reviewer.py and tests/test_agent_cli.py; I did not run the unit tests, the deterministic analysis command, or any live Pi/agent-cli review, so the stated unit-test pass count and the recovered live case remain unverified here. - The exact defect in the referenced rejected run is unknown (its output was deleted), so I cannot confirm the new retry would have recovered that specific failure. - Files not supplied in the diff (Nix packaging, workflow YAML, other test modules) were not inspected. ### Diff coverage - `README.md`: **reviewed** — included in a context-limited batch - `reviewer.py`: **reviewed** — included in a context-limited batch - `tests/test_agent_cli.py`: **reviewed** — included in a context-limited batch <details><summary>Review metadata</summary> - Reviewer: forgejo-ai-review v1 - Model: strata/strata - Guidance loaded: .forgejo/ai-review.yml, docs/pi-live-sample.md, README.md - Commits considered: 1 - Previous automated review: none found - Findings: 2 </details>
nimmo merged commit 3d47eea7de into main 2026-10-08 07:29:35 +01:00
Sign in to join this conversation.
No reviewers
No labels
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
nimmo/forgejo-auto-pr-review!31
No description provided.