diff --git a/apps/server/src/jobs/runner.test.ts b/apps/server/src/jobs/runner.test.ts index 08fc21b54..bbd40f72d 100644 --- a/apps/server/src/jobs/runner.test.ts +++ b/apps/server/src/jobs/runner.test.ts @@ -7,7 +7,7 @@ import { MemoryStorage } from "../storage/memory/adapter"; import type { JobDefinition } from "./registry"; import type { JobExecutionDiagnostic } from "./registry"; -import type { JobRunnerOptions, ResolvedJobCredential } from "./runner"; +import type { JobRunnerOptions, ResolvedJobCredential, RunnerScheduler } from "./runner"; import type { JsonValue } from "../storage/model"; function deferred() { @@ -20,6 +20,34 @@ function deferred() { return { promise, resolve, reject }; } +/** A clock that moves only when the test moves it, running each timer that comes due in order. */ +function manualClock() { + let now = Date.now(); + let timers = new Set<{ at: number; action: () => void }>(); + let scheduler: RunnerScheduler = { + now: () => new Date(now), + after(delayMs, action) { + let timer = { at: now + delayMs, action }; + timers.add(timer); + return () => void timers.delete(timer); + }, + }; + return { + scheduler, + advance(ms: number): void { + let until = now + ms; + for (;;) { + let due = [...timers].filter(timer => timer.at <= until).sort((a, b) => a.at - b.at)[0]; + if (!due) break; + timers.delete(due); + now = due.at; + due.action(); + } + now = until; + }, + }; +} + async function waitFor(check: () => boolean | Promise, timeoutMs = 1_000): Promise { let deadline = Date.now() + timeoutMs; while (!await check()) { @@ -71,9 +99,10 @@ async function setup( resolve: () => Promise = async () => undefined, enabled = true, attemptFailed?: JobRunnerOptions["attemptFailed"], + scheduler?: RunnerScheduler, ) { let storage = new MemoryStorage(); - let now = new Date(); + let now = scheduler?.now() ?? new Date(); let userId = crypto.randomUUID(); let channelId = crypto.randomUUID(); await storage.users.put({ id: userId, login: "mona", avatarUrl: "", now }); @@ -94,6 +123,7 @@ async function setup( storage, registry, lease: () => lease, + now: scheduler?.now, onChange: job => runner?.notify(job), }); let errors: unknown[] = []; @@ -113,6 +143,7 @@ async function setup( retryMaxMs: 20, shutdownGraceMs: 50, attemptFailed, + scheduler, fatal: err => errors.push(err), }); return { storage, channelId, lease, service, runner, errors }; @@ -218,13 +249,14 @@ describe("background job runner", () => { }); it("renews a claim after delayed owner resolution without reclaiming the attempt", async () => { - let started = deferred(); + let clock = manualClock(); + let asked = deferred(); + let resolved = deferred(); let release = deferred(); let registered = { ...definition( async execution => { await execution.progress("work", "started"); - started.resolve(); return release.promise; }, "active-planner", @@ -235,23 +267,33 @@ describe("background job runner", () => { }; let value = await setup( registered, - async () => { - await Bun.sleep(150); - return owner(); + () => { + asked.resolve(); + return resolved.promise; }, + true, + undefined, + clock.scheduler, ); try { let queued = await enqueue(value.service, value.channelId); + let job = async () => (await value.service.get(value.channelId, queued.job.id))?.job; value.runner.start(); - await started.promise; - await Bun.sleep(350); - expect(await value.service.get(value.channelId, queued.job.id)).toMatchObject({ - job: { state: "running", attempts: 1, failures: 0, progress: [{ state: "started" }] }, + await asked.promise; + // The owner resolves on the clock reading the first heartbeat renews the claim at. + clock.advance(100); + resolved.resolve(owner()); + await waitFor(async () => (await job())?.progress.length === 1); + expect(await job()).toMatchObject({ + state: "running", + attempts: 1, + failures: 0, + progress: [{ attempt: 1, state: "started" }], }); release.resolve({ report: "complete" }); - await waitFor(async () => - (await value.service.get(value.channelId, queued.job.id))?.job.state === "completed" - ); + await waitFor(async () => (await job())?.state === "completed"); + expect(await job()).toMatchObject({ attempts: 1, failures: 0 }); + expect(value.errors).toEqual([]); } finally { release.resolve({ report: "complete" }); await value.runner.shutdown(); diff --git a/apps/server/src/jobs/runner.ts b/apps/server/src/jobs/runner.ts index 300a06916..d5adf81b9 100644 --- a/apps/server/src/jobs/runner.ts +++ b/apps/server/src/jobs/runner.ts @@ -438,19 +438,7 @@ export class JobRunner { void this.#pause(attempt, "owner-unavailable"); }, { once: true }); } - await this.#serial(attempt, async () => { - attempt.job = await this.#options.storage.jobs.renew({ - channelId: attempt.job.channelId, - jobId: attempt.job.id, - claimOwner: this.#claimOwner, - claimGeneration: attempt.job.claimGeneration, - expectedRevision: attempt.job.revision, - claimBinding: credential.binding, - ttlMs: this.#options.claimTtlMs + this.#options.heartbeatMs + 1, - now: this.#scheduler.now(), - lease: this.#options.lease(), - }); - }); + await this.#renew(attempt, credential.binding); this.#heartbeat(attempt); if (!this.#accepted(attempt, credential)) return; attempt.releaseOwner = await this.#owner(credential.ownerKey); @@ -586,19 +574,7 @@ export class JobRunner { attempt.heartbeat = this.#scheduler.after(this.#options.heartbeatMs, () => { attempt.heartbeat = undefined; if (!attempt.accepting || this.#stopped) return; - void this.#serial(attempt, async () => { - attempt.job = await this.#options.storage.jobs.renew({ - channelId: attempt.job.channelId, - jobId: attempt.job.id, - claimOwner: this.#claimOwner, - claimGeneration: attempt.job.claimGeneration, - expectedRevision: attempt.job.revision, - claimBinding: attempt.credential?.binding, - ttlMs: this.#options.claimTtlMs + this.#options.heartbeatMs + 1, - now: this.#scheduler.now(), - lease: this.#options.lease(), - }); - }).then(async () => { + void this.#renew(attempt, attempt.credential?.binding).then(async () => { if (!attempt.accepting) return; try { if ( @@ -672,6 +648,28 @@ export class JobRunner { return result; } + /** + * Storage refuses a renewal that does not move the claim's expiry on, and a heartbeat and the + * owner's binding can renew on one clock reading, so each renewal reaches past the last. + */ + #renew(attempt: Attempt, claimBinding: JsonValue | undefined): Promise { + return this.#serial(attempt, async () => { + let now = this.#scheduler.now(); + let held = (attempt.job.claimExpiresAt?.getTime() ?? 0) - now.getTime(); + attempt.job = await this.#options.storage.jobs.renew({ + channelId: attempt.job.channelId, + jobId: attempt.job.id, + claimOwner: this.#claimOwner, + claimGeneration: attempt.job.claimGeneration, + expectedRevision: attempt.job.revision, + claimBinding, + ttlMs: Math.max(this.#options.claimTtlMs + this.#options.heartbeatMs + 1, held + 1), + now, + lease: this.#options.lease(), + }); + }); + } + #accepted(attempt: Attempt, credential?: ResolvedJobCredential): boolean { return attempt.accepting && !attempt.controller.signal.aborted diff --git a/e2e/jev-wire.ts b/e2e/jev-wire.ts index 8407e6d26..4c868b658 100644 --- a/e2e/jev-wire.ts +++ b/e2e/jev-wire.ts @@ -6,15 +6,14 @@ import type { ConversationPlan } from "../packages/protocol/index"; import type { Page } from "@playwright/test"; /** - * A second writer with the document open beside `page`'s, closed with `page`'s context. A person - * alone in a document is talking to chopin, so their room message goes to the Planner and is never - * analysed; with company it stays the conversation's. + * A second writer with the document open beside `page`'s, closed with the test's other contexts as + * `join` ends it. A person alone in a document is talking to chopin, so their room message goes to + * the Planner and is never analysed; with company it stays the conversation's. */ export async function keepCompany(page: Page, channelId: string, handle = "cy"): Promise { let browser = page.context().browser(); if (!browser) throw new Error("keepCompany needs a page from a launched browser"); - let company = await openIsolatedRoom(browser, new URL(page.url()).origin, channelId, handle, {}); - page.context().once("close", () => void company.close().catch(() => {})); + await openIsolatedRoom(browser, new URL(page.url()).origin, channelId, handle, {}); } export type WireFrame = { kind: string; rid?: string; [key: string]: unknown }; diff --git a/e2e/room.ts b/e2e/room.ts index 9f54aa982..650c62ee6 100644 --- a/e2e/room.ts +++ b/e2e/room.ts @@ -87,7 +87,11 @@ export async function openIsolatedRoom( type Fixtures = { /** The channel this test has to itself. */ room: string; - /** Open the channel as somebody. Options always receive an isolated context. */ + /** + * Open the channel as somebody. Options always receive an isolated context. Every context the + * test opened, a helper's beside it too (`keepCompany`), is closed before the test ends: the next + * test starts a trace chunk in each context still open, and one still closing fails it. + */ join: (handle: string, options?: BrowserContextOptions) => Promise; /** Set the channel's source and optional sidecar before anyone opens it. */ seed: (source: string, state?: SeedState) => Promise; @@ -104,7 +108,6 @@ export const test = base.extend({ join: async ({ baseURL, browser, context, page, room }, use) => { let first = true; - let opened: BrowserContext[] = []; await use(async (handle, options) => { let target: Page; if (first && !options) { @@ -113,7 +116,6 @@ export const test = base.extend({ } else { first = false; let isolated = await browser.newContext({ ...options, baseURL }); - opened.push(isolated); target = await isolated.newPage(); } await authenticate(target, handle, baseURL!); @@ -121,7 +123,9 @@ export const test = base.extend({ await ready(target); return target; }); - await Promise.all(opened.map(item => item.close())); + await Promise.all( + browser.contexts().filter(item => item !== context).map(item => item.close()), + ); await context.clearCookies(); },