Repository navigation
fix(security-worker): don't fail shards when a scan workspace can't be deleted - #4819
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
Make removeScanWorkspace private and drop its test-only return value. Prove the fix through processJob's recorded result instead of the helper, narrow the errno code without a cast, and tighten the spec note.
|
/clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesThis PR makes scan-workspace deletion best effort so permission errors do not replace job outcomes or stop subsequent claims. Example: A five-job worker queue encounters undeletable workspace subdirectories for jobs 2 and 5.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review No blocking findings. This maintainer-authored PR fixes a current-main shard failure while preserving container-custody safeguards, and the supplied CLI proof exercises the changed behavior successfully. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe security worker claims backend scan jobs, processes artifacts, records outcomes, and removes temporary workspaces before accepting more work. flowchart TD
A[Convex job queue] --> B[Worker CLI and pool]
B --> C[Process scan job]
C --> D[Record job outcome]
D --> E[Workspace cleanup]
E --> F[Continue claiming]
C --> G[Unconfirmed container removal]
G --> H[Preserve workspace and stop]
Technical reviewBest possible solution: Land the focused outcome-preserving cleanup change with its regression test and explicit residue policy. Do we have a high-confidence way to reproduce the issue? Current-main source establishes the failing finally-to-pool path, supported by the contributor's production excerpt and paired Linux CLI trace; no target code was executed during this review. Is this the best way to solve the issue? Best-fix verdict: best for preserving shard outcomes; catching at the pool would lose the recorded result, while privileged deletion would add machinery beyond the accepted residue policy, and the inspected CLI, processJob, logger, custody branch, qualification helper, and sibling prepublication worker support this boundary. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 4fff91800b08. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (3 earlier review cycles)Reviewed November 16, 2026, 10:24 PM ET / November 17, 2026, 03:24 UTC (Revision 4). |
After-fix proof: real worker pool under Bun 1.4.4 on LinuxRun against Setup:
Result
Probe source (pool-probe.ts)// Proof probe: drive the real runContinuouslyRefilledWorkerPool -> processJob path
// under Bun. Jobs 2 and 5 get a non-writable subdirectory (stand-in for the
// root-owned files Docker sandboxes leave) after their outcome is recorded.
// Simulated: the Convex client (records the outcome, returns null) and the
// claim queue. Real: the pool, processJob, workspace creation and rm.
import { randomUUID } from "node:crypto";
import { chmod, mkdir, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const rev = process.argv[2]!;
const { processJob, runContinuouslyRefilledWorkerPool } = await import(
join(rev, "scripts/security/run-codex-scan-worker.ts")
);
const locked: string[] = [];
const workspaces: string[] = [];
function makeJob(lock: boolean) {
const jobId = `securityScanJobs:probe-${randomUUID()}`;
return {
lock,
claimed: {
job: {
_id: jobId,
hasMaliciousSignal: false,
leaseToken: "lease",
scanMode: "endor-report-only",
source: "publish",
targetKind: "packageRelease",
},
target: {},
},
};
}
let seq = 0;
const order = new Map<string, number>();
const client = (lock: boolean, jobId: string) => ({
action: async () => {
console.log(`PROBE job ${order.get(jobId)} outcome recorded${lock ? " (workspace will be locked)" : ""}`);
const name = (await readdir(tmpdir())).find((n) => n.startsWith(`clawhub-codex-scan-${jobId}-`));
if (!name) throw new Error("workspace not found");
const ws = join(tmpdir(), name);
workspaces.push(ws);
if (lock) {
const dir = join(ws, "sandbox-output");
await mkdir(dir);
await writeFile(join(dir, "log.txt"), "x");
await chmod(dir, 0o500);
locked.push(dir);
}
return null;
},
});
const queue = [makeJob(false), makeJob(true), makeJob(false), makeJob(false), makeJob(true)];
const stats = await runContinuouslyRefilledWorkerPool({
concurrency: 2,
maxJobs: undefined,
canClaim: () => true,
claimJobs: async (limit: number) => {
const jobs = queue.splice(0, limit);
for (const j of jobs) order.set(j.claimed.job._id, ++seq);
if (jobs.length) console.log(`PROBE claimed job(s) ${jobs.map((j) => order.get(j.claimed.job._id)).join(",")}`);
return { claimedCount: jobs.length, jobs };
},
processClaimedJob: async (j: ReturnType<typeof makeJob>) => {
const result = await processJob(client(j.lock, j.claimed.job._id), "token", j.claimed, undefined);
console.log(`PROBE job ${order.get(j.claimed.job._id)} processJob resolved ${JSON.stringify(result)}`);
return result;
},
});
console.log("PROBE stats", JSON.stringify(stats), "unclaimed", queue.length);
for (const ws of workspaces) {
const left = await readdir(ws).catch((e) => `gone(${e.code})`);
console.log("PROBE left", Array.isArray(left) ? left.join(",") : left);
}
for (const d of locked) await chmod(d, 0o700).catch(() => {});
for (const ws of workspaces) await rm(ws, { recursive: true, force: true });Container runner (run.sh)#!/bin/sh
# Runs inside oven/bun:1.4.4 as the non-root "bun" user. /src is the PR checkout (read-only).
set -eu
echo "uname: $(uname -sm) bun: $(bun --version) uid: $(id -u)"
for variant in before after; do
dir=/tmp/$variant
mkdir -p $dir
# Real copy of scripts/ (so the worker can be swapped); everything else symlinked.
for entry in /src/* /src/.[!.]*; do
name=$(basename "$entry")
[ "$name" = scripts ] && continue
ln -s "$entry" "$dir/$name" 2>/dev/null || true
done
cp -R /src/scripts $dir/scripts
if [ $variant = before ]; then cp /proof/worker-main.ts $dir/scripts/security/run-codex-scan-worker.ts; fi
echo; echo "===== $variant ($( [ $variant = before ] && echo 'origin/main worker' || echo 'PR head worker'))"
bun /proof/pool-probe.ts $dir 2>&1 | grep -E 'PROBE|security_scan_(workspace_cleanup_failed|unhandled_process_failure|job_completed)' \
| sed -E 's/"time":[0-9]+,//; s/probe-[0-9a-f-]{36}/probe-<uuid>/g'
done |
|
/clawsweeper re-review |
|
🦞👀 Re-review progress:
|
End-to-end proof: the deployed worker CLI under Bun 1.4.4 on LinuxThis runs the worker the way Setup:
Result
The fake server logs to stderr and the worker to stdout, so their lines interleave by buffering, not by time. fake-convex.ts// Fake Convex deployment for the worker CLI proof. It speaks the HTTP action
// protocol ConvexHttpClient uses (POST /api/action). It serves a queue of 5
// endor-report-only package-release jobs. When a locked job's outcome arrives
// (completeCodexScanJob), it adds a mode-0500 subdirectory to that job's real
// workspace, standing in for root-owned Docker sandbox output. The worker is
// unmodified and runs as a separate process.
import { chmod, mkdir, readdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
const jobs = [1, 2, 3, 4, 5].map((n) => ({
n,
id: `securityScanJobs:proof-job-${n}`,
locked: n === 2 || n === 5,
}));
const queue = [...jobs];
const log = (msg: string) => console.error(`FAKE-CONVEX ${msg}`);
const ok = (value: unknown) => Response.json({ status: "success", value, logLines: [] });
Bun.serve({
port: Number(process.env.FAKE_CONVEX_PORT ?? 3210),
async fetch(request) {
const { path, args } = (await request.json()) as { path: string; args: [Record<string, unknown>] };
const input = args[0] ?? {};
switch (path) {
case "securityScan:claimCodexScanJobLeases": {
const leased = queue.splice(0, Number(input.limit));
if (leased.length) log(`leased job(s) ${leased.map((j) => j.n).join(",")}`);
return ok(leased.map((j) => ({ _id: j.id, leaseToken: `lease-${j.n}` })));
}
case "securityScan:hydrateCodexScanJob": {
const job = jobs.find((j) => j.id === input.jobId)!;
return ok({
job: {
_id: job.id,
leaseToken: `lease-${job.n}`,
hasMaliciousSignal: false,
scanMode: "endor-report-only",
source: "backfill",
targetKind: "packageRelease",
},
target: {},
});
}
case "securityScan:completeCodexScanJob": {
const job = jobs.find((j) => j.id === input.jobId)!;
log(`recorded completion for job ${job.n}`);
if (job.locked) {
const name = (await readdir(tmpdir())).find((entry) =>
entry.startsWith(`clawhub-codex-scan-${job.id}-`),
);
if (!name) throw new Error(`workspace for job ${job.n} not found`);
const locked = join(tmpdir(), name, "sandbox-output");
await mkdir(locked);
await writeFile(join(locked, "scanner.log"), "root-owned in production");
await chmod(locked, 0o500);
log(`locked workspace subdirectory for job ${job.n}`);
}
return ok(null);
}
case "securityScan:getCodexScanQueueHealth":
return ok({
snapshotAt: Date.now(),
queueDepth: queue.length,
queueDepthIsEstimate: false,
readyQueueDepth: queue.length,
readyQueueDepthIsEstimate: false,
oldestReadyJobAgeSeconds: 0,
oldestReadyJobNextRunAt: null,
});
default:
log(`unexpected call ${path}`);
return ok(null);
}
},
});
log("listening");run-cli.sh#!/bin/sh
# Runs inside oven/bun:1.4.4 as the non-root "bun" user. /src is the PR checkout (read-only).
# Starts the real worker CLI exactly as the workflow does, against fake-convex.ts.
set -u
echo "uname: $(uname -sm) bun: $(bun --version) uid: $(id -u)"
for variant in before after; do
dir=/tmp/$variant
mkdir -p $dir
for entry in /src/* /src/.[!.]*; do
name=$(basename "$entry")
[ "$name" = scripts ] && continue
ln -s "$entry" "$dir/$name" 2>/dev/null || true
done
cp -R /src/scripts $dir/scripts
[ $variant = before ] && cp /proof/worker-main.ts $dir/scripts/security/run-codex-scan-worker.ts
rm -rf /tmp/clawhub-codex-scan-* 2>/dev/null; chmod -R u+w /tmp/clawhub-codex-scan-* 2>/dev/null; rm -rf /tmp/clawhub-codex-scan-*
echo; echo "===== $variant ($( [ $variant = before ] && echo 'origin/main worker' || echo 'PR head worker'))"
bun /proof/fake-convex.ts 2>&1 &
fake=$!
sleep 1
(
cd $dir
CLAWHUB_ALLOW_LOCAL_CODEX_SCAN=1 CODEX_HOME=/tmp/codex-home CONVEX_URL=http://127.0.0.1:3210 \
SECURITY_SCAN_WORKER_TOKEN=fixture-worker-token CODEX_SECURITY_SCAN_WORKER_ID=proof-shard \
CODEX_SECURITY_SCAN_DIAGNOSTICS_DIR=/tmp/diag-$variant \
bun scripts/security/run-codex-scan-worker.ts \
--batch-limit 2 --lane shared --max-jobs "" --max-runtime-minutes 1 --lease-minutes 60
echo "WORKER exit code: $?"
) 2>&1 | grep -E 'FAKE-CONVEX|WORKER exit|security_scan_(jobs_claimed|workspace_cleanup_failed|unhandled_process_failure|worker_summary)' \
| sed -E 's/"time":[0-9]+,//; s/"elapsedMs":[0-9]+,//'
kill $fake 2>/dev/null; wait $fake 2>/dev/null
echo "left in /tmp: $(for d in /tmp/clawhub-codex-scan-*; do [ -e "$d" ] && printf '%s[%s] ' "$(basename "$d" | sed -E 's/-[A-Za-z0-9]{6}$//; s/^clawhub-codex-scan-securityScanJobs://')" "$(ls "$d" | tr '\n' ' ' | sed 's/ $//')"; done)"
chmod -R u+w /tmp/clawhub-codex-scan-* 2>/dev/null; rm -rf /tmp/clawhub-codex-scan-*
done |
|
/clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
/clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Summary
Since #4803 and #4805 merged, no Codex scan shard has failed because of claim errors. The one claim
Server Errorafter the merge recovered on retry, as intended. Most remaining shard failures with a log are this bug: about 1–2 an hour, going back to at least 2026-11-16.Production repro: Production run 43994280032, job 133742337590 (
priority-0), 2026-11-17 01:37 UTC:The same sequence appears in runs 43986255864 (
shared-7), 43992281182 (priority-0) and 43994280032 (shared-8).Cause: Docker-sandboxed scans leave root-owned files in the bind-mounted workspace. The bare
rminprocessJob'sfinallythen throws after the job outcome is recorded. A throw fromfinallyreplacesprocessJob's result. The pool logs an unhandled failure and setsworkerMustStop, so the shard stops claiming and exits 1 even though the scans finished.Fix: deletion moves into
removeScanWorkspace. It logssecurity_scan_workspace_cleanup_failedwith the errno code only (no path or message) and never replacesprocessJob's result or error. The custody path is unchanged: when container removal isn't confirmed, the worker still preserves the workspace and stops. The behaviour, and the accepted leftover files, are recorded in a new "Scan workspace cleanup" section inspecs/plugin-qualified-runtime.md.Not in this PR:
rmin itsfinally(scripts/security/run-prepublication-worker.ts). Follow-up.The runner has received a shutdown signal(exit 143/137). That started before these changes and is being investigated separately.Tests and review
processJob, then locks a subdirectory of its workspace after the outcome is recorded. It asserts the completed result and the logged errno code, and that the path isn't logged. With the old barermput back, it fails with the sameEACCESrejection seen in production.bun scripts/security/run-codex-scan-worker.tsentry point runs on Linux with Bun 1.4.4 against a fake Convex HTTP deployment, with 5 jobs, two of them permission-locked. Main's worker exits1after 3 claims. The PR's worker claims and completes all 5 and exits0.oven/bun:1.4.4with 5 jobs, two of them permission-locked.totalClaimed 3, totalFailed 1.security_scan_workspace_cleanup_failed code=EACCES, later jobs are still claimed and completed, and it ends withtotalCompleted 5, totalFailed 0. Only the locked subtree is left behind.bunx vitest run scripts/security/run-codex-scan-worker.test.ts: 41 passed.bun run ci:staticandbunx tsc -p tsconfig.json --noEmit: passed.bun run coverage: failed locally. Subprocess-heavy scanner suites failed withspawnSync python3 ETIMEDOUTand 15 s timeouts. Rerun alone, 8 tests in 4 files still failed. With this change reverted, 4 tests in 2 of those files still failed, and the set changed between runs. None of those suites touch the changed code. CIunitis the full run.2434893a: no blocking findings, all four high confidence. The minor findings were wording, spec placement and the test's errno assertion;7ef546f1fixes them.