diff --git a/convex/securityScan.claimPlan.runtime.test.ts b/convex/securityScan.claimPlan.runtime.test.ts
new file mode 100644
index 0000000000..123aef4ca9
--- /dev/null
+++ b/convex/securityScan.claimPlan.runtime.test.ts
@@ -0,0 +1,214 @@
+///
+/* @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();
+ 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" },
+ 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,
+ now: Date.now(),
+ });
+ 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",
+ });
+});
+
+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.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.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..32dbb6a1c8 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,260 @@ 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;
+// 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 };
+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; 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(limit * CLAIM_PLAN_WINDOW_FACTOR, CLAIM_PLAN_MIN_WINDOW),
+ );
+ // 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 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,
+ lookaheadUntil,
+ !githubSkillSyncEnabled,
+ )) {
+ 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;
+ await tierPlan.add(job);
+ }
+ return true;
+ };
+
+ let tier = 0;
+ 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", lookaheadUntil),
+ )
+ .order("asc")
+ .take(window - ready.length + limit);
+ const tierPlan = planTier(tier++);
+ for (const job of malicious) {
+ if (!tierPlan.wants(job)) break;
+ await tierPlan.add(job);
+ }
+ }
+ for (const source of CLAIM_SOURCE_ORDER) {
+ if (ready.length >= window) break;
+ if (source === "skills-sh-catalog-test") continue;
+ if (!(await addSource(source, tier++))) return plan(true);
+ if (args.lane === "priority" && source === "publish") break;
+ }
+ return plan(false);
+}
+
+export const planCodexScanClaimsInternal = internalQuery({
+ args: {
+ lane: v.union(v.literal("shared"), v.literal("priority")),
+ limit: v.number(),
+ now: 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);
+ // 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" ||
+ !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 +4005,71 @@ 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 = (legacyLimit = limit) =>
+ runMutationRef & { leaseToken: string }>>(
+ ctx,
+ internalRefs.securityScan.claimQueuedJobsInternal,
+ {
+ workerId: args.workerId,
+ lane,
+ limit: legacyLimit,
+ 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,
+ now: Date.now(),
+ },
+ );
+ if (plan.requiresLegacyClaim) {
+ claimed.push(...(await legacyClaim(limit - claimed.length)));
+ break;
+ }
+ 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. 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;
+ }
+ 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 35fd5a58f4..4b6fb47140 100644
--- a/specs/security-moderation.md
+++ b/specs/security-moderation.md
@@ -1056,6 +1056,31 @@ See also: [acceptable-usage.md](./acceptable-usage.md) for the marketplace polic
a claim error recovered by retry does not fail an otherwise healthy shard.
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 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 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).
- 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