Preserve plugin dispatch reservations and retained completions

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-27 04:02:39 -05:00
1 parent a75c0f2206
commit 9f6aa0de4e
3 files changed
+151 -16

No files matched your search

+27
View File
@@ -127,3 +127,30 @@ below. No production timeout or quiet assertion was relaxed.
The post-cleanup retry run passes all 48 shutdown/plugin cases (28 plugin and
20 shutdown). Together with the unchanged consumer selection this covers 76
unique cases. Server typecheck and build pass on the final round-two repair.
## Reservation and unregister races
A scheduled refresh can yield after selecting eligible jobs while a manual trigger
reserves one of those jobs. Previously the stale scheduled attempt reused the
same set entry, found the manual run under its row lock, and removed that entry.
The manual provider call was still running but no longer consumed scheduler
capacity. Dispatch now performs the synchronous reservation check and insertion
at one boundary; callers cannot remove a reservation they did not create. Refresh
also rechecks active and retained-settlement state after its database read.
Unregister now preserves runs whose real result is retained for settlement. For
other unfinished runs, it locks and rereads the current run before cancelling, so
a completion committed since discovery cannot be overwritten. The existing job
store still owns mutation notifications. Provider calls stay outside transactions;
no new periodic work or durable storage is introduced.
Real PostgreSQL regressions first reproduced both incorrect cancellation of saved
success/failure results and loss of a manual reservation after a delayed query
result. The corrected suite also checks concurrent completion during unregister,
manual/scheduled capacity, retries without another provider call, drain/resume,
startup, shutdown and quiet states. All 33 complete scheduler cases and server
TypeScript checks pass on the owning slice. The first full run crossed the next
hourly cron boundary during a retry fixture and legitimately produced extra runs;
its fixed clock now isolates that test from wall-clock start time while preserving
its assertions. Stack integration and latest-head CI are separate gates.
@@ -34,6 +34,8 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: pluginId, version: "1.0.0", manifestJson: {} as never });
await Promise.all(Array.from({ length: 6 }, () => db.execute(sql`select pg_sleep(0.01)`)));
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: true });
// Retry tests must not accidentally cross the next real hourly cron tick.
vi.setSystemTime(new Date("2026-10-27T12:05:00Z"));
});
afterEach(async () => {
await scheduler?.stop(); await coordinator?.stop(); scheduler = undefined; coordinator = undefined;
@@ -249,6 +251,102 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
await completed(2); await settled(); errors.length = 0;
}
});
it.each(["succeeded", "failed"] as const)("retains a completed %s result when unregistering during a settlement failure", async outcome => {
await db.execute(sql`create function plugin_settlement_failure() returns trigger language plpgsql as $$ begin if new.status in ('succeeded', 'failed') then raise exception 'settlement unavailable'; end if; return new; end $$`);
await db.execute(sql`create trigger plugin_settlement_failure before update on plugin_job_runs for each row execute function plugin_settlement_failure()`);
if (outcome === "failed") rpc.mockRejectedValueOnce(new Error("Plugin failed before unregister"));
await due(); await start();
await vi.waitFor(async () => {
await vi.advanceTimersByTimeAsync(1000);
expect(errors.length).toBeGreaterThan(0);
expect(scheduler!.diagnostics().activeJobCount).toBe(0);
}, { timeout: 5000 });
try {
await scheduler!.unregisterPlugin(pluginId);
expect((await runs())[0].status).toBe("running");
} finally {
await db.execute(sql`drop trigger plugin_settlement_failure on plugin_job_runs`);
errors.length = 0;
await scheduler!.tick(); await settled(); errors.length = 0;
}
expect((await runs())[0].status).toBe(outcome);
expect(rpc).toHaveBeenCalledOnce();
await quiet();
});
it("preserves a completion committed while unregister waits on the discovered run", async () => {
const row = await job("finishing", "");
const run = await pluginJobStore(db).createRun({ jobId: row.id, pluginId, trigger: "manual" });
await pluginJobStore(db).markRunning(run.id);
await start(); await quiet();
let release!: () => void, locked!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
const acquired = new Promise<void>(resolve => { locked = resolve; });
const finishing = db.transaction(async tx => {
await pluginJobStore(tx).completeRun(run.id, { status: "succeeded" });
locked(); await gate;
});
await acquired;
const unregistering = scheduler!.unregisterPlugin(pluginId);
try {
await vi.waitFor(async () => {
const [waiting] = await db.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity
where datname = current_database() and state = 'active' and wait_event_type = 'Lock'
and query like '%plugin_job_runs%'`);
expect(waiting.count).toBeGreaterThan(0);
});
} finally { release(); await finishing; await unregistering; }
expect((await runs())[0].status).toBe("succeeded");
expect(rpc).not.toHaveBeenCalled();
await quiet();
});
it("retains the manual reservation when a refresh read finishes after manual dispatch", async () => {
await start(2); await quiet();
const row = await due("raced");
let resumeRead!: () => void, enteredRead!: () => void, releaseCall!: () => void;
const readGate = new Promise<void>(resolve => { resumeRead = resolve; });
const readEntered = new Promise<void>(resolve => { enteredRead = resolve; });
const callGate = new Promise<void>(resolve => { releaseCall = resolve; });
rpc.mockImplementation(() => callGate);
const select = db.select.bind(db);
let held = false;
// Hold delivery of one real outstanding-run query result. The manual run
// commits after this snapshot, before the scheduled dispatch resumes.
const readSpy = vi.spyOn(db, "select").mockImplementation((fields) => {
const builder = select(fields);
if (fields?.jobId !== pluginJobRuns.jobId || held) return builder;
held = true;
const from = builder.from.bind(builder);
vi.spyOn(builder, "from").mockImplementation((table) => {
const query = from(table);
const then = query.then.bind(query);
query.then = ((fulfilled, rejected) => then(async rows => {
enteredRead(); await readGate; return rows;
}).then(fulfilled, rejected)) as typeof query.then;
return query;
});
return builder;
});
const refreshing = scheduler!.tick();
try {
await readEntered;
await scheduler!.triggerJob(row.id);
await vi.waitFor(() => expect(rpc).toHaveBeenCalledOnce());
resumeRead(); await refreshing;
expect(scheduler!.diagnostics().activeJobIds).toEqual([row.id]);
await due("waiting-one"); await due("waiting-two"); await scheduler!.tick();
await vi.waitFor(() => expect(rpc).toHaveBeenCalledTimes(2));
expect(scheduler!.diagnostics().activeJobCount).toBe(2);
} finally {
resumeRead(); readSpy.mockRestore();
await pluginJobStore(db).updateJobStatus(row.id, "paused");
releaseCall(); await refreshing; await settled();
}
await completed(3);
expect(rpc).toHaveBeenCalledTimes(3);
});
it("preserves a deadline advanced during a concurrent unchanged declaration update", async () => {
const row = await due();
const advanced = new Date(Date.now() + 600_000);
+26 -16
View File
@@ -108,6 +108,13 @@ export function createPluginJobScheduler(options: PluginJobSchedulerOptions): Pl
}
async function dispatch(job: Job, trigger: Trigger, signal?: AbortSignal): Promise<TriggerJobResult | null> {
// Reserve synchronously at the one dispatch boundary. A refresh may have
// yielded since filtering its snapshot; it cannot borrow a manual run's slot.
if (activeJobs.has(job.id) || pendingSettlements.has(job.id)) {
if (trigger !== "schedule") throw new Error(`Job "${job.jobKey}" is already running`);
return null;
}
if (trigger === "schedule" && activeJobs.size >= maxConcurrentJobs) return null;
activeJobs.add(job.id);
try {
const run = await db.transaction(async tx => {
@@ -148,7 +155,7 @@ export function createPluginJobScheduler(options: PluginJobSchedulerOptions): Pl
next = null;
for (const job of runnable) {
if (!canRun() || signal?.aborted) break;
if (blocked.has(job.id)) continue;
if (blocked.has(job.id) || activeJobs.has(job.id) || pendingSettlements.has(job.id)) continue;
if (!job.nextRunAt) {
const deadline = nextCron(job.schedule, now);
if (!deadline) continue;
@@ -219,10 +226,16 @@ export function createPluginJobScheduler(options: PluginJobSchedulerOptions): Pl
eq(pluginJobRuns.pluginId, pluginId), inArray(pluginJobRuns.status, ["pending", "queued", "running"]),
));
for (const run of runs) {
if (!activeJobs.has(run.jobId) && ["running", "queued", "pending"].includes(run.status)) {
await jobStore.completeRun(run.id, { status: "cancelled", error: "Plugin unregistered",
durationMs: run.startedAt ? Date.now() - run.startedAt.getTime() : null });
}
if (activeJobs.has(run.jobId) || pendingSettlements.has(run.jobId)) continue;
await db.transaction(async tx => {
const [current] = await tx.select().from(pluginJobRuns).where(eq(pluginJobRuns.id, run.id)).for("update");
// A completion may have committed after the discovery read. Never
// overwrite its result, or the result still retained for persistence.
if (!current || !["running", "queued", "pending"].includes(current.status)
|| activeJobs.has(current.jobId) || pendingSettlements.has(current.jobId)) return;
await pluginJobStore(tx).completeRun(current.id, { status: "cancelled", error: "Plugin unregistered",
durationMs: current.startedAt ? Date.now() - current.startedAt.getTime() : null });
});
}
},
triggerJob(jobId, trigger = "manual") {
@@ -232,17 +245,14 @@ export function createPluginJobScheduler(options: PluginJobSchedulerOptions): Pl
if (!job) throw new Error(`Job not found: ${jobId}`);
if (job.status !== "active") throw new Error(`Job "${job.jobKey}" is not active (status: ${job.status})`);
if (activeJobs.has(jobId) || pendingSettlements.has(jobId)) throw new Error(`Job "${job.jobKey}" is already running`);
activeJobs.add(jobId);
try {
const runs = await db.select({ id: pluginJobRuns.id }).from(pluginJobRuns).where(and(
eq(pluginJobRuns.jobId, jobId), inArray(pluginJobRuns.status, ["pending", "queued", "running"]),
)).limit(1);
if (runs.length) throw new Error(`Job "${job.jobKey}" already has a running execution`);
if (unregistered.has(job.pluginId) || !workerManager.isRunning(job.pluginId)) throw new Error(`Worker for plugin "${job.pluginId}" is not running`);
const result = await dispatch(job, trigger);
if (!result) throw new Error(`Job "${job.jobKey}" is no longer available`);
return result;
} catch (err) { activeJobs.delete(jobId); throw err; }
const runs = await db.select({ id: pluginJobRuns.id }).from(pluginJobRuns).where(and(
eq(pluginJobRuns.jobId, jobId), inArray(pluginJobRuns.status, ["pending", "queued", "running"]),
)).limit(1);
if (runs.length) throw new Error(`Job "${job.jobKey}" already has a running execution`);
if (unregistered.has(job.pluginId) || !workerManager.isRunning(job.pluginId)) throw new Error(`Worker for plugin "${job.pluginId}" is not running`);
const result = await dispatch(job, trigger);
if (!result) throw new Error(`Job "${job.jobKey}" is no longer available`);
return result;
})());
},
tick,