fix(deep-scan): retain accepted work across input changes and discovery deadlines

This commit is contained in:
Michael D'Angelo
2026-11-07 01:51:30 -08:00
parent 245e3d9071
commit 61e39c757c
10 changed files with 266 additions and 40 deletions
@@ -6,6 +6,7 @@ import {
} from "./src/workbench-client.js";
import { resolvePythonCommand } from "./src/python_command.js";
import { startDeepScanEngine } from "./src/deep-scan/engine.js";
import { DeepScanModelInputRecoveryError } from "./src/deep-scan/model-file-inputs.js";
import { resolveDeepWorkerParentSandbox } from "./src/deep-scan/parent-sandbox.js";
import { DeepScanCoordinatorRegistry } from "./src/deep-scan/registry.js";
import { WorkbenchDeepScanStore } from "./src/deep-scan/store.js";
@@ -92,6 +93,17 @@ export async function runCliDeepScan(): Promise<void> {
manifestPath: terminal.manifestPath,
}) + "\n",
);
} catch (error) {
if (scanId && error instanceof DeepScanModelInputRecoveryError) {
process.stdout.write(
JSON.stringify({
scanId,
error: "model_input_recovery",
message: error.message,
}) + "\n",
);
}
throw error;
} finally {
const coordinator = scanId === undefined ? undefined : registry.get(scanId);
registry.shutdown("cli_engine_closed");
@@ -1041,9 +1041,7 @@ export class DeepScanCoordinator {
nextLabel: () => string,
previousFindings: string[],
): Promise<DiscoveryOutcome[]> {
await this.options.executor.validateModelFileInputs?.(
this.discoveryAbortController.signal,
);
if (!(await this.discoveryWorkers.validateModelFileInputs())) return [];
// Reserve in dispatch order. Another coordinator may create one of these
// labels after our directory listing but before we write its prompt.
const labels: string[] = [];
@@ -77,6 +77,22 @@ type WorkerAttemptOutcome =
export class DeepScanWorkerRunner {
constructor(private readonly options: DeepScanWorkerRunnerOptions) {}
/** Discovery can stop while a model-input file is being read. */
async validateModelFileInputs(): Promise<boolean> {
const { executor, signal } = this.options;
try {
await executor.validateModelFileInputs?.(signal);
} catch (error) {
if (
!signal.aborted ||
(error !== signal.reason &&
!(error instanceof Error && error.name === "AbortError"))
)
throw error;
}
return !signal.aborted;
}
async runDiscoveryWorker(
workerId: string,
workerLabel: string,
@@ -233,8 +249,8 @@ export class DeepScanWorkerRunner {
}
// The coordinator checks the initial batch before reserving work. Retry
// delays may outlive the captured file contents.
if (attempt > 1)
await this.options.executor.validateModelFileInputs?.(signal);
if (attempt > 1 && !(await this.validateModelFileInputs()))
return await this.cancelAttempt(input, attempt - 1, lastThreadId);
let validationStarted = false;
let validationCompleted = false;
let activeThreadId = resumableThreadId;
@@ -2,9 +2,12 @@ import assert from "node:assert/strict";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { after, test } from "node:test";
import { readJson } from "./support/json.ts";
import type { CodexWorkerRequest } from "../src/deep-scan/types.ts";
import {
coordinatorFixture,
createCoordinator,
FakeExecutor,
immediateClock,
readModelFileInputs,
runCoordinator,
@@ -72,3 +75,71 @@ test("a changed model file stops discovery retries and preserves interrupted sib
),
);
});
for (const stage of ["batch", "retry"] as const) {
test(`a discovery deadline during ${stage} model-file validation retains accepted evidence`, async (t) => {
const { fixture, store } = await coordinatorFixture({
stopAfterNoNew: 99,
maxDiscoveryRuns: 8,
});
const first = new FakeExecutor({ discoveryCandidateId: "accepted" });
let turns = 0;
let discoverySignal: AbortSignal | undefined;
let entered!: () => void;
const validating = new Promise<void>((resolve) => {
entered = resolve;
});
t.mock.timers.enable({ apis: ["setTimeout"] });
const coordinator = createCoordinator(
fixture,
store,
{
async validateModelFileInputs(signal) {
discoverySignal ??= signal;
if (
signal !== discoverySignal ||
turns !== (stage === "batch" ? 1 : 2)
)
return;
entered();
return new Promise<void>((_, reject) =>
signal.addEventListener("abort", () => reject(signal.reason), {
once: true,
}),
);
},
async run(request) {
if (++turns === 1) return first.run(request);
throw new Error("transient connection failure");
},
},
{ discoveryTimeoutMs: 500, retryDelaysMs: [1], clock: immediateClock },
);
t.after(() => coordinator.cancel("fixture cleanup"));
coordinator.start();
await validating;
t.mock.timers.tick(500);
t.mock.timers.reset();
const terminal = await coordinator.wait(undefined, 5_000);
assert.equal(terminal?.status, "succeeded", terminal?.error);
assert.equal(terminal.terminalReason, "capped");
const manifest = await readJson(terminal.manifestPath);
assert.deepEqual(
manifest.findings.map(
(finding: { provenance: { candidateId: string } }) =>
finding.provenance.candidateId,
),
["accepted"],
);
assert.equal(turns, stage === "batch" ? 1 : 2);
assert.equal(store.iterations[0]?.workerIds.length, 1);
assert.deepEqual(store.finishCalls[0]?.omittedWorkerIds, []);
assert.equal(store.failureMessages.length, 0);
if (stage === "retry")
assert.ok(
store.workerUpdates.some(
(worker) => worker.status === "canceled" && worker.attempt === 1,
),
);
});
}
@@ -184,6 +184,13 @@ async function run() {
complete: true,
});
}
if (
complete &&
process.env.PACKAGE_DEEP_CHANGE_INPUT &&
basename(join(root, "..")) === "discovery-0001"
) {
await writeFile(process.env.PACKAGE_DEEP_CHANGE_INPUT, "Changed input.");
}
await trace({
phase: layout,
complete,
@@ -81,6 +81,11 @@ try {
`Validated installed SDK direct Deep Scan${retryMissingResult ? " and worker retry" : ""}.`,
),
),
runInstalledSdk(installedPlugin, executable, true).then(() =>
console.log(
"Validated model-input recovery through the installed SDK direct engine.",
),
),
runDetachedPlugin(detachedPlugin, executable).then(() =>
console.log("Validated detached plugin restart and finalization."),
),
@@ -292,27 +297,7 @@ async function runDetachedPlugin(pluginRoot, executable) {
} finally {
await rpc.close();
}
// Simulate an expired owner lease without waiting for wall-clock expiry. Keep
// the real stored workers/results and use the production recovery path.
await rm(
join(
scanDir,
"artifacts",
"deep_discovery",
`coordinator-heartbeat-${partial.coordinatorGeneration}.json`,
),
{ force: true },
);
await promisify(execFile)(
f.env.PYTHON,
[
"-c",
"import sqlite3,sys; c=sqlite3.connect(sys.argv[1]); c.execute('UPDATE deep_scan_runs SET updated_at = ? WHERE scan_id = ?', ('2000-01-01T00:00:00Z',sys.argv[2])); c.commit()",
join(f.env.CODEX_SECURITY_STATE_DIR, "workbench.sqlite3"),
scanId,
],
{ env: f.env },
);
await expireLease(f, scanDir, scanId, partial.coordinatorGeneration);
await rm(f.env.PACKAGE_DEEP_HOLD);
rpc = await server(f);
try {
@@ -368,6 +353,30 @@ async function runDetachedPlugin(pluginRoot, executable) {
await assertExecutions(f, scanId);
}
async function expireLease(f, scanDir, scanId, generation) {
// Simulate an expired owner lease without waiting for wall-clock expiry. Keep
// the real stored workers/results and use the production recovery path.
await rm(
join(
scanDir,
"artifacts",
"deep_discovery",
`coordinator-heartbeat-${generation}.json`,
),
{ force: true },
);
await promisify(execFile)(
f.env.PYTHON,
[
"-c",
"import sqlite3,sys; c=sqlite3.connect(sys.argv[1]); c.execute('UPDATE deep_scan_runs SET updated_at = ? WHERE scan_id = ?', ('2000-01-01T00:00:00Z',sys.argv[2])); c.commit()",
join(f.env.CODEX_SECURITY_STATE_DIR, "workbench.sqlite3"),
scanId,
],
{ env: f.env },
);
}
async function workbench(f, args) {
const { stdout } = await promisify(execFile)(
f.env.PYTHON,
@@ -381,9 +390,24 @@ async function workbench(f, args) {
return JSON.parse(stdout);
}
async function runInstalledSdk(pluginRoot, executable) {
const f = await fixture("installed", pluginRoot, executable);
if (retryMissingResult) {
async function runInstalledSdk(pluginRoot, executable, changeInput = false) {
const f = await fixture(
changeInput ? "input-recovery" : "installed",
pluginRoot,
executable,
);
let configPath;
if (changeInput) {
f.env.PACKAGE_DEEP_CHANGE_INPUT = join(f.home, "instructions.md");
await writeFile(f.env.PACKAGE_DEEP_CHANGE_INPUT, "Original input.");
configPath = join(f.home, "selected-config.toml");
await writeFile(
configPath,
`model_instructions_file = ${JSON.stringify(f.env.PACKAGE_DEEP_CHANGE_INPUT)}\n`,
);
f.env.CODEX_SECURITY_CONFIG_PATH = configPath;
}
if (retryMissingResult && !changeInput) {
f.env.PACKAGE_DEEP_EMPTY_ONCE = join(
f.directory,
"missing-result-completion",
@@ -399,11 +423,19 @@ async function runInstalledSdk(pluginRoot, executable) {
f.env.PACKAGE_DEEP_PARENT_THREAD = owner;
let scanId;
const client = new sdk.CodexSecurity(
{ pythonPath: f.env.PYTHON },
{
pythonPath: f.env.PYTHON,
...(changeInput && {
codexOverrides: {
model_instructions_file: f.env.PACKAGE_DEEP_CHANGE_INPUT,
},
}),
},
{
environment: f.env,
prepareRuntime: async () => ({
codexHome: f.home,
configPath,
deepScanConfigPath: join(f.home, "deep-scan-config.toml"),
environment: f.env,
credentialsAvailable: true,
@@ -434,7 +466,7 @@ async function runInstalledSdk(pluginRoot, executable) {
},
);
try {
const result = await client.run(f.target, {
const operation = client.run(f.target, {
mode: "deep",
onScanRegistered: (scan) => {
scanId = scan.scanId;
@@ -446,6 +478,63 @@ async function runInstalledSdk(pluginRoot, executable) {
stopAfterNoNew: 2,
outputDir: join(f.directory, "output"),
});
if (changeInput) {
await assert.rejects(operation, /model_instructions_file changed/);
const parent = (await workbench(f, ["get-scan", "--scan-id", scanId]))
.scan;
assert.equal(parent.progress.status, "running");
const query = [
"get-deep-scan",
"--scan-id",
scanId,
"--thread-id",
owner,
];
const paused = (await workbench(f, query)).deepScan;
assert.equal(paused.status, "running");
const accepted = paused.workers.filter(
(worker) =>
worker.kind === "discovery" && worker.status === "succeeded",
);
assert.equal(accepted.length, 1);
const receipt = await readFile(accepted[0].resultManifestPath);
await writeFile(f.env.PACKAGE_DEEP_CHANGE_INPUT, "Original input.");
await expireLease(
f,
parent.scanDir,
scanId,
paused.coordinatorGeneration,
);
const rpc = await server(f);
try {
const result = await rpc.call(
"start_codex_security_deep_scan",
{ scanId },
metadata(f, owner),
);
await assertDraft(result.manifestPath);
} finally {
await rpc.close();
}
const completed = (await workbench(f, query)).deepScan;
assert.equal(
completed.workers.filter(
(worker) =>
worker.kind === "discovery" && worker.status === "succeeded",
).length,
2,
);
assert.ok(
completed.workers.some(
(worker) =>
worker.id === accepted[0].id && worker.status === "succeeded",
),
);
assert.deepEqual(await readFile(accepted[0].resultManifestPath), receipt);
await assertExecutions(f, scanId);
return;
}
const result = await operation;
assert.equal(result.threadId, owner);
assert.equal(result.manifest.scan.status, "completed");
assert.ok(result.manifest.scan.sealedAt);
+7
View File
@@ -119,6 +119,7 @@ import { ScanProgressTracker, type DeepScanProgress } from "./scan-progress.js";
import { findScanSession } from "./scan-logs.js";
import {
DIRECT_DEEP_SCAN_CONTROL_USAGE,
DirectDeepScanInputRecoveryError,
deepScanParentToolOverrides,
readDeepScanParentConfig,
runDeepScan,
@@ -4263,6 +4264,12 @@ export class CodexSecurity {
?.stop(measuredExecution?.usage)
.catch(() => null);
if (artifactRestorationFailure !== null) throw artifactRestorationFailure;
// The coordinator deliberately kept its accepted worker receipts and run open.
if (
failure instanceof DirectDeepScanInputRecoveryError &&
!signal.aborted
)
throw failure;
const terminalTurnStatus = terminalScanTurnStatus();
const verifiedCost = snapshot?.measurement.cost;
if (
+24 -2
View File
@@ -411,6 +411,7 @@ export async function* runDeepScan(
node?.executable ?? process.execPath,
[join(options.pluginRoot, "mcp", "server.mjs"), "--deep-scan-engine"],
node?.environment ?? environment,
options.scanId,
JSON.stringify({
scanId: options.scanId,
...session,
@@ -436,10 +437,13 @@ export async function* runDeepScan(
};
}
export class DirectDeepScanInputRecoveryError extends CodexSecurityError {}
function runEngine(
command: string,
args: string[],
env: NodeJS.ProcessEnv,
scanId: string,
request: string,
signal: AbortSignal,
onDiagnostic: DirectDeepScanOptions["onDiagnostic"],
@@ -492,13 +496,31 @@ function runEngine(
signal.removeEventListener("abort", cancel);
if (signal.aborted) reject(signal.reason);
else if (processError) reject(processError);
else if (code !== 0)
else if (code !== 0) {
if (stdout.trim()) {
let receipt: unknown;
try {
receipt = JSON.parse(stdout);
} catch {
// An incomplete child reply still reports the original process error.
}
if (
isRecord(receipt) &&
receipt["scanId"] === scanId &&
receipt["error"] === "model_input_recovery" &&
typeof receipt["message"] === "string" &&
receipt["message"]
) {
reject(new DirectDeepScanInputRecoveryError(receipt["message"]));
return;
}
}
reject(
new CodexSecurityError(
stderr.trim() || `Deep Scan engine exited with code ${code}.`,
),
);
else resolve(stdout);
} else resolve(stdout);
});
});
child.stdin.write(request + "\n");
+9 -7
View File
@@ -6036,16 +6036,18 @@ describe("live scan cost tracking", () => {
type: "item.completed",
item: { type: "agent_message", text },
});
await appendSessionItem(parent, {
type: "custom_tool_call_output",
output:
'CODEX_SECURITY_SCAN_PROGRESS {"phase":"discovery","filesCompleted":0,"filesTotal":8}',
});
// The inventory marker is absent from this persisted output. Matching its
// completion is the only proof that the live 9-file inventory is newer.
// Publish the older receipt and its ordering evidence in the same batch.
// Until the persisted command is visible, the tool receipt can be newer.
await appendFile(
parent,
jsonLines([
{
type: "response_item",
payload: {
type: "custom_tool_call_output",
output: progressMarker("discovery", 0, 8),
},
},
native({
type: "CommandExecution",
command: ["inventory"],
@@ -67,6 +67,8 @@ if (request.diagnosticsVersion === 1 && process.env.SYNTHETIC_OLD_ENGINE !== '1'
process.send({ event: 'discovery_worker_replaced', scanId: request.scanId, reason: 'tool error' });
}
if (process.env.SYNTHETIC_FAIL === '1') {
if (process.env.SYNTHETIC_OLD_ENGINE !== '1')
console.log(JSON.stringify({scanId: request.scanId + "-other", error: "model_input_recovery", message: "Unrelated scan's recovery message"}));
process.stderr.write('first detail\\nlast detail');
process.exitCode = 1;
lines.close();