Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion convex/publishAttemptDispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ export function isPublishAttemptEventDispatchEnabled(env: NodeJS.ProcessEnv = pr
export async function requestPublishAttemptDispatch(
ctx: Pick<MutationCtx, "scheduler">,
attemptId: Id<"publishAttempts">,
delayMs = 0,
) {
if (!isPublishAttemptEventDispatchEnabled()) return { scheduled: false as const };
await ctx.scheduler.runAfter(
0,
delayMs,
internalRefs.publishAttemptDispatch.dispatchPublishAttemptInternal as never,
{
attemptId,
Expand Down
85 changes: 85 additions & 0 deletions convex/publishAttempts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
getPackagePublishAttemptStatusInternal,
recordSkillPublishAttemptFinalizedInternal,
releasePackagePublishAttemptFinalizationClaimInternal,
releasePrePublicationChecksClaimInternal,
releaseSkillPublishAttemptFinalizationClaimInternal,
} from "./publishAttempts";

Expand All @@ -24,6 +25,9 @@ const claimReadyFinalizationHandler = getTestHandler<unknown>(
claimReadyPublishAttemptFinalizationRetryInternal,
);
const claimPrePublicationChecksHandler = getTestHandler<unknown>(claimPrePublicationChecks);
const releasePrePublicationChecksClaimHandler = getTestHandler<unknown>(
releasePrePublicationChecksClaimInternal,
);
const releaseSkillFinalizationHandler = getTestHandler<unknown>(
releaseSkillPublishAttemptFinalizationClaimInternal,
);
Expand Down Expand Up @@ -1150,6 +1154,87 @@ describe("publishAttempts", () => {
expect(patch.checkClaimExpiresAt).toBeGreaterThan(now);
});

describe("stalled check retries", () => {
function enableDispatch() {
vi.stubEnv("SECURITY_SCAN_EVENT_DISPATCH_ENABLED", "1");
vi.stubEnv("GITHUB_APP_ID", "configured");
vi.stubEnv("GITHUB_APP_INSTALLATION_ID", "configured");
vi.stubEnv("GITHUB_APP_PRIVATE_KEY", "configured");
}
function claimedCtx(now: number, overrides: Record<string, unknown> = {}) {
return {
db: {
...createMockDb(),
get: vi.fn(async () => ({
_id: "publishAttempts:demo",
kind: "package",
status: "pending_checks",
artifactFingerprint: "fingerprint",
checkClaimId: "checks:claim",
checkClaimExpiresAt: now + 70 * 60_000,
checkFailureCount: 1,
checks: { trufflehog: { status: "pending" }, clawscan: { status: "pending" } },
...overrides,
})),
},
scheduler: { runAfter: vi.fn(async () => "_scheduled_functions:1") },
storage: { delete: vi.fn() },
};
}

it("dispatches a targeted retry after the backoff instead of waiting for a sweep", async () => {
enableDispatch();
const ctx = claimedCtx(Date.now());
await completePendingChecksHandler(ctx, {
attemptId: "publishAttempts:demo",
claimId: "checks:claim",
artifactFingerprint: "fingerprint",
trufflehog: { status: "failed", summary: "scanner unavailable" },
clawscan: { status: "failed", summary: "scanner unavailable" },
});
expect(ctx.scheduler.runAfter).toHaveBeenCalledWith(5 * 60_000, expect.anything(), {
attemptId: "publishAttempts:demo",
retryCount: 0,
});
vi.unstubAllEnvs();
});

it("releases an exact claim into backoff without counting a scanner failure", async () => {
enableDispatch();
const now = Date.now();
const ctx = claimedCtx(now);
await expect(
releasePrePublicationChecksClaimHandler(ctx, {
attemptId: "publishAttempts:demo",
claimId: "checks:claim",
}),
).resolves.toEqual({ released: true });
const patch = ctx.db.patch.mock.calls[0]?.[1] as Record<string, unknown>;
expect(patch.checkClaimExpiresAt).toBeLessThanOrEqual(Date.now() + 5 * 60_000);
expect(patch).not.toHaveProperty("checkFailureCount");
expect(patch).not.toHaveProperty("status");
expect(ctx.scheduler.runAfter).toHaveBeenCalledWith(5 * 60_000, expect.anything(), {
attemptId: "publishAttempts:demo",
retryCount: 0,
});
vi.unstubAllEnvs();
});

it("ignores a release from a worker that no longer owns the claim", async () => {
enableDispatch();
const ctx = claimedCtx(Date.now(), { checkClaimId: "checks:newer" });
await expect(
releasePrePublicationChecksClaimHandler(ctx, {
attemptId: "publishAttempts:demo",
claimId: "checks:claim",
}),
).resolves.toEqual({ released: false });
expect(ctx.db.patch).not.toHaveBeenCalled();
expect(ctx.scheduler.runAfter).not.toHaveBeenCalled();
vi.unstubAllEnvs();
});
});

it("terminalizes an attempt after three consecutive scanner execution failures", async () => {
const now = Date.now();
const ctx = {
Expand Down
57 changes: 57 additions & 0 deletions convex/publishAttempts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -874,6 +874,11 @@ export const completePendingPublishAttemptChecksInternal = internalMutation({
failedAt: terminal ? now : undefined,
updatedAt: now,
});
// Retries must not wait for the shared scheduled sweep, which a single
// stuck worker can starve for hours.
if (!terminal) {
await requestPublishAttemptDispatch(ctx, attempt._id, CHECK_RETRY_BACKOFF_MS);
}
return {
attemptId: attempt._id,
kind: attempt.kind,
Expand Down Expand Up @@ -1703,6 +1708,58 @@ export const backoffFailedPrePublicationHandoffInternal = internalMutation({
},
});

// A worker that cannot confirm ClawScan container cleanup keeps custody of its
// workspace and stops claiming, but must not hold the attempt for the whole
// lease: release the exact claim into the retry backoff and dispatch a fresh
// worker. This is operational, so it does not count as a scanner failure.
export const releasePrePublicationChecksClaimInternal = internalMutation({
args: {
attemptId: v.id("publishAttempts"),
claimId: v.string(),
},
handler: async (ctx, args) => {
const attempt = await ctx.db.get(args.attemptId);
const now = Date.now();
if (
!attempt ||
attempt.status !== "pending_checks" ||
attempt.checkClaimId !== args.claimId ||
(attempt.checkClaimExpiresAt ?? 0) <= now
) {
return { released: false };
}
await ctx.db.patch(attempt._id, {
checkClaimExpiresAt: Math.min(
attempt.checkClaimExpiresAt ?? now,
now + CHECK_RETRY_BACKOFF_MS,
),
checkClaimLastError:
"ClawScan container cleanup was unconfirmed; retrying on another worker.",
updatedAt: now,
});
await requestPublishAttemptDispatch(ctx, attempt._id, CHECK_RETRY_BACKOFF_MS);
return { released: true };
},
});

export const releasePrePublicationChecksClaim: ReturnType<typeof action> = action({
args: {
token: v.string(),
attemptId: v.id("publishAttempts"),
claimId: v.string(),
},
handler: async (ctx, args): Promise<unknown> => {
assertWorkerToken(args.token);
return await ctx.runMutation(
internal.publishAttempts.releasePrePublicationChecksClaimInternal,
{
attemptId: args.attemptId,
claimId: args.claimId,
},
);
},
});

export const claimPrePublicationChecks: ReturnType<typeof action> = action({
args: {
token: v.string(),
Expand Down
8 changes: 7 additions & 1 deletion scripts/security/run-prepublication-worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,13 @@ describe("pre-publication worker", () => {
},
});
expect(result).toEqual({ completed: false, result: undefined, workerMustStop: true });
expect(client.action).not.toHaveBeenCalled();
// Custody is kept locally, but the exact claim is released for another worker.
expect(client.action).toHaveBeenCalledTimes(1);
expect(client.action.mock.calls[0]?.[1]).toEqual({
token: "fixture",
attemptId: attempt.attemptId,
claimId: attempt.claimId,
});
tempDirs.track(preserved!);
expect(await readFile(join(preserved!, "artifact/SKILL.md"), "utf8")).toBe(
"retained mounted fixture",
Expand Down
17 changes: 17 additions & 0 deletions scripts/security/run-prepublication-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1218,6 +1218,23 @@ export async function processPrePublicationAttempt(
{ event: "prepublication_container_cleanup_unconfirmed", attemptId: attempt.attemptId },
"ClawScan container removal unconfirmed; preserving workspace and stopping worker",
);
// Custody stays here; the attempt itself retries on another worker.
try {
await client.action(api.publishAttempts.releasePrePublicationChecksClaim, {
token,
attemptId: attempt.attemptId,
claimId: attempt.claimId,
});
} catch (releaseError) {
logger.warn(
{
attemptId: attempt.attemptId,
completionError: backendFailureDiagnostic(releaseError),
event: "prepublication_claim_release_failed",
},
"pre-publication claim release failed; attempt waits for its lease to expire",
);
}
return { completed: false, result: undefined, workerMustStop: true };
}
if (truffleHogBlocked) {
Expand Down
6 changes: 5 additions & 1 deletion specs/plugin-qualified-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,11 @@ verdict.

Prepublication does not swallow this error as ordinary scan failure; it retains
workspace custody, emits workerMustStop, and stops after already-active batch
work settles. Manual scan workers similarly stop, including when recording the
work settles. Before stopping it releases its exact check claim into the
five-minute retry backoff, without counting a scanner failure, and the backend
dispatches a targeted worker for the attempt, so custody of one host never holds
the attempt for the full lease. Retryable scanner failures likewise dispatch a
targeted retry after the backoff rather than waiting for the scheduled sweep. Manual scan workers similarly stop, including when recording the
backend failure itself is unavailable. Legacy/nonqualified command paths are
unchanged. Real process-supervisor tests and executable mocked-daemon tests
cover multiple/late containers, ownership mismatches, daemon/removal failures,
Expand Down
Loading