Skip to content

fix(security): cap Endor scan container memory so shards stop losing runners - #4820

Merged
jesse-merhi merged 5 commits into
mainfrom
fix/endor-container-memory-cap
Nov 17, 2026
Merged

jesse-merhi merged 5 commits into
mainfrom
fix/endor-container-memory-cap

Conversation

@jesse-merhi

@jesse-merhi jesse-merhi commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

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) or Killed 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 /tmp tmpfs, which is RAM.

Evidence

Period exit 137 exit 143 "lost communication"
Oct 31 – Nov 6 (about 5,000 shard jobs) 0 0 0
Nov 7 – 16, per day 3–7 9–24 111–216
  • Onset: the first failing run, 42321258585 at 2026-11-07 00:56Z, lost 6 shards at once. It was the first run with a full Endor backfill queue: one shard made 36 claims, where the run before made 0.
  • SIGKILL before shutdown: in the exit-137 runs, bash prints 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.
  • Endor killed inside surviving shards: endorctl itself was killed during "full dependency analysis" on large packages, with Killed / Endor exited 137. Examples are skill-harness (749 dependencies, 511 s) and openclaw-code-agent. Those containers had no limit, so the host OOM killer did it.
  • Lost leases: jobs on a lost runner are requeued only when their lease expires, after 60–90 minutes. Publish scans that shared that runner are delayed by that much.

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.
    • An oversized scan is now killed inside its own container. The worker already handles that: a surviving shard whose endorctl was killed recorded the job as status: completed with 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 a runner-resources sample 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. free counts tmpfs as shared/cache, so used would hide it.
    • It samples inside the worker step because a shard killed for memory never runs later steps.
    • It can't help a lost runner, which keeps no log, so it covers the killed (137/143) and surviving shards. Surviving shards show how close scans get to the cap.
    • Cleanup is best effort, so the worker's exit status always passes through.
  • 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"): the package-scan-backfill cron re-enqueues missing or failed Endor reports every 30 minutes.

Not in this PR:

  • A package that never fits under 3 GiB fails again on every backfill pass. This predates the cap, but is now deterministic. A terminal "too large" result or an attempt cap would stop it.
  • Lease expiries don't count toward MAX_ATTEMPTS, so a job that kills its runner is retried indefinitely.
  • The Endor-only path logs no completion event, which is why the logs go quiet for long stretches.

Tests

  • End-to-end (trace, setup and sources): the unmodified worker CLI runs with a real Docker daemon and each variant's real docker run flags, against a fake Convex and a stand-in Endor image whose oversized package writes 4 GiB into /tmp.
    • Before: the container had no limit (15.66 GiB, the whole VM) and peaked at 3.88 GiB, and the report recorded completed.
    • After: the 3 GiB cap killed the container (Endor exited 137), job 2's report was recorded as failed, job 3 still completed, and the worker exited 0 with totalFailed 0.
  • Sampler: the step block was run verbatim in ubuntu:22.04 under both bash -e and bash -e -o pipefail, with the sampler alive, already dead, and sampling every 10 ms (40 runs).
    • The worker's exit (0, 17 or 137) was preserved every time, with no leftover processes, no stray Terminated line, and a final sample on every exit.
    • With stub sudo/dmesg, each OOM kill was printed exactly once.
  • Cap mechanism: with the exact flags, Docker set memory.max=3221225472 and memory.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 found actionlint/shellcheck clean.
  • Code review council, 2 rounds with GPT-6 Astra, GPT-6.1 Sol, Claude Fable 5.2 and Claude Opus 5.5 at high effort:
    • Round 1: all four found that the sampler's EXIT trap could replace the worker's exit status. This was reproduced and fixed.
    • Round 2 (3b231ee0): no blocking findings. Its minor findings (OOM-line repetition, stale spec retry text, test message, comment wording) are fixed in 6a4f8aee and verified above.
  • Not verified: a real Production shard under load, real endorctl peak memory for large packages that succeed today, and cgroup v1. The runner-resources lines will provide the numbers after merge.

@jesse-merhi
jesse-merhi requested a review from a team as a code owner November 17, 2026 03:14
Copilot AI balanced review requested due to automatic review settings November 17, 2026 03:14
@vercel

vercel Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
clawhub Ready Ready Preview Nov 17, 2026 5:55am UTC

Request Review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: The supplied baseline trace shows the uncapped container reaching 3.88 GiB.
  • After: Docker enforces the 3 GiB cap; the advisory report fails, the next job completes, and the worker exits successfully.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused containment through the existing owner, demonstrated through the shipped worker entry point with real Docker, with no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The exact-head worker CLI runs the production Docker invocation against a real Linux cgroup-v2 daemon: a 4 GiB tmpfs allocation exceeds the new cap, failed advisory analysis is recorded, the next job completes, and the worker exits 0; Convex and the scanner image are disclosed stand-ins, with separate sampler exit-status traces. This establishes containment and recovery, not real endorctl memory requirements or production outage elimination.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A memory-heavy advisory scan can terminate a shared worker and delay other leased release scans.
Reason: Containing resource consumption protects shared work, preserves the report-only contract, and has an explicit maintainer-authored direction.

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
Reviewed head: 6a4f8aee81038978cd3c8309f1636052a3509944

Before merge

None.

Findings

None.

Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

  • Endor Docker execution keeps the original intent (5e8aec5: The original integration isolated dependency analysis in a credential-separated, read-only container; the later simplification retained that isolation and report-only behavior.)
  • Endor backfill and failure documentation keeps the original intent (feat(security): activate scanner-only Codex plugin adjudication #4411: Automatic plugin scanning selects missing or failed advisory reports; the documentation changes align older wording with that existing routing contract.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Jesse Merhi: Raw commit 46dbc1f adds scripts/security/run-endor-plugin-scan.ts:219 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 46dbc1f6e3ee; files: scripts/security/run-endor-plugin-scan.ts)

Preflight source

Source 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

Metric Value Why it matters
Patch size +58/-3 across 5 files The change stays within the existing scan owner and workflow, with focused assertions and durable operational rationale.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P1: Reported recurring runner losses delay security-scan jobs, and the uncapped concurrent container path is present on current main.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-17T03:28:07.411Z sha 28f798b :: needs maintainer review before merge. :: none
  • reviewed 2026-11-17T05:58:00.410Z sha 6a4f8ae :: needs maintainer review before merge. :: none

Reviewed November 17, 2026, 1:02 AM ET / 06:02 UTC (Revision 3).

@jesse-merhi

Copy link
Copy Markdown
Member Author

End-to-end proof: the worker CLI with real Docker and the PR's Endor flags

This runs against PR head 6a4f8aee. The before run swaps in origin/main's run-endor-plugin-scan.ts and changes nothing else.

Setup

  • Real: the unmodified worker CLI bun scripts/security/run-codex-scan-worker.ts --batch-limit 1 --lane shared …, using Bun 1.4.4 on the macOS host.
  • Real: artifact download with sha256 verification, runEndorPluginScan, and docker run with the exact flags from each variant's run-endor-plugin-scan.ts, on a real Docker daemon (Linux arm64 VM, cgroup v2).
  • Real: the worker's diagnostics, its job completion path and its exit code.
  • Simulated: fake-convex-endor.ts speaks ConvexHttpClient's HTTP protocol. It serves 3 endor-report-only code-plugin releases in order and logs the Endor report each one records.
  • Simulated: clawhub-endor-standin:proof, a small image with the same entrypoint and scan paths as the real Endor image. For the package named *oversized* (job 2), its scanner writes 4 GiB into the /tmp tmpfs, the way endorctl's npm tree, cache and call graph grow. It reports Endor exited <code> the way scan.sh does.
  • Measured: memory is sampled once a second with docker stats.

Result

Job 2 container limit Job 2 peak sampled Job 2 recorded Endor report Job 3 Worker
Before (main) none: 15.66 GiB, the whole Docker VM 3.88 GiB (it held 4096 MiB) completed completed exit 0
After (PR) --memory 3g --memory-swap 3g: 3 GiB 2.87 GiB, then killed: Endor exited 137 failed, "Endor analysis failed. Request a rescan to try again." completed exit 0, totalFailed 0

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.

host: Darwin arm64  bun: 1.4.4  docker server: linux/arm64 29.8.2  head: 6a4f8aee

===== before (origin/main Endor flags): 0 --memory flag(s) in run-endor-plugin-scan.ts
FAKE-CONVEX listening
FAKE-CONVEX leased job 1 (proof-plugin-1)
FAKE-CONVEX job 1 recorded Endor report: status=completed
FAKE-CONVEX leased job 2 (proof-oversized-plugin-2)
FAKE-CONVEX job 2 recorded Endor report: status=completed
FAKE-CONVEX leased job 3 (proof-plugin-3)
FAKE-CONVEX job 3 recorded Endor report: status=completed
{"level":30,"service":"security-scan-worker","event":"security_scan_worker_summary","lane":"shared","totalClaimed":3,"totalClaimFailures":0,"totalCompleted":3,"totalFailed":0,"totalRetryableFailed":0,"workerId":"endor-proof-shard","msg":"security scan worker summary"}
WORKER exit code: 0
peak Endor container memory (docker stats, 1 s samples): 3.878GiB of limit 15.66GiB 
job 2 Endor diagnostic: exitCode=0 | docker args: no --memory | error: none
job 2 Endor stderr: stand-in analysis held 4096 MiB in /tmp 

===== after (PR head Endor flags): 1 --memory flag(s) in run-endor-plugin-scan.ts
FAKE-CONVEX listening
FAKE-CONVEX leased job 1 (proof-plugin-1)
FAKE-CONVEX job 1 recorded Endor report: status=completed
FAKE-CONVEX leased job 2 (proof-oversized-plugin-2)
FAKE-CONVEX job 2 recorded Endor report: status=failed reason="Endor analysis failed. Request a rescan to try again."
FAKE-CONVEX leased job 3 (proof-plugin-3)
FAKE-CONVEX job 3 recorded Endor report: status=completed
{"level":30,"service":"security-scan-worker","event":"security_scan_worker_summary","lane":"shared","totalClaimed":3,"totalClaimFailures":0,"totalCompleted":3,"totalFailed":0,"totalRetryableFailed":0,"workerId":"endor-proof-shard","msg":"security scan worker summary"}
WORKER exit code: 0
peak Endor container memory (docker stats, 1 s samples): 2.871GiB of limit 3GiB 
job 2 Endor diagnostic: exitCode=137 | docker args: --memory 3g --memory-swap 3g | error: Endor scan exited 137; see redacted stdout/stderr diagnostics
job 2 Endor stderr: Endor exited 137 

Sampler in the worker step

The step's sampler block was extracted verbatim from the workflow and run in ubuntu:22.04 (bash 5.1.16), with a stand-in worker that exits $CODE.

  • Shells: GitHub's bash -e, and bash -e -o pipefail.
  • Sampler states: alive, already dead, and sampling every 10 ms. The last runs 40 times, so the trap often fires between commands. That was the race behind an earlier version replacing the exit status.
  • Exit status: always preserved for 0, 17 and 137.
  • Cleanup: nothing left running, and no stray Terminated line.
  • Final sample: printed on every exit.
  • OOM kills: with stub sudo/dmesg and 4 kills, 3 of them in one interval, the loop prints each kill exactly once. The final sample lists all of them.
bash -e | sampler=alive | worker=0 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e | sampler=alive | worker=17 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e | sampler=alive | worker=137 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e | sampler=dead | worker=0 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e | sampler=dead | worker=17 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e | sampler=dead | worker=137 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e | sampler=fast | worker=0 | wrong exit: 0/40 | leftovers=0 | Terminated lines=0 | final sample=14
bash -e | sampler=fast | worker=17 | wrong exit: 0/40 | leftovers=0 | Terminated lines=0 | final sample=12
bash -e | sampler=fast | worker=137 | wrong exit: 0/40 | leftovers=0 | Terminated lines=0 | final sample=12
bash -e -o pipefail | sampler=alive | worker=0 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e -o pipefail | sampler=alive | worker=17 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e -o pipefail | sampler=alive | worker=137 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e -o pipefail | sampler=dead | worker=0 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e -o pipefail | sampler=dead | worker=17 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e -o pipefail | sampler=dead | worker=137 | wrong exit: 0/1 | leftovers=0 | Terminated lines=0 | final sample=1
bash -e -o pipefail | sampler=fast | worker=0 | wrong exit: 0/40 | leftovers=0 | Terminated lines=0 | final sample=12
bash -e -o pipefail | sampler=fast | worker=17 | wrong exit: 0/40 | leftovers=0 | Terminated lines=0 | final sample=12
bash -e -o pipefail | sampler=fast | worker=137 | wrong exit: 0/40 | leftovers=0 | Terminated lines=0 | final sample=13
last sample line: runner-resources 05:54:16 mem_available_mb=11240 mem_shared_mb=87 mem_total_mb=16039 swap_used_mb=634 root_disk_used=41%

step exit=137 (worker 137)
        2 runner-resources   oom: [t1] Out of memory: Killed process 101 (endorctl)
        2 runner-resources   oom: [t2] Memory cgroup out of memory: Killed process 102 (npm)
        2 runner-resources   oom: [t3] Memory cgroup out of memory: Killed process 103 (node)
        2 runner-resources   oom: [t4] Memory cgroup out of memory: Killed process 104 (node)
  oom lines printed by the sampler loop vs final sample: 8 total for 4 kills
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")"
done
image/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/Dockerfile
FROM 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-scan
step-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"

@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Nov 17, 2026
@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Nov 17, 2026
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Nov 17, 2026
@jesse-merhi
jesse-merhi merged commit ade4f45 into main Nov 17, 2026
73 of 74 checks passed
@jesse-merhi
jesse-merhi deleted the fix/endor-container-memory-cap branch November 17, 2026 06:06

This branch was successfully deployed

1 active deployment
Preview – clawhub — 6a4f8aee Deployed Nov 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants