From b1549bfe254272767d89259306c00417ec271174 Mon Sep 17 00:00:00 2001 From: Jesse Merhi <79823012+jesse-merhi@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:13:46 +1100 Subject: [PATCH 1/3] fix(security-scan): plan queue claims so concurrent shards stop conflicting 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. --- convex/securityScan.claimPlan.runtime.test.ts | 137 ++++++++ convex/securityScan.test.ts | 71 ++-- convex/securityScan.ts | 331 +++++++++++++++--- specs/security-moderation.md | 15 + 4 files changed, 475 insertions(+), 79 deletions(-) create mode 100644 convex/securityScan.claimPlan.runtime.test.ts diff --git a/convex/securityScan.claimPlan.runtime.test.ts b/convex/securityScan.claimPlan.runtime.test.ts new file mode 100644 index 0000000000..6c65453466 --- /dev/null +++ b/convex/securityScan.claimPlan.runtime.test.ts @@ -0,0 +1,137 @@ +/// +/* @vitest-environment edge-runtime */ +import { convexTest } from "convex-test"; +import { afterEach, expect, it, vi } from "vitest"; +import { api, internal } from "./_generated/api"; +import type { Doc, Id } from "./_generated/dataModel"; +import schema from "./schema"; + +const modules = import.meta.glob("./**/*.ts"); + +type JobSeed = Pick, "source"> & + Partial, "hasMaliciousSignal" | "nextRunAt">>; + +async function seedJobs(seeds: Record) { + const t = convexTest({ schema, modules, transactionLimits: true }); + const ids = await t.run(async (ctx) => { + const entries: Array<[string, Id<"securityScanJobs">]> = []; + let order = 0; + for (const [name, seed] of Object.entries(seeds)) { + order += 1; + entries.push([ + name, + await ctx.db.insert("securityScanJobs", { + targetKind: "skillVersion", + status: "queued", + source: seed.source, + priority: 0, + hasMaliciousSignal: seed.hasMaliciousSignal ?? false, + nextRunAt: seed.nextRunAt ?? order, + attempts: 0, + createdAt: order, + updatedAt: order, + }), + ]); + } + return Object.fromEntries(entries); + }); + const nameOf = new Map(Object.entries(ids).map(([name, id]) => [id, name])); + return { t, ids, nameOf }; +} + +function claimLeases( + t: ReturnType, + args: { workerId: string; lane: "shared" | "priority"; limit: number }, +) { + vi.stubEnv("SECURITY_SCAN_WORKER_TOKEN", "fixture-worker-token"); + return t.action(api.securityScan.claimCodexScanJobLeases, { + token: "fixture-worker-token", + ...args, + }); +} + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +it("claims queued work in source priority order through the planned path", async () => { + const { t, nameOf } = await seedJobs({ + backfill: { source: "backfill" }, + publish: { source: "publish" }, + maliciousBulk: { source: "bulk-rescan", hasMaliciousSignal: true }, + manual: { source: "manual" }, + future: { source: "manual", nextRunAt: Number.MAX_SAFE_INTEGER }, + }); + + const first = await claimLeases(t, { workerId: "worker-1", lane: "shared", limit: 3 }); + expect(first.map((job) => nameOf.get(job._id))).toEqual(["manual", "maliciousBulk", "publish"]); + expect(first.every((job) => job.status === "running" && job.workerId === "worker-1")).toBe(true); + + const second = await claimLeases(t, { workerId: "worker-2", lane: "shared", limit: 3 }); + // A short queue returns a short claim; the future job is never leased. + expect(second.map((job) => nameOf.get(job._id))).toEqual(["backfill"]); +}); + +it("keeps bulk sources out of the priority lane", async () => { + const { t, nameOf } = await seedJobs({ + backfill: { source: "backfill" }, + bulk: { source: "bulk-rescan" }, + publish: { source: "publish" }, + }); + + const priority = await claimLeases(t, { workerId: "priority-0", lane: "priority", limit: 4 }); + expect(priority.map((job) => nameOf.get(job._id))).toEqual(["publish"]); + await expect( + claimLeases(t, { workerId: "priority-0", lane: "priority", limit: 4 }), + ).resolves.toEqual([]); +}); + +it("skips candidates another worker leased after planning", async () => { + const { t, ids, nameOf } = await seedJobs({ + one: { source: "backfill" }, + two: { source: "backfill" }, + three: { source: "backfill" }, + }); + const plan = await t.query(internal.securityScan.planCodexScanClaimsInternal, { + lane: "shared", + limit: 2, + }); + expect(plan.requiresLegacyClaim).toBe(false); + expect(plan.candidates.map((candidate) => nameOf.get(candidate.jobId))).toEqual([ + "one", + "two", + "three", + ]); + + await t.mutation(internal.securityScan.claimPlannedJobsInternal, { + workerId: "winner", + lane: "shared", + limit: 1, + jobIds: [ids.one], + }); + const result = await t.mutation(internal.securityScan.claimPlannedJobsInternal, { + workerId: "loser", + lane: "shared", + limit: 2, + jobIds: plan.candidates.map((candidate) => candidate.jobId), + }); + + expect(result.staleCount).toBe(1); + expect(result.jobs.map((job) => nameOf.get(job._id))).toEqual(["two", "three"]); + const winner = await t.run((ctx) => ctx.db.get(ids.one)); + expect(winner).toMatchObject({ status: "running", workerId: "winner", attempts: 1 }); +}); + +it("refuses priority-lane admission of a planned bulk job", async () => { + const { t, ids } = await seedJobs({ backfill: { source: "backfill" } }); + const result = await t.mutation(internal.securityScan.claimPlannedJobsInternal, { + workerId: "priority-0", + lane: "priority", + limit: 1, + jobIds: [ids.backfill], + }); + expect(result).toEqual({ jobs: [], staleCount: 1 }); + await expect(t.run((ctx) => ctx.db.get(ids.backfill))).resolves.toMatchObject({ + status: "queued", + }); +}); diff --git a/convex/securityScan.test.ts b/convex/securityScan.test.ts index b2467b9059..7f9529da8e 100644 --- a/convex/securityScan.test.ts +++ b/convex/securityScan.test.ts @@ -3324,44 +3324,59 @@ describe("securityScan", () => { expect(getUrl).toHaveBeenCalledWith("storage:skill"); }); - it("claims several lightweight leases in one mutation without hydrating signed URLs", async () => { + it("replans a contended claim instead of reporting a short queue", async () => { vi.stubEnv("SECURITY_SCAN_WORKER_TOKEN", "worker-secret"); - const leases = Array.from({ length: 4 }, (_, index) => ({ + const lease = (id: string) => ({ ...claimedJob, - _id: `securityScanJobs:${index}`, - leaseToken: `lease-${index}`, - })); - const runMutation = vi.fn(async () => leases); - const runQuery = vi.fn(); + _id: `securityScanJobs:${id}`, + leaseToken: id, + }); + const plan = (ids: string[]) => ({ + candidates: ids.map((id) => ({ jobId: `securityScanJobs:${id}`, tier: 0 })), + requiresLegacyClaim: false, + }); + const runQuery = vi + .fn() + .mockResolvedValueOnce(plan(["a", "b"])) + .mockResolvedValueOnce(plan(["c"])); + // Another worker won "b" between planning and admission. + const runMutation = vi + .fn() + .mockResolvedValueOnce({ jobs: [lease("a")], staleCount: 1 }) + .mockResolvedValueOnce({ jobs: [lease("c")], staleCount: 0 }); const getUrl = vi.fn(); const result = await claimCodexScanJobLeasesHandler( - { - runMutation, - runQuery, - storage: { getUrl, generateUploadUrl: async () => "https://storage.example/report-upload" }, - }, - { - token: "worker-secret", - workerId: "worker-1", - lane: "shared", - limit: 4, - }, + { runMutation, runQuery, storage: { getUrl } }, + { token: "worker-secret", workerId: "worker-1", lane: "shared", limit: 2 }, ); - expect(runMutation).toHaveBeenCalledWith( - expect.anything(), - expect.objectContaining({ - workerId: "worker-1", - lane: "shared", - limit: 4, - }), - ); - expect(result).toEqual(leases); - expect(runQuery).not.toHaveBeenCalled(); + expect(result).toEqual([lease("a"), lease("c")]); + expect(runQuery.mock.calls.map(([, args]) => args.limit)).toEqual([2, 1]); + expect(runMutation.mock.calls.map(([, args]) => args.limit)).toEqual([2, 1]); expect(getUrl).not.toHaveBeenCalled(); }); + it("returns committed leases when a later claim round fails", async () => { + vi.stubEnv("SECURITY_SCAN_WORKER_TOKEN", "worker-secret"); + const committed = { ...claimedJob, _id: "securityScanJobs:a", leaseToken: "a" }; + const runQuery = vi + .fn() + .mockResolvedValueOnce({ + candidates: [{ jobId: "securityScanJobs:a", tier: 0 }], + requiresLegacyClaim: false, + }) + .mockRejectedValueOnce(new Error("Server Error")); + const runMutation = vi.fn().mockResolvedValueOnce({ jobs: [committed], staleCount: 1 }); + + await expect( + claimCodexScanJobLeasesHandler( + { runMutation, runQuery, storage: { getUrl: vi.fn() } }, + { token: "worker-secret", workerId: "worker-1", lane: "shared", limit: 2 }, + ), + ).resolves.toEqual([committed]); + }); + it("forwards exact Test GitHub Skill Sync job IDs to the lease mutation", async () => { vi.stubEnv("SECURITY_SCAN_WORKER_TOKEN", "worker-secret"); const leases = [ diff --git a/convex/securityScan.ts b/convex/securityScan.ts index a20a1e2c80..fa0340beb1 100644 --- a/convex/securityScan.ts +++ b/convex/securityScan.ts @@ -85,7 +85,7 @@ const SKILL_SCAN_ASYNC_NOTE = "Scans are asynchronous and may take time to compl const artifactBackedLlmAnalysisStatuses = new Set(["clean", "benign", "suspicious", "malicious"]); async function isGitHubSkillScanAllowed( - ctx: Pick, + ctx: Pick, githubSourceId: Id<"githubSkillSources">, ) { if (getRuntimeRolloutCapabilities().githubSkillSync.runtimeEnabled) return true; @@ -249,6 +249,7 @@ const internalRefs = internal as unknown as { updateReleaseSkillSpectorAnalysisInternal: unknown; }; securityScan: { + claimPlannedJobsInternal: unknown; claimQueuedJobsInternal: unknown; createUploadedSkillScanRequestInternal: unknown; createPublishedSkillScanRequestInternal: unknown; @@ -259,6 +260,7 @@ const internalRefs = internal as unknown as { getSkillScanRequestForUserInternal: unknown; getJobTargetInternal: unknown; listReadySourceJobsForClaimInternal: unknown; + planCodexScanClaimsInternal: unknown; recordGitHubSkillScanResultInternal: unknown; completeCatalogSkillScanJobInternal: unknown; recordSkillScanRequestFailedInternal: unknown; @@ -2863,20 +2865,8 @@ export const claimQueuedJobsInternal = internalMutation({ } }; const githubSkillSyncEnabled = getRuntimeRolloutCapabilities().githubSkillSync.runtimeEnabled; - const isJobRolloutClaimable = async (job: Doc<"securityScanJobs">) => { - if (await isRetiredAutomaticPluginScan(ctx, job)) return false; - if ( - githubSkillSyncEnabled || - job.targetKind !== "skillScanRequest" || - !job.skillScanRequestId - ) { - return true; - } - const request = await ctx.db.get(job.skillScanRequestId); - if (request?.sourceKind !== "github" || !request.githubSkillScanId) return true; - const scan = await ctx.db.get(request.githubSkillScanId); - return scan ? await isGitHubSkillScanAllowed(ctx, scan.githubSourceId) : false; - }; + const isJobRolloutClaimable = (job: Doc<"securityScanJobs">) => + isSecurityScanJobRolloutClaimable(ctx, job, githubSkillSyncEnabled); const takeReadySourceJobs = async (source: SecurityScanJobSource) => { if (remainingCapacity() === 0) return []; let takeLimit = remainingCapacity(); @@ -3068,24 +3058,11 @@ export const claimQueuedJobsInternal = internalMutation({ } catalogAttemptId = attempt._id; } - const leaseMs = securityScanLeaseMs(job.targetKind, job.scanMode, requestedLeaseMs); - const leaseToken = crypto.randomUUID(); - await ctx.db.patch(job._id, { - status: "running", - attempts: job.attempts + 1, - leaseToken, - leaseExpiresAt: now + leaseMs, + const lease = await leaseQueuedSecurityScanJob(ctx, job, { workerId: args.workerId, - lastError: undefined, - updatedAt: now, + requestedLeaseMs, + now, }); - if (job.targetKind === "skillScanRequest" && job.skillScanRequestId) { - await ctx.db.patch(job.skillScanRequestId, { - status: "running", - lastError: undefined, - updatedAt: now, - }); - } if (catalogAttemptId) { await ctx.db.patch(catalogAttemptId, { status: "running", @@ -3093,19 +3070,224 @@ export const claimQueuedJobsInternal = internalMutation({ }); catalogClaims += 1; } - claimed.push({ - ...job, - status: "running" as const, - attempts: job.attempts + 1, - leaseToken, - leaseExpiresAt: now + leaseMs, - workerId: args.workerId, - }); + claimed.push(lease); } return claimed; }, }); +async function isSecurityScanJobRolloutClaimable( + ctx: Pick, + job: Doc<"securityScanJobs">, + githubSkillSyncEnabled: boolean, +) { + if (await isRetiredAutomaticPluginScan(ctx, job)) return false; + if (githubSkillSyncEnabled || job.targetKind !== "skillScanRequest" || !job.skillScanRequestId) { + return true; + } + const request = await ctx.db.get(job.skillScanRequestId); + if (request?.sourceKind !== "github" || !request.githubSkillScanId) return true; + const scan = await ctx.db.get(request.githubSkillScanId); + return scan ? await isGitHubSkillScanAllowed(ctx, scan.githubSourceId) : false; +} + +async function leaseQueuedSecurityScanJob( + ctx: MutationCtx, + job: Doc<"securityScanJobs">, + args: { workerId: string; requestedLeaseMs: number; now: number }, +) { + const leaseMs = securityScanLeaseMs(job.targetKind, job.scanMode, args.requestedLeaseMs); + const leaseToken = crypto.randomUUID(); + const leaseExpiresAt = args.now + leaseMs; + await ctx.db.patch(job._id, { + status: "running", + attempts: job.attempts + 1, + leaseToken, + leaseExpiresAt, + workerId: args.workerId, + lastError: undefined, + updatedAt: args.now, + }); + if (job.targetKind === "skillScanRequest" && job.skillScanRequestId) { + await ctx.db.patch(job.skillScanRequestId, { + status: "running", + lastError: undefined, + updatedAt: args.now, + }); + } + return { + ...job, + status: "running" as const, + attempts: job.attempts + 1, + leaseToken, + leaseExpiresAt, + workerId: args.workerId, + }; +} + +// Queue claims are planned by a read-only query and admitted by point reads. +// A mutation that reads the shared queue-head index ranges conflicts with every +// concurrent claim that leases a row from those ranges; under fast shard refills +// Convex exhausted its OCC retries and surfaced "Server Error" to workers. +const CLAIM_PLAN_MIN_WINDOW = 128; +const CLAIM_PLAN_WINDOW_FACTOR = 4; +const MAX_CLAIM_PLAN_ROUNDS = 4; + +type ClaimPlanCandidate = { jobId: Id<"securityScanJobs">; tier: number }; +type ClaimPlan = { candidates: ClaimPlanCandidate[]; requiresLegacyClaim: boolean }; +type PlannedClaimResult = { + jobs: Array & { leaseToken: string }>; + staleCount: number; +}; + +function isPlannedClaimLaneEligible(job: Doc<"securityScanJobs">, lane: "shared" | "priority") { + if (job.source === "skills-sh-catalog-test") return false; + if (lane === "shared") return true; + // The priority lane never claims bulk sources; malicious-signal work is the exception. + return job.source === "manual" || job.source === "publish" || job.hasMaliciousSignal === true; +} + +export async function planCodexScanClaimsHandler( + ctx: Pick, + args: { lane: "shared" | "priority"; limit: number }, +): Promise { + // Read readiness on the transaction clock, as the legacy claim did. An action's + // clock can trail the enqueue mutation and hide a just-enqueued job. + const now = Date.now(); + const environment = getSkillsShFixtureEnvironmentPolicy(); + // The Test-only catalog source has admission gates owned by the legacy claim. + if (environment.allowed && environment.environment === "test") { + return { candidates: [], requiresLegacyClaim: true }; + } + const githubSkillSyncEnabled = getRuntimeRolloutCapabilities().githubSkillSync.runtimeEnabled; + const window = Math.min( + MAX_CODEX_SCAN_CLAIM_LIMIT, + Math.max(normalizeLimit(args.limit) * CLAIM_PLAN_WINDOW_FACTOR, CLAIM_PLAN_MIN_WINDOW), + ); + const candidates: ClaimPlanCandidate[] = []; + const seen = new Set>(); + const addCandidate = (job: Doc<"securityScanJobs">, tier: number) => { + if (seen.has(job._id) || job.nextRunAt > now) return; + seen.add(job._id); + candidates.push({ jobId: job._id, tier }); + }; + const isClaimable = (job: Doc<"securityScanJobs">) => + isSecurityScanJobRolloutClaimable(ctx, job, githubSkillSyncEnabled); + // Mirrors the legacy order: manual, malicious signal, then CLAIM_SOURCE_ORDER. + const addSource = async (source: SecurityScanJobSource, tier: number) => { + let scanned = 0; + for await (const job of readySourceJobsForClaimQuery( + ctx, + source, + now, + !githubSkillSyncEnabled, + )) { + if (candidates.length >= window) return true; + // Blocked legacy rows deeper than one bounded scan need the paginated claim. + if (scanned >= MAX_CODEX_SCAN_CLAIM_LIMIT) return false; + scanned += 1; + if (await isClaimable(job)) addCandidate(job, tier); + } + return true; + }; + + let tier = 0; + if (!(await addSource("manual", tier++))) return { candidates, requiresLegacyClaim: true }; + if (candidates.length < window) { + const malicious = await ctx.db + .query("securityScanJobs") + .withIndex("by_status_malicious_signal_next_run_at", (q) => + q.eq("status", "queued").eq("hasMaliciousSignal", true).lte("nextRunAt", now), + ) + .order("asc") + .take(window - candidates.length); + const maliciousTier = tier++; + for (const job of malicious) { + if (await isClaimable(job)) addCandidate(job, maliciousTier); + } + } + for (const source of CLAIM_SOURCE_ORDER) { + if (candidates.length >= window) break; + if (source === "skills-sh-catalog-test") continue; + if (!(await addSource(source, tier++))) return { candidates, requiresLegacyClaim: true }; + if (args.lane === "priority" && source === "publish") break; + } + return { candidates, requiresLegacyClaim: false }; +} + +export const planCodexScanClaimsInternal = internalQuery({ + args: { + lane: v.union(v.literal("shared"), v.literal("priority")), + limit: v.number(), + }, + handler: planCodexScanClaimsHandler, +}); + +export const claimPlannedJobsInternal = internalMutation({ + args: { + workerId: v.string(), + lane: v.union(v.literal("shared"), v.literal("priority")), + limit: v.number(), + leaseMs: v.optional(v.number()), + jobIds: v.array(v.id("securityScanJobs")), + }, + handler: async (ctx, args): Promise => { + if (args.jobIds.length > MAX_CODEX_SCAN_CLAIM_LIMIT) { + throw new ConvexError("Too many planned claim candidates"); + } + const now = Date.now(); + const limit = normalizeLimit(args.limit); + const requestedLeaseMs = args.leaseMs ?? DEFAULT_LEASE_MS; + const githubSkillSyncEnabled = getRuntimeRolloutCapabilities().githubSkillSync.runtimeEnabled; + const jobs: PlannedClaimResult["jobs"] = []; + let staleCount = 0; + // Point reads only: this mutation conflicts with another claim only when both + // pick the same row, and Convex's retry then skips the row the winner leased. + for (const jobId of new Set(args.jobIds)) { + if (jobs.length >= limit) break; + const job = await ctx.db.get(jobId); + if ( + !job || + job.status !== "queued" || + job.nextRunAt > now || + !isPlannedClaimLaneEligible(job, args.lane) || + !(await isSecurityScanJobRolloutClaimable(ctx, job, githubSkillSyncEnabled)) + ) { + staleCount += 1; + continue; + } + jobs.push( + await leaseQueuedSecurityScanJob(ctx, job, { + workerId: args.workerId, + requestedLeaseMs, + now, + }), + ); + } + return { jobs, staleCount }; + }, +}); + +/** Keep tier order, but spread concurrent workers across each tier's queue head. */ +function shuffleClaimCandidatesWithinTiers(candidates: ClaimPlanCandidate[]) { + const tiers = new Map[]>(); + for (const candidate of candidates) { + const ids = tiers.get(candidate.tier) ?? []; + ids.push(candidate.jobId); + tiers.set(candidate.tier, ids); + } + return [...tiers.keys()] + .sort((a, b) => a - b) + .flatMap((tier) => { + const ids = tiers.get(tier) ?? []; + for (let index = ids.length - 1; index > 0; index -= 1) { + const swap = Math.floor(Math.random() * (index + 1)); + [ids[index], ids[swap]] = [ids[swap], ids[index]]; + } + return ids; + }); +} + async function readCatalogClaimHealth(ctx: MutationCtx, control: Doc<"skillsShCatalogControls">) { const nativeSources = ["publish", "vt-update", "backfill", "bulk-rescan", "manual"] as const; const [nativeQueuedBySource, nativeRunningBySource, catalogQueued, catalogRunning] = @@ -3787,18 +3969,65 @@ export const claimCodexScanJobLeases = action({ }, handler: async (ctx, args) => { assertWorkerToken(args.token); - return await runMutationRef & { leaseToken: string }>>( - ctx, - internalRefs.securityScan.claimQueuedJobsInternal, - { - workerId: args.workerId, - lane: args.lane ?? "shared", - limit: normalizeLimit(args.limit), - leaseMs: args.leaseMs, - targetedJobIds: args.targetedJobIds, - assignedJobIds: args.assignedJobIds, - }, - ); + const lane = args.lane ?? "shared"; + const limit = normalizeLimit(args.limit); + const legacyClaim = () => + runMutationRef & { leaseToken: string }>>( + ctx, + internalRefs.securityScan.claimQueuedJobsInternal, + { + workerId: args.workerId, + lane, + limit, + leaseMs: args.leaseMs, + targetedJobIds: args.targetedJobIds, + assignedJobIds: args.assignedJobIds, + }, + ); + // Assigned and targeted claims already use point reads; the catalog lane + // keeps its admission gates in the legacy mutation. + if (lane === "catalog" || args.assignedJobIds !== undefined || args.targetedJobIds) { + return await legacyClaim(); + } + + const claimed: PlannedClaimResult["jobs"] = []; + for (let round = 0; round < MAX_CLAIM_PLAN_ROUNDS && claimed.length < limit; round += 1) { + let result: PlannedClaimResult; + try { + const plan = await runQueryRef( + ctx, + internalRefs.securityScan.planCodexScanClaimsInternal, + { lane, limit: limit - claimed.length }, + ); + if (plan.requiresLegacyClaim) { + if (claimed.length > 0) break; + return await legacyClaim(); + } + if (plan.candidates.length === 0) break; + result = await runMutationRef( + ctx, + internalRefs.securityScan.claimPlannedJobsInternal, + { + workerId: args.workerId, + lane, + limit: limit - claimed.length, + leaseMs: args.leaseMs, + jobIds: shuffleClaimCandidatesWithinTiers(plan.candidates), + }, + ); + } catch (error) { + // Committed leases must reach the worker; an unreturned lease would sit + // unprocessed until expiry. Report them and let the worker claim again. + if (claimed.length > 0) break; + throw error; + } + claimed.push(...result.jobs); + // Without stale candidates the plan saw the whole ready head, so a short + // claim means the queue is short. A stale candidate means another worker + // won it: replan so this worker does not mistake contention for a drain. + if (result.staleCount === 0) break; + } + return claimed; }, }); diff --git a/specs/security-moderation.md b/specs/security-moderation.md index f185e3d995..8df870b717 100644 --- a/specs/security-moderation.md +++ b/specs/security-moderation.md @@ -1053,6 +1053,21 @@ See also: [acceptable-usage.md](./acceptable-usage.md) for the marketplace polic claim-health counters, and the claim window/max-jobs limits still apply. This does not retry terminal scan failures or change their job identities. Authentication/validation failures do not enter this transient retry path. +- Shared and priority queue claims (`claimCodexScanJobLeases` without + assigned or targeted IDs) plan candidates in a read-only query and lease + them in a mutation that uses point reads only. A claim mutation must not read + the shared queue-head index ranges: every concurrent claim leases rows out + of those ranges, so at shard refill rates the old range-reading claim hit + OCC retry exhaustion ("Server Error" at the worker, from 2026-11-15). The plan + keeps the legacy tier order (manual, malicious signal, then + `CLAIM_SOURCE_ORDER`; priority lane stops after publish) over a bounded head + window, and candidates are shuffled only within a tier, so ordering inside + that window is approximate. The mutation re-checks status, `nextRunAt`, lane + eligibility and rollout claimability per row and skips a stale row. The action + replans a short claim that saw stale rows, so contention is not reported as + an empty queue. Once any lease commits, the action must return it even if + a later round fails. The catalog lane, the Test deployment's catalog source, + and blocked legacy rows deeper than one bounded scan keep the legacy claim. - Recoverable bulk skill requests use administrator-scoped request IDs. Their job identities, cursor boundary and counters commit atomically in the permanent batch audit entry. An identical replay returns that receipt before traversing From 59c74342f52d013d39ee19223dc7f4f80f5570f3 Mon Sep 17 00:00:00 2001 From: Jesse Merhi <79823012+jesse-merhi@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:32:07 +1100 Subject: [PATCH 2/3] fix(security-scan): address claim plan review findings 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. --- convex/securityScan.claimPlan.runtime.test.ts | 1 + .../securityScan.retiredQueue.runtime.test.ts | 19 ++++++++++- convex/securityScan.ts | 32 ++++++++++++------- specs/security-moderation.md | 9 ++++-- 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/convex/securityScan.claimPlan.runtime.test.ts b/convex/securityScan.claimPlan.runtime.test.ts index 6c65453466..6c6dba7551 100644 --- a/convex/securityScan.claimPlan.runtime.test.ts +++ b/convex/securityScan.claimPlan.runtime.test.ts @@ -95,6 +95,7 @@ it("skips candidates another worker leased after planning", async () => { const plan = await t.query(internal.securityScan.planCodexScanClaimsInternal, { lane: "shared", limit: 2, + now: Date.now(), }); expect(plan.requiresLegacyClaim).toBe(false); expect(plan.candidates.map((candidate) => nameOf.get(candidate.jobId))).toEqual([ diff --git a/convex/securityScan.retiredQueue.runtime.test.ts b/convex/securityScan.retiredQueue.runtime.test.ts index 8893cb176b..d3217ad5aa 100644 --- a/convex/securityScan.retiredQueue.runtime.test.ts +++ b/convex/securityScan.retiredQueue.runtime.test.ts @@ -4,7 +4,7 @@ import { convexTest } from "convex-test"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createActiveSkillSeedDefaults } from "../src/__tests__/helpers/activeSkillSeed"; import { createPackageSeedDefaults } from "../src/__tests__/helpers/packageSeed"; -import { internal } from "./_generated/api"; +import { api, internal } from "./_generated/api"; import type { Doc, Id } from "./_generated/dataModel"; import { dispatchGitHubRepositoryEvent } from "./lib/githubRepositoryDispatch"; import schema from "./schema"; @@ -220,6 +220,23 @@ describe("retired automatic plugin queue heads", () => { await assertScheduledFunctionsSucceeded(f); }); + it("never leases retired automatic plugin scans through the planned worker claim", async () => { + const f = await fixture("queued", 7); + vi.stubEnv("SECURITY_SCAN_WORKER_TOKEN", "fixture-worker-token"); + const claimed = await f.t + .action(api.securityScan.claimCodexScanJobLeases, { + token: "fixture-worker-token", + workerId: "eligible-worker", + lane: "shared", + limit: 20, + }) + .finally(() => vi.unstubAllEnvs()); + expect(new Set(claimed.map((job) => job._id))).toEqual(new Set(f.eligibleIds)); + for (const job of await readJobs(f, f.retiredIds)) { + expect(job).toMatchObject({ status: "queued", attempts: 2 }); + } + }); + it.each([true, false])( "paginates failed recovery past retained heads (dryRun=%s)", async (dryRun) => { diff --git a/convex/securityScan.ts b/convex/securityScan.ts index fa0340beb1..005c42c78a 100644 --- a/convex/securityScan.ts +++ b/convex/securityScan.ts @@ -3132,6 +3132,10 @@ async function leaseQueuedSecurityScanJob( const CLAIM_PLAN_MIN_WINDOW = 128; const CLAIM_PLAN_WINDOW_FACTOR = 4; const MAX_CLAIM_PLAN_ROUNDS = 4; +// Queries must not read the clock, so the action passes `now`. Its clock can trail +// the mutation that enqueued a job; plan slightly ahead and let the admission +// mutation, which checks readiness on its own clock, be the authority. +const CLAIM_PLAN_CLOCK_ALLOWANCE_MS = 1_000; type ClaimPlanCandidate = { jobId: Id<"securityScanJobs">; tier: number }; type ClaimPlan = { candidates: ClaimPlanCandidate[]; requiresLegacyClaim: boolean }; @@ -3149,11 +3153,9 @@ function isPlannedClaimLaneEligible(job: Doc<"securityScanJobs">, lane: "shared" export async function planCodexScanClaimsHandler( ctx: Pick, - args: { lane: "shared" | "priority"; limit: number }, + args: { lane: "shared" | "priority"; limit: number; now: number }, ): Promise { - // Read readiness on the transaction clock, as the legacy claim did. An action's - // clock can trail the enqueue mutation and hide a just-enqueued job. - const now = Date.now(); + const now = args.now; const environment = getSkillsShFixtureEnvironmentPolicy(); // The Test-only catalog source has admission gates owned by the legacy claim. if (environment.allowed && environment.environment === "test") { @@ -3219,6 +3221,7 @@ export const planCodexScanClaimsInternal = internalQuery({ args: { lane: v.union(v.literal("shared"), v.literal("priority")), limit: v.number(), + now: v.number(), }, handler: planCodexScanClaimsHandler, }); @@ -3246,10 +3249,11 @@ export const claimPlannedJobsInternal = internalMutation({ for (const jobId of new Set(args.jobIds)) { if (jobs.length >= limit) break; const job = await ctx.db.get(jobId); + // Planned slightly ahead of this clock; a row not ready yet is not contention. + if (job?.status === "queued" && job.nextRunAt > now) continue; if ( !job || job.status !== "queued" || - job.nextRunAt > now || !isPlannedClaimLaneEligible(job, args.lane) || !(await isSecurityScanJobRolloutClaimable(ctx, job, githubSkillSyncEnabled)) ) { @@ -3971,14 +3975,14 @@ export const claimCodexScanJobLeases = action({ assertWorkerToken(args.token); const lane = args.lane ?? "shared"; const limit = normalizeLimit(args.limit); - const legacyClaim = () => + const legacyClaim = (legacyLimit = limit) => runMutationRef & { leaseToken: string }>>( ctx, internalRefs.securityScan.claimQueuedJobsInternal, { workerId: args.workerId, lane, - limit, + limit: legacyLimit, leaseMs: args.leaseMs, targetedJobIds: args.targetedJobIds, assignedJobIds: args.assignedJobIds, @@ -3997,11 +4001,15 @@ export const claimCodexScanJobLeases = action({ const plan = await runQueryRef( ctx, internalRefs.securityScan.planCodexScanClaimsInternal, - { lane, limit: limit - claimed.length }, + { + lane, + limit: limit - claimed.length, + now: Date.now() + CLAIM_PLAN_CLOCK_ALLOWANCE_MS, + }, ); if (plan.requiresLegacyClaim) { - if (claimed.length > 0) break; - return await legacyClaim(); + claimed.push(...(await legacyClaim(limit - claimed.length))); + break; } if (plan.candidates.length === 0) break; result = await runMutationRef( @@ -4017,7 +4025,9 @@ export const claimCodexScanJobLeases = action({ ); } catch (error) { // Committed leases must reach the worker; an unreturned lease would sit - // unprocessed until expiry. Report them and let the worker claim again. + // unprocessed until expiry. The worker reads this short claim as a drained + // queue and stops refilling for the rest of its run; that costs throughput, + // never a lease. With nothing committed, the error reaches the worker's retry. if (claimed.length > 0) break; throw error; } diff --git a/specs/security-moderation.md b/specs/security-moderation.md index 8df870b717..09cc231639 100644 --- a/specs/security-moderation.md +++ b/specs/security-moderation.md @@ -1066,8 +1066,13 @@ See also: [acceptable-usage.md](./acceptable-usage.md) for the marketplace polic eligibility and rollout claimability per row and skips a stale row. The action replans a short claim that saw stale rows, so contention is not reported as an empty queue. Once any lease commits, the action must return it even if - a later round fails. The catalog lane, the Test deployment's catalog source, - and blocked legacy rows deeper than one bounded scan keep the legacy claim. + a later round fails; the worker then reads the short claim as a drain, which + costs refills for that run but never strands a lease. The planner query takes + `now` from the action (slightly ahead, for clock skew) because queries must + not read the clock; the admission mutation checks readiness on its own clock. + The catalog lane, the Test deployment's catalog source, and blocked legacy + rows deeper than one bounded scan keep the legacy claim (a planned claim that + hits them hands its remaining limit to the legacy claim). - Recoverable bulk skill requests use administrator-scoped request IDs. Their job identities, cursor boundary and counters commit atomically in the permanent batch audit entry. An identical replay returns that receipt before traversing From e8954dcba1e2ea212e0de0e348cdeddefab95154 Mon Sep 17 00:00:00 2001 From: roboclaw-bot <309084314+roboclaw-bot@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:36:05 +0000 Subject: [PATCH 3/3] fix(security-scan): keep not-yet-due rows from hiding ready claim work 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> --- convex/securityScan.claimPlan.runtime.test.ts | 76 ++++++++++++++++++ convex/securityScan.ts | 78 +++++++++++++------ specs/security-moderation.md | 9 ++- 3 files changed, 138 insertions(+), 25 deletions(-) diff --git a/convex/securityScan.claimPlan.runtime.test.ts b/convex/securityScan.claimPlan.runtime.test.ts index 6c6dba7551..123aef4ca9 100644 --- a/convex/securityScan.claimPlan.runtime.test.ts +++ b/convex/securityScan.claimPlan.runtime.test.ts @@ -52,8 +52,17 @@ function claimLeases( afterEach(() => { vi.unstubAllEnvs(); + vi.useRealTimers(); }); +function freezeClock() { + const now = Date.UTC(2026, 10, 16); + // Fake only the clock; convex-test still needs real timers. + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(now); + return now; +} + it("claims queued work in source priority order through the planned path", async () => { const { t, nameOf } = await seedJobs({ backfill: { source: "backfill" }, @@ -136,3 +145,70 @@ it("refuses priority-lane admission of a planned bulk job", async () => { status: "queued", }); }); + +it("does not let not-yet-due rows hide ready lower-tier work", async () => { + const now = freezeClock(); + const seeds: Record = { + readyBulk: { source: "bulk-rescan", nextRunAt: now - 1 }, + }; + // More retries than the plan window, all due inside the planner's clock allowance. + for (let index = 0; index < 200; index += 1) { + seeds[`retry-${index}`] = { source: "backfill", nextRunAt: now + 500 }; + } + const { t, nameOf } = await seedJobs(seeds); + + // A short claim ends a worker's refills, so the ready job must not be missed. + const claimed = await claimLeases(t, { workerId: "worker-1", lane: "shared", limit: 4 }); + expect(claimed.map((job) => nameOf.get(job._id))).toEqual(["readyBulk"]); +}); + +it("plans only a claim's worth of not-yet-due rows per tier", async () => { + const now = freezeClock(); + const seeds: Record = {}; + for (let index = 0; index < 10; index += 1) { + seeds[`early-${index}`] = { source: "manual", nextRunAt: now + 500 }; + } + seeds.readyOne = { source: "backfill", nextRunAt: now - 2 }; + seeds.readyTwo = { source: "backfill", nextRunAt: now - 1 }; + const { t, nameOf } = await seedJobs(seeds); + + const plan = await t.query(internal.securityScan.planCodexScanClaimsInternal, { + lane: "shared", + limit: 2, + now, + }); + expect(plan.candidates.map((candidate) => nameOf.get(candidate.jobId))).toEqual([ + "early-0", + "early-1", + "readyOne", + "readyTwo", + ]); + + const claimed = await claimLeases(t, { workerId: "worker-1", lane: "shared", limit: 2 }); + // Candidates are shuffled within a tier, so the lease order is not fixed. + expect(claimed).toHaveLength(2); + expect(new Set(claimed.map((job) => nameOf.get(job._id)))).toEqual( + new Set(["readyOne", "readyTwo"]), + ); +}); + +it("admits a row that a trailing action clock planned as not yet due", async () => { + const now = freezeClock(); + const { t, nameOf } = await seedJobs({ enqueued: { source: "publish", nextRunAt: now } }); + + // The action's clock can trail the mutation that enqueued the job. + const plan = await t.query(internal.securityScan.planCodexScanClaimsInternal, { + lane: "shared", + limit: 1, + now: now - 500, + }); + expect(plan.candidates.map((candidate) => nameOf.get(candidate.jobId))).toEqual(["enqueued"]); + + const result = await t.mutation(internal.securityScan.claimPlannedJobsInternal, { + workerId: "worker-1", + lane: "shared", + limit: 1, + jobIds: plan.candidates.map((candidate) => candidate.jobId), + }); + expect(result.jobs.map((job) => nameOf.get(job._id))).toEqual(["enqueued"]); +}); diff --git a/convex/securityScan.ts b/convex/securityScan.ts index 005c42c78a..32dbb6a1c8 100644 --- a/convex/securityScan.ts +++ b/convex/securityScan.ts @@ -3132,9 +3132,10 @@ async function leaseQueuedSecurityScanJob( const CLAIM_PLAN_MIN_WINDOW = 128; const CLAIM_PLAN_WINDOW_FACTOR = 4; const MAX_CLAIM_PLAN_ROUNDS = 4; -// Queries must not read the clock, so the action passes `now`. Its clock can trail -// the mutation that enqueued a job; plan slightly ahead and let the admission -// mutation, which checks readiness on its own clock, be the authority. +// Queries must not read the clock, so the action passes its own as `now`. That +// clock can trail the mutation that enqueued a job, so each tier also plans up to +// one claim's worth of rows due within this allowance. The admission mutation, +// which checks readiness on its own clock, is the authority. const CLAIM_PLAN_CLOCK_ALLOWANCE_MS = 1_000; type ClaimPlanCandidate = { jobId: Id<"securityScanJobs">; tier: number }; @@ -3156,65 +3157,96 @@ export async function planCodexScanClaimsHandler( args: { lane: "shared" | "priority"; limit: number; now: number }, ): Promise { const now = args.now; + const lookaheadUntil = now + CLAIM_PLAN_CLOCK_ALLOWANCE_MS; const environment = getSkillsShFixtureEnvironmentPolicy(); // The Test-only catalog source has admission gates owned by the legacy claim. if (environment.allowed && environment.environment === "test") { return { candidates: [], requiresLegacyClaim: true }; } const githubSkillSyncEnabled = getRuntimeRolloutCapabilities().githubSkillSync.runtimeEnabled; + const limit = normalizeLimit(args.limit); const window = Math.min( MAX_CODEX_SCAN_CLAIM_LIMIT, - Math.max(normalizeLimit(args.limit) * CLAIM_PLAN_WINDOW_FACTOR, CLAIM_PLAN_MIN_WINDOW), + Math.max(limit * CLAIM_PLAN_WINDOW_FACTOR, CLAIM_PLAN_MIN_WINDOW), ); - const candidates: ClaimPlanCandidate[] = []; + // Only rows due on the action's clock fill the window. Rows due within the + // allowance are planned apart, at most `limit` per tier: if they filled the + // window, admission would skip them all as not yet due, ready work in lower + // tiers would never be planned, and the worker would read the short claim as + // a drained queue. + const ready: ClaimPlanCandidate[] = []; + const early: ClaimPlanCandidate[] = []; + const plan = (requiresLegacyClaim: boolean): ClaimPlan => ({ + // Ready rows always fit; not-yet-due rows take what is left of the admission bound. + candidates: [...ready, ...early.slice(0, MAX_CODEX_SCAN_CLAIM_LIMIT - ready.length)].sort( + (a, b) => a.tier - b.tier, + ), + requiresLegacyClaim, + }); const seen = new Set>(); - const addCandidate = (job: Doc<"securityScanJobs">, tier: number) => { - if (seen.has(job._id) || job.nextRunAt > now) return; - seen.add(job._id); - candidates.push({ jobId: job._id, tier }); - }; const isClaimable = (job: Doc<"securityScanJobs">) => isSecurityScanJobRolloutClaimable(ctx, job, githubSkillSyncEnabled); + const planTier = (tier: number) => { + let earlyCount = 0; + return { + // Rows arrive in nextRunAt order, so every row after the first + // not-yet-due one is not yet due either. + wants: (job: Doc<"securityScanJobs">) => + job.nextRunAt > now ? earlyCount < limit : ready.length < window, + add: async (job: Doc<"securityScanJobs">) => { + if (seen.has(job._id) || !(await isClaimable(job))) return; + seen.add(job._id); + if (job.nextRunAt > now) { + earlyCount += 1; + early.push({ jobId: job._id, tier }); + } else { + ready.push({ jobId: job._id, tier }); + } + }, + }; + }; // Mirrors the legacy order: manual, malicious signal, then CLAIM_SOURCE_ORDER. const addSource = async (source: SecurityScanJobSource, tier: number) => { let scanned = 0; + const tierPlan = planTier(tier); for await (const job of readySourceJobsForClaimQuery( ctx, source, - now, + lookaheadUntil, !githubSkillSyncEnabled, )) { - if (candidates.length >= window) return true; + if (!tierPlan.wants(job)) return true; // Blocked legacy rows deeper than one bounded scan need the paginated claim. if (scanned >= MAX_CODEX_SCAN_CLAIM_LIMIT) return false; scanned += 1; - if (await isClaimable(job)) addCandidate(job, tier); + await tierPlan.add(job); } return true; }; let tier = 0; - if (!(await addSource("manual", tier++))) return { candidates, requiresLegacyClaim: true }; - if (candidates.length < window) { + if (!(await addSource("manual", tier++))) return plan(true); + if (ready.length < window) { const malicious = await ctx.db .query("securityScanJobs") .withIndex("by_status_malicious_signal_next_run_at", (q) => - q.eq("status", "queued").eq("hasMaliciousSignal", true).lte("nextRunAt", now), + q.eq("status", "queued").eq("hasMaliciousSignal", true).lte("nextRunAt", lookaheadUntil), ) .order("asc") - .take(window - candidates.length); - const maliciousTier = tier++; + .take(window - ready.length + limit); + const tierPlan = planTier(tier++); for (const job of malicious) { - if (await isClaimable(job)) addCandidate(job, maliciousTier); + if (!tierPlan.wants(job)) break; + await tierPlan.add(job); } } for (const source of CLAIM_SOURCE_ORDER) { - if (candidates.length >= window) break; + if (ready.length >= window) break; if (source === "skills-sh-catalog-test") continue; - if (!(await addSource(source, tier++))) return { candidates, requiresLegacyClaim: true }; + if (!(await addSource(source, tier++))) return plan(true); if (args.lane === "priority" && source === "publish") break; } - return { candidates, requiresLegacyClaim: false }; + return plan(false); } export const planCodexScanClaimsInternal = internalQuery({ @@ -4004,7 +4036,7 @@ export const claimCodexScanJobLeases = action({ { lane, limit: limit - claimed.length, - now: Date.now() + CLAIM_PLAN_CLOCK_ALLOWANCE_MS, + now: Date.now(), }, ); if (plan.requiresLegacyClaim) { diff --git a/specs/security-moderation.md b/specs/security-moderation.md index a5a6b24f7b..4b6fb47140 100644 --- a/specs/security-moderation.md +++ b/specs/security-moderation.md @@ -1071,8 +1071,13 @@ See also: [acceptable-usage.md](./acceptable-usage.md) for the marketplace polic an empty queue. Once any lease commits, the action must return it even if a later round fails; the worker then reads the short claim as a drain, which costs refills for that run but never strands a lease. The planner query takes - `now` from the action (slightly ahead, for clock skew) because queries must - not read the clock; the admission mutation checks readiness on its own clock. + `now` from the action because queries must not read the clock; the admission + mutation checks readiness on its own clock. Because the action's clock can + trail the mutation that enqueued a job, each tier also plans rows due within + a one-second allowance, but only up to one claim's worth, and they never + count toward the head window. Not-yet-due rows must not fill the window: + admission skips them, so ready work in lower tiers would go unplanned and the + worker would read the short claim as a drained queue and stop refilling. The catalog lane, the Test deployment's catalog source, and blocked legacy rows deeper than one bounded scan keep the legacy claim (a planned claim that hits them hands its remaining limit to the legacy claim).