Skip to content

Scan is recorded as complete-scan before the SDK validates the scan contract #34

Closed

Description

@mariohercules

Summary

complete-scan is recorded in the workbench before the SDK validates the scan contract. Any validation failure after that point leaves the scan permanently recorded as completed, and fail-scan is never sent.

In runScanEvents, the finalize hook runs first and collectResult runs after it:

if (options.onFinalize !== undefined) {
usage = (await options.onFinalize(usage)) ?? usage;
}
const result = await collectResult(
{
status,
finalResponse,
usage,
...(options.model === undefined ? {} : { model: options.model }),
},
threadId,

The finalize hook issues complete-scan and then clears activeScan:

onFinalize: async (usage) => {
const snapshot = await tracker.stop(usage);
throwIfAborted(signal, scanDir);
if (options.maxCostUsd !== undefined && snapshot.cost === null) {
throw new CodexSecurityError(
"Cannot evaluate the cost limit: model pricing or token usage is unavailable.",
);
}
const cost = snapshot.cost;
await workbench(workbenchOptions, [
"complete-scan",
"--scan-id",
scanId,
...(cost === null ? [] : ["--cost-json", JSON.stringify(cost)]),
]);
activeScan = null;
return snapshot.usage;
},

Because the failure handler is guarded by if (activeScan !== null), it is skipped for everything thrown after the finalize hook, so no fail-scan is recorded.

This matters because the two sides do not agree on what "complete" means. workbench_db.py complete-scan requires only the manifest (line 1499):

manifest = read_json_object(artifact_path(scan_dir, ARTIFACTS["manifest"], required=True))

while the SDK's collectResult additionally requires findings.json, coverage.json and report.md, and then runs full contract validation (Ajv schema validation of all three documents, artifact digest recomputation, seal consistency, and the expectation cross-check). Every check in that second group can reject a bundle the workbench has already accepted.

Affected version and environment

  • Released package: @openai/[email protected]
  • Confirmed on current main at f22d4a36f26d16287bcdfd707b369116e02a08c3
  • macOS 26.5.2 (build 25F84)
  • Node.js v24.5.0
  • Bun 1.3.14

Steps to reproduce

This reproduces without any API call, using the same injected-dependency pattern as tests-ts/api.test.ts. The scan directory is the bundled _bundled_plugin/examples/completed-scan fixture, which contains scan-manifest.json, findings.json and coverage.json but no report.md — so the plugin's own complete-scan artifact check passes and the SDK's collectResult rejects.

const client = new TestClient(
  {},
  {
    environment: {},
    prepareRuntime: async () => preparedRuntime(codexHome),
    resolvePluginPython: async () => "/managed/python",
    prepareOutputDir: async () => scanDir,        // contains the example bundle, no report.md
    repositoryRevision: async () => "deadbeef",
    runWorkbench: async (_options, args) => {
      commands.push(args);
      return args[0] === "register-cli-scan"
        ? { scanId: "scan_example_001", targetId: "target_sha256_example", scanDir }
        : {};
    },
    createCodex: () => ({
      startThread: () => ({
        id: null,
        async runStreamed() {
          async function* events() {
            yield { type: "thread.started", thread_id: "scan-thread" };
            yield { type: "turn.completed", usage: {} };
          }
          return { events: events() };
        },
      }),
    }),
  },
);

await client.run(repository);   // rejects

Observed result:

--- run() rejected with ---
IncompleteScanError: Codex Security scan completed without required artifacts: report.md

--- workbench commands recorded ---
["register-cli-scan","complete-scan"]

--- verdict ---
{
  "runRejected": true,
  "completeScanRecorded": true,
  "failScanRecorded": false
}

Expected behavior

A scan that fails contract validation should not remain recorded as completed. complete-scan should be issued only after collectResult succeeds, or activeScan should stay set until the result is fully built so the existing fail-scan path still runs.

Actual behavior

run() rejects and the CLI exits 2, but the workbench has already recorded the scan as completed. scans list reports it as a completed scan, and scans show, scans rerun, scans compare and list-unmatched-scan-pairs will treat the rejected bundle as a valid baseline.

Impact

The failure is visible in the moment — the user sees an error and a nonzero exit — but the recorded state contradicts it. A later comparison can silently baseline against a scan the SDK refused to accept, which is difficult to notice because nothing in scans list distinguishes it from a genuine completion.

Note on the existing tests

The invariant is already asserted for one other failure mode. tests-ts/api.test.ts pins that a cost-limit abort records fail-scan and never records complete-scan:

"fail-scan",
"--scan-id",
"scan_example_001",
"--message",
`Scan stopped: estimated cost $0.00625 exceeded the $0.005 limit; partial output remains at ${scanDir}.`,
"--cost-json",
JSON.stringify(cost),
]);
expect(commands.some((args) => args[0] === "complete-scan")).toBe(false);

There is no equivalent assertion for a contract-validation failure, which is how this path went uncovered.

The full existing suite passes on this machine (361 pass, 3 skip, 0 fail) with python3 resolving to 3.12, so this is not a local-environment artifact.

Activity

  1. mariohercules commented on Aug 1, 2026

    @mariohercules
    ContributorAuthor

    Verified fixed on current main (a8fc009). Closing.

    Completion is now split into two phases: prepare-scan-completion runs inside the event loop, and complete-scan runs only after runScanEvents returns — that is, after collectResult has validated the contract. activeScan is cleared after that call rather than inside the finalize hook, so a validation failure still reaches the fail-scan path.

    Re-running the original reproduction against main, with a bundle that fails artifact validation:

    run():              rejected: IncompleteScanError: Codex Security scan completed without required artifacts
    workbench commands: ["register-cli-scan","get-scan-feedback","prepare-scan-completion","fail-scan"]
    
    complete-scan recorded: false
    fail-scan recorded:     true
    

    Both halves of the report are addressed: the scan is no longer recorded as completed, and the failure is recorded. Thanks for the restructure.

  2. added
    bug
    on Aug 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions