Repository navigation
fix(deep-scan)!: complete shared execution and durable recovery - #1141
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Shared plugin restoration can disrupt active workers and retain a stale installed path.
Review effort: Balanced
Findings: 1
Open (2)
What changed in this PR
Prepares shared configuration and runtime state for Deep Scan worker launches.
Changes:
- Centralizes worker configuration, environment, authentication, and plugin preparation.
- Resolves profiles before worker launch and preserves complete configuration tables.
- Expands fresh/resumed worker configuration coverage.
| File | Description |
|---|---|
sdk/typescript/src/api.ts |
Adds prepared execution support and resolved runtime configuration. |
sdk/typescript/src/config.ts |
Consolidates scan composition overrides. |
sdk/typescript/src/execution-preparation.ts |
Adds worker locking and plugin restoration. |
sdk/typescript/src/runtime.ts |
Tracks and restores selected plugin roots. |
sdk/typescript/tests-ts/api-credentials.test.ts |
Updates configuration inheritance expectations. |
sdk/typescript/tests-ts/api-events.test.ts |
Updates worker launch serialization coverage. |
sdk/typescript/tests-ts/api-policy.test.ts |
Covers provider-table preservation. |
sdk/typescript/tests-ts/api-preflight-config.test.ts |
Covers profile resolution and cyber access settings. |
sdk/typescript/tests-ts/config.test.ts |
Tests pinned worker settings across shared-home changes. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| if (session.runtimeConfig !== undefined) | ||
| await restorePluginSelection(runtime.codexHome, runtime.plugin, { | ||
| codexCommand: session.source.command, | ||
| environment: session.source.environment, | ||
| signal: options.signal, | ||
| }); |
There was a problem hiding this comment.
Confirmed with a synthetic variant of the existing active-coordinator runtime test at stack tip 835f0d1. An unchanged selection preserves the installed directory and the next subprocess reaches the expected empty-stdin error. Bootstrapping a second root with the same plugin version but different helper contents replaces that directory (inode changes); the already-running coordinator's next Codex subprocess instead returns No such file or directory (os error 2). The prepared-worker restore path can perform this replacement after the first worker's startup lock has been released. The installation needs to remain stable while that worker is using it.
| installed["pluginRoot"] !== plugin.pluginRoot || | ||
| installed["version"] !== plugin.version | ||
| ) | ||
| await bootstrapPlugin(codexHome, plugin.pluginRoot, options); |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7666804547
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (this.#preparedExecution !== undefined) { | ||
| const prepared = this.#preparedExecution; | ||
| return { |
There was a problem hiding this comment.
Validate plugin version for prepared sessions
When a resumed Deep Scan supplies expectedPluginVersion, this new early return bypasses the version comparison later in #prepareSession. If the installed plugin changed between the original scan and resume, the prepared worker therefore proceeds with the incompatible plugin instead of rejecting the resume, potentially producing artifacts under different plugin semantics. Preserve the version check on this path before returning the prepared session.
AGENTS.md reference: AGENTS.md:L30-L34
Useful? React with 👍 / 👎.
| if (session.runtimeConfig !== undefined) | ||
| await restorePluginSelection(runtime.codexHome, runtime.plugin, { | ||
| codexCommand: session.source.command, | ||
| environment: session.source.environment, | ||
| signal: options.signal, |
There was a problem hiding this comment.
Keep each worker's plugin installation stable
When concurrent prepared scans share a CODEX_HOME but select different plugin roots or versions, this restoration can invoke bootstrapPlugin and replace the shared installed tree. The wrapper releases the credential-home lock on the first emitted event, so another worker can replace that tree while the first turn is still running; the first scan subsequently uses its saved runtime.plugin.installedRoot for event processing, validation, and publication, which can now be deleted or contain the other scan's plugin. Use a per-scan installation or otherwise keep the selected tree stable for the worker's full lifetime.
AGENTS.md reference: AGENTS.md:L30-L34
Useful? React with 👍 / 👎.
faizan-oai
left a comment
There was a problem hiding this comment.
Holding approval for the shared plugin-installation issue. I reproduced the existing review concern on the current stack: two different plugin selections with the same version replace the installed directory while an earlier coordinator is still using it, and its next Codex subprocess fails with No such file or directory (os error 2). The unchanged-selection control passes. Details added to the existing thread.
alandelong-oai
left a comment
There was a problem hiding this comment.
Reviewed the prepared-runtime change at 766680454707975c8f249c73c3288d6e2d1e8e29 with three independent passes and root verification. Two existing issues remain reproducible:
- Restoring a selection can replace a plugin still used by another worker. With the real bundled installer and two synthetic same-version plugins, restoration changed the installed directory inode and the running process’s next command failed because its working directory was gone.
- Prepared sessions bypass the expected plugin-version check. The ordinary SDK path rejects a synthetic version mismatch; the prepared path proceeds to output allocation.
After rebuilding the plugin, all five changed SDK test files pass: 167 tests, 3 skipped. No duplicate inline comments added.
7666804 to
ab664f3
Compare
alandelong-oai
left a comment
There was a problem hiding this comment.
Re-reviewed the restacked head with three independent passes and root verification. Per-operation plugin installs address the previous shared-install replacement problem. Two new P2 startup problems remain: legacy Deep plugins can acquire the same non-reentrant credential lock twice, and the authentication-status config rewrite bypasses that lock. Inline reproductions below.
Validation: SDK types and plugin build passed. The six focused SDK files had 170 passes, 3 skips and 1 failure; the parallel ChatGPT configuration test still expects no shared model and fails again in isolation. That test also needs to reflect the new startup-lock/event contract; its failure alone does not prove a native concurrency regression. Disposable probes used real credential locking and synthetic runtime/native boundaries, with no model calls.
| }); | ||
| checkOpen(); | ||
| const runtimeConfig = | ||
| runtime.configPath === undefined || runtime.preserveCodexHomeConfig |
There was a problem hiding this comment.
[P2] Avoid reacquiring the retained legacy Deep credential lock
For a Deep plugin without isolated configuration support, the earlier release condition keeps releaseCredentialHome held for the scan lifetime. This new runtimeConfig also enables the execution wrapper, which acquires the same non-reentrant credential lock before entering the native turn. Startup therefore waits on its own lock until canceled. In an actual SDK startup probe with managed runtime preparation and the real SQLite lock, the legacy plugin never reached the stubbed native turn and aborted after 2.1 seconds; the otherwise identical plugin with isolated-config support reached it in 92 ms. Ensure a session already holding this lock does not acquire it again.
| runtime.configPath !== undefined && | ||
| !runtime.preserveCodexHomeConfig | ||
| ) | ||
| await writeCodexConfig(join(runtime.codexHome, "config.toml"), { |
There was a problem hiding this comment.
[P2] Serialize authentication config rewrites with native startup
The preceding block releases the credential lock before this new config.toml rewrite. When cached credentials are absent (including keyring-backed authentication), another scan can hold the startup lock after installing its selected configuration while this account-status path overwrites it. Project trust is particularly affected because execution omits projects from argv and relies on the shared file. A controlled SDK probe with an injected prepared runtime and the real credential lock held by another client changed that client's model and project trust before authentication failed. Hold the same lock across this rewrite and authentication startup, or use an isolated configuration path.
22c019e to
b404833
Compare
ab664f3 to
86f0929
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 86f092967f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| await writeCodexConfig(join(runtime.codexHome, "config.toml"), { | ||
| ...sessionConfig, | ||
| ...codexSecurityPluginRegistration(runtime.plugin), | ||
| }); |
There was a problem hiding this comment.
Hold the credential-home lock while restoring probe config
When concurrent managed clients share a credential home and this scan needs the stored-credential probe, #prepareSession has already released releaseCredentialHome before this write. The write can therefore overwrite config.toml while another scan holds the lock for plugin preparation or native startup; because project trust is intentionally omitted from argv overrides, that process can read the wrong scan's project/settings configuration and fail or run with incorrect trust. Reacquire the credential-home lock and retain it through accountStatus so this restoration cannot interleave with another scan.
AGENTS.md reference: AGENTS.md:L30-L34
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Re-reviewed the real PR diff at 86f092967f3d9647d4fb6ca97c91561f3e3a6946. Three independent high-reasoning passes covered the complete changed patch and tests; root source checks and focused reproductions informed this decision.
The legacy-plugin lock deadlock is fixed at this head: both legacy and isolated-plugin probes reach native startup and release their locks. The existing authentication configuration race remains at this boundary: source releases the managed credential lock before rewriting config.toml and querying authentication, and the real managed probe observes login status with the lock absent. The later #1162 implementation holds the lock through this operation; no surviving integrated managed-runtime race is claimed.
Validation across touched paths at branch tip 06e75cfe: 1,356 SDK tests, 867 Python tests plus 100 subtests, and 108 MCP tests passed; builds, types, portable checks and installed-package checks passed. These are integration checks at the branch tip, not a claim that every intermediate PR or its CI is clean. Latest workflow runs for this unchanged head were verified successful at 2026-10-02 01:26 UTC. Earlier failed or canceled job records are superseded; this CI status correction does not alter the review decision.
b404833 to
d75c4fd
Compare
86f0929 to
9d264c7
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9d264c71c0
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| session.runtimeConfig === undefined || | ||
| session.releaseCredentialHome !== null | ||
| ? undefined | ||
| : await lockExecutionConfiguration( |
There was a problem hiding this comment.
Write config while holding the legacy Deep Scan lock
When a managed Deep Scan uses a plugin without isolated Deep Scan config support, #prepareSession retains releaseCredentialHome, so this branch skips writing sdkCodexConfig. The existing home file contains only sharedCredentialCodexConfig, while projects is also removed from native argv at line 239; consequently explicit project trust/settings are absent when Codex starts. Write the complete launch config while the already-held lock is active rather than treating a non-null release handle as proof that it was written.
AGENTS.md reference: AGENTS.md:L31-L35
Useful? React with 👍 / 👎.
d75c4fd to
8ca7ef6
Compare
9d264c7 to
234087b
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 234087b799
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const marketplaceName = options.isolateSelection | ||
| ? `${MARKETPLACE_NAME}-${await pluginSelectionDigest(root, options.signal)}` | ||
| : MARKETPLACE_NAME; |
There was a problem hiding this comment.
Reclaim inactive content-addressed plugin installations
When a local plugin is edited between scans, or the bundled plugin changes after an upgrade, this content-derived marketplace name creates a new persistent marketplace and Codex installation for every distinct revision. No cleanup path removes older digest-named marketplaces or their installed trees, so repeated development scans or upgrades continually add full plugin copies under the credential home and can eventually exhaust disk space. Retain active selections, but remove unreferenced digest installations once no scan can still be using them.
Useful? React with 👍 / 👎.
| ...prepared, | ||
| sessionConfig: structuredClone(prepared.sessionConfig), | ||
| effectiveConfig: structuredClone(prepared.effectiveConfig), | ||
| releaseCredentialHome: null, |
There was a problem hiding this comment.
Preserve inherited legacy-lock ownership for prepared workers
When a prepared Deep Scan session comes from a legacy or custom plugin without isolated Deep Scan config, the coordinator intentionally retains releaseCredentialHome for the entire scan. Replacing that handle with null makes createExecutionCodex treat the worker as unlocked and wait in lockExecutionConfiguration, while the coordinator is awaiting that worker and will release its lock only during final cleanup, so discovery or reducer startup deadlocks. Carry an explicit already-locked state without transferring release ownership to the worker.
AGENTS.md reference: AGENTS.md:L31-L35
Useful? React with 👍 / 👎.
alandelong-oai
left a comment
There was a problem hiding this comment.
Three fresh independent full-diff reviews plus root verification at 234087b79906.
The credential-home authentication race is fixed: an actual managed overlap probe preserves the other client configuration while its lock is held. Legacy native startup now retains explicit project trust in the home config and reaches the native execution boundary; both legacy and isolated variants release the lock. Four worker boundary tests pass, covering fresh/resumed settings and permissions. The new inherited-lock bot claim requires an injected internal prepared session at this own head: the public coordinator does not yet construct prepared workers here. At later activation, managed sessions release the lock before workers run. It is not retained as a demonstrated public regression. No serious introduced finding remains.
Current tip 355ec321 passed 75 report-projection tests, portable source checks, SDK build:ci and plugin build. The immediately preceding tip fec36f1d passed 1,360 SDK tests, 873 Python tests plus 100 subtests, 109 MCP tests, builds/types and the clean 600-entry installed-package check. Only report_projection.py and its test changed between those tips; SDK/MCP runtime files are byte-identical. Both descend from main 008a8b4d. These are integration checks, separate from own-head probes. No native Windows local run.
No serious outstanding finding introduced by this PR. Code review approval does not establish CI or merge readiness.
8ca7ef6 to
8311e7c
Compare
234087b to
46974dd
Compare
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
alandelong-oai
left a comment
There was a problem hiding this comment.
Retained the three independent passes for the verified identical patch and reconciled inherited touched-file changes at 46974dd6b83e.
No actionable introduced finding survives the independent reviews and root reconciliation of this exact patch and inherited changes in touched files.
Integrated tip 6ef8cbb8, based on 008a8b4d, passed 1,388 SDK tests, 879 Python tests plus 100 subtests, 109 MCP tests, portable checks, builds and the clean 600-entry installed-package check. These are branch-tip integration checks, separate from own-head probes; no local Windows execution was performed.
No serious outstanding finding introduced by this PR. Code approval is separate from CI and merge readiness.
46974dd to
d76ccce
Compare
8311e7c to
ba67e0d
Compare
alandelong-oai
left a comment
There was a problem hiding this comment.
Completed three independent full-diff passes and root verification at d76ccce26799.
No actionable introduced finding survives the independent reviews and root reconciliation of this exact patch and inherited changes in touched files.
Branch tip 3e0083d9, based on 008a8b4d, passed 1,392 SDK tests, 881 Python tests plus 100 subtests, 109 MCP tests, builds, portable source checks and the 600-entry installed-package check. These are tip checks, separate from own-head probes. No local Windows run was performed. The tip excludes the dependency update merged separately in #1184; combined validation remains outstanding.
No serious outstanding finding introduced by this PR. Code approval is separate from CI and merge readiness.
ba67e0d to
68e772b
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8120b651aa
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let pluginRoot = | ||
| savedRuntime?.plugin.pluginRoot ?? | ||
| this.#dependencies.ambientExecution?.pluginRoot; |
There was a problem hiding this comment.
Read sealed scans from the stable plugin snapshot
When a reused client reads a sealed scan after its configured local plugin directory has been edited, moved, or deleted, this new fast path selects the mutable plugin.pluginRoot; the subsequent metadata and workbench operations can therefore fail or use helper semantics different from those that produced the scan, despite bootstrapPlugin retaining the content-addressed installedRoot. Fresh evidence beyond the earlier installation-race report is that this sealed-resume path explicitly selects pluginRoot rather than the stable installed snapshot; use a retained stable plugin copy here.
AGENTS.md reference: AGENTS.md:L11-L13
Useful? React with 👍 / 👎.
| } else if (session.source.preserveProviderEnvironment) { | ||
| const nativeConfig = sharedCredentialCodexConfig( | ||
| effectiveConfig, | ||
| runtimeHome, | ||
| ); | ||
| return `Scan target paths: resolve every requested file and all non-ignored descendants of requested directories using ${python} ${helper} make-repo-scope-input --repo ${shellEnvironmentReference("CODEX_SECURITY_REPOSITORY")} --scopes-file ${scopes} --out ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR", "/scoped-source-input.jsonl")}. Before finalization, preserve every requested scope with ${python} ${helper} bind-repo-scopes --scopes-file ${scopes} --manifest ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR", "/scan-manifest.json")} --coverage ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR", "/coverage.json")}. Do not print, evaluate, or modify the target-paths file.`; | ||
| } | ||
| if (target.kind === "refs") { | ||
| return `Scan target: Git diff from ${target.base} to ${target.head}.`; | ||
| const savedConfig = recipe["config"] as JsonObject; | ||
| for (const key of ["model_providers", ...CODEX_AUTH_CONFIG_KEYS]) { |
There was a problem hiding this comment.
Preserve custom provider configuration in resume recipes
When a CLI or SDK Deep Scan uses a user-defined model provider—especially one configured with auth.command—without inherited native permissions or preserveProviderEnvironment, this branch is skipped and the saved recipe retains only scanPreflightCodexConfig, which omits custom model_providers entries. scans resume later feeds that sanitized recipe back as codexOverrides, so the provider's base URL and authentication command are unavailable and the interrupted scan cannot resume with its original authentication/settings. Preserve the selected provider table for these ordinary managed scans as well.
AGENTS.md reference: AGENTS.md:L31-L35
Useful? React with 👍 / 👎.
| const filesystem = readOnlyFilesystem( | ||
| profile["filesystem"] as JsonObject, | ||
| ); |
There was a problem hiding this comment.
Preserve repository writes for post-scan prompts
When a post-scan prompt is expected to modify the repository and the scan's permission profile grants write access there, applying readOnlyFilesystem to the entire profile silently converts that unrelated repository grant to read-only. The new follow-up thread can therefore write only its artifact subdirectory and cannot perform the documented requested repository changes that the original scan permissions allowed; restrict the read-only override to the sealed scan-artifact tree while retaining permissions for paths outside scanDir.
AGENTS.md reference: AGENTS.md:L43-L45
Useful? React with 👍 / 👎.
8120b65 to
1bd5397
Compare
465d525
into
mdangelo/codex/pr939-stack-18-native-preparation


Summary
Complete Deep Scan composition with isolated worker settings and recoverable saved results. Fresh and resumed workers use the same selected configuration; interrupted scans retain accepted findings, corrected child observations, coverage, provenance, and usage without rerunning completed work.
Changes
Testing
Completed on the integrated changes:
Full Python suite: 1,673 passed, 8 skipped, plus 162 subtests passed.
Full MCP suite: 172 passed, no failures or skips.
Ruff lint and format, MCP TypeScript check, SDK
build:ci, SDK formatting and type checks: passed.Portable plugin source compatibility and its 9 tests: passed.
Plugin and production builds, the 617-entry package check, and installed-package smoke tests: passed.
Focused recovery, worker-launch, publication-retry, and concurrent-draft regression tests: passed.
Three fresh native code reviews and independent verification on the final commit: passed, with no findings.
Full SDK suite in both seed-12345 and randomized order, three CI shards each: 3,990 passed, 48 skipped per run across 177 files. One randomized shard hit a 30-second timeout during high host load; rerunning that entire shard alone with the same seed and unchanged timeout passed. The original timeout log was retained.
Risk and rollout
The base PR remains open against
main. New changes merged intomainduring consolidation overlap this work and require a separate conflict-resolution pass before the base PR can merge.Current Deep Scan checkpoints use the v3 composition protocol. Unfinished coordinator/version-2 scans require their original version to finish, or a new scan; older sealed scans still need a usable receipt when cost tracking is required. Historical artifacts and append-only database migrations remain supported. A saved accepted v3 merge can retry publication without repeating completed discovery or matching.
--workersnow controls a batch of independent Standard scans, merged in original order before the next batch starts.--stop-after-no-newcounts successfully merged scans and is checked after each batch, so a batch can pass the threshold; failures consume discovery runs without counting toward that threshold. Option defaults are unchanged.SDK callers must allow
ScanResult.threadIdandScanResultOptions.threadIdto benull. Draft clients must reuse finding identities and coverage/deferred IDs for updates; missing IDs create new rows, except an unambiguous deferred candidate can reuse its existing ID.postScanPromptstarts a separate conversation with saved-result context underartifacts/follow-up/<id>. Requested repository changes retain the scan's existing permissions, and sealed artifacts remain protected. Publicscans resume SCAN_IDremains limited to eligible Deep Scans.Workbench compatibility changes:
begin-deep-scanreturns the SDK scan record and removes--available-parallelismand--workflow-version.get-deep-scan,claim-deep-scan-coordinator,upsert-deep-scan-worker,claim-deep-scan-dedup,commit-deep-scan-dedup,finish-deep-scan,fail-deep-scan, andrecord-deep-scan-publication-failure, plus coordinator-generation and MCP artifact-writer dispatch.write-scan-draft --scan-id <id>accepts{documents, checkpoint}on stdin when--draft-pathis omitted; staged-file input remains supported.--claim-tokento continuation/accounting operations,--defer-publicationtocancel-scanandfail-scan, and--after-stop/--cost-jsontopreserve-scan-results. Ordinary stop commands continue publishing available results by default.Source plugin builds require the SDK checkout; the distributed plugin contains its runtime dependencies. This PR targets its parent topic branch; the consolidated base PR remains open against main.
Public disclosure review