Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Track admitted foreground work through ownership handover (#1298)

Regan Bellc7a9d6859acf
diff --git a/docs/background-ownership.md b/docs/background-ownership.md
index 89007bdc8..c8c08a588 100644
--- a/docs/background-ownership.md
+++ b/docs/background-ownership.md
@@ -113,3 +113,11 @@ infrastructure proof that every legacy task has retired, including pending tasks
Do not clear task protection or terminate live turns to finish enrollment.
If enrollment is abandoned, the legacy heartbeat expiry permits older workers
to resume their existing claim loop.
+
+Synchronous turns and manually started cron callbacks are admitted work too. A
+paused deployment refuses new synchronous execution while still accepting durable
+asynchronous submissions for the active workers. Accepted turns, scheduled
+callbacks, and their nested work keep running with their existing leases; their
+completion is part of the deployment's drain acknowledgment. Resuming ownership
+restores synchronous admission without restarting or canceling those calls.
+Task protection also counts admitted foreground work while the process drains.
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index eb55dbdd4..057da27eb 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -1,3 +1,4 @@
+import type { AdmittedWork } from "../util/admitted-work.ts";
import type { EventBus } from "../util/event-bus.ts";
import type { RunStreamEvent } from "../runs/run-stream-events.ts";
import type { ResourceSearchStore, ResourceSearchHit } from "../search/resource-search.ts";
@@ -570,6 +571,7 @@ export interface App {
}
export interface AppDeps {
+ admittedWork?: AdmittedWork;
resourceSearch?: ResourceSearchStore;
swarms?: SwarmService;
identity: IdentityService;
diff --git a/src/api/app.ts b/src/api/app.ts
index e8e7e5022..9378fafc8 100644
--- a/src/api/app.ts
+++ b/src/api/app.ts
@@ -1,3 +1,4 @@
+import { WorkAdmissionClosed } from "../util/admitted-work.ts";
import { createResourceSearchMethods } from "./app-resource-search.ts";
import type { App, AppDeps } from "./app-types.ts";
import { createAppHelpers } from "./app-helpers.ts";
@@ -25,6 +26,16 @@ export function createApp(deps: AppDeps): App {
...createDeploymentMethods(deps, helpers),
...createSkillMethods(deps, helpers),
};
+ const turn = methods.turn;
+ methods.turn = async (req, replay) => {
+ if (!deps.admittedWork || req.async) return turn(req, replay);
+ try {
+ return await deps.admittedWork.run(() => turn(req, replay));
+ } catch (error) {
+ if (error instanceof WorkAdmissionClosed) return { status: "refused", reason: error.message };
+ throw error;
+ }
+ };
Object.assign(app, methods);
return Object.assign(app, createSearchMethods(deps, app, helpers), createResourceSearchMethods(deps, app, helpers));
}
diff --git a/src/cron/scheduler.ts b/src/cron/scheduler.ts
index d99c4921e..cc81b6748 100644
--- a/src/cron/scheduler.ts
+++ b/src/cron/scheduler.ts
@@ -1,3 +1,4 @@
+import { WorkAdmissionClosed, type AdmittedWork } from "../util/admitted-work.ts";
import { randomUUID } from "node:crypto";
import {
parseScopeId,
@@ -66,6 +67,7 @@ export interface Scheduler {
}
export interface SchedulerDeps {
+ admittedWork?: AdmittedWork;
crons: CronStore;
deliveries: DeliveryStore;
idempotency: IdempotencyStore;
@@ -188,6 +190,7 @@ function renderCronFireInput(cron: Cron, mentionRoster?: string): string {
export function createScheduler(deps: SchedulerDeps): Scheduler {
const now = deps.now ?? (() => Date.now());
+ const withWork = <T>(work: () => Promise<T>): Promise<T> => deps.admittedWork?.run(work) ?? work();
const maxFiresPerTick = deps.maxFiresPerTick ?? 100;
const leaderLease = deps.leaderLease ?? createNoopLeaderLease();
@@ -359,12 +362,14 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
const tick = async (nowArg?: number): Promise<void> => {
const t = nowArg ?? now();
const observed = epoch;
- await leaderLease.hold(TICK_LEASE_KEY, async () => {
- await fireDue(t, observed);
- await sweepStranded(t);
- await gcFires(t);
- await deps.sweepAsks?.(t).catch((e: unknown) => console.error("[scheduler] ask sweep failed:", errMessage(e)));
- });
+ await withWork(() =>
+ leaderLease.hold(TICK_LEASE_KEY, async () => {
+ await fireDue(t, observed);
+ await sweepStranded(t);
+ await gcFires(t);
+ await deps.sweepAsks?.(t).catch((e: unknown) => console.error("[scheduler] ask sweep failed:", errMessage(e)));
+ }),
+ );
};
const makeSweeper = () =>
@@ -474,10 +479,10 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
oldSweeps.add(work);
void work.finally(() => oldSweeps.delete(work));
};
- const pending = new Set<Promise<void>>();
+ const pending = new Set<Promise<unknown>>();
async function runQueueTask(work: () => Promise<void>): Promise<void> {
if (stopped) return;
- const task = work();
+ const task = withWork(work);
pending.add(task);
try {
await task;
@@ -488,25 +493,40 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
return {
tick,
async runNow(cronId) {
- const cron = await deps.crons.get(cronId);
- if (!cron || cron.archived || !cron.enabled) return { started: false, reason: "unavailable" };
- const t = now();
- const fireKey = `cron:${cron.id}:manual:${randomUUID()}`;
- const begin = await deps.crons.beginFire(
- cronId,
- { fireKey, threadRef: cronFireThreadRef(cron.id, fireKey), firedAt: t, status: "running" },
- { exclusive: true },
- );
- if (!begin.begun) {
- return begin.running
- ? { started: false, reason: "already_running", running: begin.running }
- : { started: false, reason: "unavailable" };
+ try {
+ const preparing = withWork(async (): Promise<RunNowResult> => {
+ const cron = await deps.crons.get(cronId);
+ if (!cron || cron.archived || !cron.enabled) return { started: false, reason: "unavailable" };
+ const t = now();
+ const fireKey = `cron:${cron.id}:manual:${randomUUID()}`;
+ const begin = await deps.crons.beginFire(
+ cronId,
+ { fireKey, threadRef: cronFireThreadRef(cron.id, fireKey), firedAt: t, status: "running" },
+ { exclusive: true },
+ );
+ if (!begin.begun) {
+ return begin.running
+ ? { started: false, reason: "already_running", running: begin.running }
+ : { started: false, reason: "unavailable" };
+ }
+ const settled = withWork(() => fire(cron, t, fireKey)).then(
+ () => undefined,
+ (e: unknown) => console.error("%s", `[scheduler] manual fire of cron ${cronId} failed:`, errMessage(e)),
+ );
+ pending.add(settled);
+ void settled.finally(() => pending.delete(settled));
+ return { started: true, fireKey, settled };
+ });
+ pending.add(preparing);
+ try {
+ return await preparing;
+ } finally {
+ pending.delete(preparing);
+ }
+ } catch (error) {
+ if (error instanceof WorkAdmissionClosed) return { started: false, reason: "unavailable" };
+ throw error;
}
- const settled = fire(cron, t, fireKey).then(
- () => undefined,
- (e: unknown) => console.error("%s", `[scheduler] manual fire of cron ${cronId} failed:`, errMessage(e)),
- );
- return { started: true, fireKey, settled };
},
notifyChanged(cronId) {
if (!deps.jobQueue) return;
@@ -570,7 +590,7 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
return pausing;
},
async drained() {
- await Promise.all([...oldSweeps, ...pending]);
+ while (oldSweeps.size || pending.size) await Promise.all([...oldSweeps, ...pending]);
},
stop() {
if (stopping) return stopping;
@@ -585,7 +605,7 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
await pausing;
await Promise.all(sweeps);
await Promise.all(oldSweeps);
- await Promise.allSettled(pending);
+ while (pending.size) await Promise.allSettled(pending);
await deps.jobQueue?.stop();
stopFailed = false;
})()
diff --git a/src/monitors/monitor-poller.ts b/src/monitors/monitor-poller.ts
index 639d4f020..9f36793a8 100644
--- a/src/monitors/monitor-poller.ts
+++ b/src/monitors/monitor-poller.ts
@@ -1,3 +1,4 @@
+import type { AdmittedWork } from "../util/admitted-work.ts";
import type { Monitor, TurnRequest, TurnResult } from "../types.ts";
import type { MonitorStore } from "./monitor-store.ts";
import type { ProcessRegistry } from "../processes/process-registry.ts";
@@ -28,6 +29,7 @@ export interface MonitorPoller {
}
export interface MonitorPollerDeps {
+ admittedWork?: AdmittedWork;
monitors: MonitorStore;
processes: ProcessRegistry;
sandbox: Sandbox;
@@ -307,7 +309,9 @@ export function createMonitorPoller(deps: MonitorPollerDeps): MonitorPoller {
const tick = async (nowArg?: number): Promise<void> => {
const t = nowArg ?? now();
const observed = epoch;
- await leaderLease.hold(TICK_LEASE_KEY, () => pollAll(t, observed));
+ const work = () => leaderLease.hold(TICK_LEASE_KEY, () => pollAll(t, observed));
+ if (deps.admittedWork) await deps.admittedWork.run(work);
+ else await work();
};
const sweeper = createSweeper(
diff --git a/src/runs/worker.ts b/src/runs/worker.ts
index 1b7b84526..0f2aab7e2 100644
--- a/src/runs/worker.ts
+++ b/src/runs/worker.ts
@@ -1,3 +1,4 @@
+import type { AdmittedWork } from "../util/admitted-work.ts";
import { randomUUID } from "node:crypto";
import { errorAlreadyRecorded, type ErrorLog } from "../admin/error-log.ts";
import { conversationScope } from "../resolution/resolution-service.ts";
@@ -113,6 +114,7 @@ export interface WorkerDeps extends ProcessDeps {
sessions: SessionStore;
canClaim?: () => boolean;
onClaimed?: () => void;
+ admittedWork?: AdmittedWork;
}
export interface Worker {
@@ -203,7 +205,9 @@ export function createWorker(deps: WorkerDeps): Worker {
claimDone = null;
deps.onClaimed?.();
try {
- await processRun(deps, run, { background: true });
+ const work = () => processRun(deps, run, { background: true });
+ if (deps.admittedWork) await deps.admittedWork.run(work);
+ else await work();
} catch (e) {
swallow("worker: background run crashed", e);
} finally {
diff --git a/src/util/admitted-work.ts b/src/util/admitted-work.ts
new file mode 100644
index 000000000..a7bf91876
--- /dev/null
+++ b/src/util/admitted-work.ts
@@ -0,0 +1,49 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+
+export class WorkAdmissionClosed extends Error {
+ constructor() {
+ super("This deployment is not accepting synchronous work");
+ }
+}
+
+export function createAdmittedWork(
+ options: { paused?: boolean; canStart?: () => boolean; onAdmitted?: () => void | Promise<void> } = {},
+) {
+ const context = new AsyncLocalStorage<{ active: boolean }>();
+ const pending = new Set<Promise<unknown>>();
+ let paused = options.paused ?? false;
+ const canRun = () => context.getStore()?.active === true || (!paused && (options.canStart?.() ?? true));
+ return {
+ canRun,
+ busy: () => pending.size > 0,
+ pause() {
+ paused = true;
+ },
+ resume() {
+ paused = false;
+ },
+ run<T>(work: () => T | Promise<T>): Promise<T> {
+ if (!canRun()) return Promise.reject(new WorkAdmissionClosed());
+ const admission = { active: true };
+ const task = context.run(admission, () =>
+ Promise.resolve().then(async () => {
+ await options.onAdmitted?.();
+ return work();
+ }),
+ );
+ pending.add(task);
+ void task
+ .finally(() => {
+ admission.active = false;
+ pending.delete(task);
+ })
+ .catch(() => {});
+ return task;
+ },
+ async drained() {
+ while (pending.size) await Promise.allSettled(pending);
+ },
+ };
+}
+
+export type AdmittedWork = ReturnType<typeof createAdmittedWork>;
diff --git a/src/wiring.ts b/src/wiring.ts
index 55e09a7ac..bfa91cb88 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1,3 +1,4 @@
+import { createAdmittedWork } from "./util/admitted-work.ts";
import { runSessionSmoke } from "./deployment/postdeploy-smoke.ts";
import {
createBackgroundOwnershipStore,
@@ -310,7 +311,7 @@ import {
import { createEcsTaskProtection, type TaskProtection } from "./runs/task-protection.ts";
import { createDrainController, type DrainController } from "./runs/drain.ts";
import { createReaper, REAPER_LEASE_KEY, type Reaper } from "./runs/reaper.ts";
-import { createSweeper, type Sweeper } from "./util/sweeper.ts";
+import { createSweeper as createUntrackedSweeper, type Sweeper } from "./util/sweeper.ts";
import {
createMemoryProcessRegistry,
createPostgresProcessRegistry,
@@ -386,7 +387,7 @@ import { createPostgresErrorLog } from "./admin/postgres-error-log.ts";
import { createMetricsSink, type MetricsSink } from "./admin/metrics-sink.ts";
import { createPostgresMetricsSink } from "./admin/postgres-metrics-sink.ts";
import { errMessage, swallowAs } from "./util/errors.ts";
-import { sleep } from "./util/async.ts";
+import { sleep, withTimeout } from "./util/async.ts";
import { createSlackInstallationStore, type SlackInstallationStore } from "./surfaces/slack-installation.ts";
export interface Runtime {
@@ -525,6 +526,14 @@ export function buildApp(
modelVerificationProbe?: typeof probeModel;
} = {},
): BuiltApp {
+ let backgroundAdmission = () => !config.backgroundDeploymentId;
+ let noteAdmitted = () => {};
+ const admittedWork = createAdmittedWork({
+ canStart: () => !config.backgroundDeploymentId || backgroundAdmission(),
+ onAdmitted: () => noteAdmitted(),
+ });
+ const createSweeper: typeof createUntrackedSweeper = (work, interval, options) =>
+ createUntrackedSweeper(() => admittedWork.run(work), interval, options);
if (config.databaseUrl && !config.connectorSecretKey) {
throw new Error("CONNECTOR_SECRET_KEY is required with durable storage");
}
@@ -691,7 +700,7 @@ export function buildApp(
: {}),
});
const deploymentLayerReady = deploymentLayerStore.hydrate();
- const deploymentLayerRefresh = createSweeper(() => deploymentLayerStore.hydrate(), 30_000, {
+ const deploymentLayerRefresh = createUntrackedSweeper(() => deploymentLayerStore.hydrate(), 30_000, {
label: "deployment layer refresh",
});
let skillsReady: Promise<void>;
@@ -1865,6 +1874,7 @@ export function buildApp(
})
: undefined;
const app = createApp({
+ admittedWork,
...(pgArtifactMap ? { resourceSearch: createPostgresResourceSearch(pgArtifactMap.pool) } : {}),
swarms,
identity,
@@ -2119,6 +2129,7 @@ export function buildApp(
const sweepAsks =
keychain && askResolution ? createAskExpirySweep({ keychain, fire: askResolution, auditLog }) : undefined;
const scheduler = createScheduler({
+ admittedWork,
requireQueueStart: Boolean(config.backgroundDeploymentId),
crons,
deliveries,
@@ -2169,6 +2180,7 @@ export function buildApp(
const monitorPoller: MonitorPoller | null =
processes && supportsProcessSessions(sandbox)
? createMonitorPoller({
+ admittedWork,
monitors,
processes,
sandbox,
@@ -2198,7 +2210,6 @@ export function buildApp(
directory,
currentScopeMembers,
});
- let backgroundAdmission = () => !config.backgroundDeploymentId;
const backgroundOwnership = config.backgroundDeploymentId
? {
store: createBackgroundOwnershipStore(artifactMap<BackgroundOwnership>("background_ownership")),
@@ -2235,10 +2246,12 @@ export function buildApp(
const drain: DrainController = createDrainController({
registry: instanceRegistry,
protection: taskProtection,
- busy: () => workers.some((w) => w.busy()),
+ busy: () => admittedWork.busy() || workers.some((w) => w.busy()),
});
+ noteAdmitted = () => drain.noteBusy();
const workers: Worker[] = Array.from({ length: Math.max(1, config.workers) }, () =>
createWorker({
+ admittedWork,
runs,
sessions,
orchestrator,
@@ -2302,6 +2315,7 @@ export function buildApp(
function startBackground(): void {
if (backgroundRunning) return;
backgroundRunning = true;
+ admittedWork.resume();
drain.start();
const generation = ++backgroundGeneration;
for (const worker of workers) {
@@ -2340,6 +2354,7 @@ export function buildApp(
else startPeriodic();
}
function stopBackground(): Promise<void> {
+ admittedWork.pause();
backgroundRunning = false;
const previous = backgroundStopping;
backgroundGeneration++;
@@ -2373,6 +2388,7 @@ export function buildApp(
const runtime: Runtime = {
start() {
flyTunnel?.monitor();
+ drain.start();
if (config.backgroundWorkEnabled && !config.backgroundDeploymentId) startBackground();
},
startBackground,
@@ -2386,16 +2402,19 @@ export function buildApp(
stopBackground,
async backgroundDrained() {
await backgroundStopping;
- await Promise.all(workers.map((worker) => worker.drained()));
+ await Promise.all([admittedWork.drained(), ...workers.map((worker) => worker.drained())]);
},
async releaseInFlightRuns() {
await Promise.all(workers.map((w) => w.releaseInFlight()));
},
async stop() {
await stopBackground();
- await Promise.all(workers.map((w) => w.stop(config.shutdownDrainMs))).catch(
- swallowAs("wiring: worker drain failed", undefined),
- );
+ await Promise.all([
+ withTimeout(() => admittedWork.drained(), config.shutdownDrainMs, "admitted work drain").catch(
+ swallowAs("wiring: admitted work drain failed", undefined),
+ ),
+ ...workers.map((w) => w.stop(config.shutdownDrainMs)),
+ ]).catch(swallowAs("wiring: worker drain failed", undefined));
await Promise.all(workers.map((w) => w.releaseInFlight()));
await drain.stop();
runs.close?.();
diff --git a/test/admitted-work.test.ts b/test/admitted-work.test.ts
new file mode 100644
index 000000000..90a0cca73
--- /dev/null
+++ b/test/admitted-work.test.ts
@@ -0,0 +1,88 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createAdmittedWork, WorkAdmissionClosed } from "../src/util/admitted-work.ts";
+
+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
+
+test("pause fences new work while accepted work drains, then rollback resumes", async () => {
+ const work = createAdmittedWork();
+ const finish = Promise.withResolvers<void>();
+ const accepted = work.run(() => finish.promise);
+ assert.equal(work.busy(), true);
+ work.pause();
+ await assert.rejects(
+ work.run(() => assert.fail("ran after pause")),
+ WorkAdmissionClosed,
+ );
+ let drained = false;
+ const drain = work.drained().then(() => {
+ drained = true;
+ });
+ await tick();
+ assert.equal(drained, false);
+ work.resume();
+ assert.equal(await work.run(() => 42), 42);
+ assert.equal(drained, false);
+ finish.resolve();
+ await accepted;
+ await drain;
+ assert.equal(work.busy(), false);
+});
+
+test("already admitted callbacks can start nested work after pause without leaking admission", async () => {
+ const work = createAdmittedWork();
+ const paused = Promise.withResolvers<void>();
+ const finish = Promise.withResolvers<void>();
+ let late!: () => Promise<void>;
+ let child!: Promise<void>;
+ const parent = work.run(async () => {
+ await paused.promise;
+ child = work.run(() => finish.promise);
+ late = () => work.run(() => assert.fail("late outside admission"));
+ });
+ work.pause();
+ paused.resolve();
+ await parent;
+ await assert.rejects(late(), WorkAdmissionClosed);
+ let drained = false;
+ const drain = work.drained().then(() => {
+ drained = true;
+ });
+ await tick();
+ assert.equal(drained, false);
+ finish.resolve();
+ await child;
+ await drain;
+});
+
+test("detached async contexts lose admission when their accepting callback finishes", async () => {
+ const work = createAdmittedWork();
+ const invoke = Promise.withResolvers<void>();
+ let delayed!: Promise<void>;
+ await work.run(() => {
+ delayed = invoke.promise.then(() => work.run(() => assert.fail("stale async context")));
+ });
+ work.pause();
+ invoke.resolve();
+ await assert.rejects(delayed, WorkAdmissionClosed);
+});
+
+test("admission is registered before callback execution and errors cannot strand busy state", async () => {
+ let admitted = false;
+ const work = createAdmittedWork({
+ onAdmitted: () => {
+ admitted = true;
+ },
+ });
+ await assert.rejects(
+ work.run(() => {
+ assert.equal(admitted, true);
+ assert.equal(work.busy(), true);
+ throw new Error("failed work");
+ }),
+ /failed work/,
+ );
+ work.pause();
+ await work.drained();
+ assert.equal(work.busy(), false);
+});
diff --git a/test/cron-scheduler.test.ts b/test/cron-scheduler.test.ts
index 57c565338..6365d446e 100644
--- a/test/cron-scheduler.test.ts
+++ b/test/cron-scheduler.test.ts
@@ -1646,3 +1646,63 @@ test("scheduler resumes new queue claims while an older admitted turn remains al
await oldWork;
await scheduler.stop();
});
+
+test("manual cron preparation and detached fire retain admission across pause", async () => {
+ const { createAdmittedWork } = await import("../src/util/admitted-work.ts");
+ const work = createAdmittedWork();
+ const crons = createCronStore();
+ const cron = await crons.create({
+ schedule: { everyMs: 1000 },
+ action: "test",
+ owner: "U1",
+ createdBy: "U1",
+ ownerScopeId: scopeId("personal", "U1"),
+ });
+ const entered = Promise.withResolvers<void>();
+ const allowLookup = Promise.withResolvers<void>();
+ const called = Promise.withResolvers<void>();
+ const finish = Promise.withResolvers<void>();
+ const get = crons.get.bind(crons);
+ crons.get = async (id) => {
+ entered.resolve();
+ await allowLookup.promise;
+ return get(id);
+ };
+ const scheduler = createScheduler({
+ admittedWork: work,
+ crons,
+ deliveries: createDeliveryStore(),
+ idempotency: createIdempotencyStore(),
+ identity: createIdentityService(),
+ run: () =>
+ work.run(async () => {
+ called.resolve();
+ await finish.promise;
+ return { status: "ok" as const, reply: "done" };
+ }),
+ });
+ const starting = scheduler.runNow(cron.id);
+ await entered.promise;
+ work.pause();
+ await scheduler.stopClaims();
+ let drained = false;
+ const draining = scheduler.drained().then(() => {
+ drained = true;
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(drained, false);
+ assert.deepEqual(await scheduler.runNow(cron.id), { started: false, reason: "unavailable" });
+ allowLookup.resolve();
+ const started = await starting;
+ assert.equal(started.started, true);
+ await called.promise;
+ assert.equal(drained, false);
+ finish.resolve();
+ await draining;
+ await work.drained();
+ work.resume();
+ const resumed = await scheduler.runNow(cron.id);
+ assert.equal(resumed.started, true);
+ if (resumed.started) await resumed.settled;
+ await scheduler.stop();
+});
diff --git a/test/deploy-drain.test.ts b/test/deploy-drain.test.ts
index 866bb5556..323c73364 100644
--- a/test/deploy-drain.test.ts
+++ b/test/deploy-drain.test.ts
@@ -154,3 +154,41 @@ test("a failing protection endpoint degrades silently and canClaim stays governe
assert.equal(drain.canClaim(), true);
drain.stop();
});
+
+test("admitted foreground work keeps task protection through background pause", async () => {
+ const { createAdmittedWork } = await import("../src/util/admitted-work.ts");
+ const changes: boolean[] = [];
+ let noteBusy = () => {};
+ const work = createAdmittedWork({ onAdmitted: () => noteBusy() });
+ const drain = createDrainController({
+ registry: { beat: async () => false },
+ protection: {
+ set: async (enabled) => {
+ changes.push(enabled);
+ },
+ },
+ busy: work.busy,
+ sweepMs: 5,
+ });
+ noteBusy = () => drain.noteBusy();
+ const finish = Promise.withResolvers<void>();
+ drain.start();
+ const admitted = work.run(() => finish.promise);
+ try {
+ await sleep(15);
+ work.pause();
+ assert.equal(changes.at(-1), true);
+ changes.length = 0;
+ await sleep(15);
+ assert.ok(changes.length > 0 && changes.every(Boolean));
+ finish.resolve();
+ await admitted;
+ await work.drained();
+ await sleep(15);
+ assert.equal(changes.at(-1), false);
+ } finally {
+ finish.resolve();
+ await admitted;
+ await drain.stop();
+ }
+});
diff --git a/test/slack-context-reconciliation.test.ts b/test/slack-context-reconciliation.test.ts
index 9d0dbc33a..5eb553927 100644
--- a/test/slack-context-reconciliation.test.ts
+++ b/test/slack-context-reconciliation.test.ts
@@ -77,6 +77,7 @@ for (const warm of [false, true]) {
assert.match(requestText, /The worker needs restarting/);
assert.match(requestText, /Alex, can you approve/);
await built.runtime.stop();
+ built.runtime.start();
const second = await built.app.turn({ ...input, text: "yes, go ahead" });
assert.equal(second.status, "ok", second.reason);
const next = JSON.stringify(JSON.parse(requests.at(-1)!).messages);
diff --git a/test/worker-reaper.test.ts b/test/worker-reaper.test.ts
index 8ddda17ec..ecd94ea7a 100644
--- a/test/worker-reaper.test.ts
+++ b/test/worker-reaper.test.ts
@@ -672,3 +672,107 @@ test("runtime pauses without closing stores and restores worker capacity after a
await built.runtime.stop();
}
});
+
+test("inline turns remain admitted through pause and queued intake survives rollback", async () => {
+ const built = buildApp(
+ testConfig({
+ dataDir: mkdtempSync(join(tmpdir(), "inline-drain-")),
+ backgroundDeploymentId: "controlled-test",
+ workers: 1,
+ }),
+ );
+ let admitted = true;
+ built.runtime.setBackgroundAdmission(() => admitted);
+ const completing = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ const complete = built.runs.complete.bind(built.runs);
+ let first = true;
+ built.runs.complete = async (...args) => {
+ if (first) {
+ first = false;
+ completing.resolve();
+ await release.promise;
+ }
+ return complete(...args);
+ };
+ const turn = (threadRef: string, async = false) =>
+ built.app.turn({
+ surface: "test",
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm", threadRef },
+ text: "hello",
+ async,
+ });
+ const running = turn("inline-before-pause");
+ try {
+ await completing.promise;
+ admitted = false;
+ await built.runtime.stopBackgroundClaims();
+ let drained = false;
+ const draining = built.runtime.backgroundDrained().then(() => {
+ drained = true;
+ });
+ await sleep(10);
+ assert.equal(drained, false);
+ assert.equal((await turn("inline-after-pause")).status, "refused");
+ const queued = await turn("queued-after-pause", true);
+ assert.equal(queued.status, "queued");
+ assert.equal((await built.runs.get(queued.runId!))?.status, "pending");
+ release.resolve();
+ assert.equal((await running).status, "ok");
+ await draining;
+ admitted = true;
+ built.runtime.startBackground();
+ assert.equal((await built.runs.waitFor(queued.runId!, 5000)).status, "done");
+ assert.equal((await turn("inline-after-resume")).status, "ok");
+ } finally {
+ release.resolve();
+ await running;
+ await built.runtime.stop();
+ }
+});
+
+test("final shutdown bounds tracked worker drain without claiming ownership is drained", async () => {
+ const built = buildApp(
+ testConfig({
+ dataDir: mkdtempSync(join(tmpdir(), "bounded-drain-")),
+ workers: 1,
+ shutdownDrainMs: 30,
+ }),
+ );
+ const completing = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ const complete = built.runs.complete.bind(built.runs);
+ built.runs.complete = async (...args) => {
+ completing.resolve();
+ await release.promise;
+ return complete(...args);
+ };
+ const queued = await built.app.turn({
+ surface: "test",
+ actor: { externalId: "U1" },
+ conversation: { kind: "dm", threadRef: "bounded-worker" },
+ text: "hello",
+ async: true,
+ });
+ built.runtime.start();
+ try {
+ await completing.promise;
+ let drained = false;
+ const ownershipDrain = built.runtime.backgroundDrained().then(() => {
+ drained = true;
+ });
+ await Promise.race([
+ built.runtime.stop(),
+ sleep(2000).then(() => assert.fail("shutdown exceeded its drain budget")),
+ ]);
+ assert.equal(drained, false);
+ assert.equal((await built.runs.get(queued.runId!))?.status, "pending");
+ release.resolve();
+ await ownershipDrain;
+ assert.equal((await built.runs.get(queued.runId!))?.status, "pending");
+ } finally {
+ release.resolve();
+ await built.runtime.backgroundDrained();
+ }
+});