Repository navigation
fix(security): cap Endor scan container memory so shards stop losing runners - #4820
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 completeClawSweeper finished reviewing this revision. The review result is being finalized. |
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.
|
Codex review: needs maintainer review before merge. What this changesThis PR caps each Endor scan container at 3 GiB without swap and adds runner resource diagnostics. Example: An Endor scan writes 4 GiB into its temporary filesystem.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open for landing: current main still leaves Endor containers uncapped, and the patch addresses a concrete worker reliability problem. No blocking findings. Priority: P1 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe hosted security worker consumes leased plugin-release jobs, runs Endor in Docker, and records advisory analysis results without changing moderation decisions. flowchart LR
A[Release scan queue] --> B[Security worker]
B --> C[Artifact preparation]
C --> D[Memory capped Endor container]
D --> E[Advisory report]
E --> F[Job completion]
G[Resource sampler] --> H[Workflow logs]
Technical reviewBest possible solution: Land the limit in the existing Docker invocation while preserving advisory failure handling and using the added diagnostics to observe production memory usage. Do we have a high-confidence way to reproduce the issue? Current source permits concurrent Endor containers to consume host memory without a container limit; the contributor's baseline demonstrates the uncapped allocation, although this review did not reproduce a hosted-runner outage. Is this the best way to solve the issue? Best-fix verdict: best for containing Endor memory consumption; lowering worker concurrency would sacrifice unrelated throughput, while increasing runner memory would leave individual scans unbounded. The Docker owner, worker caller, command runner, scanner script, adjacent tests, workflow, and specifications support this placement. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 2522012632e3. 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:
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 HistoryReviewed November 17, 2026, 1:02 AM ET / 06:02 UTC (Revision 3). |
End-to-end proof: the worker CLI with real Docker and the PR's Endor flagsThis runs against PR head Setup
Result
Without the cap, an oversized scan takes memory from the host. With it, the scan is killed inside its own container. Only its advisory report fails, and the worker moves on to the next job. Sampler in the worker stepThe step's sampler block was extracted verbatim from the workflow and run in
fake-convex-endor.ts// Fake Convex deployment for the Endor memory-cap proof. It speaks ConvexHttpClient's
// POST /api/action protocol and serves 3 endor-report-only code-plugin jobs, run in
// order. Job 2's package is "oversized". Each package.json is served from /files/<n>
// with its real sha256, so the worker downloads and verifies it as in production.
import { createHash } from "node:crypto";
const port = Number(process.env.FAKE_CONVEX_PORT ?? 3211);
const jobs = [1, 2, 3].map((n) => {
const name = n === 2 ? `proof-oversized-plugin-${n}` : `proof-plugin-${n}`;
const manifest = `${JSON.stringify({ name, version: "1.0.0" }, null, 2)}\n`;
return {
n,
id: `securityScanJobs:endor-proof-${n}`,
name,
manifest,
sha256: createHash("sha256").update(manifest).digest("hex"),
};
});
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,
async fetch(request) {
const url = new URL(request.url);
const file = url.pathname.match(/^\/files\/(\d)$/);
if (file) return new Response(jobs[Number(file[1]) - 1]!.manifest);
const { path, args } = (await request.json()) as { path: string; args: [Record<string, unknown>] };
const input = args[0] ?? {};
const job = jobs.find((j) => j.id === input.jobId);
switch (path) {
case "securityScan:claimCodexScanJobLeases": {
const leased = queue.splice(0, Number(input.limit));
if (leased.length) log(`leased job ${leased.map((j) => `${j.n} (${j.name})`).join(",")}`);
return ok(leased.map((j) => ({ _id: j.id, leaseToken: `lease-${j.n}` })));
}
case "securityScan:hydrateCodexScanJob":
return ok({
job: {
_id: job!.id,
leaseToken: `lease-${job!.n}`,
hasMaliciousSignal: false,
scanMode: "endor-report-only",
source: "backfill",
targetKind: "packageRelease",
},
target: {
package: { name: job!.name, family: "code-plugin" },
release: { version: "1.0.0" },
files: [
{
path: "package.json",
sha256: job!.sha256,
size: job!.manifest.length,
url: `http://127.0.0.1:${port}/files/${job!.n}`,
},
],
},
});
case "securityScan:completeCodexScanJob": {
const report = input.endorAnalysis as { status: string; reason?: string; reachableFunctionCount?: number };
log(`job ${job!.n} recorded Endor report: status=${report.status}${report.reason ? ` reason="${report.reason}"` : ""}`);
return ok(null);
}
case "securityScan:failCodexScanJob":
log(`job ${job!.n} FAILED: ${String(input.error).slice(0, 200)}`);
return ok({ retry: false });
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.sh#!/bin/bash
# Runs on the host: the real worker CLI (Bun) drives the real Docker daemon with the
# Endor flags from each variant's run-endor-plugin-scan.ts. Only Convex and the Endor
# image are stand-ins. Variant "before" swaps in origin/main's run-endor-plugin-scan.ts.
set -u
P=$(cd "$(dirname "$0")" && pwd)
SRC=/Users/jmerhi/.t3/worktrees/clawhub/endor-memory-cap
echo "host: $(uname -sm) bun: $(bun --version) docker server: $(docker version --format '{{.Server.Os}}/{{.Server.Arch}} {{.Server.Version}}') head: $(git -C $SRC rev-parse --short HEAD)"
for variant in before after; do
dir=$P/work-$variant; rm -rf "$dir"; 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 ] && git -C "$SRC" show origin/main:scripts/security/run-endor-plugin-scan.ts > "$dir/scripts/security/run-endor-plugin-scan.ts"
echo; echo "===== $variant ($( [ $variant = before ] && echo 'origin/main Endor flags' || echo 'PR head Endor flags')): $(grep -c '"--memory"' "$dir/scripts/security/run-endor-plugin-scan.ts") --memory flag(s) in run-endor-plugin-scan.ts"
bun "$P/fake-convex-endor.ts" & fake=$!; sleep 1
# Sample every Endor container's memory once a second (like the workflow's sampler).
( while :; do docker stats --no-stream --format '{{.Name}} {{.MemUsage}}' 2>/dev/null | grep clawhub-endor; sleep 1; done ) > "$P/stats-$variant.txt" & stats=$!
( cd "$dir" && CLAWHUB_ALLOW_LOCAL_CODEX_SCAN=1 CODEX_HOME="$P/codex-home" CONVEX_URL=http://127.0.0.1:3211 \
SECURITY_SCAN_WORKER_TOKEN=fixture-worker-token CODEX_SECURITY_SCAN_WORKER_ID=endor-proof-shard \
CODEX_SECURITY_SCAN_ENDOR_ENABLED=1 CODEX_SECURITY_SCAN_ENDOR_IMAGE=clawhub-endor-standin:proof \
CODEX_SECURITY_SCAN_DIAGNOSTICS_DIR="$P/diag-$variant" \
bun scripts/security/run-codex-scan-worker.ts --batch-limit 1 --lane shared --max-jobs "" \
--max-runtime-minutes 5 --lease-minutes 60
echo "WORKER exit code: $?" ) 2>&1 \
| grep -E 'FAKE-CONVEX|WORKER exit|security_scan_(unhandled_process_failure|worker_summary|job_failed)' \
| sed -E 's/"time":[0-9]+,//; s/"elapsedMs":[0-9]+,//'
kill $fake $stats 2>/dev/null; wait $fake $stats 2>/dev/null
if [ -s "$P/stats-$variant.txt" ]; then
echo "peak Endor container memory (docker stats, 1 s samples): $(awk '{print $2}' "$P/stats-$variant.txt" | sort -h | tail -1) of limit $(awk '{print $4}' "$P/stats-$variant.txt" | sort -u | tr '\n' ' ')"
else
echo "peak Endor container memory (docker stats, 1 s samples): no sample; every Endor container ended within one sampling interval"
fi
# Job 2's Endor result, as recorded in the worker's diagnostics.
d=$(ls -d "$P/diag-$variant"/*endor-proof-2* 2>/dev/null | head -1)
echo "job 2 Endor diagnostic: $(python3 -c "import json;e=json.load(open('$d/diagnostic.json'))['endorResult'];a=e.get('args',[]);i=a.index('--memory') if '--memory' in a else -1;print('exitCode=%s' % e.get('exitCode'), '| docker args:', ' '.join(a[i:i+4]) if i>=0 else 'no --memory', '| error:', e.get('error','none'))")"
echo "job 2 Endor stderr: $(tr '\n' ' ' < "$d/endor.stderr.redacted.log")"
doneimage/scan.sh#!/bin/sh
# Stand-in for clawhub-endor-scan. Like the real scan.sh, it does its analysis in the /tmp
# tmpfs and reports "Endor exited <code>" when the analyser dies. An "oversized" package
# writes 4 GiB there, the way endorctl's npm tree, cache and call graph grow for large packages.
name=$(sed -n 's/.*"name": *"\([^"]*\)".*/\1/p' /workspace/package.json)
if [ "${name#*oversized}" != "$name" ]; then
dd if=/dev/zero of=/tmp/analysis bs=1M count=4096 2>/dev/null
status=$?
if [ $status -ne 0 ]; then echo "Endor exited $status" >&2; exit $status; fi
echo "stand-in analysis held $(du -m /tmp/analysis | cut -f1) MiB in /tmp" >&2
sleep 3 # hold the peak long enough for the 1 s docker stats sampler
fi
echo '{"all_findings":[]}'image/entrypoint.sh#!/bin/sh
# Stand-in for clawhub-endor-entrypoint: the real one installs the egress guard and drops to node.
exec "$@"image/DockerfileFROM alpine:3.20
COPY entrypoint.sh /usr/local/bin/clawhub-endor-entrypoint
COPY scan.sh /usr/local/bin/clawhub-endor-scan
RUN chmod 755 /usr/local/bin/clawhub-endor-entrypoint /usr/local/bin/clawhub-endor-scanstep-test.sh#!/bin/bash
# Runs the workflow step's sampler block verbatim with a stand-in worker (sleep, then exit $CODE).
for shell in "bash -e" "bash -e -o pipefail"; do
for mode in alive dead fast; do
for code in 0 17 137; do
script=/proof/step.sh; pre=true; work=0.3
[ $mode = dead ] && pre='kill "$sampler"; sleep 0.1'
[ $mode = fast ] && { sed 's/while sleep 60/while sleep 0.01/' /proof/step.sh > /tmp/fast.sh; script=/tmp/fast.sh; work=0.2; }
fails=0; runs=$([ $mode = fast ] && echo 40 || echo 1); out=""
for i in $(seq $runs); do
out=$(CODE=$code PRE_EXIT="$pre" WORK=$work timeout 30 $shell $script 2>&1); rc=$?
[ $rc -ne $code ] && fails=$((fails+1))
done
left=$(ps -eo args | grep -cE '^(sleep (60|0.01)|bash -e)')
echo "$shell | sampler=$mode | worker=$code | wrong exit: $fails/$runs | leftovers=$left | Terminated lines=$(printf '%s' "$out" | grep -c Terminated) | final sample=$(printf '%s' "$out" | grep -c '^runner-resources [0-9]')"
done
done
done
echo "last sample line: $(printf '%s' "$out" | grep '^runner-resources' | tail -1)"oom-test.sh#!/bin/bash
# Stub sudo/dmesg: dmesg prints a kernel log that grows while the step runs.
mkdir -p /stub; printf '#!/bin/sh\n[ "$1" = -n ] && shift\nexec "$@"\n' > /stub/sudo
printf '#!/bin/sh\ncat /tmp/kmsg\n' > /stub/dmesg; chmod +x /stub/*; export PATH=/stub:$PATH
: > /tmp/kmsg
sed 's/while sleep 60/while sleep 0.2/' /proof/step.sh > /tmp/oom.sh
( sleep 0.5; echo "[t1] Out of memory: Killed process 101 (endorctl)" >> /tmp/kmsg
sleep 0.5; echo "[t2] Memory cgroup out of memory: Killed process 102 (npm)" >> /tmp/kmsg
echo "[t3] Memory cgroup out of memory: Killed process 103 (node)" >> /tmp/kmsg
echo "[t4] Memory cgroup out of memory: Killed process 104 (node)" >> /tmp/kmsg ) &
out=$(CODE=137 WORK=2 bash -e /tmp/oom.sh 2>&1); rc=$?
echo "step exit=$rc (worker 137)"
echo "$out" | grep 'oom:' | sort | uniq -c | sed 's/^/ /'
echo " oom lines printed by the sampler loop vs final sample: $(echo "$out" | grep -c 'oom:') total for 4 kills" |
|
/clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
/clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Summary
About 22–25% of Codex security scan shard jobs a day have been lost since 2026-11-07. Most end with "The hosted runner lost communication with the server" and leave no log. The rest end with
The runner has received a shutdown signal(exit 143) orKilled bun …(exit 137). The cause is memory exhaustion on the 16 GB hosted runner.The worker scans up to 4 packages at once. Most of that work is now Endor report-only backfill. Each Endor scan runs in a Docker container with no memory cap, and the npm tree, npm cache and call graph all live in an unbounded
/tmptmpfs, which is RAM.Evidence
Killed bun scripts/security/run-codex-scan-worker.ts …before the runner shutdown message. That is a kernel OOM kill; a cancel would send SIGTERM.endorctlitself was killed during "full dependency analysis" on large packages, withKilled/Endor exited 137. Examples areskill-harness(749 dependencies, 511 s) andopenclaw-code-agent. Those containers had no limit, so the host OOM killer did it.Change
scripts/security/run-endor-plugin-scan.ts: the Endor container runs with--memory 3g --memory-swap 3g. Pages in the tmpfs count against the cap, so one setting bounds both the heap and/tmp. 4 × 3 GB leaves room on a 16 GB runner for the worker and host-side scans.endorctlwas killed recorded the job asstatus: completedwith a failed Endor report. A few very large packages will get a failed Endor report instead of taking down the runner and every scan on it..github/workflows/security-scan-codex.yml: the worker step takes arunner-resourcessample every minute, plus a final one on exit. Each sample has available/shared memory, swap, root disk, per-container memory and new kernel OOM-kill lines.freecounts tmpfs as shared/cache, sousedwould hide it.scripts/security/endor/fixtures/run.sh: the manual isolation proof uses the same flags.specs/endor-plugin-scans.md: records the cap and why it exists. It also corrects two stale lines ("There is no backfill", "does not … retry"): thepackage-scan-backfillcron re-enqueues missing or failed Endor reports every 30 minutes.Not in this PR:
MAX_ATTEMPTS, so a job that kills its runner is retried indefinitely.Tests
docker runflags, against a fake Convex and a stand-in Endor image whose oversized package writes 4 GiB into/tmp.completed.Endor exited 137), job 2's report was recorded asfailed, job 3 still completed, and the worker exited 0 withtotalFailed 0.ubuntu:22.04under bothbash -eandbash -e -o pipefail, with the sampler alive, already dead, and sampling every 10 ms (40 runs).Terminatedline, and a final sample on every exit.sudo/dmesg, each OOM kill was printed exactly once.memory.max=3221225472andmemory.swap.max=0, and tmpfs writes counted against the cap. Council reviewers confirmed this on cgroup v2.bunx vitest run scripts/security/run-endor-plugin-scan.test.ts: 9 passed. The assertion checks that a cap exists with swap equal to memory, without repeating the value.bun run ci:static: passed. The workflow YAML parses, and reviewers foundactionlint/shellcheckclean.3b231ee0): no blocking findings. Its minor findings (OOM-line repetition, stale spec retry text, test message, comment wording) are fixed in6a4f8aeeand verified above.endorctlpeak memory for large packages that succeed today, and cgroup v1. Therunner-resourceslines will provide the numbers after merge.