Skip to content

fix(security-scan): plan queue claims so concurrent shards stop conflicting - #4805

Merged
roboclaw-bot merged 4 commits into
mainfrom
fix/security-scan-claim-contention
Nov 16, 2026
Merged

roboclaw-bot merged 4 commits into
mainfrom
fix/security-scan-claim-contention

Conversation

@jesse-merhi

Copy link
Copy Markdown
Member

Summary

Since 2026-11-15 (around 18:14 UTC), Production Security Scan Codex Worker shards have hit bursts of [Request ID: …] Server Error when they call claimCodexScanJobLeases. A read-only bunx convex logs --prod capture caught a live burst (05:38–05:45 UTC on 11-16). Every failed claim had the same cause, OCC retry exhaustion in claimQueuedJobsInternal:

Documents read from or written to the "securityScanJobs" table changed while this mutation was being run and on every subsequent retry. Another call to this mutation changed the document … (retryCount: 4)

Hundreds more conflicts in that window were retried successfully inside Convex. Claim rate reached about 95 per minute during the burst, which fits shards refilling fast after fast-failing jobs.

Cause. Each claim mutation reads the shared queue-head index ranges (manual, malicious signal, then each source) and leases rows out of those same ranges. Every concurrent claim therefore conflicts with every other one. At high refill rates, Convex exhausts its retries.

Fix. Shared and priority claims now follow the plan-then-admit pattern already used by Skill Card claims (convex/lib/skillCardClaims.ts):

  • planCodexScanClaimsInternal is a read-only query. It plans candidates over a bounded queue-head window (at least 128 rows), in the existing tier order: manual, then malicious signal, then CLAIM_SOURCE_ORDER. The priority lane still stops after publish.
  • The action shuffles candidates within each tier, so concurrent shards spread across the head of the queue.
  • claimPlannedJobsInternal leases candidates using point reads only. For each row it re-checks status, nextRunAt, lane eligibility and rollout claimability, and it skips a row another worker already leased. Two claims now conflict only when they pick the same row, and Convex's retry then skips that row.
  • The action replans a short claim that saw stale rows, so contention isn't reported as an empty queue. Once any lease commits, it is always returned, even if a later round fails.
  • These cases keep the existing claim: the catalog lane, assigned or targeted IDs, the Test deployment's catalog source, and blocked legacy rows deeper than one bounded scan.
  • Intent is recorded in specs/security-moderation.md.

Proof: real local Convex backend

I pushed the full app to an anonymous local deployment for main and for this branch. Then 10 concurrent workers claimed 1–4 jobs at a time in a tight loop against a seeded backfill queue. Because the machine was heavily loaded (load average 100+), the numbers that matter come from runs under the same load:

Run (10 workers, 1200 jobs) Claim calls Failed OCC errors 1 s timeouts Drain time
main 1002 467 (47%) 438 29 231 s
this PR, run 1 595 68 0 68 103 s
this PR, run 2 532 38 1 37 67 s

Every run leased every job exactly once: no duplicate leases and no job with more than one attempt. The remaining failures are 1 s function timeouts caused by host load, and main gets them too. An earlier run on a less loaded machine had 1 failure in 503 calls on this branch. With 20 workers on 400 jobs, 5 of 232 calls failed.

The race scripts and fixture were proof-only and are not committed.

Notes for rollout

  • The new path never runs on the Test deployment, because Test's catalog source keeps the existing claim. Production is the first place it runs. After deploying, check that worker claim_failed logs drop, and look for any claim that falls back to the existing path.
  • Ordering inside a tier is approximate within the shuffled window, by design. An old row waits roughly window ÷ limit claims at most.
  • Each claim now plans over a window of up to 128 rows, more than the old per-claim take(limit). These are cheap reads in a query, not in the conflicting mutation.
  • This PR doesn't depend on fix(security-worker): don't fail shards on recovered claim errors #4803, which stops shards being marked failed after a claim error that recovered on retry.

Tests

  • bunx tsc -p convex/tsconfig.json --noEmit, bunx tsc -p packages/schema/tsconfig.json --noEmit, bunx tsc -p packages/clawhub/tsconfig.json --noEmit: clean.
  • VITE_CONVEX_URL=https://example.invalid bunx vitest run convex/securityScan.claimPlan.runtime.test.ts convex/securityScan.test.ts convex/packageSecurityScan.runtime.test.ts convex/securityScan.retiredQueue.runtime.test.ts convex/skills.moderationBackfill.runtime.test.ts: 154 passed. The new runtime tests cover tier order, priority-lane exclusion, stale-row skipping, lane refusal, and retired plugin scans through the action. The orchestration tests cover replanning and committed-lease return.
  • bun run ci:static: passed.
  • bun run coverage locally: the Convex suites pass. 21 script tests failed on this overloaded machine: Python 3.15 and Docker subprocess timeouts in scripts/security/*, none of which import the changed code. CI is the gate for those.
  • An independent review found no P0 or P1 issues. Its P2 (a short claim after a partial commit) and its P3s (clock reads in a query, coverage through the action) are addressed in 59c7434.

…icting

Since 2026-11-15, Production security workers got "[Request ID] Server
Error" bursts from claimCodexScanJobLeases. Production logs show they are
OCC retry exhaustion in claimQueuedJobsInternal: "Documents read from or
written to the securityScanJobs table changed ... on every subsequent
retry". Each claim read the shared queue-head index ranges and leased rows
out of them, so every concurrent claim conflicted with every other. Fast
shard refills (fast-failing backfill jobs) pushed claims to ~95/min.

Shared and priority claims now plan candidates in a read-only query over a
bounded head window (legacy tier order kept), shuffle within each tier in
the action, and lease them in a new mutation that uses point reads only and
skips stale rows. The action replans a short claim that saw stale rows, and
returns committed leases even if a later round fails. The catalog lane,
assigned/targeted claims, the Test catalog source, and deep blocked legacy
rows keep the existing claim.

Local backend race (10 workers, tight claim loop): main failed 224/420
claim calls (125 OCC, 99 timeouts); this change failed 1/503, with every
job leased exactly once.
Pass the planner's clock from the action (queries must not read the
clock) with a small forward allowance, and let admission skip rows that
are not ready yet without counting them as contention. Hand the remaining
limit to the legacy claim when a replan needs it instead of stopping
short. Correct the comment and spec about how the worker reads a short
claim. Cover retired automatic plugin scans through the planned action.
Copilot AI balanced review requested due to automatic review settings November 16, 2026 06:32
@vercel

vercel Bot commented Nov 16, 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 16, 2026 11:43pm UTC

Request Review

@clawsweeper

clawsweeper Bot commented Nov 16, 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. P2 Normal backlog priority with limited blast radius. 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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 16, 2026
@clawsweeper

clawsweeper Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR separates security-scan queue discovery from lease admission to reduce conflicts between concurrent workers.

Example: Ten workers concurrently claim batches from 1,200 queued backfill jobs.

  • Before: Claim mutations read and modify overlapping queue ranges, causing transaction retries and occasional exhausted claims.
  • After: A query plans candidates, workers shuffle within priority tiers, and a mutation admits jobs through point reads.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) A useful repair with passing exact-head checks, but the readiness defect and uninspectable runtime results prevent a pass.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Concurrent security workers can fail to obtain queued scans after Convex exhausts transaction retries.
Reason: The production failure has a concrete source mechanism, and the maintainer-authored PR explicitly accepts bounded read amplification and approximate ordering within tiers.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-authored PR addresses contention still present on main, but its new planner can incorrectly report an empty queue.

Priority: P2
Reviewed head: 59c74342f52d013d39ee19223dc7f4f80f5570f3

Before merge

  • Keep future candidates from hiding runnable lower-tier jobs (P2) - The action plans at Date.now() + 1,000, so not-yet-due jobs consume the candidate window. For example, with limit 4, 128 backfill retries due in 500 ms and an already-due bulk-rescan job, planning fills its window with backfill and never visits bulk-rescan. If admission runs before those retries are due, this continue skips every candidate without incrementing staleCount. The action therefore returns [] immediately, and runContinuouslyRefilledWorkerPool marks the shared queue drained and stops refilling despite runnable work. Main excludes those future backfill rows and claims the bulk-rescan job. Prevent future rows from exhausting ready-work discovery, and add a fixed-clock regression covering this mixed-tier queue; retrying the same lookahead window alone is insufficient.

Findings

  • [P2] Keep future candidates from hiding runnable lower-tier jobs — convex/securityScan.ts:3252-3253

Tests

  • Missing end-to-end proof: Attach redacted terminal output or logs from the reported concurrent native-backend runs showing the claim entry point, recovery results and lease uniqueness; the supplied benchmark table alone does not expose that execution.
Agent review details

How this fits together

Security workers submit authenticated claim requests to Convex and receive token-bearing job leases, which they hydrate and process through the existing scanner pipeline.

flowchart TD
  A[Security workers] --> B[Authenticated claim action]
  B --> C[Read only candidate planner]
  C --> D[Tier preserving shuffle]
  D --> E[Point read admission]
  E --> F[Job leases]
  B --> G[Existing specialized claim paths]
  G --> F
Loading

Technical review

Best possible solution:

Keep query planning and point-read admission, but prevent future candidates from hiding ready jobs in lower tiers.

Do we have a high-confidence way to reproduce the issue?

Current main supports the reported shared-range conflict mechanism, and the introduced readiness failure follows from the planner, admission check and worker drain rule; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The fix uses the right boundary and an established planning pattern; additional retries retain the conflicting read set, while existing assigned-job claims cover coordinated bulk work rather than general queue discovery.

Full review comments:

  • [P2] Keep future candidates from hiding runnable lower-tier jobs — convex/securityScan.ts:3252-3253
    The action plans at Date.now() + 1,000, so not-yet-due jobs consume the candidate window. For example, with limit 4, 128 backfill retries due in 500 ms and an already-due bulk-rescan job, planning fills its window with backfill and never visits bulk-rescan. If admission runs before those retries are due, this continue skips every candidate without incrementing staleCount. The action therefore returns [] immediately, and runContinuouslyRefilledWorkerPool marks the shared queue drained and stops refilling despite runnable work. Main excludes those future backfill rows and claims the bulk-rescan job. Prevent future rows from exhausting ready-work discovery, and add a fixed-clock regression covering this mixed-tier queue; retrying the same lookahead window alone is insufficient.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against a83aceea4249.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • VITE_CONVEX_URL=https://example.invalid bunx vitest run convex/securityScan.claimPlan.runtime.test.ts convex/securityScan.test.ts convex/securityScan.retiredQueue.runtime.test.ts
  • bun run ci:static
  • bun run ci:unit
  • bun run ci:types-build

What I checked:

  • Reviewed head and live state: The PR remains open, is MEMBER-authored, and has a clean mergeable state at the reviewed head. (59c74342f52d)
  • Current-main contention mechanism: The existing claim mutation discovers jobs through shared queue indexes and leases those rows in the same transaction, matching the production OCC retry-exhaustion excerpt. (convex/securityScan.ts:2880, a83aceea4249)
  • Introduced readiness defect: Planning includes the next second of scheduled work; future candidates consume the bounded window, but admission skips them without recording a reason to replan. (convex/securityScan.ts:3253, 59c74342f52d)
  • Worker consequence: A short claim marks the queue drained; shared workers have no idle polling configured, so an incorrect empty claim ends their remaining refills. (scripts/security/run-codex-scan-worker.ts:2916, 59c74342f52d)
  • Runtime evidence inspected: The complete live body and discussion contain a production failure excerpt and native-backend benchmark summaries, but no attached terminal output, request trace, or logs showing the candidate run. (59c74342f52d)
  • Exact-head validation: Static, unit, types-build, packages, HTTP e2e and browser checks passed on the reviewed head; these checks do not exercise the delayed-window failure described in the finding. (59c74342f52d)

Likely related people:

  • Patrick Erichsen: Raw commit 8c14d84 adds convex/securityScan.ts:2342 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8c14d84d63ac; files: convex/securityScan.ts)
  • Peter Steinberger: Raw commit 35aa372 adds convex/securityScan.ts:233 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 35aa372b24a3; files: convex/securityScan.ts)
  • Vincent Koc: Raw commit ce91b2a adds convex/securityScan.ts:11 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: ce91b2a71d1a; files: convex/securityScan.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
Change size Production +290/-51; tests +199/-29; specification +20 The production growth implements discovery, admission and orchestration while retaining specialized claim paths.

Labels

Label changes:

  • add P2: The PR addresses production scan-worker contention, with a focused scheduling defect remaining in the proposed repair.
  • add merge-risk: 🚨 availability: An incorrect empty claim can stop shared workers while runnable scan jobs remain queued.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The PR addresses production scan-worker contention, with a focused scheduling defect remaining in the proposed repair.
  • merge-risk: 🚨 availability: An incorrect empty claim can stop shared workers while runnable scan jobs remain queued.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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.

Reviewed November 16, 2026, 1:47 AM ET / 06:47 UTC.

roboclaw-bot and others added 2 commits November 16, 2026 23:32
Co-authored-by: Patrick-Erichsen <20157849+Patrick-Erichsen@users.noreply.github.com>
The claim planner looked one second ahead for clock skew and counted those
not-yet-due rows toward its head window. A tier with a window's worth of
rows due inside that second filled the plan, admission skipped every one as
not yet due, and ready work in lower tiers was never planned. The worker read
the empty claim as a drained queue and stopped refilling.

Only rows due on the action's clock now fill the window. Each tier still
plans up to one claim's worth of rows due within the allowance, so a
trailing action clock cannot hide a job that was just enqueued.

Co-authored-by: Patrick-Erichsen <20157849+Patrick-Erichsen@users.noreply.github.com>
@roboclaw-bot

Copy link
Copy Markdown
Contributor

Maintainer fixup pushed at Patrick's request to land this: e8954dc (plus a merge of current main).

What it fixes. The ClawSweeper P2 is real. The planner looked one second ahead and counted those not-yet-due rows toward its head window. With a window's worth of rows due inside that second in one tier, admission skipped all of them, a ready job in a lower tier was never planned, and the action returned []. The worker reads that as a drained queue and stops refilling.

The change. Only rows due on the action's clock fill the window. Each tier still plans up to one claim's worth of rows due within the allowance, so a trailing action clock cannot hide a job that was just enqueued. The action now passes Date.now() and the planner applies the allowance itself. Admission is unchanged. specs/security-moderation.md records the rule.

Proof on a real local Convex backend (full app pushed to convex-local-backend precompiled-2026-10-22, calls through the public securityScan:claimCodexScanJobLeases action, limit 4, shared lane). Queue: 200 backfill rows due about 800 ms after the call, plus one ready bulk-rescan row.

Build Attempt 1 Attempt 2 Attempt 3
PR head 59c7434 [] [] []
e8954dc ["bulk-rescan"] ["bulk-rescan"] ["bulk-rescan"]

The backfill rows were still 260 to 320 ms from due when each call returned.

Concurrent drain, 8 workers on 400 ready jobs: both builds leased 400 unique jobs in 185 calls, with no failed calls, no duplicate leases, and no job above one attempt.

Tests. Three fixed-clock runtime tests in convex/securityScan.claimPlan.runtime.test.ts: the mixed-tier queue above, the per-tier bound on not-yet-due rows, and admission of a row that a trailing action clock planned as not yet due. The first one fails on 59c7434. vitest run over the five security-scan suites: 157 passed. tsc -p convex/tsconfig.json --noEmit: clean.

Not covered. The proof ran on one machine with a local backend, not Production. It does not measure the OCC failure rate under production load; that still rests on the numbers in the PR description.

@roboclaw-bot
roboclaw-bot merged commit 3a21350 into main Nov 16, 2026
38 checks passed
@roboclaw-bot
roboclaw-bot deleted the fix/security-scan-claim-contention branch November 16, 2026 23:49

This branch was successfully deployed

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

Labels

merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants