Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions convex/securityScan.claimPlan.runtime.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/// <reference types="vite/client" />
/* @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<Doc<"securityScanJobs">, "source"> &
Partial<Pick<Doc<"securityScanJobs">, "hasMaliciousSignal" | "nextRunAt">>;

async function seedJobs(seeds: Record<string, JobSeed>) {
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<typeof convexTest>,
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,
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",
});
});
19 changes: 18 additions & 1 deletion convex/securityScan.retiredQueue.runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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) => {
Expand Down
71 changes: 43 additions & 28 deletions convex/securityScan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
Loading
Loading