diff --git a/dev-tools/pr_review/README.md b/dev-tools/pr_review/README.md index a1ba59efef..5868950c76 100644 --- a/dev-tools/pr_review/README.md +++ b/dev-tools/pr_review/README.md @@ -131,6 +131,16 @@ Hosted findings and their associated source/incoming routes expose `display_seve Provider runs may include `duration_seconds` from an exact completed attempt or an identity-validated retained checkpoint/capture; evaluated missing, invalid or conflicting duration evidence returns `duration_seconds: null`, which is authoritative unknown. Consumers may use legacy fallback only when the field is absent, never when it is null. Import event timestamps are never treated as elapsed review time. Reads make no provider requests or historical corrections. +For one retained ambiguous Hosted reply whose complete public history and immutable prior capture prove a finished zero-result response, `records repair-provider` supports an exact response selector paired with its original attempt: + +```sh +dev-tools/pr-review records repair-provider --pr --repo \ + --response-id --attempt-id \ + --actor --scope broad [--database ] +``` + +The default is a preview; repeat with `--apply` only after reviewing that preview. This recovery mode accepts only the captured reply, full immutable request anchor, complete current response window, and exact archived-thread updates already proved against the prior completed attempt. It refuses unknown or changed reply text, substantive findings, conflicting identities, incomplete history, and changed archive evidence. It appends one zero-count source run, its exact archived artifacts, and the provider origin last; exact retries reuse those same identities. The original ambiguous state and capture remain unchanged. This repair does not itself publish a checkpoint or grant readiness. The exact recovered zero-result run may later use the explicit `records source finalize` publication path below; that path appends only publication intent/events to the original ambiguous attempt metadata and retains its state, provider identity, capture, terminal times, and immutable response origin. No other imported or manual run gains publication eligibility. + ```sh dev-tools/pr-review routes --target-pr dev-tools/pr-review routes --unassigned @@ -265,7 +275,7 @@ After adjudicating all source findings, freeze counts and publish/reuse the cano dev-tools/pr-review records source finalize --run-id ``` -The CLI finalization command publishes completed native Hosted/CLI runs after freezing their counts; manual/subagent runs remain local. The underlying store operation stays SQL-only for imports, captures, repairs and subagent completion. SQL finalization and GitHub publication are not atomic: counts can already be frozen when publication fails. The command then reports failure; repeat the same finalization to recover/reuse publication safely. This command derives the canonical counts, full reviewed SHA, file count, duration and provider markers from completed immutable native evidence. It supports CLI captures and new Hosted captures with verified request-time candidate file count and retained exact trigger attribution. Older Hosted captures missing either field fail closed and retain the historical manual workflow; no current diff or agent-supplied count substitutes for them. Advancing the live PR head does not invalidate its older reviewed checkpoint. Candidate file count describes the captured review scope; provider completion and coverage still require adjudication and do not imply physical inspection of every file. Publication adds no fix proof, allocation override, CI result, or merge permission. +The CLI finalization command publishes completed native Hosted/CLI runs after freezing their counts; manual/subagent runs remain local. It also accepts only the exact deterministic zero-result run imported by the ambiguous Hosted reply recovery above, using its original request file count, reviewed head, elapsed trigger window, and response marker. For that exception, the publication intent and append-only events live in the original ambiguous attempt metadata; they do not link the attempt to a run or rewrite its terminal history or provider origin. Runtime associates the newly published comment with the recovered run only when that durable audit binds the exact public comment. The underlying store operation stays SQL-only for imports, captures, repairs and subagent completion. SQL finalization and GitHub publication are not atomic: counts can already be frozen when publication fails. The command then reports failure; repeat the same finalization to recover/reuse publication safely. This command derives the canonical counts, full reviewed SHA, file count, duration and provider markers from completed immutable evidence. It supports CLI captures and new Hosted captures with verified request-time candidate file count and retained exact trigger attribution. Older Hosted captures missing either field fail closed and retain the historical manual workflow; no current diff or agent-supplied count substitutes for them. Advancing the live PR head does not invalidate its older reviewed checkpoint. Candidate file count describes the captured review scope; provider completion and coverage still require adjudication and do not imply physical inspection of every file. Publication adds no fix proof, allocation override, CI result, or merge permission. The structured result includes `publication` with `status: published|reused`, `comment_id`, `comment_url`, and the canonical `body`. Publishers share the existing lock primitive and retain a pre-POST intent in the existing attempt metadata. Complete paginated GitHub history and verified repository/publisher identity permit reuse of semantically matching canonical comments, including verified commit links and harmless whitespace, and reject conflicting identities or counts. An uncertain POST is recovered by reading history; if the exact comment is not visible, retries refuse another POST and retain the intent. Retry the command later for read recovery; do not manually repost or overwrite historical comments. diff --git a/dev-tools/pr_review/checkpoint_publication.py b/dev-tools/pr_review/checkpoint_publication.py index 5b130401dc..0feb5cb8ef 100644 --- a/dev-tools/pr_review/checkpoint_publication.py +++ b/dev-tools/pr_review/checkpoint_publication.py @@ -68,22 +68,47 @@ def checkpoint_body(store, *, repo, source_pr, run_id): history = store.history(source_pr, include_display=False) runs = [run for run in history["runs"] if run["run_id"] == run_id] attempts = [attempt for attempt in store.attempt_history(source_pr) if attempt["run_id"] == run_id] - if len(runs) != 1 or len(attempts) != 1: + if len(runs) != 1: + _refuse("checkpoint requires exactly one finalized source run") + run = runs[0] + recovered = False + attempt = None + if len(attempts) == 1 and attempts[0]["attempt_id"] == run_id: + attempt = attempts[0] + if (run["channel"] not in {"cli", "hosted"} or run["outcome"] != "completed" + or run["attributable"] is not True or run["finalized"] is not True + or attempt["channel"] != run["channel"] or attempt["state"] != "completed" + or attempt["candidate_sha"] != run["source_head"] or attempt["run_id"] != run_id): + _refuse("checkpoint requires completed attributable finalized native evidence") + elif not attempts and run.get("channel") == "hosted": + try: + from .sqlite_records_repair import verify_ambiguous_reply_import_for_publication + + recovered = verify_ambiguous_reply_import_for_publication( + store, repo=repo, pr_number=source_pr, run_id=run_id + ) + except (ValueError, TypeError, KeyError) as exc: + raise ReviewRecordsError(f"checkpoint recovery proof is unavailable: {exc}") from exc + run = recovered["run"] + attempt = recovered["attempt"] + else: _refuse("checkpoint requires exactly one native source run and matching attempt") - run, attempt = runs[0], attempts[0] channel = run["channel"] - if (channel not in {"cli", "hosted"} or run["outcome"] != "completed" - or run["attributable"] is not True or run["finalized"] is not True - or attempt["attempt_id"] != run_id or attempt["channel"] != channel - or attempt["state"] != "completed" or attempt["candidate_sha"] != run["source_head"]): - _refuse("checkpoint requires completed attributable finalized native evidence") - head, duration, counts = run["source_head"], attempt["duration_seconds"], run["counts"] + head, duration, counts = run["source_head"], ( + recovered["checkpoint"].duration_seconds if recovered else attempts[0]["duration_seconds"] + ), run["counts"] if (not isinstance(head, str) or not evidence.EXACT_SHA.fullmatch(head) or type(duration) is not int or duration < 0 or any(type(counts.get(key)) is not int or counts[key] < 0 for key in ("found", "accepted", "routed")) or counts["accepted"] + counts["routed"] > counts["found"]): _refuse("checkpoint source head, counts or duration is invalid") - if channel == "cli": + if recovered: + checkpoint = recovered["checkpoint"] + if checkpoint.file_count is None or checkpoint.file_count <= 0: + _refuse("recovered Hosted checkpoint lacks its captured request file count") + files = checkpoint.file_count + marker = f"" + elif channel == "cli": if not evidence.RUN_ID.fullmatch(run_id): _refuse("native CLI run has invalid marker identity") snapshot = store.cli_capture_snapshot(run_id, source_pr=source_pr) @@ -240,6 +265,29 @@ def publish_checkpoint(store, *, repo, source_pr, run_id, adapter=github): comment = matching(adapter.fetch_api_endpoint(endpoint)) fresh = store.reserve_checkpoint_publication(run_id, json.dumps(intent, sort_keys=True)) if comment is not None: + _, recovered = store._checkpoint_publication_target( + run_id, repository=repo, source_pr=source_pr + ) + if recovered: + state = store.checkpoint_publication_state(run_id) + bound = [ + event + for event in state["events"] + if event.get("type") in {"post_outcome", "reused"} + and event.get("comment_id") == comment["id"] + ] + conflicts = [ + event + for event in state["events"] + if event.get("type") in {"post_outcome", "reused"} + and event.get("comment_id") is not None + and event.get("comment_id") != comment["id"] + ] + if conflicts: + _refuse("recovered checkpoint publication audit conflicts with visible comment identity") + if not bound: + _append(store, run_id, state, {"type": "reused", "decision_id": None, + "comment_id": comment["id"]}) return _result(intent, comment, "reused") if not fresh: _refuse("prior checkpoint POST may have occurred; no verified comment is visible; retry read recovery later") diff --git a/dev-tools/pr_review/cli.py b/dev-tools/pr_review/cli.py index 356818f123..a5488198d9 100644 --- a/dev-tools/pr_review/cli.py +++ b/dev-tools/pr_review/cli.py @@ -4,8 +4,10 @@ import argparse import dataclasses +import fcntl import hashlib import json +import os import re import stat import sys @@ -59,6 +61,21 @@ def parse_args(self, args=None, namespace=None): ) ): self.error("--exact-additional-completed cannot be combined with min or max additional-completed bounds") + if getattr(parsed, "records_command", None) == "repair-provider": + response_id = getattr(parsed, "response_id", None) + attempt_id = getattr(parsed, "attempt_id", None) + selected_checkpoint = getattr(parsed, "checkpoint_id", None) + selected_all = getattr(parsed, "all", False) + if response_id is None and attempt_id is not None: + self.error("--attempt-id requires --response-id") + if response_id is not None and (attempt_id is None or selected_checkpoint is not None or selected_all): + self.error( + "--response-id requires exactly one --attempt-id and cannot be combined with checkpoint selectors" + ) + if response_id is None and selected_checkpoint is None and not selected_all: + self.error("repair-provider requires --checkpoint-id, --all, or --response-id with --attempt-id") + if response_id is not None and getattr(parsed, "continue_on_error", False): + self.error("--continue-on-error is only valid with --all") return parsed @@ -329,9 +346,15 @@ def records_database(command: argparse.ArgumentParser) -> None: help="preview or replay exact public provider checkpoints into SQLite", ) provider_repair.add_argument("--pr", required=True, type=_positive_int) - repair_selection = provider_repair.add_mutually_exclusive_group(required=True) + repair_selection = provider_repair.add_mutually_exclusive_group() repair_selection.add_argument("--checkpoint-id", action="append", type=_positive_int) repair_selection.add_argument("--all", action="store_true") + repair_selection.add_argument( + "--response-id", + type=_positive_int, + help="recover one exact captured ambiguous Hosted reply; requires --attempt-id", + ) + provider_repair.add_argument("--attempt-id", help="exact retained ambiguous Hosted attempt for --response-id") provider_repair.add_argument("--repo", help="owner/name; defaults to the current GitHub repository") provider_repair.add_argument("--actor", required=True) provider_repair.add_argument("--scope", required=True, choices=("broad", "narrow")) @@ -1365,6 +1388,31 @@ def _dispatch_records(args: argparse.Namespace) -> tuple[Any, int]: if args.records_command == "repair-provider": store.history(args.pr) repo = github.infer_repo(args.repo) + if args.response_id is not None: + if args.coverage_limit: + raise CliError("exact response recovery does not accept checkpoint coverage limits") + record_path = hosted.default_trigger_record_path(repo, args.pr, store.path.parent.parent) + descriptor = hosted._with_lock(record_path) + try: + try: + payload = github.fetch_pull_request(repo, args.pr) + except (OSError, RuntimeError, TypeError, ValueError) as exc: + raise CliError("could not read complete Hosted response history") from exc + result = sqlite_records_repair.repair_ambiguous_hosted_reply( + store, + repo=repo, + pr_number=args.pr, + attempt_id=args.attempt_id, + response_id=args.response_id, + actor=args.actor, + scope=args.scope, + hosted_payload=payload, + dry_run=not args.apply, + ) + finally: + fcntl.flock(descriptor, fcntl.LOCK_UN) + os.close(descriptor) + return {"api_version": 1, "result": result}, 0 if result["status"] != "partial" else 2 checkpoints, payload = _provider_checkpoints(args, repo) if args.continue_on_error: if not args.all: diff --git a/dev-tools/pr_review/hosted.py b/dev-tools/pr_review/hosted.py index 9c34635086..05dca6a431 100644 --- a/dev-tools/pr_review/hosted.py +++ b/dev-tools/pr_review/hosted.py @@ -1775,7 +1775,7 @@ def _is_finished_action_response(body: str, *, allow_action_wrapper: bool) -> bo _ADDRESSED_COMMIT_ANNOTATION = re.compile( - r"(?:\r?\n){2}✅ Addressed in commits ([0-9a-f]{7,40}) to ([0-9a-f]{7,40})\Z", + r"(?:\r?\n){2}✅ Addressed in commit(?:s ([0-9a-f]{7,40}) to)? ([0-9a-f]{7,40})\Z", re.IGNORECASE, ) @@ -1783,11 +1783,15 @@ def _is_finished_action_response(body: str, *, allow_action_wrapper: bool) -> bo def _archived_completed_thread_bodies( repo: str, pr_number: int, + payload: dict[str, Any], head: str, response_id: int, response_created_at: datetime, record: Mapping[str, Any] | None, current_record_path: str | Path | None, + *, + recovery_attempt_id: str | None = None, + records_reader: Any = None, ) -> dict[int, tuple[str, str]]: """Read immutable prior Hosted thread bodies for exact trigger attribution.""" @@ -1832,7 +1836,7 @@ def _archived_completed_thread_bodies( return {} try: - records = SqliteReviewRecords(database) + records = records_reader if records_reader is not None else SqliteReviewRecords(database) current_attempt = records.attempt(current_attempt_id) attempt_history = records.attempt_history(pr_number) current_history = [item for item in attempt_history if item.get("attempt_id") == current_attempt_id] @@ -1908,6 +1912,85 @@ def _archived_completed_thread_bodies( or current_observed_at != current_finished_at ): return {} + elif current_state == "ambiguous" and recovery_attempt_id == current_attempt_id: + # The explicit records-repair path may verify one previously + # captured ambiguous response. Normal trigger readers never pass + # this selector and retain the terminal-ambiguity fence below. + if ( + current_trigger_id != str(trigger_id) + or current_response_id != str(response_id) + or current_finished_at is None + or current_finished_at < response_created_at + or current_attempt.get("run_id") is not None + ): + return {} + try: + current_artifacts = records.attempt_artifacts(current_attempt_id) + if not {"hosted_review", "hosted_comments", "metadata"} <= current_artifacts.keys(): + return {} + current_metadata = json.loads(current_artifacts["metadata"]) + current_reviews = json.loads(current_artifacts["hosted_review"]) + current_comments = json.loads(current_artifacts["hosted_comments"]) + except (TypeError, ValueError, json.JSONDecodeError): + return {} + current_observed_at = ( + parse_timestamp(current_metadata.get("observed_at")) if isinstance(current_metadata, dict) else None + ) + captured_record = current_metadata.get("trigger_record") if isinstance(current_metadata, dict) else None + if ( + not isinstance(current_metadata, dict) + or current_metadata.get("state") != "ambiguous" + or current_metadata.get("terminal") is not True + or current_metadata.get("attributable") is not False + or not isinstance(current_metadata.get("repository"), str) + or current_metadata["repository"].casefold() != repo.casefold() + or current_metadata.get("pull_request") != pr_number + or current_metadata.get("head_sha") != head + or current_metadata.get("trigger_id") != trigger_id + or current_metadata.get("response_id") != response_id + or current_observed_at != current_finished_at + or not isinstance(captured_record, dict) + or captured_record.get("sqlite_attempt_id") != current_attempt_id + or captured_record.get("head_sha") != head + or not isinstance(current_reviews, list) + or not isinstance(current_comments, dict) + or not isinstance(current_comments.get("comments"), list) + or not isinstance(current_comments.get("review_threads"), list) + ): + return {} + captured_triggers = [ + item + for item in current_comments["comments"] + if isinstance(item, dict) and immutable_database_id(item) == trigger_id + ] + captured_responses = [ + item + for item in current_comments["comments"] + if isinstance(item, dict) and immutable_database_id(item) == response_id + ] + try: + live_comments = payload["data"]["repository"]["pullRequest"]["comments"]["nodes"] + live_responses = [ + item + for item in live_comments + if isinstance(item, dict) and immutable_database_id(item) == response_id + ] + except (KeyError, TypeError): + return {} + if ( + len(captured_triggers) != 1 + or len(captured_responses) != 1 + or len(live_responses) != 1 + or len(current_reviews) != 0 + or parse_timestamp(captured_responses[0].get("createdAt")) != response_created_at + or parse_timestamp(captured_responses[0].get("updatedAt")) is None + or parse_timestamp(captured_responses[0].get("updatedAt")) < response_created_at + or not isinstance(captured_responses[0].get("body"), str) + or not _is_finished_action_response(captured_responses[0]["body"], allow_action_wrapper=True) + or captured_responses[0].get("body") != live_responses[0].get("body") + or captured_responses[0].get("updatedAt") != live_responses[0].get("updatedAt") + ): + return {} else: # A terminal ambiguous or failed capture cannot be retroactively # promoted by a later change in the public GitHub response. @@ -2359,6 +2442,8 @@ def finished_reply_without_findings( current_record_path: str | Path | None = None, repo: str | None = None, pr_number: int | None = None, + recovery_attempt_id: str | None = None, + records_reader: Any = None, ) -> bool: """Accept CodeRabbit's terminal full-review reply when its complete window is empty. @@ -2457,11 +2542,14 @@ def in_window(value: Any) -> bool | None: _archived_completed_thread_bodies( repo, pr_number, + payload, head, response_id, created, record, current_record_path, + recovery_attempt_id=recovery_attempt_id, + records_reader=records_reader, ) if isinstance(repo, str) and type(pr_number) is int and pr_number > 0 else {} @@ -2515,6 +2603,46 @@ def operational_trigger_state( return _trigger_state(repo, pr_number, payload, record, current_record_path, now=now, operational=True) +def recover_ambiguous_reply_state( + repo: str, + pr_number: int, + payload: dict[str, Any], + record: dict[str, Any], + *, + attempt_id: str, + response_id: int, + records_reader: Any, + current_record_path: str | Path | None = None, +) -> TriggerState: + """Verify one exact ambiguous reply for the explicit records-repair path. + + This does not change the stored attempt or the behavior of ordinary Hosted + readers. The named response must remain bound to the captured attempt; the + regular trigger classifier still evaluates its complete public window. + """ + + if ( + not isinstance(attempt_id, str) + or not attempt_id + or type(response_id) is not int + or response_id <= 0 + or not isinstance(record, dict) + or record.get("sqlite_attempt_id") != attempt_id + or type((record.get("trigger") or {}).get("id")) is not int + ): + raise ValueError("ambiguous reply recovery requires exact attempt, trigger, and response identities") + return _trigger_state( + repo, + pr_number, + payload, + record, + current_record_path, + recovery_attempt_id=attempt_id, + recovery_response_id=response_id, + records_reader=records_reader, + ) + + def _trigger_state( repo: str, pr_number: int, @@ -2524,6 +2652,9 @@ def _trigger_state( *, now: datetime | None = None, operational: bool = False, + recovery_attempt_id: str | None = None, + recovery_response_id: int | None = None, + records_reader: Any = None, ) -> TriggerState: pr = payload["data"]["repository"]["pullRequest"] current_head = pr.get("headRefOid", "") @@ -2747,6 +2878,10 @@ def _trigger_state( current_record_path, repo, pr_number, + recovery_attempt_id=( + recovery_attempt_id if immutable_database_id(item) == recovery_response_id else None + ), + records_reader=records_reader, ): state = ( "ambiguous_retired_predecessor" diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 4c7a9cea17..304ef6d21b 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -704,8 +704,9 @@ def review_stop_audit( """Refresh complete review evidence for a human-directed channel stop. Retained ambiguous responses remain explicitly non-counting. Each pin - must name one verified immutable terminal response; only those exact - response blockers are removed from the generic audit. + must name one verified immutable terminal response. An exact recovered + Hosted publication is attributable through its source audit instead of + being treated as an unretained ambiguity. """ required_anchor = ("child_head", "parent_identity", "parent_head", "merge_base", "patch_id") @@ -819,6 +820,16 @@ def review_stop_audit( channel_history = {channel: list(self.history(pr, channel, now=audit_now)) for channel in ("hosted", "cli")} ambiguous_terminal_responses: list[dict[str, Any]] = [] + verified_recovered_terminal_responses: list[tuple[dict[str, Any], dict[str, Any]]] = [] + public_comments = self._comments(payload) + public_checkpoints, unparsed_checkpoints = evidence.parse_checkpoint_comments(public_comments) + if unparsed_checkpoints: + raise ControllerError("GitHub history contains an unparsed review checkpoint") + checkpoints_by_response: dict[int, list[evidence.Checkpoint]] = {} + for checkpoint in public_checkpoints: + if checkpoint.type.casefold() == "hosted" and checkpoint.hosted_review_id is not None: + checkpoints_by_response.setdefault(checkpoint.hosted_review_id, []).append(checkpoint) + public_comments_by_id = {item["id"]: item for item in public_comments if type(item.get("id")) is int} terminal_rate_limits: list[dict[str, Any]] = [] for path in self._complete_trigger_paths(self.repo, pr): try: @@ -828,7 +839,36 @@ def review_stop_audit( raise ControllerError("a Hosted trigger record cannot be completely audited") from error observation = self._terminal_ambiguous_hosted_observation(pr, record, state, payload) if observation is not None: - ambiguous_terminal_responses.append(observation) + recovered_source = None + matching_checkpoints = checkpoints_by_response.get(observation["response_id"], ()) + if len(matching_checkpoints) == 1: + checkpoint = matching_checkpoints[0] + public_comment = public_comments_by_id.get(checkpoint.comment_id) + public_body = public_comment.get("body") if isinstance(public_comment, Mapping) else None + if isinstance(public_body, str): + recovered_source = self._recovered_hosted_publication(pr, checkpoint, public_body) + recovered_identity = ( + ( + str(recovered_source.get("attempt_id")), + str(recovered_source.get("trigger_id")), + str(recovered_source.get("response_id")), + str(recovered_source.get("head")), + ) + if isinstance(recovered_source, Mapping) + else None + ) + terminal_identity = ( + str(record.get("sqlite_attempt_id")), + str(observation["trigger_id"]), + str(observation["response_id"]), + str(observation["captured_head"]), + ) + if recovered_identity == terminal_identity: + verified_recovered_terminal_responses.append( + (observation, {**recovered_source, "checkpoint_id": matching_checkpoints[0].comment_id}) + ) + else: + ambiguous_terminal_responses.append(observation) cooldown_value = getattr(state, "cooldown_until", None) cooldown_until = hosted.parse_timestamp(cooldown_value) trigger_id = state.trigger_comment_id @@ -860,6 +900,32 @@ def review_stop_audit( "attributable": True, } ) + active_reservations = list(audit["active_reservations"]) + unmatched_responses = list(audit["unmatched_responses"]) + ambiguous_responses = list(audit["ambiguous_responses"]) + terminal_observation_count = len(ambiguous_terminal_responses) + len(verified_recovered_terminal_responses) + isolated_recovered_terminal_responses: list[dict[str, Any]] = [] + if verified_recovered_terminal_responses: + if ( + active_reservations.count("ambiguous") == terminal_observation_count + and ambiguous_responses.count("unattributed trigger response") == terminal_observation_count + ): + for _observation, recovered_source in verified_recovered_terminal_responses: + active_reservations.remove("ambiguous") + ambiguous_responses.remove("unattributed trigger response") + isolated_recovered_terminal_responses.append( + { + "attempt_id": recovered_source["attempt_id"], + "trigger_id": int(recovered_source["trigger_id"]), + "response_id": int(recovered_source["response_id"]), + "captured_head": recovered_source["head"], + "run_id": recovered_source["run_id"], + "checkpoint_id": recovered_source["checkpoint_id"], + "finished_at": recovered_source["run"]["finished_at"], + } + ) + else: + ambiguous_terminal_responses.extend(item for item, _source in verified_recovered_terminal_responses) fingerprints = [item["fingerprint"] for item in ambiguous_terminal_responses] if len(set(fingerprints)) != len(fingerprints): raise ControllerError("terminal ambiguous Hosted responses have duplicate immutable fingerprints") @@ -870,9 +936,6 @@ def review_stop_audit( raise ControllerError("retained Hosted ambiguity does not identify one current immutable response") retained_by_fingerprint[fingerprint] = matching[0] - active_reservations = list(audit["active_reservations"]) - unmatched_responses = list(audit["unmatched_responses"]) - ambiguous_responses = list(audit["ambiguous_responses"]) # A proven terminal response has ended execution; its provider reset or # bounded local retry backoff remains a repository admission hold. active_terminal_rate_limits = [ @@ -993,6 +1056,7 @@ def review_stop_audit( "checkpoints": checkpoints, "channel_histories": channel_history, "ambiguous_terminal_responses": ambiguous_terminal_responses, + "recovered_terminal_responses": isolated_recovered_terminal_responses, "terminal_rate_limits": terminal_rate_limits, "active_hosted_reservations": list(audit.get("active_hosted_reservations", ())), "active_cli_reviews": list(active_cli_reviews), @@ -2010,6 +2074,7 @@ def _current_hosted_history( payload: dict[str, Any], emitted_hosted_response_ids: set[int], *, + verified_recovered_responses: set[tuple[str, str, str, str]] | None = None, operational_only: bool = False, now: datetime | None = None, ) -> list[dict[str, Any]]: @@ -2080,6 +2145,20 @@ def _current_hosted_history( ): values.append(self._uncheckpointed_hosted_observation(pr, state)) elif state.state in {"active", "awaiting_response", "ambiguous", "unattributed", "timed_out"}: + recovered_identity = ( + str(record.get("sqlite_attempt_id")), + str(state.trigger_comment_id), + str(state.response_id), + state.head_sha, + ) + if ( + not operational_only + and state.state == "ambiguous" + and state.terminal is True + and isinstance(verified_recovered_responses, set) + and recovered_identity in verified_recovered_responses + ): + continue if ( operational_only and state.state == "ambiguous" @@ -2234,6 +2313,8 @@ def _source_resolution_status( channel: str, checkpoint: evidence.Checkpoint, source_head: str, + *, + recovered_run_id: str | None = None, ) -> str | None: """Bind structured checkpoints to durable proof; leave legacy ones unbound.""" @@ -2249,6 +2330,22 @@ def _source_resolution_status( return None if self.records is None: return None + if recovered_run_id is not None: + try: + return self.records.source_resolution_status( + recovered_run_id, + source_pr=pr, + source_channel=channel, + source_head=source_head, + accepted_count=checkpoint.accepted, + classify_pending=True, + ) + except RecordsNotBootstrapped: + return None + except github.HostedPreflightDeadlineExceeded: + raise + except (ReviewRecordsError, OSError): + return "unavailable" if pr not in self._records_histories: try: self._records_histories[pr] = self.records.history(pr, include_display=False) @@ -2365,6 +2462,131 @@ def _source_resolution_status( except (ReviewRecordsError, OSError): return "unavailable" + def _recovered_hosted_publication( + self, + pr: int, + checkpoint: evidence.Checkpoint, + public_body: str, + ) -> dict[str, Any] | bool | None: + """Bind a public Hosted checkpoint to the exact recovered source run. + + ``False`` means a matching unresolved ambiguous response exists but its + durable recovery/publication association is absent or conflicting, so + ordinary Hosted attribution must not take over. + """ + + if self.records is None or type(checkpoint.hosted_review_id) is not int: + return None + try: + history = self._records_histories.get(pr) + if history is None: + history = self.records.history(pr, include_display=False) + self._records_histories[pr] = history + except RecordsNotBootstrapped: + return None + except (ReviewRecordsError, OSError): + return False + attempts = history.get("attempts") if isinstance(history, Mapping) else None + if not isinstance(attempts, list): + return None + candidates = [ + item + for item in attempts + if isinstance(item, Mapping) + and item.get("channel") == "hosted" + and item.get("state") == "ambiguous" + and item.get("run_id") is None + and item.get("provider_review_id") == str(checkpoint.hosted_review_id) + ] + if not candidates: + return None + if len(candidates) != 1: + return False + original = candidates[0] + attempt_id = original.get("attempt_id") + head = original.get("candidate_sha") + trigger_id = original.get("trigger_id") + if ( + not isinstance(attempt_id, str) + or not isinstance(head, str) + or not isinstance(trigger_id, str) + or not trigger_id.isdecimal() + or checkpoint.reviewed_sha is None + or not head.casefold().startswith(checkpoint.reviewed_sha.casefold()) + ): + return False + run_id = "hosted-reply-" + hashlib.sha256( + f"{self.repo.casefold()}\0{pr}\0{attempt_id}\0{checkpoint.hosted_review_id}".encode() + ).hexdigest()[:48] + try: + attempt = self.records.attempt(attempt_id) + metadata = attempt.get("metadata") + state = self.records.checkpoint_publication_state(run_id) + except (ReviewRecordsError, OSError, ValueError, TypeError): + return False + intent = state.get("intent") + if ( + attempt.get("state") != "ambiguous" + or attempt.get("run_id") is not None + or attempt.get("source_pr") != pr + or attempt.get("candidate_sha") != head + or not isinstance(metadata, Mapping) + or not isinstance(metadata.get("repository"), str) + or metadata["repository"].casefold() != self.repo.casefold() + or not isinstance(intent, Mapping) + or intent.get("repository") != self.repo + or intent.get("source_pr") != pr + or intent.get("run_id") != run_id + or not isinstance(intent.get("actor_login"), str) + or not isinstance(public_body, str) + or not isinstance(checkpoint.author_login, str) + or intent["actor_login"].casefold() != checkpoint.author_login.casefold() + ): + return False + try: + from .checkpoint_publication import _same_checkpoint + + comment = { + "id": checkpoint.comment_id, + "body": public_body, + "created_at": checkpoint.created_at, + "issue_url": f"https://api.github.com/repos/{self.repo}/issues/{pr}", + "user": {"id": intent.get("actor_id"), "login": checkpoint.author_login}, + } + if not _same_checkpoint(comment, intent["body"], repo=self.repo, source_pr=pr): + return False + except (KeyError, TypeError, ValueError, evidence.EvidenceError): + return False + bindings = [ + event + for event in state.get("events", []) + if isinstance(event, Mapping) + and event.get("type") in {"post_outcome", "reused"} + and type(event.get("comment_id")) is int + ] + if ( + any(event["comment_id"] != checkpoint.comment_id for event in bindings) + or not any( + event["comment_id"] == checkpoint.comment_id + and (event.get("type") == "reused" or event.get("outcome") == "published") + for event in bindings + ) + ): + return False + runs = [item for item in history.get("runs", []) if item.get("run_id") == run_id] + if len(runs) != 1 or runs[0].get("source_head") != head or runs[0].get("finished_at") is None: + return False + return { + "run_id": run_id, + "run": runs[0], + "attempt": attempt, + "attempt_id": attempt_id, + "trigger_id": trigger_id, + "response_id": checkpoint.hosted_review_id, + "head": head, + "metadata": metadata, + } + def review_activity_identities(self, pr: int, channel: str) -> Mapping[str, Mapping[str, str]]: """Return cached display aliases without changing policy observations or fetching evidence.""" @@ -2408,6 +2630,7 @@ def history(self, pr: int, channel: str, *, now: datetime | None = None) -> Sequ emitted_cli_sources: set[tuple[str, str]] = set() emitted_hosted_review_ids: set[int] = set() emitted_hosted_response_ids: set[int] = set() + verified_recovered_responses: set[tuple[str, str, str, str]] = set() cli_common: Path | None = None cli_records: Any = None cli_context_error: evidence.EvidenceError | None = None @@ -2429,6 +2652,7 @@ def history(self, pr: int, channel: str, *, now: datetime | None = None) -> Sequ attributable = False provisional = False anchor: dict[str, Any] = {} + recovered_source = None if channel == "cli": if cli_context_error is None: try: @@ -2448,22 +2672,59 @@ def history(self, pr: int, channel: str, *, now: datetime | None = None) -> Sequ provisional = capture.metadata.get("provisional", "false").casefold() == "true" anchor = self._anchor(capture.metadata) else: - matched = self._hosted_trigger_for_checkpoint(pr, head, checkpoint, reviews, payload) - if matched is None: + public_body = next( + (item["body"] for item in comments if item.get("id") == checkpoint.comment_id), + "", + ) + recovered_source = self._recovered_hosted_publication(pr, checkpoint, public_body) + if recovered_source is False: continue - record, proof = matched + if isinstance(recovered_source, Mapping): + source_run = recovered_source["run"] + original_metadata = recovered_source["metadata"] + verified_recovered_responses.add( + ( + str(recovered_source["attempt_id"]), + str(recovered_source["trigger_id"]), + str(recovered_source["response_id"]), + str(recovered_source["head"]), + ) + ) + anchor = dict(original_metadata["anchor"]) + proof = { + "review_id": checkpoint.hosted_review_id, + "commit_id": source_run["source_head"], + "verified_completed_at": source_run["finished_at"], + } + completed = attributable = True + exact_head = source_run["source_head"] + else: + matched = self._hosted_trigger_for_checkpoint(pr, head, checkpoint, reviews, payload) + if matched is None: + continue + record, proof = matched + anchor = dict(record["anchor"]) + completed = attributable = True + exact_head = str(proof["commit_id"]) if checkpoint.hosted_review_id is not None and not checkpoint.correction: if checkpoint.hosted_review_id in emitted_hosted_review_ids: continue emitted_hosted_review_ids.add(checkpoint.hosted_review_id) if state_response_id := proof.get("review_id"): emitted_hosted_response_ids.add(state_response_id) - completed = attributable = True - exact_head = str(proof["commit_id"]) - anchor = dict(record["anchor"]) source_resolution_status = ( - self._source_resolution_status(pr, channel, checkpoint, exact_head) - if (checkpoint.accepted > 0 or (channel == "cli" and completed)) and not checkpoint.correction + self._source_resolution_status( + pr, + channel, + checkpoint, + exact_head, + recovered_run_id=(recovered_source["run_id"] if isinstance(recovered_source, Mapping) else None), + ) + if ( + checkpoint.accepted > 0 + or (channel == "cli" and completed) + or isinstance(recovered_source, Mapping) + ) and not checkpoint.correction else None ) if ( @@ -2493,6 +2754,8 @@ def history(self, pr: int, channel: str, *, now: datetime | None = None) -> Sequ "source_run_id": ( checkpoint.run_id if channel == "cli" + else recovered_source["run_id"] + if channel == "hosted" and isinstance(recovered_source, Mapping) else f"hosted-review:{checkpoint.hosted_review_id}" if checkpoint.hosted_review_id is not None else f"hosted-review:{proof.get('review_id')}" @@ -2526,6 +2789,8 @@ def history(self, pr: int, channel: str, *, now: datetime | None = None) -> Sequ display_identity["run_id"] = checkpoint.run_id if channel == "hosted" and checkpoint.hosted_review_id is not None: display_identity["provider_review_id"] = str(checkpoint.hosted_review_id) + if channel == "hosted" and isinstance(recovered_source, Mapping): + display_identity["run_id"] = recovered_source["run_id"] display_identities[value["checkpoint"]] = display_identity values.append(value) if channel == "cli" and cli_context_error is None: @@ -2571,7 +2836,16 @@ def history(self, pr: int, channel: str, *, now: datetime | None = None) -> Sequ } ) if channel == "hosted": - values.extend(self._current_hosted_history(pr, head, payload, emitted_hosted_response_ids, now=now)) + values.extend( + self._current_hosted_history( + pr, + head, + payload, + emitted_hosted_response_ids, + verified_recovered_responses=verified_recovered_responses, + now=now, + ) + ) parsed_scope_changes = { (item.comment_id, item.created_at, item.description, item.updated_at) for item in scope_changes } diff --git a/dev-tools/pr_review/sqlite_records_repair.py b/dev-tools/pr_review/sqlite_records_repair.py index 5c790681b3..10c2649a13 100644 --- a/dev-tools/pr_review/sqlite_records_repair.py +++ b/dev-tools/pr_review/sqlite_records_repair.py @@ -26,7 +26,7 @@ from pathlib import Path from typing import Any -from . import evidence, github, sqlite_hosted_capture, sqlite_provider_imports, sqlite_review_records +from . import evidence, github, hosted, sqlite_hosted_capture, sqlite_provider_imports, sqlite_review_records from .sqlite_review_records import ReviewRecordsError, SqliteReviewRecords _API_VERSION = 1 @@ -111,9 +111,7 @@ def _validate_request( prior = by_comment.get(comment_id) if prior is not None: if prior[0] != fingerprint: - raise SqliteRecordsRepairError( - f"public checkpoint comment {comment_id} has conflicting parsed content" - ) + raise SqliteRecordsRepairError(f"public checkpoint comment {comment_id} has conflicting parsed content") continue by_comment[comment_id] = (fingerprint, checkpoint) @@ -122,13 +120,9 @@ def _validate_request( def _require_origin_link_api(records: SqliteReviewRecords) -> None: if not callable(getattr(records, "link_provider_origin", None)): - raise SqliteRecordsRepairError( - "provider origin-link API is unavailable; no repair was written" - ) + raise SqliteRecordsRepairError("provider origin-link API is unavailable; no repair was written") if not callable(getattr(records, "archive_imported_artifacts", None)): - raise SqliteRecordsRepairError( - "historical artifact API is unavailable; no repair was written" - ) + raise SqliteRecordsRepairError("historical artifact API is unavailable; no repair was written") def _clone_records(records: SqliteReviewRecords, destination: Path) -> SqliteReviewRecords: @@ -207,7 +201,8 @@ def import_checkpoint(target: SqliteReviewRecords) -> dict[str, Any]: try: matching_attempts = [ - item for item in records.attempt_history(pr_number) + item + for item in records.attempt_history(pr_number) if item["channel"] == ("hosted" if checkpoint.type == "Hosted" else "cli") and ( item["attempt_id"] == checkpoint.run_id @@ -253,12 +248,12 @@ def import_checkpoint(target: SqliteReviewRecords) -> dict[str, Any]: raise SqliteRecordsRepairError( "matching provider attempt is not linked to its exact completed source run" ) - if attempt["checkpoint_id"] is not None and checkpoint.comment_id is not None and ( - attempt["checkpoint_id"] != str(checkpoint.comment_id) + if ( + attempt["checkpoint_id"] is not None + and checkpoint.comment_id is not None + and (attempt["checkpoint_id"] != str(checkpoint.comment_id)) ): - raise SqliteRecordsRepairError( - "matching provider attempt names a different public checkpoint" - ) + raise SqliteRecordsRepairError("matching provider attempt names a different public checkpoint") if checkpoint.type == "Hosted" and not any( path.exists() or path.is_symlink() @@ -323,6 +318,7 @@ def import_checkpoint(target: SqliteReviewRecords) -> dict[str, Any]: ) if expected_run is None or stored_run is None: raise SqliteRecordsRepairError("matching attempt has no verifiable completed source run") + def observation_projection( history: Mapping[str, Any], run_id: str, *, original: bool = False ) -> dict[str, tuple[Any, ...]]: @@ -340,9 +336,11 @@ def observation_projection( original_decisions[item["finding_id"]]["target_pr"] if original and item["finding_id"] in original_decisions else routes.get(item["route_id"], {}).get("target_pr") - if item["route_id"] is not None else None, + if item["route_id"] is not None + else None, ) - for item in history["findings"] if item["run_id"] == run_id + for item in history["findings"] + if item["run_id"] == run_id } def decision_projection( @@ -350,28 +348,29 @@ def decision_projection( ) -> dict[str, tuple[Any, ...]]: keys = { item["finding_id"]: item["source_finding_key"] - for item in history["findings"] if item["run_id"] == run_id + for item in history["findings"] + if item["run_id"] == run_id } result = { keys[item["finding_id"]]: (item["decision"], item["target_pr"], item["reason"]) for item in history["decisions"] - if item["run_id"] == run_id and item["scope"] == "source" - and item["finding_id"] in keys + if item["run_id"] == run_id and item["scope"] == "source" and item["finding_id"] in keys } if corrected: for correction in history["corrections"]: if correction["run_id"] == run_id and correction["finding_id"] in keys: result[keys[correction["finding_id"]]] = ( - correction["decision"], correction["target_pr"], correction["reason"] + correction["decision"], + correction["target_pr"], + correction["reason"], ) return result - def decision_target_projection( - history: Mapping[str, Any], run_id: str - ) -> dict[str, tuple[Any, ...]]: + def decision_target_projection(history: Mapping[str, Any], run_id: str) -> dict[str, tuple[Any, ...]]: keys = { item["finding_id"]: item["source_finding_key"] - for item in history["findings"] if item["run_id"] == run_id + for item in history["findings"] + if item["run_id"] == run_id } routes = {item["route_id"]: item for item in history["routes"]} result: dict[str, tuple[Any, ...]] = {} @@ -392,15 +391,9 @@ def decision_target_projection( return result expected_observations = observation_projection(probe_history, imported["run_id"]) - expected_decisions = decision_projection( - probe_history, imported["run_id"], corrected=False - ) - original_observations = observation_projection( - stored_history, attempt["run_id"], original=True - ) - original_decisions = decision_projection( - stored_history, attempt["run_id"], corrected=False - ) + expected_decisions = decision_projection(probe_history, imported["run_id"], corrected=False) + original_observations = observation_projection(stored_history, attempt["run_id"], original=True) + original_decisions = decision_projection(stored_history, attempt["run_id"], corrected=False) current_observations = observation_projection(stored_history, attempt["run_id"]) current_decisions = decision_projection(stored_history, attempt["run_id"]) stored_decision_targets = decision_target_projection(stored_history, attempt["run_id"]) @@ -422,18 +415,10 @@ def decision_target_projection( "matching provider attempt conflicts with captured run identity or counts" ) if ( - { - key: value[0] for key, value in original_observations.items() - } - != { - key: value[0] for key, value in expected_observations.items() - } - or { - key: (value[0], value[2]) for key, value in original_decisions.items() - } - != { - key: (value[0], value[2]) for key, value in expected_decisions.items() - } + {key: value[0] for key, value in original_observations.items()} + != {key: value[0] for key, value in expected_observations.items()} + or {key: (value[0], value[2]) for key, value in original_decisions.items()} + != {key: (value[0], value[2]) for key, value in expected_decisions.items()} or set(current_observations) != set(current_decisions) or any( current_observations[key][0] != current_decisions[key][0] @@ -555,9 +540,7 @@ def _retained_hosted_attempt_import( ): raise SqliteRecordsRepairError("retained Hosted evidence conflicts with its immutable attempt identity") - matching_reviews = [ - review for review in reviews if github.immutable_database_id(review) == review_id - ] + matching_reviews = [review for review in reviews if github.immutable_database_id(review) == review_id] if len(matching_reviews) != 1: raise SqliteRecordsRepairError("retained Hosted evidence has no unique exact provider review") review = matching_reviews[0] @@ -607,8 +590,7 @@ def _retained_hosted_attempt_import( if has_sections: for kind, count in (("outside_diff", outside_diff), ("duplicate", duplicate)): archived_finding_keys.update( - f"hosted-summary:review:{review_id}:{kind}:{ordinal}" - for ordinal in range(1, count + 1) + f"hosted-summary:review:{review_id}:{kind}:{ordinal}" for ordinal in range(1, count + 1) ) history = records.history(pr_number) @@ -650,7 +632,8 @@ def _retained_hosted_attempt_import( if ( checkpoint.raw_found != observed_counts["found"] or checkpoint.accepted != observed_counts["accepted"] - or checkpoint.routed is not None and checkpoint.routed != observed_counts["routed"] + or checkpoint.routed is not None + and checkpoint.routed != observed_counts["routed"] ): raise SqliteRecordsRepairError("Hosted checkpoint counts do not match retained source findings and decisions") @@ -719,7 +702,14 @@ def _existing_hosted_checkpoint_archive( if rows: raise SqliteRecordsRepairError("retained Hosted archive exists without its exact checkpoint origin") return None, False - expected_origin = (repo.casefold(), pr_number, "hosted", f"review:{review_id}", checkpoint.comment_id, fingerprint) + expected_origin = ( + repo.casefold(), + pr_number, + "hosted", + f"review:{review_id}", + checkpoint.comment_id, + fingerprint, + ) if origin != expected_origin: raise SqliteRecordsRepairError("retained Hosted archive is linked to a different checkpoint identity") if not rows: @@ -733,7 +723,9 @@ def _existing_hosted_checkpoint_archive( archived: dict[str, str] = {} for kind, content, source_sha256, redactions in rows: try: - sanitized, stored_digest, detected_redactions = sqlite_review_records._archive_artifact(kind, content) + sanitized, stored_digest, detected_redactions = sqlite_review_records._archive_artifact( + kind, content + ) except ReviewRecordsError as exc: raise SqliteRecordsRepairError(f"linked Hosted archive artifact {kind} is invalid") from exc if ( @@ -746,7 +738,9 @@ def _existing_hosted_checkpoint_archive( or redactions < 0 or (redactions == 0 and source_sha256 != stored_digest) ): - raise SqliteRecordsRepairError(f"linked Hosted archive artifact {kind} has invalid sanitized content or receipt") + raise SqliteRecordsRepairError( + f"linked Hosted archive artifact {kind} has invalid sanitized content or receipt" + ) archived[kind] = content except (sqlite3.DatabaseError, ReviewRecordsError, OSError) as exc: raise SqliteRecordsRepairError(f"cannot validate existing Hosted archive: {exc}") from exc @@ -1045,8 +1039,7 @@ def repair_provider_checkpoints( } actual_artifact_kinds = sorted(artifacts) actual_artifact_sha256 = { - kind: hashlib.sha256(content.encode("utf-8")).hexdigest() - for kind, content in sorted(artifacts.items()) + kind: hashlib.sha256(content.encode("utf-8")).hexdigest() for kind, content in sorted(artifacts.items()) } item = { **expected, @@ -1122,6 +1115,783 @@ def repair_provider_checkpoints( } +def _ambiguous_reply_proof( + records: SqliteReviewRecords, + *, + repo: str, + pr_number: int, + attempt_id: str, + response_id: int, + hosted_payload: dict[str, Any], +) -> dict[str, Any]: + """Validate one exact stored ambiguous reply against complete public history.""" + + if not isinstance(repo, str) or not _REPOSITORY.fullmatch(repo): + raise SqliteRecordsRepairError("repository must be an exact owner/name pair") + if not isinstance(attempt_id, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,99}", attempt_id): + raise SqliteRecordsRepairError("ambiguous reply recovery requires one exact attempt ID") + if type(response_id) is not int or response_id <= 0: + raise SqliteRecordsRepairError("ambiguous reply recovery requires one exact response ID") + try: + pull = sqlite_hosted_capture._complete_pull_request(hosted_payload, pr_number) + except (sqlite_hosted_capture.HostedCaptureError, KeyError, TypeError, ValueError) as exc: + raise SqliteRecordsRepairError(f"complete Hosted history is unavailable: {exc}") from exc + + attempt_matches = [ + item + for item in records.attempt_history(pr_number) + if item.get("attempt_id") == attempt_id and item.get("channel") == "hosted" + ] + if len(attempt_matches) != 1: + raise SqliteRecordsRepairError("exact Hosted attempt is missing or duplicated") + attempt = records.attempt(attempt_id) + history_attempt = attempt_matches[0] + metadata = attempt.get("metadata") + stored_response_id = history_attempt.get("provider_review_id") + trigger_id_text = history_attempt.get("trigger_id") + candidate_sha = attempt.get("candidate_sha") + if ( + attempt.get("source_pr") != pr_number + or attempt.get("state") != "ambiguous" + or attempt.get("run_id") is not None + or history_attempt.get("state") != "ambiguous" + or history_attempt.get("run_id") is not None + or stored_response_id != str(response_id) + or not isinstance(trigger_id_text, str) + or not trigger_id_text.isdecimal() + or not isinstance(candidate_sha, str) + or hosted.EXACT_SHA.fullmatch(candidate_sha) is None + or not isinstance(metadata, dict) + or metadata.get("request_kind") != "full" + or not isinstance(metadata.get("repository"), str) + or metadata["repository"].casefold() != repo.casefold() + ): + raise SqliteRecordsRepairError("stored attempt is not the exact unresolved Hosted response") + anchor = metadata.get("anchor") + if ( + not isinstance(anchor, dict) + or anchor.get("pr") != pr_number + or anchor.get("child_head") != candidate_sha + or not isinstance(anchor.get("parent_identity"), str) + or not anchor["parent_identity"] + or not isinstance(anchor.get("parent_head"), str) + or hosted.EXACT_SHA.fullmatch(anchor["parent_head"]) is None + or not isinstance(anchor.get("merge_base"), str) + or hosted.EXACT_SHA.fullmatch(anchor["merge_base"]) is None + or not isinstance(anchor.get("patch_id"), str) + or re.fullmatch(r"[0-9a-f]{64}", anchor["patch_id"]) is None + or metadata.get("actual_base_ref") != anchor["parent_identity"] + or metadata.get("actual_base_sha") != anchor["parent_head"] + ): + raise SqliteRecordsRepairError("stored attempt lacks its complete immutable candidate anchor") + + artifacts = records.attempt_artifacts(attempt_id) + if set(artifacts) != {"hosted_comments", "hosted_review", "metadata"}: + raise SqliteRecordsRepairError("ambiguous Hosted attempt lacks its complete original capture") + try: + archived_comments = json.loads(artifacts["hosted_comments"]) + archived_reviews = json.loads(artifacts["hosted_review"]) + capture = json.loads(artifacts["metadata"]) + except (TypeError, ValueError, json.JSONDecodeError) as exc: + raise SqliteRecordsRepairError("ambiguous Hosted attempt capture is malformed") from exc + record = capture.get("trigger_record") if isinstance(capture, dict) else None + if ( + not isinstance(capture, dict) + or capture.get("state") != "ambiguous" + or capture.get("terminal") is not True + or capture.get("attributable") is not False + or not isinstance(capture.get("repository"), str) + or capture["repository"].casefold() != repo.casefold() + or capture.get("pull_request") != pr_number + or capture.get("head_sha") != candidate_sha + or capture.get("trigger_id") != int(trigger_id_text) + or capture.get("response_id") != response_id + or not isinstance(record, dict) + or record.get("sqlite_attempt_id") != attempt_id + or not isinstance(record.get("repository"), str) + or record["repository"].casefold() != repo.casefold() + or record.get("pr_number") != pr_number + or record.get("head_sha") != candidate_sha + or record.get("anchor") != anchor + or not isinstance(archived_comments, dict) + or not isinstance(archived_comments.get("comments"), list) + or not isinstance(archived_comments.get("review_threads"), list) + or not isinstance(archived_reviews, list) + or archived_reviews + ): + raise SqliteRecordsRepairError("original Hosted capture conflicts with the immutable attempt") + try: + record = sqlite_hosted_capture._validate_trigger_record(record["repository"], pr_number, record) + except sqlite_hosted_capture.HostedCaptureError as exc: + raise SqliteRecordsRepairError(f"stored Hosted trigger identity is invalid: {exc}") from exc + trigger_id = int(trigger_id_text) + if record["trigger"].get("id") != trigger_id: + raise SqliteRecordsRepairError("stored Hosted trigger differs from the ambiguous attempt") + + comments = pull["comments"]["nodes"] + public_triggers = [item for item in comments if github.immutable_database_id(item) == trigger_id] + public_responses = [item for item in comments if github.immutable_database_id(item) == response_id] + captured_triggers = [ + item + for item in archived_comments["comments"] + if isinstance(item, dict) and github.immutable_database_id(item) == trigger_id + ] + captured_responses = [ + item + for item in archived_comments["comments"] + if isinstance(item, dict) and github.immutable_database_id(item) == response_id + ] + if ( + len(public_triggers) != 1 + or len(public_responses) != 1 + or len(captured_triggers) != 1 + or len(captured_responses) != 1 + ): + raise SqliteRecordsRepairError("trigger or reply is missing or duplicated in retained/public history") + public_trigger, captured_trigger = public_triggers[0], captured_triggers[0] + public_response, captured_response = public_responses[0], captured_responses[0] + if ( + public_trigger.get("body") != captured_trigger.get("body") + or public_trigger.get("createdAt") != captured_trigger.get("createdAt") + or public_trigger.get("url") != captured_trigger.get("url") + or (public_trigger.get("author") or {}).get("login", "").casefold() + != (captured_trigger.get("author") or {}).get("login", "").casefold() + or public_response.get("body") != captured_response.get("body") + or public_response.get("createdAt") != captured_response.get("createdAt") + or public_response.get("updatedAt") != captured_response.get("updatedAt") + or not github.is_coderabbit_login((public_response.get("author") or {}).get("login")) + ): + raise SqliteRecordsRepairError("public trigger/reply changed from the immutable terminal capture") + + attempt_observed_at = hosted.parse_timestamp(history_attempt.get("finished_at")) + capture_observed_at = hosted.parse_timestamp(capture.get("observed_at")) + response_created_at = hosted.parse_timestamp(captured_response.get("createdAt")) + response_updated_at = hosted.parse_timestamp(captured_response.get("updatedAt")) + if ( + attempt_observed_at is None + or capture_observed_at != attempt_observed_at + or response_created_at is None + or response_updated_at is None + or response_created_at > attempt_observed_at + or response_updated_at < response_created_at + ): + raise SqliteRecordsRepairError("retained Hosted response timestamps conflict with the original observation") + + try: + state = hosted.recover_ambiguous_reply_state( + repo, + pr_number, + hosted_payload, + record, + attempt_id=attempt_id, + response_id=response_id, + records_reader=records, + current_record_path=hosted.default_trigger_record_path(repo, pr_number, records.path.parent.parent), + ) + except (KeyError, TypeError, ValueError) as exc: + raise SqliteRecordsRepairError(f"Hosted reply recovery proof is unavailable: {exc}") from exc + if ( + state.state != "completed" + or state.terminal is not True + or state.attributed is not True + or state.trigger_comment_id != trigger_id + or state.response_id != response_id + or state.head_sha != candidate_sha + or not isinstance(state.duration_seconds, int) + or state.duration_seconds < 0 + ): + raise SqliteRecordsRepairError("exact Hosted response does not prove one complete zero-result window") + finished_at = captured_response.get("updatedAt") + started_at = record["trigger"].get("created_at") + if hosted.parse_timestamp(finished_at) is None or hosted.parse_timestamp(started_at) is None: + raise SqliteRecordsRepairError("Hosted response or trigger has no valid immutable completion time") + reviewed_file_count = metadata.get("reviewed_file_count") + if type(reviewed_file_count) is not int or reviewed_file_count <= 0: + raise SqliteRecordsRepairError("ambiguous Hosted attempt lacks its captured reviewed file count") + + window = sqlite_hosted_capture.archive_window( + pull, + record, + finished_at=finished_at, + response_id=response_id, + ) + # The successful proof permits an old finding thread only when its + # immutable creation predates this trigger and its exact addressed footer + # edit falls inside this trigger's response window. Retain that proof thread. + trigger_at = hosted.parse_timestamp(started_at) + finished_dt = hosted.parse_timestamp(finished_at) + assert trigger_at is not None and finished_dt is not None + captured_thread_ids = {thread.get("id") for thread in window["review_threads"] if isinstance(thread, dict)} + for thread in pull["reviewThreads"]["nodes"]: + nodes = thread.get("comments", {}).get("nodes", []) + has_in_window_edit = any( + github.is_coderabbit_login((item.get("author") or {}).get("login")) + and (created := hosted.parse_timestamp(item.get("createdAt"))) is not None + and created <= trigger_at + and (updated := hosted.parse_timestamp(item.get("updatedAt"))) is not None + and trigger_at < updated <= finished_dt + for item in nodes + ) + if has_in_window_edit and thread.get("id") not in captured_thread_ids: + window["review_threads"].append(thread) + captured_thread_ids.add(thread.get("id")) + + proof = { + "attempt_id": attempt_id, + "trigger_id": trigger_id, + "response_id": response_id, + "candidate_sha": candidate_sha, + "anchor": anchor, + "response_created_at": public_response.get("createdAt"), + "response_updated_at": finished_at, + "duration_seconds": state.duration_seconds, + "counts": {"found": 0, "accepted": 0, "routed": 0}, + "classifier": "hosted finished-reply complete-window proof", + } + checkpoint = evidence.Checkpoint( + comment_id=response_id, + created_at=public_response["createdAt"], + type="Hosted", + raw_found=0, + accepted=0, + reviewed_sha=candidate_sha, + file_count=reviewed_file_count, + correction=False, + updated_at=finished_at, + run_id=None, + hosted_review_id=response_id, + duration_seconds=state.duration_seconds, + duration_invalid=False, + author_login=(public_response.get("author") or {}).get("login"), + routed=0, + ) + checkpoint_fingerprint = sqlite_provider_imports._checkpoint_fingerprint(checkpoint) + capture_metadata = { + "capture_format": "firemud-hosted-ambiguous-reply-recovery/v1", + "repository": repo.casefold(), + "pull_request": pr_number, + "checkpoint": checkpoint.as_json(), + "checkpoint_fields": dataclasses.asdict(checkpoint), + "checkpoint_fingerprint": checkpoint_fingerprint, + "attempt_id": attempt_id, + "head_sha": candidate_sha, + "anchor": anchor, + "trigger_id": trigger_id, + "trigger_record": record, + "response_id": response_id, + "state": "completed", + "terminal": True, + "attributable": True, + "observed_at": finished_at, + "trigger_state": state.as_dict(), + "zero_reply_proof": proof, + } + archive_artifacts = { + "hosted_review": _artifact_text(window["reviews"]), + "hosted_comments": _artifact_text({"comments": window["comments"], "review_threads": window["review_threads"]}), + "metadata": _artifact_text(capture_metadata), + } + try: + sqlite_provider_imports._validate_archive_artifacts(archive_artifacts) + except sqlite_provider_imports.ProviderImportError as exc: + raise SqliteRecordsRepairError(str(exc)) from exc + fingerprint = checkpoint_fingerprint + run_id = ( + "hosted-reply-" + + hashlib.sha256(f"{repo.casefold()}\0{pr_number}\0{attempt_id}\0{response_id}".encode()).hexdigest()[:48] + ) + return { + "attempt": attempt, + "attempt_artifacts": artifacts, + "record": record, + "state": state, + "run_id": run_id, + "provider_id": f"trigger:{trigger_id}", + "checkpoint_id": response_id, + "checkpoint_fingerprint": fingerprint, + "started_at": started_at, + "finished_at": finished_at, + "reviewer": (public_response.get("author") or {}).get("login"), + "artifacts": archive_artifacts, + } + + +def _verify_ambiguous_reply_import( + records: SqliteReviewRecords, + *, + repo: str, + pr_number: int, + proof: Mapping[str, Any], +) -> dict[str, Any]: + history = records.history(pr_number) + run_id = proof["run_id"] + trigger_id = int(proof["provider_id"].split(":", 1)[1]) + runs = [item for item in history["runs"] if item.get("run_id") == run_id] + origins = [ + item + for item in history["provider_origins"] + if item.get("repository") == repo.casefold() + and item.get("source_pr") == pr_number + and item.get("channel") == "hosted" + and item.get("provider_id") == proof["provider_id"] + ] + artifacts = [item for item in history["imported_artifacts"] if item.get("run_id") == run_id] + expected_artifacts = { + kind: sqlite_review_records._archive_artifact(kind, content)[1:] for kind, content in proof["artifacts"].items() + } + actual_artifacts = {item["kind"]: (item["source_sha256"], item["redactions"]) for item in artifacts} + attempts = [item for item in history["attempts"] if item.get("attempt_id") == proof["attempt"]["attempt_id"]] + if len(attempts) != 1 or attempts[0].get("state") != "ambiguous" or attempts[0].get("run_id") is not None: + raise SqliteRecordsRepairError("original ambiguous attempt changed during reply recovery") + if proof["attempt_artifacts"] != records.attempt_artifacts(proof["attempt"]["attempt_id"]): + raise SqliteRecordsRepairError("original ambiguous capture changed during reply recovery") + if len(runs) != 1: + raise SqliteRecordsRepairError("recovered Hosted source run is missing or duplicated") + run = runs[0] + if ( + run.get("source_pr") != pr_number + or run.get("channel") != "hosted" + or run.get("outcome") != "completed" + or run.get("attributable") is not True + or run.get("finalized") is not True + or run.get("source_head") != proof["attempt"]["candidate_sha"] + or run.get("started_at") != proof["started_at"] + or run.get("finished_at") != proof["finished_at"] + or run.get("counts") != {"found": 0, "accepted": 0, "routed": 0} + ): + raise SqliteRecordsRepairError("recovered source run does not reproduce the exact zero-result identity") + if ( + len(origins) != 1 + or origins[0].get("run_id") != run_id + or origins[0].get("checkpoint_id") != proof["checkpoint_id"] + or origins[0].get("checkpoint_fingerprint") != proof["checkpoint_fingerprint"] + or actual_artifacts != expected_artifacts + or set(actual_artifacts) != set(proof["artifacts"]) + ): + raise SqliteRecordsRepairError("recovered reply origin or archived artifacts do not match proof") + linked = sqlite_hosted_capture._linked_ambiguous_reply_recovery( + history, + repo, + pr_number, + attempts[0], + str(trigger_id), + ) + if linked is None or linked.get("run_id") != run_id or linked.get("counts") != run["counts"]: + raise SqliteRecordsRepairError("recovered reply is not visible through the canonical sync reader") + return {"run": run, "origin": origins[0], "artifacts": sorted(actual_artifacts)} + + +def verify_ambiguous_reply_import_for_publication( + records: SqliteReviewRecords, + *, + repo: str, + pr_number: int, + run_id: str, +) -> dict[str, Any]: + """Re-prove the exact stored zero-reply import without provider reads. + + Publication may use only the deterministic import made by + ``repair_ambiguous_hosted_reply``. This checks its original unresolved + attempt, archived recovery proof, imported artifacts and immutable provider + origin every time publication state is read or changed. + """ + + if not isinstance(records, SqliteReviewRecords): + raise SqliteRecordsRepairError("reply publication requires a SqliteReviewRecords store") + if not isinstance(repo, str) or not _REPOSITORY.fullmatch(repo): + raise SqliteRecordsRepairError("reply publication requires an exact repository") + if type(pr_number) is not int or pr_number <= 0: + raise SqliteRecordsRepairError("reply publication requires an exact source PR") + history = records.history(pr_number) + runs = [item for item in history["runs"] if item.get("run_id") == run_id] + if len(runs) != 1: + raise SqliteRecordsRepairError("recovered Hosted source run is missing or duplicated") + run = runs[0] + if run.get("channel") != "hosted" or run.get("source_pr") != pr_number: + raise SqliteRecordsRepairError("source run is not a recovered Hosted reply") + + imported = records.imported_run_artifacts(run_id) + if set(imported) != {"hosted_comments", "hosted_review", "metadata"}: + raise SqliteRecordsRepairError("recovered Hosted reply archive is incomplete") + contents: dict[str, str] = {} + for kind, item in imported.items(): + content = item.get("content") + digest = item.get("source_sha256") + redactions = item.get("redactions") + if ( + not isinstance(content, str) + or not isinstance(digest, str) + or re.fullmatch(r"[0-9a-f]{64}", digest) is None + or type(redactions) is not int + or redactions < 0 + ): + raise SqliteRecordsRepairError("recovered Hosted reply archive metadata is malformed") + try: + stored, stored_digest, stored_redactions = sqlite_review_records._archive_artifact(kind, content) + except ReviewRecordsError as exc: + raise SqliteRecordsRepairError("recovered Hosted reply archive is invalid") from exc + if stored != content or (redactions == 0 and (stored_digest != digest or stored_redactions != redactions)): + raise SqliteRecordsRepairError("recovered Hosted reply archive digest or redaction state conflicts") + contents[kind] = content + try: + metadata = json.loads(contents["metadata"]) + archived_comments = json.loads(contents["hosted_comments"]) + sqlite_provider_imports._validate_archive_artifacts(contents) + except (KeyError, TypeError, ValueError, json.JSONDecodeError, sqlite_provider_imports.ProviderImportError) as exc: + raise SqliteRecordsRepairError("recovered Hosted reply archive is malformed") from exc + if not isinstance(metadata, dict) or metadata.get("capture_format") != "firemud-hosted-ambiguous-reply-recovery/v1": + raise SqliteRecordsRepairError("source run is not the canonical ambiguous-reply recovery import") + + attempt_id = metadata.get("attempt_id") + response_id = metadata.get("response_id") + trigger_id = metadata.get("trigger_id") + head = metadata.get("head_sha") + anchor = metadata.get("anchor") + trigger_record = metadata.get("trigger_record") + if ( + metadata.get("repository") != repo.casefold() + or metadata.get("pull_request") != pr_number + or metadata.get("state") != "completed" + or metadata.get("terminal") is not True + or metadata.get("attributable") is not True + or not isinstance(attempt_id, str) + or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,99}", attempt_id) + or type(response_id) is not int + or response_id <= 0 + or type(trigger_id) is not int + or trigger_id <= 0 + or not isinstance(head, str) + or hosted.EXACT_SHA.fullmatch(head) is None + or not isinstance(anchor, dict) + or not isinstance(trigger_record, dict) + or metadata.get("trigger_record", {}).get("sqlite_attempt_id") != attempt_id + or trigger_record.get("anchor") != anchor + or trigger_record.get("head_sha") != head + or trigger_record.get("repository", "").casefold() != repo.casefold() + or trigger_record.get("pr_number") != pr_number + or (trigger_record.get("trigger") or {}).get("id") != trigger_id + ): + raise SqliteRecordsRepairError("recovered Hosted reply identity conflicts with its archive") + expected_run_id = "hosted-reply-" + hashlib.sha256( + f"{repo.casefold()}\0{pr_number}\0{attempt_id}\0{response_id}".encode() + ).hexdigest()[:48] + if run_id != expected_run_id: + raise SqliteRecordsRepairError("source run ID is not the deterministic recovery identity") + + attempt = records.attempt(attempt_id) + attempt_rows = [item for item in history["attempts"] if item.get("attempt_id") == attempt_id] + if ( + len(attempt_rows) != 1 + or attempt.get("source_pr") != pr_number + or attempt.get("channel") != "hosted" + or attempt.get("state") != "ambiguous" + or attempt.get("run_id") is not None + or attempt.get("candidate_sha") != head + or attempt_rows[0].get("state") != "ambiguous" + or attempt_rows[0].get("run_id") is not None + or attempt_rows[0].get("trigger_id") != str(trigger_id) + or attempt_rows[0].get("provider_review_id") != str(response_id) + or attempt_rows[0].get("candidate_sha") != head + ): + raise SqliteRecordsRepairError("original ambiguous attempt identity or terminal state changed") + attempt_metadata = attempt.get("metadata") + if ( + not isinstance(attempt_metadata, dict) + or attempt_metadata.get("request_kind") != "full" + or attempt_metadata.get("repository", "").casefold() != repo.casefold() + or type(attempt_metadata.get("reviewed_file_count")) is not int + or attempt_metadata["reviewed_file_count"] <= 0 + or attempt_metadata.get("anchor") != anchor + ): + raise SqliteRecordsRepairError("original Hosted request lacks its immutable scope metadata") + original_artifacts = records.attempt_artifacts(attempt_id) + if set(original_artifacts) != {"hosted_comments", "hosted_review", "metadata"}: + raise SqliteRecordsRepairError("original ambiguous Hosted capture is incomplete") + try: + original_capture = json.loads(original_artifacts["metadata"]) + original_comments = json.loads(original_artifacts["hosted_comments"]) + original_reviews = json.loads(original_artifacts["hosted_review"]) + except (TypeError, ValueError, json.JSONDecodeError) as exc: + raise SqliteRecordsRepairError("original ambiguous Hosted capture is malformed") from exc + if ( + not isinstance(original_capture, dict) + or original_capture.get("state") != "ambiguous" + or original_capture.get("terminal") is not True + or original_capture.get("attributable") is not False + or original_capture.get("repository", "").casefold() != repo.casefold() + or original_capture.get("pull_request") != pr_number + or original_capture.get("head_sha") != head + or original_capture.get("trigger_id") != trigger_id + or original_capture.get("response_id") != response_id + or original_capture.get("trigger_record") != trigger_record + or original_capture.get("observed_at") != attempt_rows[0].get("finished_at") + or not isinstance(original_comments, dict) + or not isinstance(original_comments.get("comments"), list) + or not isinstance(original_comments.get("review_threads"), list) + or original_reviews + ): + raise SqliteRecordsRepairError("original ambiguous Hosted capture conflicts with recovered identity") + try: + trigger_repository = trigger_record.get("repository") + if not isinstance(trigger_repository, str) or trigger_repository.casefold() != repo.casefold(): + raise SqliteRecordsRepairError("recovered Hosted trigger repository conflicts with its origin") + trigger_record = sqlite_hosted_capture._validate_trigger_record( + trigger_repository, pr_number, trigger_record + ) + except sqlite_hosted_capture.HostedCaptureError as exc: + raise SqliteRecordsRepairError("recovered Hosted trigger record is invalid") from exc + original_trigger = [ + item for item in original_comments["comments"] + if isinstance(item, dict) and github.immutable_database_id(item) == trigger_id + ] + original_response = [ + item for item in original_comments["comments"] + if isinstance(item, dict) and github.immutable_database_id(item) == response_id + ] + recovered_trigger = [ + item for item in archived_comments.get("comments", []) + if isinstance(item, dict) and github.immutable_database_id(item) == trigger_id + ] if isinstance(archived_comments, dict) else [] + recovered_response = [ + item for item in archived_comments.get("comments", []) + if isinstance(item, dict) and github.immutable_database_id(item) == response_id + ] if isinstance(archived_comments, dict) else [] + if ( + len(original_trigger) != 1 + or len(original_response) != 1 + or len(recovered_trigger) != 1 + or len(recovered_response) != 1 + or original_trigger[0] != recovered_trigger[0] + or original_response[0] != recovered_response[0] + or not github.is_coderabbit_login((original_response[0].get("author") or {}).get("login")) + or original_response[0].get("createdAt") != (metadata.get("zero_reply_proof") or {}).get("response_created_at") + or original_response[0].get("updatedAt") != (metadata.get("zero_reply_proof") or {}).get("response_updated_at") + ): + raise SqliteRecordsRepairError("recovered Hosted response differs from its immutable captured comments") + + trigger_state = metadata.get("trigger_state") + zero_proof = metadata.get("zero_reply_proof") + checkpoint_fields = metadata.get("checkpoint_fields") + try: + checkpoint = evidence.Checkpoint(**checkpoint_fields) + checkpoint_fingerprint = sqlite_provider_imports._checkpoint_fingerprint(checkpoint) + except (TypeError, ValueError, sqlite_provider_imports.ProviderImportError) as exc: + raise SqliteRecordsRepairError("recovered checkpoint fields are malformed") from exc + finished_at = metadata.get("observed_at") + started_at = (trigger_record.get("trigger") or {}).get("created_at") + if ( + not isinstance(trigger_state, dict) + or trigger_state.get("state") != "completed" + or trigger_state.get("terminal") is not True + or trigger_state.get("attributed") is not True + or trigger_state.get("trigger_comment_id") != trigger_id + or trigger_state.get("response_id") != response_id + or trigger_state.get("head_sha") != head + or type(trigger_state.get("duration_seconds")) is not int + or trigger_state["duration_seconds"] < 0 + or (metadata.get("zero_reply_proof") or {}).get("duration_seconds") != trigger_state.get("duration_seconds") + or not isinstance(zero_proof, dict) + or zero_proof.get("attempt_id") != attempt_id + or zero_proof.get("trigger_id") != trigger_id + or zero_proof.get("response_id") != response_id + or zero_proof.get("candidate_sha") != head + or zero_proof.get("anchor") != anchor + or zero_proof.get("counts") != {"found": 0, "accepted": 0, "routed": 0} + or type(attempt_metadata["reviewed_file_count"]) is not int + or checkpoint.comment_id != response_id + or checkpoint.type != "Hosted" + or checkpoint.raw_found != 0 + or checkpoint.accepted != 0 + or checkpoint.routed != 0 + or checkpoint.reviewed_sha != head + or checkpoint.file_count != attempt_metadata["reviewed_file_count"] + or checkpoint.hosted_review_id != response_id + or checkpoint.duration_seconds != trigger_state["duration_seconds"] + or checkpoint.duration_invalid is not False + or checkpoint.created_at != metadata.get("checkpoint", {}).get("created_at") + or checkpoint.updated_at != finished_at + or checkpoint.created_at != original_response[0].get("createdAt") + or checkpoint.updated_at != original_response[0].get("updatedAt") + or metadata.get("checkpoint") != checkpoint.as_json() + or metadata.get("checkpoint_fingerprint") != checkpoint_fingerprint + or run.get("source_head") != head + or run.get("started_at") != started_at + or run.get("finished_at") != finished_at + or run.get("counts") != {"found": 0, "accepted": 0, "routed": 0} + or run.get("finalized") is not True + or run.get("attributable") is not True + or run.get("outcome") != "completed" + ): + raise SqliteRecordsRepairError("recovered Hosted zero-result proof or checkpoint does not match its source") + trigger_at = hosted.parse_timestamp(started_at) + finished_at_value = hosted.parse_timestamp(finished_at) + if ( + trigger_at is None + or finished_at_value is None + or (finished_at_value - trigger_at).total_seconds() != trigger_state["duration_seconds"] + ): + raise SqliteRecordsRepairError("recovered Hosted duration does not match its immutable trigger window") + origins = [item for item in history["provider_origins"] if item.get("run_id") == run_id] + expected_origin = { + "repository": repo.casefold(), + "source_pr": pr_number, + "channel": "hosted", + "provider_id": f"trigger:{trigger_id}", + "checkpoint_id": response_id, + "checkpoint_fingerprint": checkpoint_fingerprint, + "run_id": run_id, + } + if len(origins) != 1 or origins[0] != expected_origin: + raise SqliteRecordsRepairError("recovered Hosted provider origin conflicts with immutable response") + linked = sqlite_hosted_capture._linked_ambiguous_reply_recovery( + history, repo, pr_number, attempt_rows[0], str(trigger_id) + ) + if linked is None or linked.get("run_id") != run_id or linked.get("checkpoint_id") != response_id: + raise SqliteRecordsRepairError("recovered Hosted result is not linked by the canonical recovery reader") + if any(item.get("run_id") == run_id for item in history["findings"] + history["decisions"]): + raise SqliteRecordsRepairError("recovered zero-result source unexpectedly contains findings or decisions") + return { + "run": run, + "attempt": attempt, + "attempt_id": attempt_id, + "checkpoint": checkpoint, + "checkpoint_fingerprint": checkpoint_fingerprint, + "trigger_id": trigger_id, + "response_id": response_id, + "run_id": run_id, + "repository": repo.casefold(), + "source_pr": pr_number, + } + + +def repair_ambiguous_hosted_reply( + records: SqliteReviewRecords, + *, + repo: str, + pr_number: int, + attempt_id: str, + response_id: int, + actor: str, + scope: str, + hosted_payload: dict[str, Any], + dry_run: bool = True, +) -> dict[str, Any]: + """Repair one exact captured ambiguous zero reply through existing record APIs.""" + + if not isinstance(records, SqliteReviewRecords): + raise SqliteRecordsRepairError("reply recovery requires a SqliteReviewRecords store") + if not isinstance(actor, str) or not actor.strip() or len(actor) > 100: + raise SqliteRecordsRepairError("repair actor must be non-empty text of at most 100 characters") + if scope not in {"broad", "narrow"}: + raise SqliteRecordsRepairError("repair scope must be broad or narrow") + if not isinstance(dry_run, bool): + raise SqliteRecordsRepairError("dry_run must be boolean") + proof = _ambiguous_reply_proof( + records, + repo=repo, + pr_number=pr_number, + attempt_id=attempt_id, + response_id=response_id, + hosted_payload=hosted_payload, + ) + + def import_stages(target: SqliteReviewRecords) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: + imported = target.import_completed_run( + run_id=proof["run_id"], + source_pr=pr_number, + channel="hosted", + findings=(), + source_decisions=(), + source_head=proof["attempt"]["candidate_sha"], + reviewer=proof["reviewer"], + scope=scope, + coverage_limits=(), + started_at=proof["started_at"], + finished_at=proof["finished_at"], + finalized_at=proof["finished_at"], + ) + archived = target.archive_imported_artifacts(proof["run_id"], proof["artifacts"]) + origin = target.link_provider_origin( + repository=repo.casefold(), + source_pr=pr_number, + channel="hosted", + provider_id=proof["provider_id"], + checkpoint_id=proof["checkpoint_id"], + checkpoint_fingerprint=proof["checkpoint_fingerprint"], + run_id=proof["run_id"], + ) + return imported, archived, origin + + with tempfile.TemporaryDirectory(prefix="pr-review-reply-repair-") as scratch: + clone = _clone_records(records, Path(scratch) / "records.sqlite3") + try: + clone_imported, clone_archived, clone_origin = import_stages(clone) + clone_readback = _verify_ambiguous_reply_import(clone, repo=repo, pr_number=pr_number, proof=proof) + except (ReviewRecordsError, sqlite3.DatabaseError, OSError) as exc: + raise SqliteRecordsRepairError(f"reply recovery preflight refused: {exc}") from exc + expected = { + "attempt_id": attempt_id, + "response_id": response_id, + "trigger_id": int(proof["provider_id"].split(":", 1)[1]), + "candidate_sha": proof["attempt"]["candidate_sha"], + "anchor": proof["attempt"]["metadata"]["anchor"], + "run_id": proof["run_id"], + "provider_id": proof["provider_id"], + "checkpoint_id": proof["checkpoint_id"], + "checkpoint_fingerprint": proof["checkpoint_fingerprint"], + "started_at": proof["started_at"], + "finished_at": proof["finished_at"], + "duration_seconds": proof["state"].duration_seconds, + "counts": {"found": 0, "accepted": 0, "routed": 0}, + "artifact_sha256": { + kind: hashlib.sha256(content.encode("utf-8")).hexdigest() + for kind, content in sorted(proof["artifacts"].items()) + }, + "stages": ["completed_zero_run", "archived_artifacts", "provider_origin_last"], + "readback": clone_readback, + "action": "already_recovered" + if all(item.get("idempotent_replay") is True for item in (clone_imported, clone_archived, clone_origin)) + else "would_recover", + } + if dry_run: + return { + "api_version": _API_VERSION, + "status": "preview", + "dry_run": True, + "repository": repo.casefold(), + "source_pr": pr_number, + "items": [expected], + } + + try: + imported, archived, origin = import_stages(records) + readback = _verify_ambiguous_reply_import(records, repo=repo, pr_number=pr_number, proof=proof) + except (ReviewRecordsError, sqlite3.DatabaseError, OSError, SqliteRecordsRepairError) as exc: + return { + "api_version": _API_VERSION, + "status": "partial", + "dry_run": False, + "repository": repo.casefold(), + "source_pr": pr_number, + "items": [{**expected, "status": "partial"}], + "error": _partial_diagnostic(exc) if isinstance(exc, (OSError, sqlite3.DatabaseError)) else str(exc), + } + expected["action"] = ( + "already_recovered" + if all(item.get("idempotent_replay") is True for item in (imported, archived, origin)) + else "recovered" + ) + expected["readback"] = readback + return { + "api_version": _API_VERSION, + "status": "complete", + "dry_run": False, + "repository": repo.casefold(), + "source_pr": pr_number, + "items": [expected], + } + + def archive_incomplete_checkpoint( records: SqliteReviewRecords, *, @@ -1136,18 +1906,26 @@ def archive_incomplete_checkpoint( """Retain real old evidence and name what prevents a completed import.""" repo, selected = _validate_request( - records, repo=repo, pr_number=pr_number, checkpoints=(checkpoint,), - actor="historical-repair", scope="broad", coverage_limits=(), + records, + repo=repo, + pr_number=pr_number, + checkpoints=(checkpoint,), + actor="historical-repair", + scope="broad", + coverage_limits=(), ) if len(selected) != 1 or not isinstance(missing_reason, str) or not missing_reason.strip(): raise SqliteRecordsRepairError("incomplete checkpoint requires one source and a reason") if not isinstance(dry_run, bool): raise SqliteRecordsRepairError("dry_run must be boolean") artifacts = { - "metadata": _artifact_text({ - "checkpoint": checkpoint.as_json(), "missing_reason": missing_reason, - "archive_scope": "exact-checkpoint-and-linked-review", - }), + "metadata": _artifact_text( + { + "checkpoint": checkpoint.as_json(), + "missing_reason": missing_reason, + "archive_scope": "exact-checkpoint-and-linked-review", + } + ), } if checkpoint.type == "Hosted": if hosted_payload is None: @@ -1157,37 +1935,53 @@ def archive_incomplete_checkpoint( except (sqlite_hosted_capture.HostedCaptureError, KeyError, TypeError, ValueError) as exc: raise SqliteRecordsRepairError(f"complete public Hosted history is unavailable: {exc}") from exc matches = [ - item for item in pull["comments"]["nodes"] - if github.immutable_database_id(item) == checkpoint.comment_id + item for item in pull["comments"]["nodes"] if github.immutable_database_id(item) == checkpoint.comment_id ] if len(matches) != 1: raise SqliteRecordsRepairError("public Hosted checkpoint comment is missing or duplicated") item = matches[0] - parsed, _ = evidence.parse_checkpoint_comments([{ - "id": checkpoint.comment_id, "body": item.get("body"), - "created_at": item.get("createdAt"), "updated_at": item.get("updatedAt"), - "author_login": ((item.get("author") or {}).get("login")), - }]) - if len(parsed) != 1 or sqlite_provider_imports._checkpoint_fingerprint(parsed[0]) != sqlite_provider_imports._checkpoint_fingerprint(checkpoint): + parsed, _ = evidence.parse_checkpoint_comments( + [ + { + "id": checkpoint.comment_id, + "body": item.get("body"), + "created_at": item.get("createdAt"), + "updated_at": item.get("updatedAt"), + "author_login": ((item.get("author") or {}).get("login")), + } + ] + ) + if len(parsed) != 1 or sqlite_provider_imports._checkpoint_fingerprint( + parsed[0] + ) != sqlite_provider_imports._checkpoint_fingerprint(checkpoint): raise SqliteRecordsRepairError("public Hosted checkpoint changed during historical repair") linked_reviews = [ - review for review in pull["reviews"]["nodes"] + review + for review in pull["reviews"]["nodes"] if github.immutable_database_id(review) == checkpoint.hosted_review_id ] artifacts["hosted_review"] = _artifact_text(linked_reviews) - artifacts["hosted_comments"] = _artifact_text({ - "comments": [item], - "review_threads": [], - }) + artifacts["hosted_comments"] = _artifact_text( + { + "comments": [item], + "review_threads": [], + } + ) else: try: capture = evidence._load_cli_capture( - checkpoint, repo, pr_number, common, - validate_checkpoint_decisions=False, records=records, sql_first=False, + checkpoint, + repo, + pr_number, + common, + validate_checkpoint_decisions=False, + records=records, + sql_first=False, ) except evidence.EvidenceError as exc: metadata = { - "checkpoint": checkpoint.as_json(), "missing_reason": missing_reason, + "checkpoint": checkpoint.as_json(), + "missing_reason": missing_reason, "archive_scope": "exact-checkpoint-and-linked-review", "capture_error": str(exc), } @@ -1208,11 +2002,13 @@ def archive_incomplete_checkpoint( clone = _clone_records(records, Path(scratch) / "records.sqlite3") try: preview = clone.record_historical_gap( - repository=repo, source_pr=pr_number, + repository=repo, + source_pr=pr_number, channel="hosted" if checkpoint.type == "Hosted" else "cli", checkpoint_id=checkpoint.comment_id, checkpoint_fingerprint=fingerprint, - checkpoint=checkpoint.as_json(), artifacts=artifacts, + checkpoint=checkpoint.as_json(), + artifacts=artifacts, missing_reason=missing_reason, ) except (ReviewRecordsError, sqlite3.DatabaseError, OSError) as exc: @@ -1221,11 +2017,13 @@ def archive_incomplete_checkpoint( return {"status": "incomplete_preview", "dry_run": True, **preview} try: applied = target.record_historical_gap( - repository=repo, source_pr=pr_number, + repository=repo, + source_pr=pr_number, channel="hosted" if checkpoint.type == "Hosted" else "cli", checkpoint_id=checkpoint.comment_id, checkpoint_fingerprint=fingerprint, - checkpoint=checkpoint.as_json(), artifacts=artifacts, + checkpoint=checkpoint.as_json(), + artifacts=artifacts, missing_reason=missing_reason, ) except (ReviewRecordsError, sqlite3.DatabaseError, OSError) as exc: @@ -1237,5 +2035,6 @@ def archive_incomplete_checkpoint( "MissingHistoricalEvidenceError", "SqliteRecordsRepairError", "archive_incomplete_checkpoint", + "repair_ambiguous_hosted_reply", "repair_provider_checkpoints", ] diff --git a/dev-tools/pr_review/sqlite_review_records.py b/dev-tools/pr_review/sqlite_review_records.py index 7f658745ac..b325eb24fd 100644 --- a/dev-tools/pr_review/sqlite_review_records.py +++ b/dev-tools/pr_review/sqlite_review_records.py @@ -1012,34 +1012,104 @@ def reserve_checkpoint_publication(self, attempt_id: str, content: str) -> bool: intent = json.loads(content) if not isinstance(intent, dict): raise ReviewRecordsError("checkpoint publication intent must be an object") + if intent.get("run_id") != attempt_id: + raise ReviewRecordsError("checkpoint publication intent has a different source run") + target_attempt_id, recovered = self._checkpoint_publication_target( + attempt_id, repository=intent.get("repository"), source_pr=intent.get("source_pr") + ) with self._write_connection() as connection: row = connection.execute( - "SELECT state, run_id, metadata_json FROM review_attempts WHERE attempt_id = ?", (attempt_id,) + "SELECT state, run_id, metadata_json FROM review_attempts WHERE attempt_id = ?", + (target_attempt_id,), ).fetchone() - if row is None or row[:2] != ("completed", attempt_id): - raise ReviewRecordsError("checkpoint publication requires an exact completed attempt") + expected_identity = ("ambiguous", None) if recovered else ("completed", target_attempt_id) + if row is None or row[:2] != expected_identity: + raise ReviewRecordsError("checkpoint publication requires its exact immutable source attempt") metadata = json.loads(row[2]) if not isinstance(metadata, dict): raise ReviewRecordsError("checkpoint attempt metadata is malformed") + if recovered: + prior_run_id = metadata.get("checkpoint_publication_run_id") + if prior_run_id not in (None, attempt_id): + raise ReviewRecordsError("original attempt already has a different recovered publication") if "checkpoint_publication_intent" in metadata: if metadata["checkpoint_publication_intent"] != intent: raise ReviewRecordsError("checkpoint publication intent conflicts with prior attribution") return False metadata["checkpoint_publication_intent"] = intent + if recovered: + metadata["checkpoint_publication_run_id"] = attempt_id connection.execute( "UPDATE review_attempts SET metadata_json = ? WHERE attempt_id = ?", - (json.dumps(metadata, sort_keys=True), attempt_id), + (json.dumps(metadata, sort_keys=True), target_attempt_id), ) return True @_translate_database_errors def checkpoint_publication_state(self, attempt_id: str) -> dict[str, Any]: """Local read-only publication projection; missing old diagnostics remain unknown.""" - attempt = self.attempt(attempt_id) - if attempt["state"] != "completed" or attempt["run_id"] != attempt_id: + attempt_id = _safe_identifier(attempt_id, "run ID", maximum=100) + target_attempt_id, recovered = self._checkpoint_publication_target(attempt_id) + attempt = self.attempt(target_attempt_id) + if recovered and attempt["metadata"].get("checkpoint_publication_run_id") != attempt_id: + raise ReviewRecordsError("recovered checkpoint publication has no exact durable run association") + if not recovered and (attempt["state"] != "completed" or attempt["run_id"] != attempt_id): raise ReviewRecordsError("checkpoint publication requires an exact completed attempt") return self._checkpoint_publication_state(attempt_id, attempt["metadata"]) + def _checkpoint_publication_target( + self, + run_id: str, + *, + repository: str | None = None, + source_pr: int | None = None, + ) -> tuple[str, bool]: + """Resolve only a native attempt or the canonical zero-reply recovery.""" + + try: + attempt = self.attempt(run_id) + except AttemptNotFound: + attempt = None + if attempt is not None and attempt["state"] == "completed" and attempt["run_id"] == run_id: + if repository is not None and attempt["metadata"].get("repository") != repository: + raise ReviewRecordsError("checkpoint publication repository conflicts with native attempt") + if source_pr is not None and attempt["source_pr"] != source_pr: + raise ReviewRecordsError("checkpoint publication PR conflicts with native attempt") + return run_id, False + + try: + source = self.run_source(run_id) + imported = self.imported_run_artifacts(run_id) + archive = json.loads(imported.get("metadata", {}).get("content", "{}")) + except (ReviewRecordsError, TypeError, ValueError, json.JSONDecodeError) as exc: + raise ReviewRecordsError("checkpoint publication requires completed native evidence") from exc + archived_repository = archive.get("repository") if isinstance(archive, dict) else None + exact_repository = repository or archived_repository + exact_pr = source_pr or source.get("source_pr") + if ( + source.get("channel") != "hosted" + or source.get("outcome") != "completed" + or source.get("attributable") is not True + or not isinstance(exact_repository, str) + or not isinstance(exact_pr, int) + ): + raise ReviewRecordsError("checkpoint publication requires exact recovered Hosted evidence") + try: + from .sqlite_records_repair import verify_ambiguous_reply_import_for_publication + + verified = verify_ambiguous_reply_import_for_publication( + self, repo=exact_repository, pr_number=exact_pr, run_id=run_id + ) + except (ValueError, TypeError, KeyError) as exc: + raise ReviewRecordsError("checkpoint publication recovery proof is invalid") from exc + if ( + archived_repository != exact_repository.casefold() + or source.get("source_pr") != exact_pr + or verified.get("repository") != exact_repository.casefold() + ): + raise ReviewRecordsError("checkpoint publication recovery attribution conflicts") + return verified["attempt_id"], True + @staticmethod def _checkpoint_publication_state(attempt_id: str, metadata: dict[str, Any]) -> dict[str, Any]: intent = metadata.get("checkpoint_publication_intent") @@ -1078,7 +1148,8 @@ def append_checkpoint_publication_event( Original intent, provider archives and review records are never rewritten. The caller holds the publication lock through decision, consume and POST. """ - attempt_id = _safe_identifier(attempt_id, "attempt ID", maximum=100) + attempt_id = _safe_identifier(attempt_id, "run ID", maximum=100) + target_attempt_id, recovered = self._checkpoint_publication_target(attempt_id) if not isinstance(expected_state_sha256, str) or not re.fullmatch(r"[0-9a-f]{64}", expected_state_sha256): raise ReviewRecordsError("checkpoint publication state digest is invalid") event = dict(event) @@ -1161,11 +1232,15 @@ def append_checkpoint_publication_event( raise ReviewRecordsError("checkpoint reused comment identity is invalid") with self._write_connection() as connection: row = connection.execute( - "SELECT state, run_id, metadata_json FROM review_attempts WHERE attempt_id = ?", (attempt_id,) + "SELECT state, run_id, metadata_json FROM review_attempts WHERE attempt_id = ?", + (target_attempt_id,), ).fetchone() - if row is None or row[:2] != ("completed", attempt_id): - raise ReviewRecordsError("checkpoint publication requires an exact completed attempt") + expected_identity = ("ambiguous", None) if recovered else ("completed", target_attempt_id) + if row is None or row[:2] != expected_identity: + raise ReviewRecordsError("checkpoint publication requires its exact immutable source attempt") metadata = json.loads(row[2]) + if recovered and metadata.get("checkpoint_publication_run_id") != attempt_id: + raise ReviewRecordsError("recovered checkpoint publication has no exact durable run association") state = self._checkpoint_publication_state(attempt_id, metadata) if state["intent"] is None or state["state_sha256"] != expected_state_sha256: raise ReviewRecordsError("checkpoint publication intent is missing or state digest is stale") @@ -1191,7 +1266,7 @@ def append_checkpoint_publication_event( metadata["checkpoint_publication_events"] = [*events, event] connection.execute( "UPDATE review_attempts SET metadata_json = ? WHERE attempt_id = ?", - (json.dumps(metadata, sort_keys=True), attempt_id), + (json.dumps(metadata, sort_keys=True), target_attempt_id), ) return self._checkpoint_publication_state(attempt_id, metadata) @@ -1236,6 +1311,24 @@ def attempt_artifacts( self._check_deadline(deadline) return {kind: content for kind, content in rows} + @_translate_database_errors + def imported_run_artifacts(self, run_id: str) -> dict[str, dict[str, Any]]: + """Read retained imported artifacts and their immutable source digests.""" + + run_id = _safe_identifier(run_id, "run ID", maximum=100) + self._require_regular_database() + with contextlib.closing(self._connect(read_only=True)) as connection: + self._require_compatible(connection) + rows = connection.execute( + "SELECT kind, content, source_sha256, redactions FROM imported_artifacts " + "WHERE run_id = ? ORDER BY kind", + (run_id,), + ).fetchall() + return { + kind: {"content": content, "source_sha256": source_sha256, "redactions": redactions} + for kind, content, source_sha256, redactions in rows + } + @_translate_database_errors def link_attempt_run(self, attempt_id: str, run_id: str, *, _connection: sqlite3.Connection | None = None) -> None: """Bind one completed, attributable source run to its exact attempt.""" diff --git a/dev-tools/validation/test_pr_review_checkpoint_publication.py b/dev-tools/validation/test_pr_review_checkpoint_publication.py index 47d3d92d3d..e298754ba9 100644 --- a/dev-tools/validation/test_pr_review_checkpoint_publication.py +++ b/dev-tools/validation/test_pr_review_checkpoint_publication.py @@ -2,20 +2,35 @@ import concurrent.futures import copy +import dataclasses import json import subprocess import sys import tempfile import unittest from pathlib import Path +from types import SimpleNamespace from unittest.mock import patch ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "dev-tools")) +import test_pr_review_evidence_hosted as evidence_hosted_fixtures import test_pr_review_sqlite_hosted_capture as hosted_fixtures +import test_pr_review_sqlite_records_repair as repair_fixtures from pr_review import checkpoint_publication as publication -from pr_review import cli, evidence, github, sqlite_hosted_capture, sqlite_provider_imports, sqlite_store +from pr_review import ( + cli, + controller, + evidence, + github, + policy, + runtime, + sqlite_hosted_capture, + sqlite_provider_imports, + sqlite_store, + state, +) from pr_review.sqlite_finding_text import _safe_finding_detail from pr_review.sqlite_review_records import FindingObservation, ReviewRecordsError, SqliteReviewRecords @@ -31,9 +46,10 @@ def __init__(self): self.posts = 0 self.uncertain = False self.hide = False + self.repo = REPO def _fetch_api_object(self, endpoint): - return {"id": 123, "full_name": REPO} + return {"id": 123, "full_name": self.repo} def fetch_authenticated_user(self): return {"id": 456, "login": "owner"} @@ -96,6 +112,532 @@ def cli_run(self, *, finalize=True, duration=67, repository=REPO): def publish(self, run_id=RUN): return publication.publish_checkpoint(self.store, repo=REPO, source_pr=PR, run_id=run_id, adapter=self.github) + def recovered_run(self, repo=REPO, *, resolved_threads=False): + fixture = repair_fixtures.SqliteRecordsRepairTest() + fixture.setUp() + self.addCleanup(fixture.doCleanups) + with ( + patch.object(repair_fixtures, "REPO", repo), + patch.object(evidence_hosted_fixtures, "REPO", repo), + ): + payload, record, record_path = fixture.ambiguous_reply_recovery_fixture() + if resolved_threads: + for thread in payload["data"]["repository"]["pullRequest"]["reviewThreads"]["nodes"]: + thread["isResolved"] = True + thread["isOutdated"] = True + fixture.recovery_record_path = record_path + record_path.write_text(json.dumps(record), encoding="utf-8") + recovered = fixture.recover_ambiguous_reply(payload, dry_run=False) + return fixture, payload, recovered["items"][0]["run_id"] + + def finalize_recovered(self, fixture, run_id, repo=REPO): + finalize = publication.publish_checkpoint + args = SimpleNamespace( + acceptance_fixture=None, + state_path=None, + records_command="source", + source_command="finalize", + database=str(fixture.database), + run_id=run_id, + finalized_at=None, + repo=repo, + ) + with ( + patch.object(cli.github, "infer_repo", return_value=repo), + patch.object( + publication, + "publish_checkpoint", + side_effect=lambda store, **options: finalize(store, adapter=self.github, **options), + ), + ): + return cli._dispatch_records(args) + + def recovered_stop_audit(self, fixture, payload): + pull = payload["data"]["repository"]["pullRequest"] + metadata = fixture.records.attempt("current-hosted-attempt")["metadata"] + base_sha = metadata.get("actual_base_sha", metadata["anchor"]["parent_head"]) + base_ref = metadata.get("actual_base_ref", "develop") + pull.update({"number": PR, "baseRefName": base_ref, "baseRefOid": base_sha}) + live = SimpleNamespace( + pull_request=lambda number: SimpleNamespace( + number=number, + head_sha=pull["headRefOid"], + base_sha=base_sha, + base_ref_name=base_ref, + ), + branch_head=lambda _ref: base_sha, + ) + observer = runtime.LiveEvidence(REPO, live, records=fixture.records) + anchor = dict(metadata["anchor"]) + anchor.update( + { + "pr_base_oid": base_sha, + "base_ref": base_ref, + "effective_parent_head": base_sha, + "enforce_parent_identity_ref": True, + } + ) + with ( + patch.object(observer, "_payload", return_value=payload), + patch.object(observer, "_complete_trigger_paths", return_value=[fixture.recovery_record_path]), + patch.object( + runtime.hosted, + "current_trigger_record_paths", + return_value=[fixture.recovery_record_path], + ), + ): + return observer.review_stop_audit(PR, anchor) + + def test_recovered_reply_publication_preserves_mixed_case_provider_repository(self): + repo = "owner/FireMUD" + fixture, _, run_id = self.recovered_run(repo=repo) + self.github.repo = repo + + response, status = self.finalize_recovered(fixture, run_id, repo=repo) + + self.assertEqual(status, 0) + self.assertEqual(response["result"]["publication"]["status"], "published") + self.assertIn("", response["result"]["publication"]["body"]) + self.assertEqual(fixture.records.attempt("current-hosted-attempt")["metadata"]["repository"], repo) + self.assertEqual(fixture.records.history(PR)["provider_origins"][0]["repository"], repo.casefold()) + + def test_exact_recovered_zero_run_publishes_through_source_finalize_and_resolves_once(self): + fixture, payload, run_id = self.recovered_run(resolved_threads=True) + store = fixture.records + original_attempt = store.attempt("current-hosted-attempt") + original_artifacts = store.attempt_artifacts("current-hosted-attempt") + original_history = store.history(PR) + recovered_head = original_history["runs"][0]["source_head"] + + response, status = self.finalize_recovered(fixture, run_id) + + publication_result = response["result"]["publication"] + self.assertEqual(status, 0) + self.assertEqual(publication_result["status"], "published") + self.assertEqual( + publication_result["body"], + f"Hosted: 0 Found / 0 Accepted / 0 Routed · {recovered_head} · 1 files · 20s\n" + "\n", + ) + self.assertEqual(store.history(PR)["runs"], original_history["runs"]) + self.assertEqual(len(store.history(PR)["attempts"]), len(original_history["attempts"])) + current_attempt = store.attempt("current-hosted-attempt") + for field in ( + "attempt_id", + "source_pr", + "channel", + "candidate_sha", + "started_at", + "finished_at", + "state", + "run_id", + ): + self.assertEqual(current_attempt[field], original_attempt[field], field) + original_attempt_row = next( + item for item in original_history["attempts"] if item["attempt_id"] == "current-hosted-attempt" + ) + current_attempt_row = next( + item for item in store.history(PR)["attempts"] if item["attempt_id"] == "current-hosted-attempt" + ) + for field in ( + "started_at", + "finished_at", + "duration_seconds", + "state", + "run_id", + "trigger_id", + "provider_review_id", + "candidate_sha", + ): + self.assertEqual(current_attempt_row[field], original_attempt_row[field], field) + self.assertEqual(store.attempt_artifacts("current-hosted-attempt"), original_artifacts) + appended_metadata = copy.deepcopy(current_attempt["metadata"]) + for key in ( + "checkpoint_publication_run_id", + "checkpoint_publication_intent", + "checkpoint_publication_events", + ): + appended_metadata.pop(key, None) + self.assertEqual(appended_metadata, original_attempt["metadata"]) + self.assertEqual(store.checkpoint_publication_state(run_id)["intent"]["run_id"], run_id) + self.assertEqual( + [event["type"] for event in store.checkpoint_publication_state(run_id)["events"]], + ["post_started", "post_outcome"], + ) + repeated, repeated_status = self.finalize_recovered(fixture, run_id) + self.assertEqual(repeated_status, 0) + self.assertEqual(repeated["result"]["publication"]["status"], "reused") + self.assertEqual(self.github.posts, 1) + + public_comment = self.github.comments[0] + pull = payload["data"]["repository"]["pullRequest"] + pull["headRefOid"] = recovered_head + pull["changedFiles"] = 1 + pull["comments"]["nodes"].append( + { + "databaseId": public_comment["id"], + "body": public_comment["body"], + "createdAt": public_comment["created_at"], + "updatedAt": public_comment["updated_at"], + "author": {"login": public_comment["user"]["login"]}, + } + ) + observer = runtime.LiveEvidence(REPO, None, records=store) + observer.prefetch_payload(PR, payload) + parsed, unparsed = evidence.parse_checkpoint_comments(observer._comments(payload)) + self.assertEqual(unparsed, 0) + target = next(item for item in parsed if item.comment_id == public_comment["id"]) + pubstate = store.checkpoint_publication_state(run_id) + self.assertEqual(pubstate["intent"]["repository"], REPO) + self.assertEqual(pubstate["intent"]["source_pr"], PR) + self.assertEqual(pubstate["intent"]["run_id"], run_id) + self.assertEqual(pubstate["intent"]["actor_login"], target.author_login) + self.assertTrue( + publication._same_checkpoint( + { + "id": target.comment_id, + "body": public_comment["body"], + "created_at": target.created_at, + "issue_url": f"https://api.github.com/repos/{REPO}/issues/{PR}", + "user": {"id": pubstate["intent"]["actor_id"], "login": target.author_login}, + }, + pubstate["intent"]["body"], + repo=REPO, + source_pr=PR, + ) + ) + recovered_binding = observer._recovered_hosted_publication(PR, target, public_comment["body"]) + self.assertIsInstance(recovered_binding, dict) + current_record = runtime.hosted.load_trigger_reservation(fixture.recovery_record_path, REPO, PR) + current_state = runtime.hosted.trigger_state( + REPO, PR, payload, current_record, fixture.recovery_record_path + ) + ambiguous_current_state = dataclasses.replace( + current_state, + state="ambiguous", + terminal=True, + attributed=False, + trigger_comment_id=int(recovered_binding["trigger_id"]), + response_id=recovered_binding["response_id"], + head_sha=recovered_binding["head"], + reason="the retained current trigger remains terminally ambiguous", + ) + with ( + patch.object( + runtime.hosted, "current_trigger_record_paths", return_value=[fixture.recovery_record_path] + ), + patch.object(runtime.hosted, "trigger_state", return_value=ambiguous_current_state), + ): + history = observer.history(PR, "hosted") + self.assertFalse(any(item.get("checkpoint") == "trigger:10" for item in history)) + published = [item for item in history if item.get("comment_id") == public_comment["id"]] + self.assertEqual(len(published), 1) + self.assertTrue(published[0]["completed"]) + self.assertTrue(published[0]["attributable"]) + self.assertEqual(published[0]["source_run_id"], run_id) + self.assertEqual(published[0]["head"], recovered_head) + self.assertEqual(published[0]["verified_completed_at"], "2026-09-23T00:02:20Z") + self.assertEqual(published[0]["source_resolution_status"], "resolved") + original_anchor = published[0] + allocation = state.ReviewAllocation( + pr=PR, + channel="hosted", + head=recovered_head, + parent_identity=original_anchor["parent_identity"], + parent_head=original_anchor["parent_head"], + merge_base=original_anchor["merge_base"], + patch_id=original_anchor["patch_id"], + baseline_checkpoints=(), + reason="recovered publication fixture", + min_additional_completed=1, + max_additional_completed=1, + ) + allocation_snapshot = controller.ReviewController._bounded_allocation_evidence(allocation, history) + self.assertIsNone(allocation_snapshot["error"]) + self.assertEqual(len(allocation_snapshot["results"]), 1) + self.assertEqual(allocation_snapshot["results"][0]["source_run_id"], run_id) + self.assertEqual(allocation_snapshot["in_flight"], 0) + self.assertEqual(len(allocation_snapshot["results"]), allocation.max_additional_completed) + minimum_remaining = max( + 0, + (allocation.min_additional_completed or 0) - len(allocation_snapshot["results"]), + ) + self.assertEqual(minimum_remaining, 0) + review_state = state.ReviewState(ordered_prs=(PR,)) + self.assertFalse( + any(item.get("held") or item.get("unstable") for item in history), + repr([item for item in history if item.get("held") or item.get("unstable")]), + ) + self.assertEqual( + policy.completion_status(review_state, policy.Channel.HOSTED, history), + policy.ReviewStatus.COMPLETE, + ) + stop_audit = self.recovered_stop_audit(fixture, payload) + self.assertEqual(stop_audit["ambiguous_terminal_responses"], []) + self.assertEqual(stop_audit["active_reservations"], []) + self.assertEqual( + stop_audit["ambiguous_responses"], ["response has no preceding full-review trigger"] + ) + self.assertIn( + "ambiguous Hosted response: response has no preceding full-review trigger", + stop_audit["blockers"], + ) + self.assertEqual( + stop_audit["recovered_terminal_responses"], + [ + { + "attempt_id": "current-hosted-attempt", + "trigger_id": 10, + "response_id": 11, + "captured_head": recovered_head, + "run_id": run_id, + "checkpoint_id": public_comment["id"], + "finished_at": "2026-09-23T00:02:20Z", + } + ], + ) + self.assertEqual(store.attempt("current-hosted-attempt"), current_attempt) + self.assertEqual(store.attempt_artifacts("current-hosted-attempt"), original_artifacts) + self.assertEqual(store.history(PR)["provider_origins"], original_history["provider_origins"]) + + def test_review_stop_audit_keeps_recovered_terminal_ambiguous_without_exact_public_association(self): + for association in ("missing", "conflicting"): + with self.subTest(association=association): + fixture, payload, run_id = self.recovered_run(resolved_threads=True) + _, status = self.finalize_recovered(fixture, run_id) + self.assertEqual(status, 0) + recovered_head = fixture.records.history(PR)["runs"][0]["source_head"] + pull = payload["data"]["repository"]["pullRequest"] + pull["headRefOid"] = recovered_head + pull["changedFiles"] = 1 + if association == "conflicting": + public_comment = self.github.comments[0] + conflicting_body = public_comment["body"].replace( + "", + "", + ) + pull["comments"]["nodes"].append( + { + "databaseId": public_comment["id"], + "body": conflicting_body, + "createdAt": public_comment["created_at"], + "updatedAt": public_comment["updated_at"], + "author": {"login": public_comment["user"]["login"]}, + } + ) + + audit = self.recovered_stop_audit(fixture, payload) + self.assertEqual(audit["recovered_terminal_responses"], []) + self.assertEqual(len(audit["ambiguous_terminal_responses"]), 1) + self.assertEqual(audit["ambiguous_terminal_responses"][0]["trigger_id"], 10) + self.assertEqual(audit["ambiguous_terminal_responses"][0]["response_id"], 11) + self.assertEqual(audit["active_reservations"], ["ambiguous"]) + self.assertIn("unattributed trigger response", audit["ambiguous_responses"]) + + def test_recovered_public_checkpoint_without_exact_durable_association_is_not_attributed(self): + fixture, payload, run_id = self.recovered_run() + _, status = self.finalize_recovered(fixture, run_id) + self.assertEqual(status, 0) + public_comment = self.github.comments[0] + pull = payload["data"]["repository"]["pullRequest"] + recovered_head = fixture.records.history(PR)["runs"][0]["source_head"] + pull["headRefOid"] = recovered_head + pull["changedFiles"] = 1 + pull["comments"]["nodes"].append( + { + "databaseId": public_comment["id"], + "body": public_comment["body"], + "createdAt": public_comment["created_at"], + "updatedAt": public_comment["updated_at"], + "author": {"login": public_comment["user"]["login"]}, + } + ) + original_state = fixture.records.checkpoint_publication_state(run_id) + observer = runtime.LiveEvidence(REPO, None, records=fixture.records) + observer.prefetch_payload(PR, payload) + current_record = runtime.hosted.load_trigger_reservation(fixture.recovery_record_path, REPO, PR) + current_state = runtime.hosted.trigger_state( + REPO, PR, payload, current_record, fixture.recovery_record_path + ) + ambiguous_current_state = dataclasses.replace( + current_state, + state="ambiguous", + terminal=True, + attributed=False, + response_id=11, + reason="the retained current trigger remains terminally ambiguous", + ) + with ( + patch.object( + fixture.records, + "checkpoint_publication_state", + return_value={**original_state, "events": []}, + ), + patch.object( + runtime.hosted, "current_trigger_record_paths", return_value=[fixture.recovery_record_path] + ), + patch.object(runtime.hosted, "trigger_state", return_value=ambiguous_current_state), + patch.object(observer, "_hosted_trigger_for_checkpoint") as legacy_attribution, + ): + history = observer.history(PR, "hosted") + legacy_attribution.assert_not_called() + self.assertFalse(any(item.get("comment_id") == public_comment["id"] for item in history)) + unresolved = next(item for item in history if item.get("checkpoint") == "trigger:10") + self.assertTrue(unresolved["terminal_ambiguous"]) + self.assertTrue(unresolved["held"]) + + observer_wrong_head = runtime.LiveEvidence(REPO, None, records=fixture.records) + observer_wrong_head.prefetch_payload(PR, payload) + wrong_head_state = dataclasses.replace(ambiguous_current_state, head_sha="b" * 40) + with ( + patch.object( + runtime.hosted, "current_trigger_record_paths", return_value=[fixture.recovery_record_path] + ), + patch.object(runtime.hosted, "trigger_state", return_value=wrong_head_state), + ): + conflicting_history = observer_wrong_head.history(PR, "hosted") + self.assertTrue(any(item.get("comment_id") == public_comment["id"] for item in conflicting_history)) + conflicting_trigger = next( + item for item in conflicting_history if item.get("checkpoint") == "trigger:10" + ) + self.assertTrue(conflicting_trigger["terminal_ambiguous"]) + + def test_recovered_matching_readback_and_uncertain_post_bind_without_reposting(self): + fixture, _, run_id = self.recovered_run() + body, _ = publication.checkpoint_body(fixture.records, repo=REPO, source_pr=PR, run_id=run_id) + self.github.uncertain = True + self.github.hide = True + with self.assertRaisesRegex(ReviewRecordsError, "retry read recovery later"): + publication.publish_checkpoint( + fixture.records, repo=REPO, source_pr=PR, run_id=run_id, adapter=self.github + ) + self.assertEqual(self.github.posts, 1) + self.assertEqual( + [event["type"] for event in fixture.records.checkpoint_publication_state(run_id)["events"]], + ["post_started", "post_outcome"], + ) + self.github.hide = False + self.github.uncertain = False + result = publication.publish_checkpoint( + fixture.records, repo=REPO, source_pr=PR, run_id=run_id, adapter=self.github + ) + self.assertEqual(result["status"], "reused") + self.assertEqual(result["body"], body) + self.assertEqual(self.github.posts, 1) + events = fixture.records.checkpoint_publication_state(run_id)["events"] + self.assertEqual([event["type"] for event in events], ["post_started", "post_outcome", "reused"]) + self.assertEqual(events[-1]["comment_id"], 789) + + def test_recovered_existing_matching_comment_is_durably_associated_on_first_readback(self): + fixture, _, run_id = self.recovered_run() + body, _ = publication.checkpoint_body(fixture.records, repo=REPO, source_pr=PR, run_id=run_id) + self.github.comments.append( + { + "id": 790, + "body": body, + "user": self.github.fetch_authenticated_user(), + "created_at": "2026-09-29T02:00:00Z", + "updated_at": "2026-09-29T02:00:00Z", + "issue_url": f"https://api.github.com/repos/{REPO}/issues/{PR}", + "html_url": f"https://github.com/{REPO}/pull/{PR}#issuecomment-790", + } + ) + result = publication.publish_checkpoint( + fixture.records, repo=REPO, source_pr=PR, run_id=run_id, adapter=self.github + ) + self.assertEqual(result["status"], "reused") + self.assertEqual(self.github.posts, 0) + state = fixture.records.checkpoint_publication_state(run_id) + self.assertEqual([event["type"] for event in state["events"]], ["reused"]) + self.assertEqual(state["events"][0]["comment_id"], 790) + + def test_generic_import_and_changed_recovery_proofs_cannot_publish(self): + self.store.import_completed_run( + run_id="imported-hosted-zero", + source_pr=PR, + channel="hosted", + findings=(), + source_decisions=(), + source_head=HEAD, + started_at="2026-09-29T01:00:00Z", + finished_at="2026-09-29T01:01:00Z", + finalized_at="2026-09-29T01:01:00Z", + ) + with self.assertRaises(ReviewRecordsError): + publication.checkpoint_body(self.store, repo=REPO, source_pr=PR, run_id="imported-hosted-zero") + + mutations = ("origin", "head", "counts", "archive", "time", "files") + for mutation in mutations: + with self.subTest(mutation=mutation): + fixture, _, run_id = self.recovered_run() + store = fixture.records + if mutation in {"origin", "head", "counts"}: + original = store.history + + def changed_history(pr, _original=original, _run_id=run_id, _mutation=mutation, **kwargs): + value = _original(pr, **kwargs) + target = next(item for item in value["runs"] if item["run_id"] == _run_id) + if _mutation == "origin": + value["provider_origins"][0]["provider_id"] = "review:11" + elif _mutation == "head": + target["source_head"] = "b" * 40 + else: + target["counts"] = {"found": 1, "accepted": 0, "routed": 0} + return value + + with ( + patch.object(store, "history", side_effect=changed_history), + self.assertRaises(ReviewRecordsError), + ): + publication.checkpoint_body(store, repo=REPO, source_pr=PR, run_id=run_id) + elif mutation == "archive": + original = store.imported_run_artifacts + + def changed_archive(selected_run_id, _original=original): + value = _original(selected_run_id) + damaged = json.loads(value["metadata"]["content"]) + damaged["head_sha"] = "b" * 40 + value["metadata"]["content"] = json.dumps(damaged, sort_keys=True) + return value + + with ( + patch.object(store, "imported_run_artifacts", side_effect=changed_archive), + self.assertRaises(ReviewRecordsError), + ): + publication.checkpoint_body(store, repo=REPO, source_pr=PR, run_id=run_id) + elif mutation == "time": + original = store.history + + def changed_time(pr, _original=original, **kwargs): + value = _original(pr, **kwargs) + target = next( + item + for item in value["attempts"] + if item["attempt_id"] == "current-hosted-attempt" + ) + target["finished_at"] = "2026-09-23T00:02:07Z" + return value + + with ( + patch.object(store, "history", side_effect=changed_time), + self.assertRaises(ReviewRecordsError), + ): + publication.checkpoint_body(store, repo=REPO, source_pr=PR, run_id=run_id) + else: + original = store.attempt + + def changed_files(attempt_id, _original=original, **kwargs): + value = _original(attempt_id, **kwargs) + if attempt_id == "current-hosted-attempt": + value["metadata"]["reviewed_file_count"] = 0 + return value + + with ( + patch.object(store, "attempt", side_effect=changed_files), + self.assertRaises(ReviewRecordsError), + ): + publication.checkpoint_body(store, repo=REPO, source_pr=PR, run_id=run_id) + def test_cli_canonical_counts_markers_and_retry_keep_older_head(self): self.cli_run() result = self.publish() diff --git a/dev-tools/validation/test_pr_review_evidence_hosted.py b/dev-tools/validation/test_pr_review_evidence_hosted.py index 5696ea0e2d..50fd1495a2 100644 --- a/dev-tools/validation/test_pr_review_evidence_hosted.py +++ b/dev-tools/validation/test_pr_review_evidence_hosted.py @@ -81,13 +81,22 @@ def trigger_record(head: str = HEAD): } -def archived_addressed_reply_fixture(common: Path, *, include_baseline: bool = True): +def archived_addressed_reply_fixture( + common: Path, + *, + include_baseline: bool = True, + singular_footer: bool = False, + current_attempt_metadata: dict | None = None, +): trigger_at = "2026-09-23T00:02:00Z" old_trigger_at = "2026-09-23T00:00:50Z" old_started_at = "2026-09-23T00:00:40Z" old_finished_at = "2026-09-23T00:01:15Z" old_body = "An archived CodeRabbit finding.\n\n" - addressed_body = f"{old_body}\n\n✅ Addressed in commits {'c' * 7} to {HEAD[:7]}" + footer = ( + f"✅ Addressed in commit {HEAD[:7]}" if singular_footer else f"✅ Addressed in commits {'c' * 7} to {HEAD[:7]}" + ) + addressed_body = f"{old_body}\n\n{footer}" inline = { "databaseId": 30, "author": {"login": "coderabbitai[bot]"}, @@ -169,7 +178,7 @@ def archived_addressed_reply_fixture(common: Path, *, include_baseline: bool = T channel="hosted", candidate_sha=HEAD, started_at="2026-09-23T00:01:50Z", - metadata={"repository": REPO}, + metadata={"repository": REPO, **(current_attempt_metadata or {})}, ) trigger = comment(10, "owner", hosted.FULL_COMMAND, trigger_at) @@ -2611,6 +2620,16 @@ def test_finished_reply_accepts_only_exact_archived_addressed_thread_updates(sel self.assertTrue(state.attributed) self.assertEqual(state.response_id, 11) + def test_finished_reply_accepts_exact_singular_addressed_commit_footer(self): + with tempfile.TemporaryDirectory() as directory: + payload, record, record_path = archived_addressed_reply_fixture(Path(directory), singular_footer=True) + + state = hosted.trigger_state(REPO, PR, payload, record, record_path) + + self.assertEqual(state.state, "completed") + self.assertTrue(state.attributed) + self.assertEqual(state.response_id, 11) + def test_runtime_zero_reply_proof_uses_custom_trigger_record_database(self): with tempfile.TemporaryDirectory() as directory: payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) @@ -2687,6 +2706,8 @@ def test_finished_reply_keeps_unproven_or_changed_thread_output_ambiguous(self): ("unknown baseline", False, None), ("modified archived body", True, "modified_body"), ("addressed range ends on another head", True, "mismatched_range"), + ("unknown footer", True, "unknown_footer"), + ("created at trigger boundary", True, "created_at_trigger"), ("new inline comment", True, "new_comment"), ("positive finding count", True, "positive_count"), ("incomplete coverage", True, "incomplete_coverage"), @@ -2706,6 +2727,12 @@ def test_finished_reply_keeps_unproven_or_changed_thread_output_ambiguous(self): ) elif mutation == "mismatched_range": thread_nodes[0]["body"] = thread_nodes[0]["body"].replace(f"to {HEAD[:7]}", f"to {BASE[:7]}") + elif mutation == "unknown_footer": + thread_nodes[0]["body"] = thread_nodes[0]["body"].replace( + f"to {HEAD[:7]}", f"to {HEAD[:7]} with additional notes" + ) + elif mutation == "created_at_trigger": + thread_nodes[0]["createdAt"] = "2026-09-23T00:02:00Z" elif mutation == "new_comment": thread_nodes.append( { diff --git a/dev-tools/validation/test_pr_review_runtime.py b/dev-tools/validation/test_pr_review_runtime.py index bbf2f22b2f..db8d58dd18 100644 --- a/dev-tools/validation/test_pr_review_runtime.py +++ b/dev-tools/validation/test_pr_review_runtime.py @@ -945,6 +945,7 @@ def test_archived_thread_history_wait_uses_remaining_hosted_budget(self) -> None archived = hosted._archived_completed_thread_bodies( "owner/repo", 42, + self._payload(), HEAD, 11, response_at, diff --git a/dev-tools/validation/test_pr_review_sqlite_records_cli.py b/dev-tools/validation/test_pr_review_sqlite_records_cli.py index d6c577afd2..5ead509f62 100644 --- a/dev-tools/validation/test_pr_review_sqlite_records_cli.py +++ b/dev-tools/validation/test_pr_review_sqlite_records_cli.py @@ -21,6 +21,81 @@ class ReviewRecordsCliTest(unittest.TestCase): + def test_repair_provider_response_selector_requires_exact_attempt_and_excludes_other_modes(self) -> None: + prefix = [ + "records", + "repair-provider", + "--pr", + "3249", + "--repo", + "owner/repo", + "--actor", + "operator", + "--scope", + "broad", + ] + parsed = cli._parser().parse_args( + [*prefix, "--response-id", "6278948453", "--attempt-id", "81a9fc04c0c04e08a427a1bf8185128d"] + ) + self.assertEqual(parsed.response_id, 6278948453) + self.assertEqual(parsed.attempt_id, "81a9fc04c0c04e08a427a1bf8185128d") + for invalid in ( + [*prefix, "--response-id", "6278948453"], + [*prefix, "--attempt-id", "81a9fc04c0c04e08a427a1bf8185128d"], + [*prefix, "--response-id", "6278948453", "--attempt-id", "attempt", "--all"], + [*prefix, "--response-id", "6278948453", "--attempt-id", "attempt", "--continue-on-error"], + ): + with self.subTest(arguments=invalid), self.assertRaises(SystemExit): + cli._parser().parse_args(invalid) + + def test_ambiguous_reply_recovery_fetches_and_repairs_under_hosted_request_lock(self) -> None: + database = self.temporary_directory.name + self.database = Path(database) / "firemud" / "pr-review-stack.sqlite3" + self.database.parent.mkdir(parents=True) + SqliteStateStore(self.database).update(lambda state: state) + SqliteReviewRecords(self.database).bootstrap() + lock_path = cli.hosted.default_trigger_record_path("owner/repo", 3249, self.database.parent.parent) + lock_path = lock_path.parent / "request.lock" + + def assert_locked(*_args): + descriptor = os.open(lock_path, os.O_RDWR) + try: + with self.assertRaises(BlockingIOError): + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + finally: + os.close(descriptor) + return {"data": {"repository": {"pullRequest": {"number": 3249}}}} + + with ( + patch.object(cli.github, "fetch_pull_request", side_effect=assert_locked) as fetch, + patch.object( + cli.sqlite_records_repair, + "repair_ambiguous_hosted_reply", + side_effect=lambda *args, **kwargs: (assert_locked(), {"status": "preview"})[1], + ) as repair, + ): + code, result = self.invoke( + "repair-provider", + "--pr", + "3249", + "--repo", + "owner/repo", + "--response-id", + "6278948453", + "--attempt-id", + "81a9fc04c0c04e08a427a1bf8185128d", + "--actor", + "operator", + "--scope", + "broad", + "--database", + str(self.database), + ) + self.assertEqual(code, 0, result) + self.assertEqual(result["result"]["status"], "preview") + fetch.assert_called_once_with("owner/repo", 3249) + repair.assert_called_once() + def test_records_source_resolve_requires_a_full_commit_sha(self) -> None: prefix = [ "records", diff --git a/dev-tools/validation/test_pr_review_sqlite_records_repair.py b/dev-tools/validation/test_pr_review_sqlite_records_repair.py index 77e16dad22..67e6c96d80 100644 --- a/dev-tools/validation/test_pr_review_sqlite_records_repair.py +++ b/dev-tools/validation/test_pr_review_sqlite_records_repair.py @@ -19,6 +19,7 @@ cli, evidence, hosted, + runtime, sqlite_hosted_capture, sqlite_provider_imports, sqlite_records_repair, @@ -64,13 +65,15 @@ def checkpoint( counts += f" / {routed} routed" heading = f"{channel}: {counts} · {HEAD[:12]} · 1 files" comments, unparsed = evidence.parse_checkpoint_comments( - [{ - "id": comment_id, - "body": heading + "\n" + marker, - "created_at": "2026-09-27T12:00:00Z", - "updated_at": updated_at, - "author_login": author_login, - }] + [ + { + "id": comment_id, + "body": heading + "\n" + marker, + "created_at": "2026-09-27T12:00:00Z", + "updated_at": updated_at, + "author_login": author_login, + } + ] ) if unparsed or len(comments) != 1: raise AssertionError("fixture checkpoint did not parse canonically") @@ -121,8 +124,7 @@ def cli_capture( capture_dir = self.common / "coderabbit-review-logs" / run_id capture_dir.mkdir(parents=True) legacy_metadata = ( - f"run_id={run_id}\nrepository={REPO}\npull_request={PR}\n" - f"candidate_sha={HEAD}\ncandidate_files=1\n" + f"run_id={run_id}\nrepository={REPO}\npull_request={PR}\ncandidate_sha={HEAD}\ncandidate_files=1\n" ) metadata = { "run_id": run_id, @@ -155,53 +157,366 @@ def late_reply_checkpoint(self, *, state="ambiguous", candidate=None, repository payload["data"]["repository"]["pullRequest"]["number"] = fixtures.PR payload["data"]["repository"]["pullRequest"]["reviewThreads"]["nodes"] = [] record["anchor"] = { - "child_head": fixtures.HEAD, "parent_identity": "develop", - "parent_head": fixtures.BASE, "merge_base": fixtures.BASE, "patch_id": "archived-patch", + "child_head": fixtures.HEAD, + "parent_identity": "develop", + "parent_head": fixtures.BASE, + "merge_base": fixtures.BASE, + "patch_id": "archived-patch", } record["sqlite_attempt_id"] = "late-reply" record_path.write_text(json.dumps(record), encoding="utf-8") self.records.start_attempt( - attempt_id="late-reply", source_pr=fixtures.PR, channel="hosted", - candidate_sha=candidate or fixtures.HEAD, started_at=record["trigger"]["created_at"], + attempt_id="late-reply", + source_pr=fixtures.PR, + channel="hosted", + candidate_sha=candidate or fixtures.HEAD, + started_at=record["trigger"]["created_at"], metadata={"repository": repository}, ) if state != "started": self.records.finish_attempt( - "late-reply", state=state, finished_at="2026-09-23T00:02:10Z", - trigger_id=trigger_id, provider_review_id="11", + "late-reply", + state=state, + finished_at="2026-09-23T00:02:10Z", + trigger_id=trigger_id, + provider_review_id="11", diagnostic="initial reply has no completion proof", artifacts={"metadata": '{"initial": "immutable observation"}'}, ) - body = (f"Hosted: 0 found / 0 accepted / 0 routed · {fixtures.HEAD} · 1 files\n" - "") + body = ( + f"Hosted: 0 found / 0 accepted / 0 routed · {fixtures.HEAD} · 1 files\n" + ) at = "2026-09-23T00:03:00Z" payload["data"]["repository"]["pullRequest"]["comments"]["nodes"].append( fixtures.comment(40, "owner", body, at) ) - checkpoint = evidence.parse_checkpoint_comments([{ - "id": 40, "body": body, "created_at": at, "updated_at": at, "author_login": "owner", - }])[0][0] + checkpoint = evidence.parse_checkpoint_comments( + [ + { + "id": 40, + "body": body, + "created_at": at, + "updated_at": at, + "author_login": "owner", + } + ] + )[0][0] return payload, checkpoint + def ambiguous_reply_recovery_fixture(self, *, singular_footer=True): + import test_pr_review_evidence_hosted as fixtures + + anchor = { + "child_head": fixtures.HEAD, + "parent_identity": "develop", + "parent_head": fixtures.BASE, + "merge_base": fixtures.BASE, + "patch_id": "a" * 64, + "pr": fixtures.PR, + } + payload, record, record_path = fixtures.archived_addressed_reply_fixture( + self.common, + singular_footer=singular_footer, + current_attempt_metadata={ + "request_kind": "full", + "actual_base_ref": "develop", + "actual_base_sha": fixtures.BASE, + "anchor": anchor, + "reviewed_file_count": 1, + }, + ) + self.database = self.common / "firemud" / "pr-review-stack.sqlite3" + self.records = SqliteReviewRecords(self.database) + pull = payload["data"]["repository"]["pullRequest"] + pull["number"] = fixtures.PR + trigger = next(item for item in pull["comments"]["nodes"] if item["databaseId"] == 10) + response = next(item for item in pull["comments"]["nodes"] if item["databaseId"] == 11) + record.update( + { + "repository": REPO, + "pr_number": PR, + "head_sha": fixtures.HEAD, + "anchor": anchor, + "sqlite_attempt_id": "current-hosted-attempt", + } + ) + initial_response = dict(response) + initial_comments = {"comments": [trigger, initial_response], "review_threads": []} + capture = { + "state": "ambiguous", + "terminal": True, + "attributable": False, + "repository": REPO, + "pull_request": PR, + "head_sha": fixtures.HEAD, + "trigger_id": 10, + "response_id": 11, + "observed_at": "2026-09-23T00:02:08Z", + "trigger_record": record, + } + self.records.finish_attempt( + "current-hosted-attempt", + state="ambiguous", + finished_at="2026-09-23T00:02:08Z", + duration_seconds=18, + trigger_id="10", + provider_review_id="11", + diagnostic="terminal response was initially ambiguous", + artifacts={ + "hosted_review": "[]", + "hosted_comments": json.dumps(initial_comments), + "metadata": json.dumps(capture), + }, + ) + return payload, record, record_path + + def recover_ambiguous_reply(self, payload, *, dry_run=True): + return sqlite_records_repair.repair_ambiguous_hosted_reply( + self.records, + repo=REPO, + pr_number=PR, + attempt_id="current-hosted-attempt", + response_id=11, + actor="operator", + scope="broad", + hosted_payload=payload, + dry_run=dry_run, + ) + + def test_ambiguous_reply_recovery_previews_then_replays_exact_zero_source_once(self): + payload, _, _ = self.ambiguous_reply_recovery_fixture() + before = self.records.history(PR) + original_attempt_artifacts = self.records.attempt_artifacts("current-hosted-attempt") + archived_h5 = self.records.attempt_artifacts("old-hosted-attempt") + + preview = self.recover_ambiguous_reply(payload) + + self.assertEqual(preview["status"], "preview") + self.assertEqual( + preview["items"][0]["stages"], + [ + "completed_zero_run", + "archived_artifacts", + "provider_origin_last", + ], + ) + self.assertEqual(self.records.history(PR), before) + result = self.recover_ambiguous_reply(payload, dry_run=False) + after = self.records.history(PR) + replay = self.recover_ambiguous_reply(payload, dry_run=False) + + self.assertEqual(result["status"], "complete") + self.assertEqual(replay["items"][0]["action"], "already_recovered") + imported = self.records.imported_run_artifacts(preview["items"][0]["run_id"]) + self.assertEqual(set(imported), {"hosted_comments", "hosted_review", "metadata"}) + for artifact in imported.values(): + self.assertEqual(artifact["redactions"], 0) + self.assertEqual( + artifact["source_sha256"], hashlib.sha256(artifact["content"].encode("utf-8")).hexdigest() + ) + self.assertEqual(len(after["runs"]), 1) + self.assertEqual(after["runs"][0]["run_id"], preview["items"][0]["run_id"]) + self.assertEqual(after["runs"][0]["counts"], {"found": 0, "accepted": 0, "routed": 0}) + self.assertEqual(after["runs"][0]["finished_at"], "2026-09-23T00:02:20Z") + self.assertEqual(after["runs"][0]["duration_seconds"], preview["items"][0]["duration_seconds"]) + self.assertEqual(after["runs"][0]["duration_seconds"], 20) + self.assertEqual(len(after["provider_origins"]), 1) + self.assertEqual(after["provider_origins"][0]["provider_id"], "trigger:10") + self.assertEqual( + {item["kind"] for item in after["imported_artifacts"]}, + { + "hosted_comments", + "hosted_review", + "metadata", + }, + ) + attempt = next(item for item in after["attempts"] if item["attempt_id"] == "current-hosted-attempt") + self.assertEqual(attempt["state"], "ambiguous") + self.assertIsNone(attempt["run_id"]) + self.assertEqual(self.records.attempt_artifacts("current-hosted-attempt"), original_attempt_artifacts) + self.assertEqual(self.records.attempt_artifacts("old-hosted-attempt"), archived_h5) + + def test_ambiguous_reply_partial_stages_are_not_sync_visible_and_retry_finishes(self): + payload, _, _ = self.ambiguous_reply_recovery_fixture() + attempt = next( + item for item in self.records.history(PR)["attempts"] if item["attempt_id"] == "current-hosted-attempt" + ) + with patch.object(self.records, "archive_imported_artifacts", side_effect=ReviewRecordsError("interrupted")): + partial = self.recover_ambiguous_reply(payload, dry_run=False) + self.assertEqual(partial["status"], "partial") + history = self.records.history(PR) + self.assertEqual(len(history["runs"]), 1) + self.assertEqual(history["provider_origins"], []) + self.assertEqual(history["imported_artifacts"], []) + self.assertIsNone(sqlite_hosted_capture._linked_ambiguous_reply_recovery(history, REPO, PR, attempt, "10")) + self.assertEqual(self.records.attempt("current-hosted-attempt")["state"], "ambiguous") + + with patch.object(self.records, "link_provider_origin", side_effect=ReviewRecordsError("interrupted")): + partial = self.recover_ambiguous_reply(payload, dry_run=False) + self.assertEqual(partial["status"], "partial") + history = self.records.history(PR) + self.assertEqual(len(history["imported_artifacts"]), 3) + self.assertEqual(history["provider_origins"], []) + self.assertIsNone(sqlite_hosted_capture._linked_ambiguous_reply_recovery(history, REPO, PR, attempt, "10")) + + recovered = self.recover_ambiguous_reply(payload, dry_run=False) + self.assertEqual(recovered["status"], "complete") + self.assertIsNotNone( + sqlite_hosted_capture._linked_ambiguous_reply_recovery(self.records.history(PR), REPO, PR, attempt, "10") + ) + + def test_ambiguous_reply_recovery_rejects_changed_unknown_or_conflicting_evidence(self): + cases = ( + "unknown_reply_text", + "wrapper_with_substantive_suffix", + "wrong_footer_head", + "unknown_footer", + "missing_response_update", + "changed_response_creation", + "changed_response_update", + "new_substantive_thread", + "incomplete_history", + "changed_original_body", + "conflicting_response", + ) + for mutation in cases: + with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as directory: + self.common = Path(directory) + self.database = self.common / "controller.sqlite3" + sqlite_store.SqliteStateStore(self.database).update(lambda state: state) + self.records = SqliteReviewRecords(self.database) + self.records.bootstrap() + payload, _, _ = self.ambiguous_reply_recovery_fixture() + pull = payload["data"]["repository"]["pullRequest"] + response = next(item for item in pull["comments"]["nodes"] if item["databaseId"] == 11) + if mutation == "unknown_reply_text": + response["body"] += "\nAdditional review findings were identified." + elif mutation == "wrapper_with_substantive_suffix": + response["body"] += "\nA critical finding remains unresolved." + elif mutation == "wrong_footer_head": + inline = pull["reviewThreads"]["nodes"][0]["comments"]["nodes"][0] + inline["body"] = inline["body"].rsplit("Addressed in commit ", 1)[0] + "Addressed in commit 0123456" + elif mutation == "unknown_footer": + inline = pull["reviewThreads"]["nodes"][0]["comments"]["nodes"][0] + inline["body"] = inline["body"].rsplit("Addressed in commit ", 1)[0] + "Resolved in commit abcdef0" + elif mutation == "missing_response_update": + response["updatedAt"] = None + elif mutation == "changed_response_creation": + response["createdAt"] = "2026-09-23T00:02:09Z" + elif mutation == "changed_response_update": + response["updatedAt"] = "2026-09-23T00:02:19Z" + elif mutation == "new_substantive_thread": + pull["reviewThreads"]["nodes"].append( + { + "comments": { + "nodes": [ + { + "databaseId": 99, + "author": {"login": "coderabbitai[bot]"}, + "body": "A new actionable finding.", + "createdAt": "2026-09-23T00:02:16Z", + "updatedAt": "2026-09-23T00:02:16Z", + } + ] + } + } + ) + elif mutation == "incomplete_history": + pull["reviews"] = {"nodes": [], "pageInfo": {"hasNextPage": True}} + elif mutation == "changed_original_body": + inline = pull["reviewThreads"]["nodes"][0]["comments"]["nodes"][0] + inline["body"] = inline["body"].replace("An archived CodeRabbit finding.", "Changed finding.") + elif mutation == "conflicting_response": + pull["reviews"]["nodes"].append( + { + "databaseId": 11, + "author": {"login": "coderabbitai[bot]"}, + "state": "COMMENTED", + "submittedAt": "2026-09-23T00:02:20Z", + "commit": {"oid": HEAD}, + "body": " finding", + } + ) + before = self.records.history(PR) + with self.assertRaises(SqliteRecordsRepairError): + self.recover_ambiguous_reply(payload, dry_run=False) + self.assertEqual(self.records.history(PR), before) + + def test_ambiguous_reply_recovery_does_not_relax_normal_held_observation(self): + _, _, _ = self.ambiguous_reply_recovery_fixture() + held = sqlite_hosted_capture._linked_ambiguous_reply_recovery( + self.records.history(PR), + REPO, + PR, + next( + item for item in self.records.history(PR)["attempts"] if item["attempt_id"] == "current-hosted-attempt" + ), + "10", + ) + self.assertIsNone(held) + observation = runtime.LiveEvidence._uncheckpointed_hosted_observation( + PR, + hosted.TriggerState( + "completed", + True, + True, + REPO, + PR, + HEAD, + HEAD, + 10, + "2026-09-23T00:02:00Z", + "https://example.test/comments/10", + "full", + 11, + "2026-09-23T00:02:08Z", + "https://example.test/comments/11", + None, + "", + duration_seconds=18, + ), + ) + self.assertTrue(observation["held"]) + self.assertNotIn("completed", observation) + self.assertNotIn("attributable", observation) + self.assertEqual(self.records.history(PR)["runs"], []) + def test_late_verified_reply_preserves_ambiguous_attempt_and_appends_exact_source(self): payload, checkpoint = self.late_reply_checkpoint() before = self.records.history(PR) artifacts = self.records.attempt_artifacts("late-reply") with patch.object(hosted, "_git_common_dir", return_value=self.common): preview = repair_provider_checkpoints( - self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], actor="operator", - common=self.common, hosted_payload=payload, + self.records, + repo=REPO, + pr_number=PR, + checkpoints=[checkpoint], + actor="operator", + common=self.common, + hosted_payload=payload, ) self.assertEqual(preview["status"], "preview") self.assertEqual(self.records.history(PR), before) result = repair_provider_checkpoints( - self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], actor="operator", - common=self.common, hosted_payload=payload, dry_run=False, + self.records, + repo=REPO, + pr_number=PR, + checkpoints=[checkpoint], + actor="operator", + common=self.common, + hosted_payload=payload, + dry_run=False, ) after = self.records.history(PR) replay = repair_provider_checkpoints( - self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], actor="operator", - common=self.common, hosted_payload=payload, dry_run=False, + self.records, + repo=REPO, + pr_number=PR, + checkpoints=[checkpoint], + actor="operator", + common=self.common, + hosted_payload=payload, + dry_run=False, ) self.assertEqual(result["status"], "complete") self.assertEqual(replay["status"], "complete") @@ -215,7 +530,8 @@ def test_late_verified_reply_preserves_ambiguous_attempt_and_appends_exact_sourc def test_late_reply_retains_hold_when_provider_reply_is_still_active(self): payload, checkpoint = self.late_reply_checkpoint() response = next( - item for item in payload["data"]["repository"]["pullRequest"]["comments"]["nodes"] + item + for item in payload["data"]["repository"]["pullRequest"]["comments"]["nodes"] if item.get("databaseId") == 11 ) response["body"] = "Reviewing your changes, please wait." @@ -225,8 +541,14 @@ def test_late_reply_retains_hold_when_provider_reply_is_still_active(self): self.assertRaises(SqliteRecordsRepairError), ): repair_provider_checkpoints( - self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], actor="operator", - common=self.common, hosted_payload=payload, dry_run=False, + self.records, + repo=REPO, + pr_number=PR, + checkpoints=[checkpoint], + actor="operator", + common=self.common, + hosted_payload=payload, + dry_run=False, ) self.assertEqual(self.records.history(PR), before) @@ -245,8 +567,14 @@ def test_late_reply_rejects_wrong_immutable_attempt_identity(self): self.assertRaisesRegex(SqliteRecordsRepairError, "immutable ambiguous attempt"), ): repair_provider_checkpoints( - self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], - actor="operator", common=self.common, hosted_payload=payload, dry_run=False, + self.records, + repo=REPO, + pr_number=PR, + checkpoints=[checkpoint], + actor="operator", + common=self.common, + hosted_payload=payload, + dry_run=False, ) self.assertEqual(self.records.history(PR), before) @@ -311,22 +639,37 @@ def imported_resolution_fixture(self, channel: str) -> tuple[evidence.Checkpoint # A real immutable comment author was omitted by the older as_json archive. checkpoint = dataclasses.replace(checkpoint, author_login="checkpoint-owner") report = repair_provider_checkpoints( - self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], - actor="backfill-reviewer", common=self.common, dry_run=False, + self.records, + repo=REPO, + pr_number=PR, + checkpoints=[checkpoint], + actor="backfill-reviewer", + common=self.common, + dry_run=False, ) return checkpoint, report["items"][0]["run_id"] def resolution_status(self, checkpoint: evidence.Checkpoint, run_id: str, channel: str) -> str | None: return self.records.source_resolution_status( - run_id, source_pr=PR, source_channel=channel, source_head=HEAD, - accepted_count=1, source_checkpoint=checkpoint, source_repository=REPO, + run_id, + source_pr=PR, + source_channel=channel, + source_head=HEAD, + accepted_count=1, + source_checkpoint=checkpoint, + source_repository=REPO, ) def resolve_imported_finding(self, run_id: str) -> None: key = self.records.history(PR)["findings"][0]["source_finding_key"] self.records.record_source_resolution( - run_id, key, source_pr=PR, resolution_id="resolution.imported", - fix_sha="d" * 40, actor="fix-owner", proof_note="focused regression passed", + run_id, + key, + source_pr=PR, + resolution_id="resolution.imported", + fix_sha="d" * 40, + actor="fix-owner", + proof_note="focused regression passed", ) def test_imported_cli_exact_origin_honors_unresolved_and_resolved_source(self) -> None: @@ -341,9 +684,12 @@ def test_imported_cli_exact_origin_honors_unresolved_and_resolved_source(self) - self.resolve_imported_finding(imported_id) self.assertEqual(self.resolution_status(checkpoint, checkpoint.run_id, "cli"), "resolved") from pr_review.runtime import LiveEvidence, LiveGitHub + live = LiveEvidence(REPO, LiveGitHub(REPO), records=self.records) self.assertEqual(live._source_resolution_status(PR, "cli", checkpoint, HEAD), "resolved") - self.assertEqual(self.resolution_status(dataclasses.replace(checkpoint, comment_id=11), checkpoint.run_id, "cli"), "pending") + self.assertEqual( + self.resolution_status(dataclasses.replace(checkpoint, comment_id=11), checkpoint.run_id, "cli"), "pending" + ) def test_older_import_archive_replays_without_changing_immutable_bytes(self) -> None: checkpoint, imported_id = self.imported_resolution_fixture("cli") @@ -358,14 +704,26 @@ def test_older_import_archive_replays_without_changing_immutable_bytes(self) -> "UPDATE imported_artifacts SET content = ?, source_sha256 = ? WHERE run_id = ? AND kind = 'metadata'", (old_content, hashlib.sha256(old_content.encode()).hexdigest(), imported_id), ) - before = connection.execute("SELECT * FROM imported_artifacts WHERE run_id = ? ORDER BY kind", (imported_id,)).fetchall() + before = connection.execute( + "SELECT * FROM imported_artifacts WHERE run_id = ? ORDER BY kind", (imported_id,) + ).fetchall() replay = repair_provider_checkpoints( - self.records, repo=REPO, pr_number=PR, checkpoints=[checkpoint], - actor="backfill-reviewer", common=self.common, dry_run=False, + self.records, + repo=REPO, + pr_number=PR, + checkpoints=[checkpoint], + actor="backfill-reviewer", + common=self.common, + dry_run=False, ) self.assertEqual(replay["items"][0]["action"], "already_imported") with sqlite3.connect(self.database) as connection: - self.assertEqual(connection.execute("SELECT * FROM imported_artifacts WHERE run_id = ? ORDER BY kind", (imported_id,)).fetchall(), before) + self.assertEqual( + connection.execute( + "SELECT * FROM imported_artifacts WHERE run_id = ? ORDER BY kind", (imported_id,) + ).fetchall(), + before, + ) supplied = {row[1]: row[2] for row in before} metadata["checkpoint_fields"] = dataclasses.asdict(dataclasses.replace(checkpoint, author_login="wrong-owner")) supplied["metadata"] = json.dumps(metadata) @@ -377,47 +735,77 @@ def test_imported_source_checkpoint_binding_allows_only_semantically_neutral_edi self.resolve_imported_finding(imported_id) self.assertEqual(self.resolution_status(checkpoint, imported_id, "hosted"), "resolved") edited = dataclasses.replace(checkpoint, updated_at="2026-09-28T12:00:00Z") - parsed, unparsed = evidence.parse_checkpoint_comments([{ - "id": checkpoint.comment_id, - "created_at": checkpoint.created_at, - "updated_at": edited.updated_at, - "author": {"login": checkpoint.author_login}, - "body": f"Hosted: 1 found / 1 accepted / 0 routed · {HEAD[:12]} · 1 files\n\n\n", - }]) + parsed, unparsed = evidence.parse_checkpoint_comments( + [ + { + "id": checkpoint.comment_id, + "created_at": checkpoint.created_at, + "updated_at": edited.updated_at, + "author": {"login": checkpoint.author_login}, + "body": f"Hosted: 1 found / 1 accepted / 0 routed · {HEAD[:12]} · 1 files\n\n\n", + } + ] + ) self.assertEqual(unparsed, 0) self.assertEqual(self.resolution_status(parsed[0], imported_id, "hosted"), "resolved") for change in ({"raw_found": 2}, {"hosted_review_id": 701}, {"file_count": 2}, {"duration_seconds": 20}): with self.subTest(change=change): - self.assertEqual(self.resolution_status(dataclasses.replace(edited, **change), imported_id, "hosted"), "pending") + self.assertEqual( + self.resolution_status(dataclasses.replace(edited, **change), imported_id, "hosted"), "pending" + ) with sqlite3.connect(self.database) as connection: - row = connection.execute("SELECT content FROM imported_artifacts WHERE run_id = ? AND kind = 'metadata'", (imported_id,)).fetchone() + row = connection.execute( + "SELECT content FROM imported_artifacts WHERE run_id = ? AND kind = 'metadata'", (imported_id,) + ).fetchone() metadata = json.loads(row[0]) metadata.pop("checkpoint_fields") metadata["checkpoint"].pop("author_login", None) old_content = json.dumps(metadata) - connection.execute("UPDATE imported_artifacts SET content = ? WHERE run_id = ? AND kind = 'metadata'", (old_content, imported_id)) + connection.execute( + "UPDATE imported_artifacts SET content = ? WHERE run_id = ? AND kind = 'metadata'", + (old_content, imported_id), + ) self.assertEqual(self.resolution_status(edited, imported_id, "hosted"), "resolved") - self.assertEqual(self.resolution_status(dataclasses.replace(edited, author_login="different-owner"), imported_id, "hosted"), "pending") + self.assertEqual( + self.resolution_status(dataclasses.replace(edited, author_login="different-owner"), imported_id, "hosted"), + "pending", + ) metadata["checkpoint"]["raw_found"] = 2 with sqlite3.connect(self.database) as connection: - connection.execute("UPDATE imported_artifacts SET content = ? WHERE run_id = ? AND kind = 'metadata'", (json.dumps(metadata), imported_id)) + connection.execute( + "UPDATE imported_artifacts SET content = ? WHERE run_id = ? AND kind = 'metadata'", + (json.dumps(metadata), imported_id), + ) self.assertEqual(self.resolution_status(edited, imported_id, "hosted"), "pending") with sqlite3.connect(self.database) as connection: - connection.execute("UPDATE imported_artifacts SET content = ? WHERE run_id = ? AND kind = 'metadata'", (old_content, imported_id)) - connection.execute("UPDATE provider_origins SET checkpoint_fingerprint = ? WHERE run_id = ?", ("0" * 64, imported_id)) + connection.execute( + "UPDATE imported_artifacts SET content = ? WHERE run_id = ? AND kind = 'metadata'", + (old_content, imported_id), + ) + connection.execute( + "UPDATE provider_origins SET checkpoint_fingerprint = ? WHERE run_id = ?", ("0" * 64, imported_id) + ) self.assertEqual(self.resolution_status(edited, imported_id, "hosted"), "pending") def test_missing_old_capture_is_archived_as_gap_without_review_credit(self) -> None: checkpoint = self.checkpoint("CLI", "") preview = archive_incomplete_checkpoint( - self.records, repo=REPO, pr_number=PR, checkpoint=checkpoint, - missing_reason="original capture is unavailable", common=self.common, + self.records, + repo=REPO, + pr_number=PR, + checkpoint=checkpoint, + missing_reason="original capture is unavailable", + common=self.common, ) self.assertEqual(preview["status"], "incomplete_preview") self.assertEqual(self.records.history(PR)["historical_gaps"], []) applied = archive_incomplete_checkpoint( - self.records, repo=REPO, pr_number=PR, checkpoint=checkpoint, - missing_reason="original capture is unavailable", common=self.common, + self.records, + repo=REPO, + pr_number=PR, + checkpoint=checkpoint, + missing_reason="original capture is unavailable", + common=self.common, dry_run=False, ) self.assertEqual(applied["status"], "incomplete_archived") @@ -428,8 +816,12 @@ def test_missing_old_capture_is_archived_as_gap_without_review_credit(self) -> N self.assertEqual(history["historical_gaps"][0]["checkpoint_id"], checkpoint.comment_id) self.assertEqual(history["historical_gaps"][0]["missing_reason"], "original capture is unavailable") replay = archive_incomplete_checkpoint( - self.records, repo=REPO, pr_number=PR, checkpoint=checkpoint, - missing_reason="original capture is unavailable", common=self.common, + self.records, + repo=REPO, + pr_number=PR, + checkpoint=checkpoint, + missing_reason="original capture is unavailable", + common=self.common, dry_run=False, ) self.assertTrue(replay["idempotent_replay"]) @@ -454,9 +846,7 @@ def test_missing_capture_uses_explicit_missing_evidence_repair_error(self) -> No def test_failed_capture_archives_loader_diagnostic_without_review_credit(self) -> None: run_id = "run.Malformed" self.cli_capture(run_id) - (self.common / "coderabbit-review-logs" / run_id / "stdout").write_text( - "not-json\n", encoding="utf-8" - ) + (self.common / "coderabbit-review-logs" / run_id / "stdout").write_text("not-json\n", encoding="utf-8") checkpoint = self.checkpoint("CLI", f"") archived = archive_incomplete_checkpoint( @@ -487,8 +877,12 @@ def test_failed_capture_archives_loader_diagnostic_without_review_credit(self) - def test_historical_gap_rejects_a_changed_reason(self) -> None: checkpoint = self.checkpoint("CLI", "") archive_incomplete_checkpoint( - self.records, repo=REPO, pr_number=PR, checkpoint=checkpoint, - missing_reason="original capture is unavailable", common=self.common, + self.records, + repo=REPO, + pr_number=PR, + checkpoint=checkpoint, + missing_reason="original capture is unavailable", + common=self.common, dry_run=False, ) with self.assertRaisesRegex( @@ -496,8 +890,12 @@ def test_historical_gap_rejects_a_changed_reason(self) -> None: "^historical gap conflicts with existing checkpoint evidence$", ): archive_incomplete_checkpoint( - self.records, repo=REPO, pr_number=PR, checkpoint=checkpoint, - missing_reason="different claim", common=self.common, + self.records, + repo=REPO, + pr_number=PR, + checkpoint=checkpoint, + missing_reason="different claim", + common=self.common, dry_run=False, ) @@ -522,23 +920,17 @@ def test_preview_validates_both_channels_without_writing_live_database_or_captur self.assertEqual(report["status"], "preview") self.assertEqual([item["action"] for item in report["items"]], ["would_import", "would_import"]) self.assertEqual(report["items"][0]["artifact_kinds"], ["hosted_comments", "hosted_review", "metadata"]) - self.assertEqual( - report["items"][1]["artifact_kinds"], ["cli_diagnostic", "cli_events", "metadata"] - ) + self.assertEqual(report["items"][1]["artifact_kinds"], ["cli_diagnostic", "cli_events", "metadata"]) self.assertEqual(self.records.history(PR)["runs"], []) with sqlite3.connect(self.database) as connection: self.assertEqual(connection.execute("SELECT COUNT(*) FROM provider_origins").fetchone()[0], 0) self.assertEqual(connection.execute("SELECT COUNT(*) FROM imported_artifacts").fetchone()[0], 0) self.assertEqual((self.common / "firemud" / "hosted-review.700" / "snapshot.json").read_bytes(), hosted_bytes) for name, contents in cli_files.items(): - self.assertEqual( - (self.common / "coderabbit-review-logs" / "run.Repair1" / name).read_bytes(), contents - ) + self.assertEqual((self.common / "coderabbit-review-logs" / "run.Repair1" / name).read_bytes(), contents) def test_repair_requires_canonical_importer_archive_artifacts(self) -> None: - checkpoint = self.checkpoint( - "CLI", "", comment_id=12 - ) + checkpoint = self.checkpoint("CLI", "", comment_id=12) def import_without_archive(records: SqliteReviewRecords, **kwargs: object) -> dict[str, object]: checkpoint_arg = kwargs["checkpoint"] @@ -599,8 +991,7 @@ def test_apply_archives_capture_and_origin_then_replays_exactly(self) -> None: self.assertEqual(self.records.history(PR)["runs"][0]["counts"], {"found": 1, "accepted": 1, "routed": 0}) with sqlite3.connect(self.database) as connection: origin = connection.execute( - "SELECT repository, source_pr, channel, provider_id, checkpoint_id, run_id " - "FROM provider_origins" + "SELECT repository, source_pr, channel, provider_id, checkpoint_id, run_id FROM provider_origins" ).fetchone() artifacts = connection.execute( "SELECT kind, source_sha256 FROM imported_artifacts ORDER BY kind" @@ -612,12 +1003,8 @@ def test_apply_archives_capture_and_origin_then_replays_exactly(self) -> None: def test_apply_reports_partial_after_raw_database_failure_and_keeps_prior_item(self) -> None: self.cli_capture("run.Partial1") self.cli_capture("run.Partial2") - first = self.checkpoint( - "CLI", "", comment_id=14, accepted=0, routed=1 - ) - second = self.checkpoint( - "CLI", "", comment_id=15, accepted=0, routed=1 - ) + first = self.checkpoint("CLI", "", comment_id=14, accepted=0, routed=1) + second = self.checkpoint("CLI", "", comment_id=15, accepted=0, routed=1) original_import_one = sqlite_records_repair._import_one calls = 0 @@ -655,9 +1042,7 @@ def fail_on_second_apply(*args: object, **kwargs: object) -> tuple[dict[str, obj def test_apply_reports_actual_drifted_item_without_false_origin_or_archive(self) -> None: self.cli_capture("run.Drift1") - checkpoint = self.checkpoint( - "CLI", "", comment_id=16, accepted=0, routed=1 - ) + checkpoint = self.checkpoint("CLI", "", comment_id=16, accepted=0, routed=1) original_import_one = sqlite_records_repair._import_one calls = 0 @@ -681,7 +1066,9 @@ def mutate_after_preflight(*args: object, **kwargs: object) -> tuple[dict[str, o ) self.assertEqual(report["status"], "partial") - self.assertEqual(report["error"], "source evidence changed after preflight; exact imported run is retained for audit") + self.assertEqual( + report["error"], "source evidence changed after preflight; exact imported run is retained for audit" + ) self.assertEqual(len(report["items"]), 1) item = report["items"][0] self.assertEqual(item["action"], "drifted") @@ -756,9 +1143,7 @@ def test_replay_after_source_decision_correction_keeps_origin_and_current_counts def test_repair_links_exact_automatically_recorded_cli_attempt_without_duplicate(self) -> None: self.cli_capture() self.record_cli_attempt() - checkpoint = self.checkpoint( - "CLI", "", accepted=0, routed=1 - ) + checkpoint = self.checkpoint("CLI", "", accepted=0, routed=1) # The partial native archive cannot be used by ordinary SQL-first # reads, but explicit repair can recover it from the exact raw capture. @@ -782,9 +1167,7 @@ def test_repair_links_exact_automatically_recorded_cli_attempt_without_duplicate self.assertEqual([run["run_id"] for run in self.records.history(PR)["runs"]], ["run.Repair1"]) with sqlite3.connect(self.database) as connection: origin = connection.execute("SELECT provider_id, run_id FROM provider_origins").fetchone() - artifact_run_ids = connection.execute( - "SELECT DISTINCT run_id FROM imported_artifacts" - ).fetchall() + artifact_run_ids = connection.execute("SELECT DISTINCT run_id FROM imported_artifacts").fetchall() self.assertEqual(origin, ("run:run.Repair1", "run.Repair1")) self.assertEqual(artifact_run_ids, [("run.Repair1",)]) replay = repair_provider_checkpoints( @@ -962,8 +1345,7 @@ def _record_synced_hosted_attempt(self, *, capture_snapshot: bool) -> tuple[str, started_at=started_at, ) checkpoint_body = ( - f"Hosted: 1 found / 1 accepted / 0 routed · {HEAD[:12]} · 1 files\n" - "" + f"Hosted: 1 found / 1 accepted / 0 routed · {HEAD[:12]} · 1 files\n" ) payload = { "data": { @@ -979,10 +1361,7 @@ def _record_synced_hosted_attempt(self, *, capture_snapshot: bool) -> tuple[str, "body": hosted.FULL_COMMAND, "createdAt": "2026-09-27T11:58:00Z", "updatedAt": "2026-09-27T11:58:00Z", - "url": ( - f"https://github.example/{REPO}/pull/{PR}" - f"#issuecomment-{trigger_id}" - ), + "url": (f"https://github.example/{REPO}/pull/{PR}#issuecomment-{trigger_id}"), }, { "databaseId": 10, @@ -1070,8 +1449,7 @@ def _record_synced_hosted_reply_attempt(self) -> tuple[str, evidence.Checkpoint, response_updated = "2026-09-27T11:55:00Z" checkpoint_at = "2026-09-27T12:00:00Z" checkpoint_body = ( - f"Hosted: 0 found / 0 accepted / 0 routed · {HEAD[:12]} · 1 files\n" - "" + f"Hosted: 0 found / 0 accepted / 0 routed · {HEAD[:12]} · 1 files\n" ) trigger_comment = { "databaseId": trigger_id, @@ -1183,9 +1561,7 @@ def test_repair_links_exact_automatically_recorded_hosted_attempt_without_duplic self.assertEqual(report["status"], "complete") self.assertEqual(report["items"][0]["action"], "already_imported") self.assertEqual(report["items"][0]["run_id"], attempt_id) - self.assertEqual( - [run["run_id"] for run in self.records.history(PR)["runs"]], [attempt_id] - ) + self.assertEqual([run["run_id"] for run in self.records.history(PR)["runs"]], [attempt_id]) with sqlite3.connect(self.database) as connection: origin = connection.execute("SELECT provider_id, run_id FROM provider_origins").fetchone() self.assertEqual(origin, ("review:700", attempt_id)) @@ -1448,8 +1824,7 @@ def test_repair_links_retained_synced_hosted_attempt_without_private_snapshot(se def test_repair_refuses_retained_synced_hosted_checkpoint_count_mismatch(self) -> None: attempt_id, _, payload = self._record_synced_hosted_attempt(capture_snapshot=False) checkpoint_body = ( - f"Hosted: 2 found / 2 accepted / 0 routed · {HEAD[:12]} · 1 files\n" - "" + f"Hosted: 2 found / 2 accepted / 0 routed · {HEAD[:12]} · 1 files\n" ) comment = payload["data"]["repository"]["pullRequest"]["comments"]["nodes"][1] comment["body"] = checkpoint_body @@ -1519,9 +1894,7 @@ def test_repair_refuses_retained_synced_hosted_archive_with_wrong_review_head(se def test_repair_refuses_mismatched_automatic_attempt_without_duplicate_or_origin(self) -> None: self.cli_capture() self.record_cli_attempt(disposition="accepted") - checkpoint = self.checkpoint( - "CLI", "", accepted=0, routed=1 - ) + checkpoint = self.checkpoint("CLI", "", accepted=0, routed=1) with self.assertRaisesRegex( SqliteRecordsRepairError, @@ -1600,9 +1973,7 @@ def test_existing_run_decision_conflict_is_refused_without_live_mutation(self) - self.assertEqual(connection.execute("SELECT COUNT(*) FROM provider_origins").fetchone()[0], 0) def test_trigger_anchored_zero_result_uses_importer_proven_identity_without_review_object(self) -> None: - checkpoint = self.checkpoint( - "Hosted", "", comment_id=13, raw=0, accepted=0, routed=0 - ) + checkpoint = self.checkpoint("Hosted", "", comment_id=13, raw=0, accepted=0, routed=0) checkpoint = dataclasses.replace(checkpoint, reviewed_sha=HEAD) archive = { "hosted_comments": json.dumps([{"id": 999, "body": "Review complete: no findings"}]), @@ -1641,9 +2012,7 @@ def import_trigger(records: SqliteReviewRecords, **kwargs: object) -> dict[str, self.assertEqual(report["items"][0]["provider_id"], "trigger:999") self.assertEqual(self.records.history(PR)["runs"][0]["counts"], {"found": 0, "accepted": 0, "routed": 0}) with sqlite3.connect(self.database) as connection: - origin = connection.execute( - "SELECT provider_id, checkpoint_id FROM provider_origins" - ).fetchone() + origin = connection.execute("SELECT provider_id, checkpoint_id FROM provider_origins").fetchone() kinds = connection.execute("SELECT kind FROM imported_artifacts ORDER BY kind").fetchall() self.assertEqual(origin, ("trigger:999", 13)) self.assertEqual([row[0] for row in kinds], ["hosted_comments", "metadata"]) @@ -1651,15 +2020,32 @@ def import_trigger(records: SqliteReviewRecords, **kwargs: object) -> dict[str, def test_provider_import_rejects_empty_or_ambiguous_checkpoint_selection(self) -> None: records = type("FakeRecords", (), {"history": lambda self, pr: {"pr": pr}})() arguments = [ - "records", "import-provider", "--pr", str(PR), "--channel", "hosted", - "--checkpoint-id", "10", "--actor", "backfill-reviewer", "--scope", "broad", - "--repo", REPO, "--database", str(self.database), + "records", + "import-provider", + "--pr", + str(PR), + "--channel", + "hosted", + "--checkpoint-id", + "10", + "--actor", + "backfill-reviewer", + "--scope", + "broad", + "--repo", + REPO, + "--database", + str(self.database), ] with ( patch.object(cli, "_records_store", return_value=records), patch.object(cli.github, "infer_repo", return_value=REPO), patch.object(cli.sqlite_records_repair, "repair_provider_checkpoints") as importer, - patch.object(cli, "_provider_checkpoints", side_effect=[([], {"empty": True}), ([object(), object()], {"ambiguous": True})]), + patch.object( + cli, + "_provider_checkpoints", + side_effect=[([], {"empty": True}), ([object(), object()], {"ambiguous": True})], + ), ): for _ in range(2): errors = io.StringIO()