Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(plugin): make stopped result recovery explicit (#713)

soyeon-oai76a762386c8b
diff --git a/plugins/codex-security/mcp-app/package-lock.json b/plugins/codex-security/mcp-app/package-lock.json
index 3a7bbe2d8..1e1a067b8 100644
--- a/plugins/codex-security/mcp-app/package-lock.json
+++ b/plugins/codex-security/mcp-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "codex-security-mcp-app",
- "version": "0.1.157",
+ "version": "0.1.158",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "codex-security-mcp-app",
- "version": "0.1.157",
+ "version": "0.1.158",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@openai/codex-sdk": "0.149.1",
diff --git a/plugins/codex-security/mcp-app/package.json b/plugins/codex-security/mcp-app/package.json
index 58a373cfb..93bd853d7 100644
--- a/plugins/codex-security/mcp-app/package.json
+++ b/plugins/codex-security/mcp-app/package.json
@@ -1,6 +1,6 @@
{
"name": "codex-security-mcp-app",
- "version": "0.1.157",
+ "version": "0.1.158",
"type": "module",
"private": true,
"scripts": {
diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.ts
index 19ee2cb82..520f1a774 100644
--- a/plugins/codex-security/mcp-app/server.ts
+++ b/plugins/codex-security/mcp-app/server.ts
@@ -766,6 +766,17 @@ export function createCodexSecurityServer(): McpServer {
_meta: appMeta
}, async ({ scanId }) => cancelSecurityScan(scanId));
+ server.registerTool("recover_codex_security_scan_results", {
+ title: "Recover Codex Security Scan Results",
+ description: "App-only. Explicitly validate and republish retained checkpoints for one stopped scan, updating its artifacts, finding index, and counts.",
+ inputSchema: scanSchema,
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
+ _meta: appMeta
+ }, async ({ scanId }) => scanActionResult(
+ await runWorkbench(["recover-scan-results", "--scan-id", scanId]),
+ "Recovered retained Codex Security scan results."
+ ));
+
registerScanHandoffTools(server, { appMeta, runWorkbench, workspaceResult });
server.registerTool("get_codex_security_scan", {
@@ -786,7 +797,7 @@ export function createCodexSecurityServer(): McpServer {
server.registerTool("list_codex_security_scans", {
title: "List Codex Security Scans",
- description: "App-only. Read plugin-owned scan summaries for native Security navigation and route recovery.",
+ description: "App-only. Read persisted plugin-owned scan summaries for native Security navigation.",
inputSchema: scanListSchema,
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
_meta: appMeta
@@ -1633,6 +1644,8 @@ async function executeWorkbench(
"get-workspace",
"inspect-setup",
"list-findings",
+ "preserve-scan-results",
+ "recover-scan-results",
"request-finding-remediation",
"request-finding-remediation-action",
"save-workspace",
diff --git a/plugins/codex-security/mcp-app/src/types.ts b/plugins/codex-security/mcp-app/src/types.ts
index 574711eae..ad0ff5af5 100644
--- a/plugins/codex-security/mcp-app/src/types.ts
+++ b/plugins/codex-security/mcp-app/src/types.ts
@@ -32,6 +32,7 @@ export interface ScanResults {
progress?: JsonObject;
remediationAvailable?: boolean;
remediationUnavailableReason?: string;
+ resultsRecoveryNeeded: boolean;
scanDir: string;
scanId: string;
scope?: string;
diff --git a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.mjs b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.mjs
index 4f664dc98..7ba7927bc 100644
--- a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.mjs
+++ b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.mjs
@@ -1129,6 +1129,9 @@ try {
const getScan = toolList.result.tools.find(
(tool) => tool.name === "get_codex_security_scan",
);
+ const recoverScanResults = toolList.result.tools.find(
+ (tool) => tool.name === "recover_codex_security_scan_results",
+ );
const listScans = toolList.result.tools.find(
(tool) => tool.name === "list_codex_security_scans",
);
@@ -1551,6 +1554,10 @@ try {
]);
assert.equal(getScan.annotations.readOnlyHint, false);
assert.deepEqual(getScan._meta.ui.visibility, ["app"]);
+ assert.equal(recoverScanResults.annotations.readOnlyHint, false);
+ assert.equal(recoverScanResults.annotations.destructiveHint, true);
+ assert.equal(recoverScanResults.annotations.idempotentHint, true);
+ assert.deepEqual(recoverScanResults._meta.ui.visibility, ["app"]);
assert.equal(listScans.annotations.readOnlyHint, true);
assert.deepEqual(listScans._meta.ui.visibility, ["app"]);
assert.equal(listGlobalFindings.annotations.readOnlyHint, true);
@@ -3231,6 +3238,15 @@ try {
rotatedFailure.result.structuredContent.scan.progress.status,
"failed",
);
+ const unavailableRecovery = await requestAndWait(2040, "tools/call", {
+ name: "recover_codex_security_scan_results",
+ arguments: { scanId: fallbackScanId },
+ });
+ assert.equal(unavailableRecovery.result.isError, true);
+ assert.match(
+ unavailableRecovery.result.content[0].text,
+ /No saved stopped-scan results were available to recover/,
+ );
const silentRefresh = await requestAndWait(11, "tools/call", {
name: "open_codex_security_workspace",
diff --git a/plugins/codex-security/references/scan-contract.md b/plugins/codex-security/references/scan-contract.md
index 97f9efca0..f49de0975 100644
--- a/plugins/codex-security/references/scan-contract.md
+++ b/plugins/codex-security/references/scan-contract.md
@@ -37,6 +37,16 @@ A sealed manifest records the terminal timestamp and hashes for the canonical do
Only `completed` supports a completed-scan conclusion. For every stopped outcome, consumers must preserve retained findings and coverage while treating absence of findings as inconclusive.
+### Stopped Result Recovery
+
+To validate and republish retained checkpoints for a failed, non-canceled workbench scan, run:
+
+```text
+<python_command> <plugin_dir>/scripts/workbench_db.py recover-scan-results --scan-id <scan_id>
+```
+
+Recovery can add only checkpoints that pass the stopped-scan source-integrity checks. It is not available for running, completed, or canceled scans. After cancellation, the owning continuation may retry publication only from the source set frozen at cancellation through `preserve-scan-results`; it cannot admit later checkpoints.
+
## Target Snapshots
Choose the target kind based on the reviewed content, not the scan invocation:
diff --git a/plugins/codex-security/scripts/workbench_cli.py b/plugins/codex-security/scripts/workbench_cli.py
index e4ceb29d8..998a0c151 100644
--- a/plugins/codex-security/scripts/workbench_cli.py
+++ b/plugins/codex-security/scripts/workbench_cli.py
@@ -247,6 +247,16 @@ def parse_args(description: str) -> argparse.Namespace:
preserve_scan.add_argument("--claim-token")
preserve_scan.add_argument("--coordinator-generation", type=positive_int)
+ recovery_help = (
+ "Validate and republish retained checkpoints for a failed, non-canceled scan."
+ )
+ recover_scan = subparsers.add_parser(
+ "recover-scan-results", help=recovery_help, description=recovery_help
+ )
+ recover_scan.add_argument(
+ "--scan-id", required=True, help="ID of the stopped scan to recover."
+ )
+
write_scan_draft = subparsers.add_parser("write-scan-draft")
write_scan_draft.add_argument("--scan-id", required=True)
write_scan_draft.add_argument("--draft-path", required=True)
diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.py
index 219efcb6b..49591f96a 100644
--- a/plugins/codex-security/scripts/workbench_db.py
+++ b/plugins/codex-security/scripts/workbench_db.py
@@ -1861,20 +1861,10 @@ def preserve_scan_results_locked(connection: sqlite3.Connection, scan_id: str) -
return saved_results.preserve_scan_results_locked(_WORKBENCH_DB_CONTEXT, connection, scan_id)
-def refresh_stopped_scan_results(
- connection: sqlite3.Connection, scan_id: str, *, strict: bool = False
-) -> None:
- saved_results.refresh_stopped_scan_results(
- _WORKBENCH_DB_CONTEXT, connection, scan_id, strict=strict
- )
-
-
-def refresh_all_stopped_scan_results(connection: sqlite3.Connection) -> None:
- scan_ids = [
- row["id"] for row in connection.execute("SELECT id FROM scans WHERE status = 'failed'")
- ]
- for scan_id in scan_ids:
- refresh_stopped_scan_results(connection, scan_id)
+def recover_scan_results(
+ connection: sqlite3.Connection, args: argparse.Namespace
+) -> dict[str, Any]:
+ return saved_results.recover_scan_results(_WORKBENCH_DB_CONTEXT, connection, args)
def preserve_scan_results(
@@ -2733,7 +2723,6 @@ def record_linear_publications(
def export_findings(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:
- refresh_stopped_scan_results(connection, args.scan_id, strict=True)
scan = require_scan(connection, args.scan_id)
if scan["status"] != "complete" and not (
scan["status"] == "failed" and scan["seal_manifest_digest"]
@@ -3090,8 +3079,8 @@ def workspace_state(
workspace_id: str,
*,
result_scan_id: str | None = None,
+ result_scan: dict[str, Any] | None = None,
thread_id: str | None = None,
- refresh_stopped: bool = False,
) -> dict[str, Any]:
workspace = require_workspace(connection, workspace_id)
if thread_id is not None and workspace["thread_id"] != optional_text(thread_id, maximum=512):
@@ -3112,11 +3101,11 @@ def workspace_state(
}
selected_scan_id = result_scan_id or workspace["active_scan_id"]
if selected_scan_id:
- if refresh_stopped:
- refresh_stopped_scan_results(connection, selected_scan_id)
selected_scan = require_scan(connection, selected_scan_id)
result["userContext"] = selected_scan["user_context"]
- result["results"] = scan_result(connection, selected_scan)
+ result["results"] = (
+ result_scan if result_scan is not None else scan_result(connection, selected_scan)
+ )
return result
target_metadata = None
@@ -3158,14 +3147,17 @@ def scan_context(
occurrence_id: str | None = None,
) -> dict[str, Any]:
scan = require_scan(connection, scan_id)
- workspace = workspace_state(connection, scan["workspace_id"], result_scan_id=scan["id"])
+ result = scan_result(connection, scan, occurrence_id=occurrence_id)
+ workspace_result = result if occurrence_id is None else scan_result(connection, scan)
+ workspace = workspace_state(
+ connection,
+ scan["workspace_id"],
+ result_scan_id=scan["id"],
+ result_scan=workspace_result,
+ )
context = {
"otherRunningDeepScans": deep_scan.other_running_deep_scans(connection, scan["id"]),
- "scan": (
- workspace["results"]
- if occurrence_id is None
- else scan_result(connection, scan, occurrence_id=occurrence_id)
- ),
+ "scan": result,
"workspace": workspace,
}
if scan["recipe_json"] is not None:
@@ -3175,7 +3167,6 @@ def scan_context(
def list_findings(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[str, Any]:
- refresh_stopped_scan_results(connection, args.scan_id)
scan = require_scan(connection, args.scan_id)
backfill_legacy_finding_details(connection, scan)
limit = min(args.limit, FINDINGS_PAGE_MAX)
@@ -3318,6 +3309,9 @@ def scan_result(
"remediationAvailable": remediation_available,
"remediationUnavailableReason": remediation_unavailable_reason,
"reportAvailable": "markdownReport" in artifacts,
+ "resultsRecoveryNeeded": saved_results.scan_results_recovery_needed(
+ _WORKBENCH_DB_CONTEXT, connection, scan
+ ),
"scanDir": scan["scan_dir"],
"scanId": scan["id"],
"scope": scan["scope"],
@@ -3885,7 +3879,6 @@ def main() -> None:
connection,
args.workspace_id,
thread_id=args.thread_id,
- refresh_stopped=True,
)
elif args.command == "save-workspace":
result = save_workspace(connection, args)
@@ -3914,12 +3907,10 @@ def main() -> None:
elif args.command == "record-deep-scan-publication-failure":
result = deep_scan.record_deep_scan_publication_failure(connection, args)
elif args.command == "get-scan":
- refresh_stopped_scan_results(connection, args.scan_id)
result = scan_context(connection, args.scan_id, args.occurrence_id)
elif args.command == "get-scan-feedback":
result = get_scan_feedback(connection, require_scan(connection, args.scan_id))
elif args.command == "list-scans":
- refresh_all_stopped_scan_results(connection)
result = scan_history.list_scans(connection, args)
elif args.command == "list-unmatched-scan-pairs":
result = scan_history.list_unmatched_scan_pairs(
@@ -3953,10 +3944,8 @@ def main() -> None:
read_coverage=coverage_for_comparison,
)
elif args.command == "list-global-findings":
- refresh_all_stopped_scan_results(connection)
result = native_indexes.list_global_findings(connection, args)
elif args.command == "list-repositories":
- refresh_all_stopped_scan_results(connection)
result = native_indexes.list_repositories(connection, args)
elif args.command == "list-findings":
result = list_findings(connection, args)
@@ -3976,6 +3965,8 @@ def main() -> None:
result = fail_scan(connection, args)
elif args.command == "preserve-scan-results":
result = preserve_scan_results(connection, args)
+ elif args.command == "recover-scan-results":
+ result = recover_scan_results(connection, args)
elif args.command == "write-scan-draft":
result = write_scan_draft(connection, args)
elif args.command == "mark-handoff-delivered":
diff --git a/plugins/codex-security/scripts/workbench_saved_results.py b/plugins/codex-security/scripts/workbench_saved_results.py
index b28958971..d6c2f431a 100644
--- a/plugins/codex-security/scripts/workbench_saved_results.py
+++ b/plugins/codex-security/scripts/workbench_saved_results.py
@@ -98,6 +98,249 @@ def _children(scan_dir: Path, relative: str) -> list[str]:
return sorted(child.name for child in cursor.iterdir())
+def _latest_successful_reducer(workers: list[Any]) -> Any | None:
+ return max(
+ (
+ worker
+ for worker in workers
+ if worker["kind"] == "dedup"
+ and worker["status"] == "succeeded"
+ and worker["result_manifest_path"]
+ ),
+ key=lambda worker: (worker["completed_at"] or "", worker["id"]),
+ default=None,
+ )
+
+
+def _saved_result_paths(scan_dir: Path, workers: list[Any]) -> Iterator[str]:
+ latest_reducer = _latest_successful_reducer(workers)
+
+ def checkpoints(directory: str) -> Iterator[str]:
+ for name in _children(scan_dir, directory):
+ if re.fullmatch(r"[0-9a-f]{64}\.json", name):
+ yield f"{directory}/{name}"
+
+ yield from checkpoints("checkpoints")
+ for worker in workers:
+ if worker["kind"] not in {"dedup", "discovery"}:
+ continue
+ try:
+ output = Path(worker["artifact_dir"]).relative_to(scan_dir).as_posix()
+ except (TypeError, ValueError):
+ continue
+ attempts = (Path(output).parent if Path(output).name == "output" else Path(output)) / (
+ "attempts"
+ )
+ directories = [output] + [
+ (attempts / name).as_posix()
+ for name in _children(scan_dir, attempts.as_posix())
+ if re.fullmatch(r"attempt-\d+", name)
+ ]
+ for directory in directories:
+ checkpoint_paths = list(checkpoints(f"{directory}/checkpoints"))
+ if worker["kind"] == "discovery" or checkpoint_paths:
+ yield f"{directory}/result.json"
+ yield from checkpoint_paths
+ if worker["result_manifest_path"] and (
+ worker["kind"] == "discovery"
+ or (latest_reducer is not None and worker["id"] == latest_reducer["id"])
+ ):
+ try:
+ yield Path(worker["result_manifest_path"]).relative_to(scan_dir).as_posix()
+ except ValueError:
+ continue
+
+
+def _read_saved_result(scan_dir: Path, relative: str, scan_id: str) -> tuple[dict[str, Any], str]:
+ draft = _read_scan_local_json(scan_dir, relative, "Saved scan checkpoint")
+ if draft.get("scanId") != scan_id:
+ raise ContractError("checkpoint belongs to a different scan")
+ if not isinstance(draft.get("findings"), list) or not isinstance(draft.get("coverage"), dict):
+ raise ContractError("checkpoint has no semantic findings or coverage")
+ return draft, _digest(draft)
+
+
+def _read_saved_parent_result(
+ scan_dir: Path, scan_id: str
+) -> tuple[dict[str, Any], dict[str, Any]]:
+ manifest = _read_scan_local_json(scan_dir, "scan-manifest.json", "Saved parent manifest")
+ findings = _read_scan_local_json(scan_dir, "findings.json", "Saved parent findings")
+ coverage = _read_scan_local_json(scan_dir, "coverage.json", "Saved parent coverage")
+ parent_scan = manifest.get("scan")
+ if not isinstance(parent_scan, dict):
+ raise ContractError("Saved parent manifest has no scan object")
+ if (parent_scan.get("sealedAt") or parent_scan.get("artifacts")) and (
+ parent_scan.get("id", scan_id) != scan_id
+ or findings.get("scanId", scan_id) != scan_id
+ or coverage.get("scanId", scan_id) != scan_id
+ ):
+ raise ContractError("Saved parent documents belong to a different scan")
+ parent = {
+ "scanId": scan_id,
+ "findings": findings.get("findings"),
+ "coverage": coverage,
+ **{
+ key: parent_scan[key]
+ for key in ("scope", "threatModel", "complete")
+ if key in parent_scan
+ },
+ }
+ if not isinstance(parent["findings"], list):
+ raise ContractError("Saved parent draft has no findings array")
+ return manifest, parent
+
+
+def _source_digests(value: Any, label: str) -> dict[str, str]:
+ if not isinstance(value, dict) or not all(
+ isinstance(relative, str) and isinstance(digest, str) for relative, digest in value.items()
+ ):
+ raise ContractError(f"{label} source digests are malformed.")
+ return value
+
+
+def _saved_results_changed(db: Any, connection: Any, scan: Any) -> bool:
+ try:
+ scan_dir = db.require_canonical_scan_directory(Path(scan["scan_dir"]))
+ manifest_path = db.artifact_path(scan_dir, db.ARTIFACTS["manifest"], required=False)
+ workers = connection.execute(
+ "SELECT id, kind, status, completed_at, artifact_dir, result_manifest_path "
+ "FROM deep_scan_workers WHERE scan_id = ?",
+ (scan["id"],),
+ ).fetchall()
+ paths = set(_saved_result_paths(scan_dir, workers))
+ frozen_sources = scan["retained_source_digests_json"]
+
+ def has_saved_source() -> bool:
+ for path in paths:
+ try:
+ _read_saved_result(scan_dir, path, scan["id"])
+ return True
+ except (ContractError, OSError, ValueError):
+ continue
+ return False
+
+ if manifest_path is None:
+ if frozen_sources is not None:
+ return bool(_source_digests(json.loads(frozen_sources), "Frozen stopped-scan"))
+ return has_saved_source()
+ if scan["seal_manifest_digest"] is None:
+ try:
+ _read_saved_parent_result(scan_dir, scan["id"])
+ return True
+ except (ContractError, OSError, ValueError):
+ pass
+ return has_saved_source()
+ manifest = _read_scan_local_json(
+ scan_dir,
+ manifest_path.relative_to(scan_dir).as_posix(),
+ "Saved scan manifest",
+ )
+ manifest_scan = manifest.get("scan")
+ if not isinstance(manifest_scan, dict):
+ return True
+ published_sources = _source_digests(
+ manifest_scan.get("preservedSources", {}), "Published scan"
+ )
+ current_sources = dict(published_sources)
+ for path in paths:
+ try:
+ _, current_sources[path] = _read_saved_result(scan_dir, path, scan["id"])
+ except (ContractError, OSError, ValueError):
+ continue
+ return current_sources != published_sources
+ except (ContractError, OSError, SystemExit, ValueError):
+ return False
+
+
+def _recovery_source_digests(
+ db: Any, connection: Any, scan: Any
+) -> tuple[dict[str, str], bool]:
+ scan_dir = db.require_canonical_scan_directory(Path(scan["scan_dir"]))
+ frozen_sources: dict[str, str] | None = None
+ include_parent = True
+ raw_frozen_sources = scan["retained_source_digests_json"]
+ if raw_frozen_sources is not None:
+ frozen_sources = _source_digests(
+ json.loads(raw_frozen_sources), "Saved stopped-scan"
+ )
+ include_parent = False
+
+ manifest_path = db.artifact_path(scan_dir, db.ARTIFACTS["manifest"], required=False)
+ if manifest_path is not None:
+ manifest = _read_scan_local_json(
+ scan_dir,
+ manifest_path.relative_to(scan_dir).as_posix(),
+ "Saved scan manifest",
+ )
+ manifest_scan = manifest.get("scan")
+ if not isinstance(manifest_scan, dict):
+ raise ContractError("Saved scan manifest has no scan object")
+ if scan["seal_manifest_digest"] is not None or (
+ manifest_scan.get("sealedAt") is not None
+ or manifest_scan.get("artifacts") is not None
+ ):
+ if "preservedSources" in manifest_scan:
+ published_sources = _source_digests(
+ manifest_scan["preservedSources"], "Published scan"
+ )
+ include_parent = not published_sources
+ if published_sources:
+ if frozen_sources is not None and frozen_sources != published_sources:
+ raise ContractError(
+ "Stopped scan sources changed after terminal publication."
+ )
+ frozen_sources = published_sources
+ elif frozen_sources is None:
+ frozen_sources = {}
+ else:
+ include_parent = True
+
+ recovery_sources = dict(frozen_sources or {})
+ for relative, expected_digest in recovery_sources.items():
+ try:
+ _, digest = _read_saved_result(scan_dir, relative, scan["id"])
+ except (ContractError, OSError, ValueError) as exc:
+ raise ContractError(
+ "Frozen stopped-scan checkpoint set is incomplete."
+ ) from exc
+ if digest != expected_digest:
+ raise ContractError("checkpoint changed after the scan stopped")
+
+ workers = connection.execute(
+ "SELECT id, kind, status, completed_at, artifact_dir, result_manifest_path "
+ "FROM deep_scan_workers WHERE scan_id = ?",
+ (scan["id"],),
+ ).fetchall()
+ for relative in (
+ set(_saved_result_paths(scan_dir, workers)) - recovery_sources.keys()
+ ):
+ try:
+ _, recovery_sources[relative] = _read_saved_result(
+ scan_dir, relative, scan["id"]
+ )
+ except (ContractError, OSError, ValueError):
+ continue
+ return recovery_sources, include_parent
+
+
+def scan_results_recovery_needed(db: Any, connection: Any, scan: Any) -> bool:
+ if scan["status"] != "failed" or scan["canceled_at"] is not None:
+ return False
+ warnings = json.loads(scan["completion_warnings_json"])
+ if any(
+ isinstance(warning, str) and warning.startswith(_PUBLICATION_FOLLOW_UP_WARNING)
+ for warning in warnings
+ ):
+ return True
+ publication_error = connection.execute(
+ "SELECT publication_error_message FROM deep_scan_runs WHERE scan_id = ?",
+ (scan["id"],),
+ ).fetchone()
+ if publication_error is not None and publication_error["publication_error_message"]:
+ return True
+ return _saved_results_changed(db, connection, scan)
+
+
def _finding_key(finding: dict[str, Any]) -> str:
# Wording and evidence may improve between checkpoints; distinct source locations
# must not collide merely because two workers chose the same semantic identity.
@@ -227,43 +470,7 @@ def merge_saved_results(
parent_manifest: dict[str, Any] | None = None
if frozen_source_digests is None or allow_frozen_legacy_parent:
try:
- parent_manifest = _read_scan_local_json(
- scan_dir, "scan-manifest.json", "Saved parent manifest"
- )
- parent_findings = _read_scan_local_json(
- scan_dir, "findings.json", "Saved parent findings"
- )
- parent_coverage = _read_scan_local_json(
- scan_dir, "coverage.json", "Saved parent coverage"
- )
- parent_scan = parent_manifest.get("scan")
- if not isinstance(parent_scan, dict):
- raise ContractError("Saved parent manifest has no scan object")
- if (parent_scan.get("sealedAt") or parent_scan.get("artifacts")) and (
- parent_scan.get("id", scan_id) != scan_id
- or parent_findings.get("scanId", scan_id) != scan_id
- or parent_coverage.get("scanId", scan_id) != scan_id
- ):
- raise ContractError("Saved parent documents belong to a different scan")
- parent = {
- "scanId": scan_id,
- "findings": parent_findings.get("findings"),
- "coverage": parent_coverage,
- **{
- key: parent_scan[key]
- for key in ("scope", "threatModel", "complete")
- if key in parent_scan
- },
- }
- if not isinstance(parent["findings"], list):
- raise ContractError("Saved parent draft has no findings array")
- if not parent_scan.get("sealedAt"):
- payload = _encoded(parent)
- write_scan_local_bytes(
- scan_dir,
- f"checkpoints/{hashlib.sha256(payload).hexdigest()}.json",
- payload,
- )
+ parent_manifest, parent = _read_saved_parent_result(scan_dir, scan_id)
except (ContractError, OSError, ValueError) as exc:
if not stopped:
raise
@@ -271,6 +478,18 @@ def merge_saved_results(
warnings.append(f"Could not read the saved parent draft: {exc}")
parent_manifest = None
parent = None
+ if parent_manifest is not None and parent is not None:
+ parent_scan = parent_manifest["scan"]
+ if not parent_scan.get("sealedAt") or allow_frozen_legacy_parent:
+ payload = _encoded(parent)
+ parent_digest = hashlib.sha256(payload).hexdigest()
+ parent_checkpoint = f"checkpoints/{parent_digest}.json"
+ write_scan_local_bytes(scan_dir, parent_checkpoint, payload)
+ if frozen_source_digests is not None:
+ frozen_source_digests = {
+ **frozen_source_digests,
+ parent_checkpoint: parent_digest,
+ }
sources: list[tuple[str, dict[str, Any], str | None]] = []
parent_preserved_sources: dict[str, str] = {}
@@ -283,18 +502,9 @@ def merge_saved_results(
paths: dict[str, str | None] = {}
current_results: set[str] = set()
reducer_outputs: list[tuple[Any, str, list[str], int]] = []
- accepted_reducers = [
- worker
- for worker in workers
- if worker["kind"] == "dedup"
- and worker["status"] == "succeeded"
- and worker["result_manifest_path"]
- ]
+ reducer = _latest_successful_reducer(workers)
latest_reducer: str | None = None
- if accepted_reducers:
- reducer = max(
- accepted_reducers, key=lambda worker: (worker["completed_at"] or "", worker["id"])
- )
+ if reducer is not None:
try:
latest_reducer = Path(reducer["result_manifest_path"]).relative_to(scan_dir).as_posix()
paths[latest_reducer] = None
@@ -371,14 +581,7 @@ def merge_saved_results(
for relative, worker_id in paths.items():
try:
- draft = _read_scan_local_json(scan_dir, relative, "Saved scan checkpoint")
- if draft.get("scanId") != scan_id:
- raise ContractError("checkpoint belongs to a different scan")
- if not isinstance(draft.get("findings"), list) or not isinstance(
- draft.get("coverage"), dict
- ):
- raise ContractError("checkpoint has no semantic findings or coverage")
- digest = _digest(draft)
+ draft, digest = _read_saved_result(scan_dir, relative, scan_id)
if frozen_source_digests is not None and frozen_source_digests[relative] != digest:
raise ContractError("checkpoint changed after the scan stopped")
source_digests[relative] = digest
@@ -393,7 +596,7 @@ def merge_saved_results(
drafts_by_path = {relative: draft for relative, draft, _ in sources}
latest_reducer_key = (
(reducer["completed_at"] or "", reducer["id"], int(reducer["attempt"] or 0))
- if accepted_reducers and latest_reducer in drafts_by_path
+ if reducer is not None and latest_reducer in drafts_by_path
else None
)
if latest_reducer_key is None:
@@ -875,21 +1078,26 @@ def _restore_published_outputs(scan_dir: Path, snapshots: dict[str, bytes | None
write_scan_local_bytes(scan_dir, relative, contents)
-def preserve_scan_results_locked(db: Any, connection: Any, scan_id: str) -> bool:
+def preserve_scan_results_locked(
+ db: Any,
+ connection: Any,
+ scan_id: str,
+ *,
+ recovery_source_digests: dict[str, str] | None = None,
+ include_parent_with_recovery: bool = False,
+) -> bool:
"""Publish or verify retained terminal results through the workbench host."""
scan = db.require_scan(connection, scan_id)
if scan["status"] != "failed":
return False
frozen_source_digests: dict[str, str] | None = None
raw_frozen_sources = scan["retained_source_digests_json"]
- if raw_frozen_sources is not None:
- parsed_frozen_sources = json.loads(raw_frozen_sources)
- if not isinstance(parsed_frozen_sources, dict) or not all(
- isinstance(relative, str) and isinstance(digest, str)
- for relative, digest in parsed_frozen_sources.items()
- ):
- raise ContractError("Saved stopped-scan source digests are malformed.")
- frozen_source_digests = parsed_frozen_sources
+ if recovery_source_digests is not None:
+ frozen_source_digests = recovery_source_digests
+ elif raw_frozen_sources is not None:
+ frozen_source_digests = _source_digests(
+ json.loads(raw_frozen_sources), "Saved stopped-scan"
+ )
scan_dir = db.require_canonical_scan_directory(Path(scan["scan_dir"]))
deep_run = connection.execute(
"SELECT status FROM deep_scan_runs WHERE scan_id = ?", (scan_id,)
@@ -942,8 +1150,8 @@ def preserve_scan_results_locked(db: Any, connection: Any, scan_id: str) -> bool
)
db.index_findings(connection, scan_id, findings, scan["completed_at"])
connection.execute(
- "UPDATE scans SET seal_manifest_digest = ?, retained_source_digests_json = "
- "COALESCE(retained_source_digests_json, ?), completion_warnings_json = ?, "
+ "UPDATE scans SET seal_manifest_digest = ?, retained_source_digests_json = ?, "
+ "completion_warnings_json = ?, "
"updated_at = ? WHERE id = ? AND status = 'failed'",
(
digest,
@@ -990,7 +1198,8 @@ def preserve_scan_results_locked(db: Any, connection: Any, scan_id: str) -> bool
return True
record_publication(existing, existing_findings)
return True
- raise ContractError("Stopped scan sources changed after terminal publication.")
+ if recovery_source_digests is None:
+ raise ContractError("Stopped scan sources changed after terminal publication.")
binding = {**db.workbench_completion_binding(scan, scan["completed_at"]), "status": outcome}
documents = merge_saved_results(
scan_dir,
@@ -1008,10 +1217,14 @@ def preserve_scan_results_locked(db: Any, connection: Any, scan_id: str) -> bool
).strip(),
frozen_source_digests=frozen_source_digests,
allow_frozen_legacy_parent=(
- frozen_source_digests == {}
- and isinstance(existing_scan, dict)
- and existing_scan.get("sealedAt") is not None
- and "preservedSources" not in existing_scan
+ include_parent_with_recovery
+ or (
+ recovery_source_digests is None
+ and frozen_source_digests == {}
+ and isinstance(existing_scan, dict)
+ and existing_scan.get("sealedAt") is not None
+ and "preservedSources" not in existing_scan
+ )
),
)
if documents is None:
@@ -1056,19 +1269,27 @@ def preserve_scan_results_locked(db: Any, connection: Any, scan_id: str) -> bool
return True
-def refresh_stopped_scan_results(
- db: Any, connection: Any, scan_id: str, *, strict: bool = False
-) -> None:
- scan = db.require_scan(connection, scan_id)
- if scan["status"] != "failed":
- return
- scan_id = scan["id"]
+def recover_scan_results(db: Any, connection: Any, args: Any) -> dict[str, Any]:
+ scan_id = db.require_uuid(args.scan_id, "scan-id")
with db.scan_completion_lock(scan_id):
- if strict:
- if preserve_scan_results_locked(db, connection, scan_id):
- db.deep_scan.clear_deep_scan_publication_failure(connection, scan_id)
- else:
- preserve_stopped_results_after_transition(db, connection, scan_id)
+ scan = db.require_scan(connection, scan_id)
+ if scan["status"] != "failed":
+ raise SystemExit("Only a stopped scan can recover terminal results.")
+ if scan["canceled_at"] is not None:
+ raise SystemExit("Canceled scans cannot recover terminal results.")
+ recovery_source_digests, include_parent = _recovery_source_digests(
+ db, connection, scan
+ )
+ if not preserve_scan_results_locked(
+ db,
+ connection,
+ scan_id,
+ recovery_source_digests=recovery_source_digests,
+ include_parent_with_recovery=include_parent,
+ ):
+ raise SystemExit("No saved stopped-scan results were available to recover.")
+ db.deep_scan.clear_deep_scan_publication_failure(connection, scan_id)
+ return db.scan_context(connection, scan_id)
def preserve_scan_results(db: Any, connection: Any, args: Any) -> dict[str, Any]:
diff --git a/plugins/codex-security/tests/test_cli_dry_runs.py b/plugins/codex-security/tests/test_cli_dry_runs.py
index e358a4db1..2713fe936 100644
--- a/plugins/codex-security/tests/test_cli_dry_runs.py
+++ b/plugins/codex-security/tests/test_cli_dry_runs.py
@@ -25,6 +25,14 @@ def test_all_scripts_support_help() -> None:
assert "usage:" in result.stdout.lower(), script.name
+def test_recover_scan_results_help_describes_its_contract() -> None:
+ result = run_script("workbench_db.py", "recover-scan-results", "--help")
+
+ assert result.returncode == 0, result.stderr
+ assert "failed, non-canceled scan" in result.stdout
+ assert "retained checkpoints" in result.stdout
+
+
def test_finalizer_cli_completes_checked_in_scan_bundle(tmp_path: Path) -> None:
scan_dir = tmp_path / "completed-scan"
shutil.copytree(PLUGIN_ROOT / "examples" / "completed-scan", scan_dir)
diff --git a/plugins/codex-security/tests/test_workbench_completion_binding.py b/plugins/codex-security/tests/test_workbench_completion_binding.py
index 58462c90b..401496ccf 100644
--- a/plugins/codex-security/tests/test_workbench_completion_binding.py
+++ b/plugins/codex-security/tests/test_workbench_completion_binding.py
@@ -514,6 +514,14 @@ def test_deep_completion_rejects_invalid_target_even_with_recoverable_inventory(
assert "target.kind" in str(failed["stderr"])
recorded = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
assert recorded["progress"]["status"] == "failed"
+ assert recorded["resultsRecoveryNeeded"] is True
+ assert json.loads(coverage_path.read_text())["inventoryStrategy"] == ""
+
+ recovered = run_workbench(
+ state_dir, "recover-scan-results", "--scan-id", scan_id
+ )["scan"]
+
+ assert recovered["resultsRecoveryNeeded"] is False
preserved_coverage = json.loads(coverage_path.read_text())
assert preserved_coverage["inventoryStrategy"] == "repository"
assert preserved_coverage["completeness"] == "partial"
diff --git a/plugins/codex-security/tests/test_workbench_db_exports.py b/plugins/codex-security/tests/test_workbench_db_exports.py
index 85aff1207..51601c837 100644
--- a/plugins/codex-security/tests/test_workbench_db_exports.py
+++ b/plugins/codex-security/tests/test_workbench_db_exports.py
@@ -142,20 +142,20 @@ def test_late_parent_draft_is_retained_without_mutating_frozen_stopped_seal(
assert "saved checkpoint" in str(rejected["stderr"])
assert (scan_dir / "scan-manifest.json").read_bytes() == seal
assert checkpoint_path.read_bytes() == json.dumps(payload).encode()
- refreshed = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
- assert refreshed["findingCount"] == 1
+ recovered = run_workbench(state_dir, "recover-scan-results", "--scan-id", scan_id)["scan"]
+ assert recovered["findingCount"] == 2
coverage = json.loads((scan_dir / "coverage.json").read_text())
- assert not any(item.get("id") == "late-review" for item in coverage["deferred"])
- assert refreshed["progress"]["status"] == "failed"
- assert refreshed["progress"]["updatedAt"] == stopped["progress"]["updatedAt"]
- assert refreshed["updatedAt"] == stopped["updatedAt"]
+ assert any(item.get("id") == "late-review" for item in coverage["deferred"])
+ assert recovered["progress"]["status"] == "failed"
+ assert recovered["progress"]["updatedAt"] > stopped["progress"]["updatedAt"]
+ assert recovered["updatedAt"] > stopped["updatedAt"]
assert (
json.loads((scan_dir / "scan-manifest.json").read_text())["scan"]["completedAt"]
== json.loads(seal)["scan"]["completedAt"]
)
unchanged = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
- assert unchanged["progress"]["updatedAt"] == refreshed["progress"]["updatedAt"]
- assert unchanged["updatedAt"] == refreshed["updatedAt"]
+ assert unchanged["progress"]["updatedAt"] == recovered["progress"]["updatedAt"]
+ assert unchanged["updatedAt"] == recovered["updatedAt"]
def test_canceled_scan_does_not_accept_checkpoints_written_after_cancellation(
diff --git a/plugins/codex-security/tests/test_workbench_deep_scan.py b/plugins/codex-security/tests/test_workbench_deep_scan.py
index 545e9b575..f33bb5cc8 100644
--- a/plugins/codex-security/tests/test_workbench_deep_scan.py
+++ b/plugins/codex-security/tests/test_workbench_deep_scan.py
@@ -3320,7 +3320,7 @@ def test_failure_capped_completion_preserves_partial_results_and_exact_omissions
assert replayed == finished
-def test_late_worker_rejection_does_not_mutate_frozen_stopped_results(tmp_path: Path) -> None:
+def test_late_worker_rejection_supersedes_stopped_checkpoint_finding(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
codex_home = tmp_path / "codex-home"
target = tmp_path / "target"
@@ -3403,14 +3403,21 @@ def test_late_worker_rejection_does_not_mutate_frozen_stopped_results(tmp_path:
)
)
- refreshed = run_workbench(
+ recovery_needed = run_workbench(
state_dir, "get-scan", "--scan-id", scan_id, environment=deep_environment(codex_home)
)["scan"]
+ assert recovery_needed["resultsRecoveryNeeded"] is True
+ recovered = run_workbench(
+ state_dir,
+ "recover-scan-results",
+ "--scan-id",
+ scan_id,
+ environment=deep_environment(codex_home),
+ )["scan"]
final_findings = json.loads(findings_path.read_text())["findings"]
final_coverage = json.loads(coverage_path.read_text())
- assert refreshed["findingCount"] == len(final_findings) == 1
- assert final_findings[0]["summary"] == provisional["summary"]
- assert not any(
+ assert recovered["findingCount"] == len(final_findings) == 0
+ assert any(
item.get("candidateId") == "candidate-late-rejection"
and item.get("disposition") == "rejected"
for item in final_coverage["surfaces"]
diff --git a/plugins/codex-security/tests/test_workbench_standard_deep_results.py b/plugins/codex-security/tests/test_workbench_standard_deep_results.py
index 8ee2f6277..8ca01b9fd 100644
--- a/plugins/codex-security/tests/test_workbench_standard_deep_results.py
+++ b/plugins/codex-security/tests/test_workbench_standard_deep_results.py
@@ -90,6 +90,18 @@ def test_stopped_deep_scan_ignores_late_worker_checkpoints_without_reducer(
late["findings"][0]["locations"][0]["endLine"] = 92
archived = result_path.parent / "attempts" / "attempt-01" / "checkpoints"
write_checkpoint(archived, late)
+ recovery_needed = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
+ assert recovery_needed["resultsRecoveryNeeded"] is (termination != "canceled")
+ if termination == "canceled":
+ rejected = run_workbench(
+ state_dir,
+ "recover-scan-results",
+ "--scan-id",
+ scan_id,
+ check=False,
+ )
+ assert rejected["returncode"] != 0
+ assert "Canceled scans cannot recover" in str(rejected["stderr"])
wrong_owner = run_workbench(
state_dir,
"preserve-scan-results",
@@ -123,7 +135,7 @@ def test_stopped_deep_scan_ignores_late_worker_checkpoints_without_reducer(
assert (scan_dir / "scan-manifest.json").read_bytes() == seal
-def test_reopened_workspace_ignores_late_stopped_scan_checkpoints(tmp_path: Path) -> None:
+def test_scan_reads_require_explicit_late_result_recovery(tmp_path: Path) -> None:
state_dir, codex_home, target, scan_dir, scan_id = deep_scan_fixture(tmp_path)
_, result_path = accepted_standard_worker(state_dir, codex_home, scan_dir, scan_id)
contract_dir = tmp_path / "contract"
@@ -153,10 +165,17 @@ def test_reopened_workspace_ignores_late_stopped_scan_checkpoints(tmp_path: Path
"failed",
environment={"CODEX_HOME": str(codex_home)},
)
+ stopped = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
+ assert stopped["resultsRecoveryNeeded"] is False
late = copy.deepcopy(checkpoint)
late["findings"][0]["locations"][0]["startLine"] = 91
late["findings"][0]["locations"][0]["endLine"] = 92
- write_checkpoint(result_path.parent / "attempts" / "attempt-01" / "checkpoints", late)
+ late_path = write_checkpoint(
+ result_path.parent / "attempts" / "attempt-01" / "checkpoints", late
+ )
+ manifest_path = scan_dir / "scan-manifest.json"
+ published_after_checkpoint = late_path.stat().st_mtime_ns + 1_000_000
+ os.utime(manifest_path, ns=(published_after_checkpoint, published_after_checkpoint))
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
workspace_id = connection.execute(
"SELECT workspace_id FROM scans WHERE id = ?", (scan_id,)
@@ -170,7 +189,494 @@ def test_reopened_workspace_ignores_late_stopped_scan_checkpoints(tmp_path: Path
environment={"CODEX_HOME": str(codex_home)},
)
assert reopened["results"]["findingCount"] == 1
- assert json.loads((scan_dir / "findings.json").read_text())["findings"]
+ stale = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
+ assert stale["findingCount"] == 1
+ assert stale["resultsRecoveryNeeded"] is True
+ assert (
+ run_workbench(state_dir, "list-findings", "--scan-id", scan_id)["findingsPage"]["total"]
+ == 1
+ )
+
+ recovered = run_workbench(
+ state_dir,
+ "recover-scan-results",
+ "--scan-id",
+ scan_id,
+ environment={"CODEX_HOME": str(codex_home)},
+ )
+
+ assert recovered["scan"]["findingCount"] == 2
+ assert recovered["scan"]["resultsRecoveryNeeded"] is False
+ assert len(json.loads((scan_dir / "findings.json").read_text())["findings"]) == 2
+
+
+def test_explicit_recovery_rejects_changed_frozen_source(tmp_path: Path) -> None:
+ state_dir, codex_home, target, scan_dir, scan_id = deep_scan_fixture(tmp_path)
+ _, result_path = accepted_standard_worker(state_dir, codex_home, scan_dir, scan_id)
+ contract_dir = tmp_path / "contract"
+ contract_dir.mkdir()
+ write_completed_contract(contract_dir, scan_id, target, relative_path="app.py")
+ finding = json.loads((contract_dir / "findings.json").read_text())["findings"][0]
+ checkpoint = {
+ "scanId": scan_id,
+ "complete": False,
+ "findings": [finding],
+ "coverage": {
+ "completeness": "partial",
+ "surfaces": [],
+ "explicitExclusions": [],
+ "deferred": [],
+ },
+ }
+ write_checkpoint(result_path.parent / "checkpoints", checkpoint)
+ run_workbench(
+ state_dir,
+ "fail-deep-scan",
+ "--scan-id",
+ scan_id,
+ "--message",
+ "Worker stopped.",
+ "--deep-status",
+ "failed",
+ environment={"CODEX_HOME": str(codex_home)},
+ )
+ manifest_path = scan_dir / "scan-manifest.json"
+ original_manifest = manifest_path.read_bytes()
+ original_findings = (scan_dir / "findings.json").read_bytes()
+ preserved_sources = json.loads(original_manifest)["scan"]["preservedSources"]
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ original_record = connection.execute(
+ "SELECT seal_manifest_digest, retained_source_digests_json "
+ "FROM scans WHERE id = ?",
+ (scan_id,),
+ ).fetchone()
+ frozen_path = scan_dir / next(iter(preserved_sources))
+ frozen_path.write_text("{truncated")
+
+ late = copy.deepcopy(checkpoint)
+ late["findings"][0]["locations"][0]["startLine"] = 91
+ late["findings"][0]["locations"][0]["endLine"] = 92
+ write_checkpoint(
+ result_path.parent / "attempts" / "attempt-01" / "checkpoints", late
+ )
+ assert (
+ run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"][
+ "resultsRecoveryNeeded"
+ ]
+ is True
+ )
+
+ rejected = run_workbench(
+ state_dir,
+ "recover-scan-results",
+ "--scan-id",
+ scan_id,
+ environment={"CODEX_HOME": str(codex_home)},
+ check=False,
+ )
+
+ assert rejected["returncode"] != 0
+ assert "Frozen stopped-scan checkpoint set is incomplete" in str(rejected["stderr"])
+ assert (scan_dir / "scan-manifest.json").read_bytes() == original_manifest
+ assert (scan_dir / "findings.json").read_bytes() == original_findings
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ assert (
+ connection.execute(
+ "SELECT seal_manifest_digest, retained_source_digests_json "
+ "FROM scans WHERE id = ?",
+ (scan_id,),
+ ).fetchone()
+ == original_record
+ )
+
+
+def test_explicit_recovery_preserves_unfrozen_parent_with_late_checkpoint(
+ tmp_path: Path,
+) -> None:
+ state_dir, codex_home, target, scan_dir, scan_id = deep_scan_fixture(tmp_path)
+ _, result_path = accepted_standard_worker(state_dir, codex_home, scan_dir, scan_id)
+ contract_dir = tmp_path / "contract"
+ contract_dir.mkdir()
+ write_completed_contract(contract_dir, scan_id, target, relative_path="app.py")
+ for filename in ("findings.json", "coverage.json", "scan-manifest.json"):
+ (scan_dir / filename).write_bytes((contract_dir / filename).read_bytes())
+ parent_finding = json.loads((contract_dir / "findings.json").read_text())["findings"][0]
+
+ scripts_dir = Path(__file__).resolve().parents[1] / "scripts"
+ wrapper = tmp_path / "fail_before_sources_are_frozen.py"
+ wrapper.write_text(
+ "import sys\n"
+ f"sys.path.insert(0, {str(scripts_dir)!r})\n"
+ "import workbench_db\n"
+ "import workbench_saved_results\n"
+ "def fail_before_sources_are_frozen(*args, **kwargs):\n"
+ " raise OSError('injected early publication failure')\n"
+ "workbench_saved_results.merge_saved_results = fail_before_sources_are_frozen\n"
+ "raise SystemExit(workbench_db.main())\n"
+ )
+ failed = subprocess.run(
+ [
+ sys.executable,
+ str(wrapper),
+ "fail-deep-scan",
+ "--scan-id",
+ scan_id,
+ "--message",
+ "Worker stopped.",
+ ],
+ capture_output=True,
+ env={
+ **os.environ,
+ "CODEX_HOME": str(codex_home),
+ "CODEX_SECURITY_STATE_DIR": str(state_dir),
+ },
+ text=True,
+ check=False,
+ )
+ assert failed.returncode == 0, failed.stderr
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ assert (
+ connection.execute(
+ "SELECT retained_source_digests_json FROM scans WHERE id = ?", (scan_id,)
+ ).fetchone()[0]
+ is None
+ )
+
+ late_finding = copy.deepcopy(parent_finding)
+ late_finding["occurrenceId"] = "occ_111111111111111111111111"
+ late_finding["ruleId"] = "late.checkpoint"
+ late_finding["title"] = "Late checkpoint finding"
+ late = json.loads(result_path.read_text())
+ late["complete"] = False
+ late["findings"] = [late_finding]
+ write_checkpoint(result_path.parent / "checkpoints", late)
+
+ recovered = run_workbench(
+ state_dir,
+ "recover-scan-results",
+ "--scan-id",
+ scan_id,
+ environment={"CODEX_HOME": str(codex_home)},
+ )["scan"]
+
+ assert recovered["findingCount"] == 2
+ assert {finding["title"] for finding in recovered["findings"]} == {
+ parent_finding["title"],
+ late_finding["title"],
+ }
+
+
+def test_explicit_recovery_preserves_sealed_parent_with_empty_source_map(
+ tmp_path: Path,
+) -> None:
+ state_dir, codex_home, target, scan_dir, scan_id = deep_scan_fixture(tmp_path)
+ _, result_path = accepted_standard_worker(state_dir, codex_home, scan_dir, scan_id)
+ result_path.unlink()
+ contract_dir = tmp_path / "contract"
+ contract_dir.mkdir()
+ scripts_dir = Path(__file__).resolve().parents[1] / "scripts"
+ write_completed_contract(
+ contract_dir,
+ scan_id,
+ target,
+ relative_path="app.py",
+ coverage_mode="deep_repository",
+ )
+ subprocess.run(
+ [
+ sys.executable,
+ str(scripts_dir / "finalize_scan_contract.py"),
+ "--scan-dir",
+ str(contract_dir),
+ ],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ for filename in ("findings.json", "coverage.json", "scan-manifest.json"):
+ (scan_dir / filename).write_bytes((contract_dir / filename).read_bytes())
+ sealed_manifest = (scan_dir / "scan-manifest.json").read_bytes()
+ parent_finding = json.loads((contract_dir / "findings.json").read_text())[
+ "findings"
+ ][0]
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ connection.execute(
+ "UPDATE scans SET seal_manifest_digest = ? WHERE id = ?",
+ (f"sha256:{hashlib.sha256(sealed_manifest).hexdigest()}", scan_id),
+ )
+
+ run_workbench(
+ state_dir,
+ "fail-deep-scan",
+ "--scan-id",
+ scan_id,
+ "--message",
+ "Worker stopped.",
+ environment={"CODEX_HOME": str(codex_home)},
+ )
+ assert (
+ json.loads((scan_dir / "scan-manifest.json").read_text())["scan"][
+ "preservedSources"
+ ]
+ == {}
+ )
+
+ late_finding = copy.deepcopy(parent_finding)
+ late_finding["occurrenceId"] = "occ_111111111111111111111111"
+ late_finding["identity"]["anchor"] = "late-checkpoint"
+ late_finding["ruleId"] = "late.checkpoint"
+ late_finding["title"] = "Late checkpoint finding"
+ late = {
+ "scanId": scan_id,
+ "complete": False,
+ "findings": [late_finding],
+ "coverage": {
+ "completeness": "partial",
+ "surfaces": [],
+ "explicitExclusions": [],
+ "deferred": [],
+ },
+ }
+ write_checkpoint(result_path.parent / "checkpoints", late)
+
+ manifest_before_failed_recovery = (scan_dir / "scan-manifest.json").read_bytes()
+ findings_before_failed_recovery = (scan_dir / "findings.json").read_bytes()
+ wrapper = tmp_path / "fail_parent_checkpoint_write.py"
+ wrapper.write_text(
+ "import sys\n"
+ f"sys.path.insert(0, {str(scripts_dir)!r})\n"
+ "import workbench_db\n"
+ "import workbench_saved_results\n"
+ "original_write = workbench_saved_results.write_scan_local_bytes\n"
+ "def fail_parent_checkpoint(scan_dir, relative_path, payload, **kwargs):\n"
+ " if relative_path.startswith('checkpoints/'):\n"
+ " raise OSError('injected parent checkpoint failure')\n"
+ " return original_write(scan_dir, relative_path, payload, **kwargs)\n"
+ "workbench_saved_results.write_scan_local_bytes = fail_parent_checkpoint\n"
+ "raise SystemExit(workbench_db.main())\n"
+ )
+ failed = subprocess.run(
+ [
+ sys.executable,
+ str(wrapper),
+ "recover-scan-results",
+ "--scan-id",
+ scan_id,
+ ],
+ capture_output=True,
+ env={
+ **os.environ,
+ "CODEX_HOME": str(codex_home),
+ "CODEX_SECURITY_STATE_DIR": str(state_dir),
+ },
+ text=True,
+ check=False,
+ )
+ assert failed.returncode != 0
+ assert "injected parent checkpoint failure" in failed.stderr
+ assert (scan_dir / "scan-manifest.json").read_bytes() == manifest_before_failed_recovery
+ assert (scan_dir / "findings.json").read_bytes() == findings_before_failed_recovery
+
+ recovered = run_workbench(
+ state_dir,
+ "recover-scan-results",
+ "--scan-id",
+ scan_id,
+ environment={"CODEX_HOME": str(codex_home)},
+ )["scan"]
+
+ assert recovered["findingCount"] == 2
+ assert {finding["title"] for finding in recovered["findings"]} == {
+ parent_finding["title"],
+ late_finding["title"],
+ }
+
+ later_finding = copy.deepcopy(parent_finding)
+ later_finding["occurrenceId"] = "occ_222222222222222222222222"
+ later_finding["identity"]["anchor"] = "later-checkpoint"
+ later_finding["ruleId"] = "later.checkpoint"
+ later_finding["title"] = "Later checkpoint finding"
+ later = copy.deepcopy(late)
+ later["findings"] = [later_finding]
+ write_checkpoint(
+ result_path.parent / "attempts" / "attempt-02" / "checkpoints", later
+ )
+
+ recovered_again = run_workbench(
+ state_dir,
+ "recover-scan-results",
+ "--scan-id",
+ scan_id,
+ environment={"CODEX_HOME": str(codex_home)},
+ )["scan"]
+
+ assert recovered_again["findingCount"] == 3
+ assert {finding["title"] for finding in recovered_again["findings"]} == {
+ parent_finding["title"],
+ late_finding["title"],
+ later_finding["title"],
+ }
+
+
+ "published_sources",
+ [None, {}],
+ ids=["missing-source-map", "empty-source-map"],
+)
+def test_explicit_recovery_retries_frozen_parent_after_write_failure(
+ tmp_path: Path,
+ published_sources: dict[str, str] | None,
+) -> None:
+ state_dir, codex_home, target, scan_dir, scan_id = deep_scan_fixture(tmp_path)
+ _, result_path = accepted_standard_worker(state_dir, codex_home, scan_dir, scan_id)
+ contract_dir = tmp_path / "contract"
+ contract_dir.mkdir()
+ scripts_dir = Path(__file__).resolve().parents[1] / "scripts"
+ write_completed_contract(
+ contract_dir,
+ scan_id,
+ target,
+ relative_path="app.py",
+ coverage_mode="deep_repository",
+ )
+ subprocess.run(
+ [
+ sys.executable,
+ str(scripts_dir / "finalize_scan_contract.py"),
+ "--scan-dir",
+ str(contract_dir),
+ ],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ if published_sources is not None:
+ manifest_path = contract_dir / "scan-manifest.json"
+ manifest = json.loads(manifest_path.read_text())
+ manifest["scan"]["preservedSources"] = published_sources
+ manifest_path.write_text(json.dumps(manifest))
+ for filename in ("findings.json", "coverage.json", "scan-manifest.json"):
+ (scan_dir / filename).write_bytes((contract_dir / filename).read_bytes())
+ parent_manifest = (scan_dir / "scan-manifest.json").read_bytes()
+ parent_finding = json.loads((contract_dir / "findings.json").read_text())[
+ "findings"
+ ][0]
+ parent_scan = json.loads(parent_manifest)["scan"]
+ if published_sources is None:
+ assert "preservedSources" not in parent_scan
+ else:
+ assert parent_scan["preservedSources"] == published_sources
+
+ late_finding = copy.deepcopy(parent_finding)
+ late_finding["occurrenceId"] = "occ_111111111111111111111111"
+ late_finding["identity"]["anchor"] = "late-checkpoint"
+ late_finding["ruleId"] = "late.checkpoint"
+ late_finding["title"] = "Late checkpoint finding"
+ late = json.loads(result_path.read_text())
+ late["complete"] = False
+ late["findings"] = [late_finding]
+ result_path.write_text(json.dumps(late))
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ connection.execute(
+ "UPDATE scans SET seal_manifest_digest = ? WHERE id = ?",
+ (f"sha256:{hashlib.sha256(parent_manifest).hexdigest()}", scan_id),
+ )
+
+ wrapper = tmp_path / "fail_after_sources_are_frozen.py"
+ wrapper.write_text(
+ "import sys\n"
+ f"sys.path.insert(0, {str(scripts_dir)!r})\n"
+ "import workbench_db\n"
+ "import workbench_saved_results\n"
+ "def fail_after_sources_are_frozen(prepared):\n"
+ " raise OSError('injected late publication failure')\n"
+ "workbench_saved_results._write_prepared_scan_finalization = "
+ "fail_after_sources_are_frozen\n"
+ "raise SystemExit(workbench_db.main())\n"
+ )
+ failed = subprocess.run(
+ [
+ sys.executable,
+ str(wrapper),
+ "fail-deep-scan",
+ "--scan-id",
+ scan_id,
+ "--message",
+ "Worker stopped.",
+ ],
+ capture_output=True,
+ env={
+ **os.environ,
+ "CODEX_HOME": str(codex_home),
+ "CODEX_SECURITY_STATE_DIR": str(state_dir),
+ },
+ text=True,
+ check=False,
+ )
+ assert failed.returncode == 0, failed.stderr
+ assert (scan_dir / "scan-manifest.json").read_bytes() == parent_manifest
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ seal_digest, frozen_before = connection.execute(
+ "SELECT seal_manifest_digest, retained_source_digests_json "
+ "FROM scans WHERE id = ?",
+ (scan_id,),
+ ).fetchone()
+ assert seal_digest is not None
+ assert json.loads(frozen_before)
+ assert (
+ run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"][
+ "resultsRecoveryNeeded"
+ ]
+ is True
+ )
+
+ recovered = run_workbench(
+ state_dir,
+ "recover-scan-results",
+ "--scan-id",
+ scan_id,
+ environment={"CODEX_HOME": str(codex_home)},
+ )["scan"]
+
+ assert recovered["resultsRecoveryNeeded"] is False
+ assert recovered["findingCount"] == 2
+ assert {finding["title"] for finding in recovered["findings"]} == {
+ parent_finding["title"],
+ late_finding["title"],
+ }
+ published_sources = json.loads((scan_dir / "scan-manifest.json").read_text())[
+ "scan"
+ ]["preservedSources"]
+ frozen_sources = json.loads(frozen_before)
+ assert published_sources.items() >= frozen_sources.items()
+ parent_sources = published_sources.keys() - frozen_sources.keys()
+ assert len(parent_sources) == 1
+ parent_source = next(iter(parent_sources))
+ assert parent_source.startswith("checkpoints/")
+ assert Path(parent_source).stem == published_sources[parent_source]
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ assert json.loads(
+ connection.execute(
+ "SELECT retained_source_digests_json FROM scans WHERE id = ?",
+ (scan_id,),
+ ).fetchone()[0]
+ ) == published_sources
+
+
+def test_unsealed_manifest_without_saved_results_does_not_offer_recovery(
+ tmp_path: Path,
+) -> None:
+ state_dir, _, _, scan_dir, scan_id = deep_scan_fixture(tmp_path)
+ (scan_dir / "scan-manifest.json").write_text(json.dumps({"scan": {"status": "failed"}}))
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ connection.execute(
+ "UPDATE scans SET status = 'failed', failure_message = 'Worker stopped.' WHERE id = ?",
+ (scan_id,),
+ )
+
+ failed = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
+
+ assert failed["resultsRecoveryNeeded"] is False
@pytest.mark.parametrize(
@@ -492,7 +998,7 @@ def test_existing_non_canceled_output_recovers_structured_publication_failure(
run_workbench(
state_dir,
- "get-scan",
+ "recover-scan-results",
"--scan-id",
scan_id,
environment=environment,
diff --git a/sdk/typescript/tests-ts/stopped-scan-results.test.ts b/sdk/typescript/tests-ts/stopped-scan-results.test.ts
index 8aeec802c..5e35b37b2 100644
--- a/sdk/typescript/tests-ts/stopped-scan-results.test.ts
+++ b/sdk/typescript/tests-ts/stopped-scan-results.test.ts
@@ -83,6 +83,7 @@ const stoppedScanProbe = [
" workbench_db.cancel_scan_locked(connection, argparse.Namespace(scan_id=scan_id, thread_id=None))",
" workbench_db.saved_results._write_prepared_scan_finalization = original_write",
" connection.close()",
+ " run('preserve-scan-results', '--scan-id', scan_id, '--thread-id', 'stopped-result-owner')",
" stored = run('get-scan', '--scan-id', scan_id)['scan']",
" findings_path = scan_dir / 'findings.json'",
" findings = json.loads(findings_path.read_text(encoding='utf-8'))['findings'] if findings_path.exists() else []",
@@ -250,14 +251,19 @@ test("retries a legacy stopped seal after transient publication failure", () =>
{ encoding: "utf8" },
);
expect(result.status, result.stderr).toBe(0);
- expect(JSON.parse(result.stdout)).toEqual({
+ const recovered = JSON.parse(result.stdout);
+ expect(recovered).toMatchObject({
firstFailed: true,
frozenAfterFailure: "{}",
retryPublished: true,
- frozenAfterSuccess: {},
status: "failed",
findingCount: 1,
});
+ const frozenSources = Object.entries(recovered.frozenAfterSuccess);
+ expect(frozenSources).toHaveLength(1);
+ const [checkpointPath, checkpointDigest] = frozenSources[0]!;
+ expect(checkpointDigest).toMatch(/^[0-9a-f]{64}$/);
+ expect(checkpointPath).toBe(`checkpoints/${checkpointDigest}.json`);
}, 30_000);
test("preserves distinct instances from one worker candidate", () => {