From 6909acd59cfa63e204c7ed5c3c8bd8bb92fc4062 Mon Sep 17 00:00:00 2001 From: William Aaron Cheung Date: Mon, 23 Nov 2026 18:40:13 +0800 Subject: [PATCH] fix(pr-review): avoid false session-limit classification on retry --- .github/actions/CLAUDE-CI.md | 4 +- .github/actions/claude-pr-review/README.md | 4 +- .github/actions/claude-pr-review/action.yml | 4 +- .../claude-pr-review/review_pipeline.py | 82 ++++++++++- .../claude-pr-review/test_review_pipeline.py | 138 ++++++++++++++++++ 5 files changed, 224 insertions(+), 8 deletions(-) diff --git a/.github/actions/CLAUDE-CI.md b/.github/actions/CLAUDE-CI.md index 82c37fb..441b8cc 100644 --- a/.github/actions/CLAUDE-CI.md +++ b/.github/actions/CLAUDE-CI.md @@ -285,7 +285,7 @@ The `pr-review` action additionally accepts: - `debug_logs` - deprecated and ignored. The analysis session's full output is now always printed. Consumers still passing it are unaffected; drop it at your convenience. -The semantic-analysis stage runs under a turn budget: 12 for a low-risk incremental review, +The semantic-analysis stage runs under a turn budget: 24 for a low-risk incremental review, 44 for a strong-tier one, and 56 for `deep`. Set `max_turns` to override any of these. Roughly ten turns go on mandated context — six pipeline files plus repo guidance — before the diff is read, and a small diff inside a large file spends many more paging through it, so the @@ -304,7 +304,7 @@ with: github_identity_token: ${{ steps.app-token.outputs.token }} ``` -The semantic stage is bounded to 12 turns for fast incremental reviews, 44 for standard +The semantic stage is bounded to 24 turns for fast incremental reviews, 44 for standard full or high-risk reviews, and 56 for explicit deep reviews, unless `max_turns` overrides it. ## Inspecting a review run diff --git a/.github/actions/claude-pr-review/README.md b/.github/actions/claude-pr-review/README.md index 19777a0..834f369 100644 --- a/.github/actions/claude-pr-review/README.md +++ b/.github/actions/claude-pr-review/README.md @@ -21,7 +21,7 @@ Family: [Claude CI](../CLAUDE-CI.md). | `model` | no | `claude-opus-4-7` | Model used for full, high-risk, and deep reviews. | | `incremental_model` | no | | Model used for low-risk incremental reviews. Empty uses the Claude Code default (Sonnet class). | | `review_depth` | no | `standard` | `standard` runs one lead review. `deep` asks the lead to fan out review dimensions and adversarially verify them before returning structured data. | -| `max_turns` | no | | Optional override for the per-invocation turn budget (`--max-turns`). Empty (default) uses the built-in budget derived from model tier and review depth (fast 12, standard 44, deep 56). Set a positive integer to pin the ceiling for the main analysis pass; the retry pass keeps its 1.5x headroom relative to this value. | +| `max_turns` | no | | Optional override for the per-invocation turn budget (`--max-turns`). Empty (default) uses the built-in budget derived from model tier and review depth (fast 24, standard 44, deep 56). Set a positive integer to pin the ceiling for the main analysis pass; the retry pass keeps its 1.5x headroom relative to this value. | | `debug_logs` | no | `false` | Deprecated and ignored. The analysis session's full output — its tool calls, the files it opened, and the ones it never read — is now always printed, and the whole `.pr-review` state directory plus the session transcript are uploaded as a run artifact. Kept only so consumers that still pass it do not break. | | `state_artifact` | no | `true` | `true` uploads the `.pr-review` state directory — routing input, both diffs, the raw model output, the compiled payload, the pipeline trace, and the analysis session transcript — as a run artifact. This is the only copy that outlives the runner, so leave it on unless the repository forbids artifacts. | | `state_artifact_retention_days` | no | `14` | Retention in days for the review state artifact. | @@ -96,6 +96,6 @@ jobs: step. - A PR that edits the calling repository's own `claude.yml` skips the review by design of `claude-code-action`; it works again once the change merges. -- Turn budgets: 12 for a low-risk incremental round, 44 for a strong-tier +- Turn budgets: 24 for a low-risk incremental round, 44 for a strong-tier one, 56 for `deep`; `max_turns` overrides, and the retry gets half again as many. diff --git a/.github/actions/claude-pr-review/action.yml b/.github/actions/claude-pr-review/action.yml index 3020751..83968bd 100644 --- a/.github/actions/claude-pr-review/action.yml +++ b/.github/actions/claude-pr-review/action.yml @@ -46,7 +46,7 @@ inputs: description: > Optional override for the per-invocation turn budget (`--max-turns`). Empty (default) uses the built-in budget derived from model tier and - review depth (fast 12, standard 44, deep 56). Set a positive integer to + review depth (fast 24, standard 44, deep 56). Set a positive integer to pin the ceiling for the main analysis pass; the retry pass keeps its 1.5x headroom relative to this value. debug_logs: @@ -156,7 +156,7 @@ runs: max_turns=44 if [[ "$MODEL_TIER" == "fast" ]]; then selected_model="$INCREMENTAL_MODEL" - max_turns=12 + max_turns=24 fi if [[ "$REVIEW_DEPTH" == "deep" ]]; then max_turns=56 diff --git a/.github/actions/claude-pr-review/review_pipeline.py b/.github/actions/claude-pr-review/review_pipeline.py index 52903e9..7b887f1 100644 --- a/.github/actions/claude-pr-review/review_pipeline.py +++ b/.github/actions/claude-pr-review/review_pipeline.py @@ -1162,6 +1162,74 @@ def iter_json_strings(value: Any): yield from iter_json_strings(item) +def iter_transcript_error_strings(value: Any): + """Yield strings only from error-bearing records in a Claude transcript. + + Every Claude Code session emits a routine ``rate_limit_event`` with + ``status: "allowed"``, ``rateLimitType: "five_hour"``, and + ``overageStatus: "rejected"``, and ``user``/``assistant`` turns contain + repository files and diffs read during the review. Walking every string in + the JSON tree would misclassify normal sessions (such as + ``error_max_turns``) or PRs discussing rate limits as provider quota + failures. + """ + if isinstance(value, list): + for item in value: + yield from iter_transcript_error_strings(item) + return + if not isinstance(value, dict): + return + entry_type = value.get("type") + if entry_type == "rate_limit_event": + info = value.get("rate_limit_info") + source = info if isinstance(info, dict) else value + status = str(source.get("status") or "").strip().lower() + if status == "rejected": + yield "rate_limit" + for key in ("rateLimitType", "message", "error"): + text = source.get(key) + if isinstance(text, str) and text: + yield text + return + if entry_type == "assistant": + if value.get("is_api_error_message") is True or bool( + value.get("error") + ): + error_text = value.get("error") + if isinstance(error_text, str) and error_text: + yield error_text + message = value.get("message") + if isinstance(message, dict): + yield from iter_json_strings(message.get("content")) + return + if entry_type == "result": + if value.get("is_error") is not True: + return + is_max_turns = ( + value.get("subtype") == "error_max_turns" + or value.get("terminal_reason") == "max_turns" + ) + if not is_max_turns: + result_text = value.get("result") + if isinstance(result_text, str) and result_text: + yield result_text + for error_item in value.get("errors") or (): + if isinstance(error_item, str): + if error_item and not is_max_turns: + yield error_item + elif isinstance(error_item, dict): + status = str(error_item.get("status") or "").strip().lower() + if status != "allowed": + yield from iter_json_strings(error_item) + return + if entry_type in {"system", "user"}: + return + if entry_type is None: + status = str(value.get("status") or "").strip().lower() + if status != "allowed": + yield from iter_json_strings(value) + + def load_json_value(path: Path) -> Any: try: return json.loads(path.read_text(encoding="utf-8")) @@ -1221,13 +1289,13 @@ def classify_model_text(text: str) -> dict[str, Any] | None: def classify_model_failure(*, execution_file: str = "") -> dict[str, Any]: - """Read the first analysis transcript and decide whether retry can help.""" + """Read an analysis transcript and decide whether retry can help.""" chunks: list[str] = [] path = Path(execution_file) if execution_file else None if path is not None and path.is_file(): value = load_json_value(path) if value is not None: - chunks.extend(iter_json_strings(value)) + chunks.extend(iter_transcript_error_strings(value)) else: try: chunks.append(path.read_text(encoding="utf-8", errors="replace")) @@ -2549,6 +2617,16 @@ def compile_command(args: argparse.Namespace) -> None: raw = os.environ.get("REVIEW_STRUCTURED_OUTPUT", "") if not raw: classified = read_json_file(state_dir / MODEL_FAILURE_FILENAME) or {} + if not ( + classified.get("code") and classified.get("retryable") is False + ): + retry_transcript = state_dir / "analysis-retry-transcript.json" + if retry_transcript.is_file(): + classified = classify_model_failure( + execution_file=str(retry_transcript), + ) + if classified.get("code"): + write_model_failure(state_dir, classified) if classified.get("code") and classified.get("retryable") is False: raise PipelineError( str( diff --git a/.github/actions/claude-pr-review/test_review_pipeline.py b/.github/actions/claude-pr-review/test_review_pipeline.py index 5f90798..ce07460 100644 --- a/.github/actions/claude-pr-review/test_review_pipeline.py +++ b/.github/actions/claude-pr-review/test_review_pipeline.py @@ -2471,6 +2471,102 @@ def test_classify_session_limit_from_transcript(self): self.assertIn("session limit", classified["message"].lower()) self.assertIn("11:30am", classified["message"]) + def test_classify_ignores_allowed_rate_limit_event_and_max_turns_transcript( + self, + ): + transcript = [ + { + "type": "rate_limit_event", + "rate_limit_info": { + "status": "allowed", + "resetsAt": 1795431000, + "rateLimitType": "five_hour", + "overageStatus": "rejected", + "overageDisabledReason": "org_level_disabled", + "isUsingOverage": False, + }, + }, + { + "type": "user", + "tool_use_result": { + "content": ( + "You've hit your session limit · rateLimitType: " + "five_hour · rate_limit in reviewed file" + ) + }, + }, + { + "type": "assistant", + "message": { + "content": [ + { + "type": "text", + "text": ( + "Checking rate limit and session limit " + "handling in the PR diff." + ), + } + ] + }, + }, + { + "type": "result", + "subtype": "error_max_turns", + "is_error": True, + "terminal_reason": "max_turns", + "errors": ["Reached maximum number of turns (24)"], + }, + ] + with tempfile.TemporaryDirectory() as directory: + path = Path(directory, "analysis-transcript.json") + path.write_text(json.dumps(transcript), encoding="utf-8") + classified = pipeline.classify_model_failure( + execution_file=str(path) + ) + + self.assertTrue(classified["retryable"]) + self.assertEqual(classified["code"], "") + + def test_classify_rejected_rate_limit_event_and_api_error_assistant_message( + self, + ): + transcript = [ + { + "type": "rate_limit_event", + "rate_limit_info": { + "status": "rejected", + "resetsAt": 1795431000, + "rateLimitType": "five_hour", + }, + }, + { + "type": "assistant", + "is_api_error_message": True, + "error": "rate_limit", + "message": { + "content": [ + { + "type": "text", + "text": ( + "You've hit your session limit · resets " + "3:00pm (UTC)" + ), + } + ] + }, + }, + ] + with tempfile.TemporaryDirectory() as directory: + path = Path(directory, "analysis-transcript.json") + path.write_text(json.dumps(transcript), encoding="utf-8") + classified = pipeline.classify_model_failure( + execution_file=str(path) + ) + + self.assertEqual(classified["code"], "MODEL_SESSION_LIMIT") + self.assertFalse(classified["retryable"]) + self.assertIn("3:00pm", classified["message"]) + def test_classify_missing_file_is_retryable(self): classified = pipeline.classify_model_failure( execution_file="/no/such/transcript.json" @@ -2510,6 +2606,48 @@ def test_compile_uses_classified_session_limit(self): self.assertEqual(raised.exception.code, "MODEL_SESSION_LIMIT") self.assertIn("session limit", str(raised.exception)) + def test_compile_classifies_retry_transcript_when_first_attempt_was_retryable( + self, + ): + with tempfile.TemporaryDirectory() as directory: + state = Path(directory) + (state / "review-input.json").write_text( + json.dumps(review_input()), + encoding="utf-8", + ) + pipeline.write_model_failure( + state, + { + "code": "", + "retryable": True, + "message": "", + "remediation": "", + }, + ) + (state / "analysis-retry-transcript.json").write_text( + json.dumps( + [ + { + "type": "result", + "subtype": "success", + "is_error": True, + "result": ( + "You've hit your session limit · resets " + "4:00pm (UTC)" + ), + } + ] + ), + encoding="utf-8", + ) + with mock.patch.dict("os.environ", {"REVIEW_STRUCTURED_OUTPUT": ""}): + with self.assertRaises(pipeline.PipelineError) as raised: + pipeline.compile_command( + SimpleNamespace(state_dir=str(state)) + ) + self.assertEqual(raised.exception.code, "MODEL_SESSION_LIMIT") + self.assertIn("4:00pm", str(raised.exception)) + def test_failed_status_includes_provider_message_and_run_url(self): payload = { "repository": "megaeth-labs/example",