You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/09 02:30:23 UTC
(maka) branch main updated: fix(runtime-host): distinguish idle retention from active background work (#5060)
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/main by this push:
new 8d5c4612c4 fix(runtime-host): distinguish idle retention from active background work (#5060)
8d5c4612c4 is described below
commit 8d5c4612c46b19270f00fe7aea33c39dff23dbe5
Author: Wang <m4...@gmail.com>
AuthorDate: Wed Sep 9 10:30:19 2026 +0800
fix(runtime-host): distinguish idle retention from active background work (#5060)
* fix(runtime-host): include daily review in safe host handoff
Pause Daily Review scheduling during cooperative handoff, wait for active generation, and restore scheduling on cancellation or successor recovery. Track generation separately so completed work can unblock automatic retries.
Generated-by: OpenAI Codex
* fix(runtime-host): distinguish idle retention from active background work
Classify durable Daily Review schedules, scheduled tasks, and Goals as idle retention. Track review generation, scheduled dispatch, Goal evaluation/admission, and persistence as active work so startup handoff and quit probes share the same accounting. Show background activity separately in handoff copy.
Generated-by: OpenAI Codex
* fix(runtime-host): retain activity throughout hosted admission
Acquire the admission residency at the shared root authority before asynchronous gates, keeping it until execution takes over or admission fails.
Generated-by: OpenAI Codex
---
.../src/__tests__/daily-review-coordinator.test.ts | 126 ++++++++++++++++++
.../src/__tests__/execution-composition.test.ts | 123 ++++++++++++++++-
.../src/__tests__/goal-coordinator.test.ts | 8 +-
.../src/__tests__/host-handoff.test.ts | 26 ++++
.../runtime-host/src/__tests__/host-kernel.test.ts | 57 ++++++++
.../src/__tests__/root-turn-coordinator.test.ts | 148 +++++++++++++++++++++
.../scheduled-task-coordinator-recovery.test.ts | 12 +-
.../runtime-host/src/client/host-handoff-copy.ts | 18 ++-
.../src/server/daily-review-coordinator.ts | 80 +++++++++--
.../src/server/execution-composition.ts | 21 ++-
.../runtime-host/src/server/goal-coordinator.ts | 21 +--
packages/runtime-host/src/server/host-kernel.ts | 11 +-
.../src/server/root-turn-coordinator.ts | 6 +-
.../src/server/scheduled-task-coordinator.ts | 49 ++++---
.../src/__tests__/goal-continuation.test.ts | 35 +++++
packages/runtime/src/goal-continuation.ts | 8 +-
16 files changed, 691 insertions(+), 58 deletions(-)
diff --git a/packages/runtime-host/src/__tests__/daily-review-coordinator.test.ts b/packages/runtime-host/src/__tests__/daily-review-coordinator.test.ts
index 6eb94115c2..2f8e62bcde 100644
--- a/packages/runtime-host/src/__tests__/daily-review-coordinator.test.ts
+++ b/packages/runtime-host/src/__tests__/daily-review-coordinator.test.ts
@@ -22,6 +22,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { test } from 'node:test';
+import { deferred, waitFor } from '@maka/core/test-only/async-primitives';
import {
dailyReviewArchiveId,
localDayBoundsAt,
@@ -34,6 +35,7 @@ import { resolveStorageRoot, tryAcquireInteractiveRootOwner } from '@maka/storag
import { openInteractiveUsageStoresForWrite } from '@maka/storage/usage-stores';
import type { ConnectionContext } from '../server/operation-dispatcher.js';
import { HostDailyReviewCoordinator } from '../server/daily-review-coordinator.js';
+import { HostResidencyRegistry } from '../server/host-residency-registry.js';
const CONTEXT: ConnectionContext = {
hostEpoch: 'host-epoch',
@@ -42,6 +44,123 @@ const CONTEXT: ConnectionContext = {
acquireResidency: () => ({ release: () => undefined }),
};
+test('Daily Review handoff fences an admitted timer tick and cancellation resumes a due review', async () => {
+ let now = new Date(2026, 8, 9, 12).getTime();
+ const timers = new Set<() => void>();
+ const residencies = new HostResidencyRegistry();
+ await withCoordinator(
+ async ({ coordinator, store }) => {
+ const snapshot = await store.readConfig();
+ await store.updateConfig(snapshot.revision, {
+ enabled: true,
+ executeTime: '13:00',
+ modelKey: '',
+ });
+ await coordinator.recover();
+ assert.equal(timers.size, 1);
+ assert.equal(residencies.activeCount, 1);
+ assert.equal(residencies.drainCount, 0);
+ const tick = [...timers][0]!;
+ now = new Date(2026, 8, 9, 13).getTime();
+ tick(); // The config read has started, but has not returned yet.
+ const hold = coordinator.holdForHandoff();
+ assert.ok(hold);
+ assert.equal(coordinator.holdForHandoff(), undefined);
+ assert.equal(timers.size, 0);
+ tick(); // A callback already queued before clearInterval must also be fenced.
+ await hold.settled();
+ const archiveId = dailyReviewArchiveId(localDayBoundsAt(now, -1), 1);
+ assert.equal(await store.getArchive(archiveId), null);
+ const proof = hold.residencies();
+ assert.ok(proof);
+ assert.equal(residencies.hasDrainResidenciesExcept(proof), false);
+ hold.release();
+ hold.release();
+ assert.equal(timers.size, 1);
+ await waitFor(async () => (await store.getArchive(archiveId)) !== null);
+ assert.equal((await store.getArchive(archiveId))?.trigger, 'cron');
+ assert.equal((await store.readConfig()).config.enabled, true);
+ const next = coordinator.holdForHandoff();
+ assert.ok(next);
+ await next.settled();
+ coordinator.beginDrain();
+ next.release();
+ assert.equal(timers.size, 0);
+ assert.equal(residencies.drainCount, 0);
+ },
+ undefined,
+ false,
+ undefined,
+ {
+ now: () => now,
+ acquireResidency: (kind) => residencies.acquire('daily-review', kind),
+ setInterval: (callback) => {
+ timers.add(callback);
+ return callback;
+ },
+ clearInterval: (timer) => {
+ timers.delete(timer as () => void);
+ },
+ },
+ );
+});
+
+test('Daily Review handoff waits for an active analysis to publish without interrupting it', async () => {
+ const entered = deferred<void>();
+ const finish = deferred<void>();
+ const residencies = new HostResidencyRegistry();
+ await withCoordinator(
+ async ({ coordinator, store }) => {
+ const running = coordinator.handlers['daily-review.mutate'](
+ {
+ kind: 'run',
+ range: 1,
+ offsetDays: 0,
+ modelKeyOverride: '',
+ replaceExisting: false,
+ },
+ CONTEXT,
+ );
+ await entered.promise;
+ assert.equal(residencies.drainCount, 1);
+ const hold = coordinator.holdForHandoff();
+ assert.ok(hold);
+ try {
+ assert.equal(hold.residencies(), undefined);
+ let settled = false;
+ const waiting = hold.settled().then(() => {
+ settled = true;
+ });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ assert.equal(settled, false);
+ finish.resolve();
+ const result = await running;
+ await waiting;
+ assert.equal(result.ok, true);
+ assert.ok(hold.residencies());
+ assert.equal(residencies.drainCount, 0);
+ assert.equal((await store.listArchivePage(null, 1)).archives.length, 1);
+ } finally {
+ finish.resolve();
+ hold.release();
+ await running;
+ }
+ },
+ undefined,
+ true,
+ {
+ list: async () => {
+ entered.resolve();
+ await finish.promise;
+ return [];
+ },
+ },
+ {
+ acquireResidency: (kind) => residencies.acquire('daily-review', kind),
+ },
+ );
+});
+
test('Daily Review refuses to archive an incomplete canonical Usage projection', async () => {
await withCoordinator(async ({ coordinator, store, root, drainCount }) => {
appendCorruptAuthorityEvent(root, 'session-missing', 'run-missing');
@@ -401,6 +520,12 @@ async function withCoordinator(
sessions: ConstructorParameters<typeof HostDailyReviewCoordinator>[0]['sessions'] = {
list: async () => [],
},
+ lifecycle: Partial<
+ Pick<
+ ConstructorParameters<typeof HostDailyReviewCoordinator>[0],
+ 'now' | 'acquireResidency' | 'setInterval' | 'clearInterval'
+ >
+ > = {},
): Promise<void> {
const base = await mkdtemp(join(tmpdir(), 'maka-daily-review-coordinator-'));
const root = join(base, 'interactive');
@@ -423,6 +548,7 @@ async function withCoordinator(
requestDrain: () => {
drains += 1;
},
+ ...lifecycle,
});
try {
if (recoverBeforeRun) await coordinator.recover();
diff --git a/packages/runtime-host/src/__tests__/execution-composition.test.ts b/packages/runtime-host/src/__tests__/execution-composition.test.ts
index fef1a5020a..772a457dd3 100644
--- a/packages/runtime-host/src/__tests__/execution-composition.test.ts
+++ b/packages/runtime-host/src/__tests__/execution-composition.test.ts
@@ -60,9 +60,14 @@ import {
type InteractiveRootOwner,
} from '@maka/storage/root-authority';
import { openInteractiveUsageStoresForWrite } from '@maka/storage/usage-stores';
+import { openInteractiveDailyReviewAuthorityForWrite } from '@maka/storage/daily-review-authority';
+import { openInteractiveScheduledTaskStoreForWrite } from '@maka/storage/scheduled-task-store';
import { openInteractiveShellRunStoreForWrite } from '@maka/storage/shell-run-authority';
import { openInteractiveRuntimePolicyStoresForWrite } from '@maka/storage/runtime-policy-stores';
-import { HostResidencyRegistry } from '../server/host-residency-registry.js';
+import {
+ HostResidencyRegistry,
+ type HostResidencyKind,
+} from '../server/host-residency-registry.js';
import {
createExecutionRuntimeHostComposition,
runtimeHostFilesystemWorkerRuntime,
@@ -87,6 +92,115 @@ const HANDOFF_TEST_COMPOSITION = createRunCompositionSnapshot({
contextWindow: null,
});
+test('idle schedules and armed or paused Goals allow production handoff and recover in the successor', {
+ timeout: 20_000,
+}, async () => {
+ await withCompositionRoot(async ({ root, owner }) => {
+ const store = await openInteractiveDailyReviewAuthorityForWrite(owner.lease);
+ const snapshot = await store.readConfig();
+ await store.updateConfig(snapshot.revision, {
+ enabled: true,
+ executeTime: '00:00',
+ modelKey: '',
+ });
+ const schedules = await openInteractiveScheduledTaskStoreForWrite(owner.lease);
+ await schedules.create(
+ {
+ title: 'Future reminder',
+ intentBody: 'Remind me tomorrow',
+ schedule: { kind: 'once', runAt: Date.now() + 86_400_000 },
+ effect: { kind: 'notify', channel: 'local' },
+ createdBy: { kind: 'user' },
+ },
+ Date.now(),
+ );
+ schedules.close();
+ const residencies = new HostResidencyRegistry();
+ const { composition, manager } = await createCapturedExecutionComposition(owner, {
+ residencies,
+ });
+ const expected = [
+ { label: 'daily-review', count: 1 },
+ { label: 'goal', count: 2 },
+ { label: 'scheduled-task', count: 1 },
+ ];
+ try {
+ const context = {
+ hostEpoch: 'old-host',
+ connectionId: 'test',
+ principal: 'local_os_user' as const,
+ acquireResidency: () => ({ release() {} }),
+ };
+ for (const pause of [false, true]) {
+ const session = await manager.createSession({
+ cwd: root,
+ llmConnectionId: FAKE_CONNECTION_ID,
+ llmConnectionSlug: 'fake',
+ model: 'fake-model',
+ permissionMode: 'ask',
+ });
+ const armed = await composition.handlers['goal.arm'](
+ {
+ sessionId: session.id,
+ condition: 'Finish later',
+ maxIterations: null,
+ tokenBudget: null,
+ },
+ context,
+ );
+ assert.ok(armed.ok);
+ if (pause) {
+ const paused = await composition.handlers['goal.control'](
+ {
+ sessionId: session.id,
+ goalId: armed.result.goal.goalId,
+ expectedRevision: armed.result.goal.revision,
+ action: 'pause',
+ },
+ context,
+ );
+ assert.ok(paused.ok);
+ }
+ }
+ await waitFor(async () => residencies.drainCount === 0);
+ assert.deepEqual(residencies.snapshot(), expected);
+ const cancelled = await composition.prepareHandoff!('old-host', new AbortController().signal);
+ assert.ok(cancelled);
+ assert.equal(await cancelled.seal(), true);
+ const cancelledProof = await cancelled.residencies();
+ assert.ok(cancelledProof);
+ assert.equal(residencies.hasDrainResidenciesExcept(cancelledProof), false);
+ cancelled.cancel();
+ const prepared = await composition.prepareHandoff!('old-host', new AbortController().signal);
+ assert.ok(prepared);
+ assert.equal(await prepared.seal(), true);
+ const proof = await prepared.residencies();
+ assert.ok(proof);
+ assert.equal(residencies.hasDrainResidenciesExcept(proof), false);
+ await prepared.detach();
+ } finally {
+ await composition.close();
+ }
+ assert.equal(residencies.activeCount, 0);
+ await owner.close();
+ const successorOwner = await tryAcquireInteractiveRootOwner(
+ await resolveStorageRoot({ path: root, kind: 'interactive' }),
+ );
+ assert.ok(successorOwner);
+ try {
+ const successor = await createCapturedExecutionComposition(successorOwner, { residencies });
+ try {
+ await waitFor(async () => residencies.drainCount === 0);
+ assert.deepEqual(residencies.snapshot(), expected);
+ } finally {
+ await successor.composition.close();
+ }
+ } finally {
+ await successorOwner.close();
+ }
+ });
+});
+
test('production composition resumes a sealed logical Root after all stores and runtime owners reopen', {
timeout: 20_000,
}, async () => {
@@ -2128,7 +2242,12 @@ async function createCapturedExecutionComposition(
const composition = await createExecutionRuntimeHostComposition(
{
...compositionContext(owner),
- ...(residencies ? { acquireResidency: (label: string) => residencies.acquire(label) } : {}),
+ ...(residencies
+ ? {
+ acquireResidency: (label: string, kind?: HostResidencyKind) =>
+ residencies.acquire(label, kind),
+ }
+ : {}),
},
{},
{ primaryBackendFactory },
diff --git a/packages/runtime-host/src/__tests__/goal-coordinator.test.ts b/packages/runtime-host/src/__tests__/goal-coordinator.test.ts
index 16c619d717..19758f04f6 100644
--- a/packages/runtime-host/src/__tests__/goal-coordinator.test.ts
+++ b/packages/runtime-host/src/__tests__/goal-coordinator.test.ts
@@ -87,7 +87,8 @@ test('one Host Goal is shared across clients with CAS control and crash-clear re
start: () => goalTurn,
};
},
- acquireResidency: () => {
+ acquireResidency: (kind) => {
+ if (kind !== 'idle') return { release() {} };
acquired++;
return { release: () => released++ };
},
@@ -288,7 +289,10 @@ test('session retirement forgets a terminal Goal without recreating deleted auth
close: async () => {},
},
admitTurn: () => assert.fail('A terminal Goal must not admit a continuation'),
- acquireResidency: () => assert.fail('A terminal Goal must not retain Host residency'),
+ acquireResidency: (kind) => {
+ assert.notEqual(kind, 'idle', 'A terminal Goal must not retain Host residency');
+ return { release() {} };
+ },
onProjectionChanged: (sessionId) => projectionChanges.push(sessionId),
requestDrain: () => drainRequests++,
});
diff --git a/packages/runtime-host/src/__tests__/host-handoff.test.ts b/packages/runtime-host/src/__tests__/host-handoff.test.ts
index 3ebe8ebb0b..8a140d3f0f 100644
--- a/packages/runtime-host/src/__tests__/host-handoff.test.ts
+++ b/packages/runtime-host/src/__tests__/host-handoff.test.ts
@@ -31,6 +31,7 @@ import {
} from '../client/host-handoff.js';
import { decodeClientFrame, decodeHostFrame } from '../protocol/index.js';
import { decodeHostActivitySnapshot, isHostActivityIdle } from '../protocol/host-status.js';
+import { formatHostHandoff } from '../client/host-handoff-copy.js';
const idle = { connections: 0, activeOperations: 0, processUptimeSeconds: 1, residencies: [] };
const target = {
@@ -94,6 +95,31 @@ test('compatible connection needs no handoff surface', async () => {
);
});
+test('handoff copy exposes background work even with zero operations and keeps legacy counts unknown', () => {
+ const view: HostHandoffView = {
+ revision: 'test',
+ target,
+ state: 'attention',
+ reason: 'busy',
+ mayExitNaturally: false,
+ actions: ['cancel', 'interrupt'],
+ defaultAction: 'cancel',
+ activity: {
+ ...idle,
+ residencies: [{ label: 'memory-extraction', count: 2 }],
+ drainResidencies: 2,
+ },
+ };
+ for (const [locale, known, unknown] of [
+ ['en', '2 background activities', 'Background activity count unknown'],
+ ['zh-CN', '2 个后台工作', '后台工作数量未知'],
+ ['zh-TW', '2 個背景工作', '背景工作數量未知'],
+ ] as const) {
+ assert.ok(formatHostHandoff(view, locale).detail.includes(known));
+ assert.ok(formatHostHandoff({ ...view, activity: idle }, locale).detail.includes(unknown));
+ }
+});
+
test('maintenance evidence distinguishes idle retention without guessing for legacy activity', () => {
const retention = { ...idle, residencies: [{ label: 'process-retention', count: 1 }] };
assert.equal(isHostActivityIdle(decodeHostActivitySnapshot(retention)), false);
diff --git a/packages/runtime-host/src/__tests__/host-kernel.test.ts b/packages/runtime-host/src/__tests__/host-kernel.test.ts
index f6b5307f58..44cda8ac95 100644
--- a/packages/runtime-host/src/__tests__/host-kernel.test.ts
+++ b/packages/runtime-host/src/__tests__/host-kernel.test.ts
@@ -1333,6 +1333,63 @@ describe('non-serving Runtime Host kernel', () => {
});
});
+ test('quit activity ignores idle scheduler retention but preserves active work protection', async () => {
+ await withHostPaths(async (paths) => {
+ const owner = await tryAcquireInteractiveRootOwner(
+ await resolveStorageRoot({ path: paths.root, kind: 'interactive' }),
+ );
+ assert.ok(owner);
+ let context!: RuntimeHostCompositionContext;
+ const host = await RuntimeHostKernel.start({
+ owner,
+ composition: defineInteractiveRuntimeHostComposition(async (value) => {
+ context = value;
+ const retained = ['daily-review', 'scheduled-task', 'goal'].map((label) =>
+ context.acquireResidency(label, 'idle'),
+ );
+ return testComposition({
+ beginDrain: () => retained.forEach((lease) => lease.release()),
+ });
+ }),
+ });
+ try {
+ const connected = await retryConnect(paths, CURRENT_PROTOCOL);
+ assert.equal(connected.kind, 'connected');
+ if (connected.kind !== 'connected') return;
+ const diagnostics = () => connected.connection.request('host.diagnostics.query', {});
+ const idle = await diagnostics();
+ assert.equal(idle.activeResidencies, 3);
+ assert.equal(idle.upgradeBlockingActivity, false);
+ for (const label of ['daily-review', 'scheduled-task', 'goal', 'runtime-resource']) {
+ const active = context.acquireResidency(label);
+ try {
+ assert.equal((await diagnostics()).upgradeBlockingActivity, true, label);
+ assert.deepEqual(
+ await connected.connection.request('host.upgrade.prepare', {
+ expectedHostEpoch: host.hostEpoch,
+ allowInterruptActiveTasks: false,
+ }),
+ { kind: 'active_tasks' },
+ );
+ } finally {
+ active.release();
+ }
+ assert.equal((await diagnostics()).upgradeBlockingActivity, false);
+ }
+ assert.deepEqual(
+ await connected.connection.request('host.upgrade.prepare', {
+ expectedHostEpoch: host.hostEpoch,
+ allowInterruptActiveTasks: false,
+ }),
+ { kind: 'prepared', pid: process.pid },
+ );
+ await host.closed;
+ } finally {
+ await host.close();
+ }
+ });
+ });
+
test('idle process retention permits a fenced handoff but never claims natural exit', async () => {
await withHostPaths(async (paths) => {
const capability = await resolveStorageRoot({ path: paths.root, kind: 'interactive' });
diff --git a/packages/runtime-host/src/__tests__/root-turn-coordinator.test.ts b/packages/runtime-host/src/__tests__/root-turn-coordinator.test.ts
index fecfda1536..a082dc8b68 100644
--- a/packages/runtime-host/src/__tests__/root-turn-coordinator.test.ts
+++ b/packages/runtime-host/src/__tests__/root-turn-coordinator.test.ts
@@ -20,6 +20,12 @@
import { deferred, withTimeout } from '@maka/core/test-only/async-primitives';
import assert from 'node:assert/strict';
import { readInvocation, seedInvocation } from '@maka/runtime/test-only/invocation-fixture';
+import { GoalManager } from '@maka/runtime/goal-state';
+import {
+ GoalContinuationCoordinator,
+ volatileGoalDurability,
+} from '@maka/runtime/goal-continuation';
+import { HostGoalExecutionCoordinator } from '../server/goal-execution-coordinator.js';
import { runtimeInvocationOutcome } from '@maka/core/runtime-invocation';
import { createRunCompositionSnapshot } from '@maka/core/run-composition';
import {
@@ -137,6 +143,148 @@ function assertStartedTurn(outcome: TurnStartOutcome): asserts outcome is Starte
}
}
+for (const cancel of [false, true]) {
+ test(`Goal admission retains activity across the Session gate (${cancel ? 'cancel' : 'complete'})`, async () => {
+ const admissionGate = deferred<void>();
+ const backendStarted = deferred<void>();
+ const finishBackend = deferred<void>();
+ const fixture = await createFailureFixture({
+ registerBackend: (backends) =>
+ backends.register(
+ 'ai-sdk',
+ (context) =>
+ new (class extends FakeBackend {
+ override async *send(input: BackendSendInput): AsyncIterable<SessionEvent> {
+ backendStarted.resolve();
+ await finishBackend.promise;
+ yield* super.send(input);
+ }
+ })(context),
+ ),
+ });
+ const goals = new GoalManager({ generateId: randomUUID, now: Date.now });
+ const executions = new HostGoalExecutionCoordinator({
+ executions: fixture.coordinator,
+ runtime: fixture.manager,
+ matchesActive: (sessionId, checkpoint, lease) =>
+ goals.matchesActive(sessionId, checkpoint) && goals.matchesControlLease(sessionId, lease),
+ });
+ let goalActivities = 0;
+ const continuation = new GoalContinuationCoordinator({
+ goalManager: goals,
+ acquireActivity: () => {
+ goalActivities++;
+ const residency = fixture.acquireResidency();
+ return {
+ release: () => {
+ goalActivities--;
+ residency.release();
+ },
+ };
+ },
+ evaluator: {
+ evaluate: async () =>
+ '{"met":true,"impossible":false,"progress":true,"waiting":false,"reason":"done"}',
+ },
+ getRecentContext: async () => '',
+ durability: volatileGoalDurability,
+ admitTurn: (...args) => executions.admitTurn(...args),
+ });
+ const blocker = fixture.sessionAdmission.run(fixture.sessionId, () => admissionGate.promise);
+ try {
+ const queued = fixture.sessionAdmission.waitForNextQueuedRun();
+ goals.create(fixture.sessionId, 'finish work');
+ continuation.recoverActiveGoal(fixture.sessionId);
+ await queued;
+ await waitUntil(() => goalActivities === 0);
+ assert.equal(
+ fixture.liveResidencies(),
+ 1,
+ 'Hosted admission must own activity after the Goal drain has finished',
+ );
+
+ if (cancel) goals.pause(fixture.sessionId);
+ admissionGate.resolve();
+ await blocker;
+ if (!cancel) {
+ await backendStarted.promise;
+ // Admission must release its temporary lease while the execution remains live.
+ await waitUntil(() => fixture.liveResidencies() === 1);
+ const hold = continuation.holdForHandoff();
+ assert.ok(hold);
+ await withTimeout(hold.settled(), 1_000, 'Goal handoff must not await the full execution');
+ finishBackend.resolve();
+ await fixture.coordinator.whenIdle(fixture.sessionId);
+ hold.release();
+ }
+ await waitUntil(() => fixture.liveResidencies() === 0);
+ assert.equal(fixture.drainRequested(), false);
+ assert.equal(goals.get(fixture.sessionId)?.status, cancel ? 'paused' : 'achieved');
+ } finally {
+ admissionGate.resolve();
+ finishBackend.resolve();
+ await blocker;
+ executions.beginDrain();
+ await continuation.close();
+ await fixture.coordinator.close();
+ await fixture.messages.close();
+ await fixture.dispose();
+ }
+ });
+}
+
+for (const prepared of [false, true]) {
+ test(`Hosted admission releases activity after a rejected gate (${prepared ? 'prepared' : 'direct'})`, async () => {
+ const gate = deferred<'executing' | 'cancelled'>();
+ const entered = deferred<void>();
+ const fixture = await createFailureFixture({
+ registerBackend: (backends) =>
+ backends.register('ai-sdk', (context) => new FakeBackend(context)),
+ });
+ const input = {
+ sessionId: fixture.sessionId,
+ turnId: randomUUID(),
+ runId: randomUUID(),
+ userMessageId: randomUUID(),
+ execution: { kind: 'goal' as const, goalId: randomUUID() },
+ content: { text: 'continue' },
+ admitExecution: () => {
+ entered.resolve();
+ return gate.promise;
+ },
+ start: () => assert.fail('Rejected admission must never start execution'),
+ };
+ const preparation = prepared ? fixture.coordinator.prepare(fixture.sessionId) : undefined;
+ if (preparation) assert.equal(preparation.kind, 'prepared');
+ const admission =
+ preparation?.kind === 'prepared'
+ ? preparation.admission.admit(input)
+ : fixture.coordinator.admit(input);
+ const rejected = assert.rejects(admission, /admission gate failed/);
+ try {
+ await entered.promise;
+ assert.equal(fixture.liveResidencies(), 1);
+ gate.reject(new Error('admission gate failed'));
+ await rejected;
+ assert.equal(fixture.liveResidencies(), 0);
+ assert.equal(fixture.coordinator.whenIdle(fixture.sessionId), undefined);
+ assert.equal(fixture.drainRequested(), false);
+ // A consumed preparation rejects without acquiring a second lease.
+ if (preparation?.kind === 'prepared') {
+ await assert.rejects(preparation.admission.admit(input), /already consumed/);
+ preparation.admission.release();
+ assert.equal(fixture.liveResidencies(), 0);
+ }
+ } finally {
+ gate.reject(new Error('admission gate failed'));
+ await rejected;
+ await fixture.coordinator.close();
+ await fixture.messages.close();
+ await fixture.dispose();
+ }
+ });
+}
+
test('turn.start rejects the reserved WorkHub Coordination Session identity', async () => {
const fixture = await createFailureFixture({
registerBackend: (backends) =>
diff --git a/packages/runtime-host/src/__tests__/scheduled-task-coordinator-recovery.test.ts b/packages/runtime-host/src/__tests__/scheduled-task-coordinator-recovery.test.ts
index e65fb6845d..a9e1940a63 100644
--- a/packages/runtime-host/src/__tests__/scheduled-task-coordinator-recovery.test.ts
+++ b/packages/runtime-host/src/__tests__/scheduled-task-coordinator-recovery.test.ts
@@ -27,6 +27,7 @@ import type { RootTurnAdmission } from '@maka/storage/execution-stores';
import { openInteractiveScheduledTaskStoreForWrite } from '@maka/storage/scheduled-task-store';
import { resolveStorageRoot, tryAcquireInteractiveRootOwner } from '@maka/storage/root-authority';
import { SessionNotFoundError } from '@maka/storage/session-store';
+import { HostResidencyRegistry } from '../server/host-residency-registry.js';
import {
HostScheduledTaskCoordinator,
scheduledTaskExecutionFingerprint,
@@ -407,7 +408,7 @@ test('scheduler handoff waits for an admitted native effect and cancellation res
let clock = 1_000;
let timer: (() => void) | undefined;
let effects = 0;
- const residency = { release: () => {} };
+ const residencies = new HostResidencyRegistry();
const coordinator = new HostScheduledTaskCoordinator({
store,
sessions: null as never,
@@ -428,7 +429,7 @@ test('scheduler handoff waits for an admitted native effect and cancellation res
},
createSession: async () => {},
changes: { publish: () => {} },
- acquireResidency: () => residency,
+ acquireResidency: (kind) => residencies.acquire('scheduled-task', kind),
requestDrain: () => assert.fail('scheduler must not drain'),
now: () => clock,
setTimeout: (callback) => {
@@ -453,11 +454,14 @@ test('scheduler handoff waits for an admitted native effect and cancellation res
await coordinator.prepareRecovery();
coordinator.start();
await waitFor(() => timer !== undefined);
+ await waitFor(() => residencies.drainCount === 0);
+ assert.equal(residencies.activeCount, 1);
clock = task.nextFireAt!;
const fire = timer!;
timer = undefined;
fire();
await entered.promise;
+ assert.equal(residencies.drainCount, 1);
const hold = coordinator.holdForHandoff();
assert.ok(hold);
let settled = false;
@@ -470,10 +474,12 @@ test('scheduler handoff waits for an admitted native effect and cancellation res
await ready;
assert.equal(timer, undefined);
assert.equal(effects, 1);
- assert.deepEqual(hold.residencies(), [residency]);
+ assert.equal(residencies.hasDrainResidenciesExcept(hold.residencies()), false);
+ assert.equal(residencies.activeCount, 1);
assert.equal((await store.listPendingFires()).length, 0);
hold.release();
await waitFor(() => timer !== undefined);
+ await waitFor(() => residencies.drainCount === 0);
assert.equal(effects, 1);
} finally {
effect.resolve({});
diff --git a/packages/runtime-host/src/client/host-handoff-copy.ts b/packages/runtime-host/src/client/host-handoff-copy.ts
index c6b68eca7d..660126c689 100644
--- a/packages/runtime-host/src/client/host-handoff-copy.ts
+++ b/packages/runtime-host/src/client/host-handoff-copy.ts
@@ -116,6 +116,20 @@ export function formatHostHandoff(
descriptions.operator_required = guidance[view.recoveryBlocker];
}
const activity = view.activity;
+ const background = activity?.drainResidencies;
+ const backgroundFacts = !activity
+ ? ''
+ : background !== undefined
+ ? tw
+ ? `${background} 個背景工作`
+ : zh
+ ? `${background} 个后台工作`
+ : `${background} background activities`
+ : tw
+ ? '背景工作數量未知'
+ : zh
+ ? '后台工作数量未知'
+ : 'Background activity count unknown';
const facts = activity
? tw
? `${activity.connections} 個連線 · ${activity.activeOperations} 個進行中的操作`
@@ -203,7 +217,9 @@ export function formatHostHandoff(
: zh
? '正在完成交接或安全收尾,请稍候。'
: 'Finishing the handoff or its safe recovery. Please wait.'
- : [facts, waiting, repairNotice, view.operatorStep].filter(Boolean).join('\n'),
+ : [facts, backgroundFacts, waiting, repairNotice, view.operatorStep]
+ .filter(Boolean)
+ .join('\n'),
actions: view.actions.map((action) => ({ action, label: labels[action] })),
};
}
diff --git a/packages/runtime-host/src/server/daily-review-coordinator.ts b/packages/runtime-host/src/server/daily-review-coordinator.ts
index 2d62df383f..15615ea234 100644
--- a/packages/runtime-host/src/server/daily-review-coordinator.ts
+++ b/packages/runtime-host/src/server/daily-review-coordinator.ts
@@ -52,6 +52,7 @@ import {
import type { DailyReviewOperationHandlerMap } from './operation-dispatcher.js';
import type { HostDailyReviewModel } from './execution-model-authority.js';
import type { RuntimeHostResidency } from './host-kernel.js';
+import type { HostResidencyKind } from './host-residency-registry.js';
import {
CanonicalUsageProjectionIncompleteError,
readCanonicalUsageBuckets,
@@ -66,7 +67,7 @@ export interface HostDailyReviewCoordinatorInput {
readonly usage: InteractiveUsageStoresWriter;
readonly sessions: Pick<ExecutionSessionWriter, 'list'>;
readonly model: HostDailyReviewModel;
- readonly acquireResidency: () => RuntimeHostResidency;
+ readonly acquireResidency: (kind?: HostResidencyKind) => RuntimeHostResidency;
readonly requestDrain: () => void;
readonly now?: () => number;
readonly setInterval?: (callback: () => void, delayMs: number) => unknown;
@@ -84,7 +85,7 @@ export class HostDailyReviewCoordinator {
readonly #usage: InteractiveUsageStoresWriter;
readonly #sessions: HostDailyReviewCoordinatorInput['sessions'];
readonly #model: HostDailyReviewModel;
- readonly #acquireResidency: () => RuntimeHostResidency;
+ readonly #acquireResidency: HostDailyReviewCoordinatorInput['acquireResidency'];
readonly #requestDrain: () => void;
readonly #now: () => number;
readonly #setInterval: (callback: () => void, delayMs: number) => unknown;
@@ -103,6 +104,8 @@ export class HostDailyReviewCoordinator {
#prepared = false;
#started = false;
#schedulerEnabled = false;
+ #handoffHeld = false;
+ #schedulerTask: Promise<void> | undefined;
#draining = false;
#timer: unknown;
#residency: RuntimeHostResidency | undefined;
@@ -156,10 +159,51 @@ export class HostDailyReviewCoordinator {
}
}
+ holdForHandoff():
+ | {
+ settled(): Promise<void>;
+ residencies(): readonly RuntimeHostResidency[] | undefined;
+ release(): void;
+ }
+ | undefined {
+ if (this.#draining || this.#handoffHeld) return undefined;
+ this.#handoffHeld = true;
+ this.#stopTimer();
+ let released = false;
+ return {
+ settled: async () => {
+ // Include scheduler reads as well as generation: a tick may still be
+ // checking configuration or an archive when the hold is acquired.
+ while (this.#schedulerTask || this.#inFlight.size > 0) {
+ await Promise.allSettled([
+ this.#schedulerTask,
+ ...[...this.#inFlight.values()].map((entry) => entry.promise),
+ ]);
+ }
+ },
+ residencies: () => {
+ if (released || this.#draining || this.#schedulerTask || this.#inFlight.size > 0)
+ return undefined;
+ return this.#residency ? [this.#residency] : [];
+ },
+ release: () => {
+ if (released) return;
+ released = true;
+ this.#handoffHeld = false;
+ if (this.#draining) return;
+ this.#reconcileScheduler(this.#schedulerEnabled);
+ void this.#tickScheduler().catch((error: unknown) => this.#handleSchedulerError(error));
+ },
+ };
+ }
+
close(): Promise<void> {
this.#closeTask ??= (async () => {
this.beginDrain();
- await Promise.allSettled([...this.#inFlight.values()].map((entry) => entry.promise));
+ await Promise.allSettled([
+ this.#schedulerTask,
+ ...[...this.#inFlight.values()].map((entry) => entry.promise),
+ ]);
})();
return this.#closeTask;
}
@@ -315,6 +359,10 @@ export class HostDailyReviewCoordinator {
await inFlight.promise.catch(() => undefined);
return this.#run(input);
}
+ // Keep actual generation distinct from the idle scheduler hold. Besides
+ // protecting a run when scheduling is disabled, its release tells handoff
+ // observers that work finished after a bounded safe-pause attempt timed out.
+ const residency = this.#acquireResidency();
const pending = this.#generateArchive(archiveId, day, now, modelKeyOverride, input);
const entry = {
modelKeyOverride,
@@ -327,6 +375,7 @@ export class HostDailyReviewCoordinator {
return await pending;
} finally {
if (this.#inFlight.get(archiveId) === entry) this.#inFlight.delete(archiveId);
+ residency.release();
}
}
@@ -426,28 +475,42 @@ export class HostDailyReviewCoordinator {
}
#reconcileScheduler(enabled: boolean): void {
+ this.#schedulerEnabled = enabled;
if (!enabled || this.#draining) {
this.#stopScheduler();
return;
}
- this.#residency ??= this.#acquireResidency();
+ if (this.#handoffHeld) return;
+ this.#residency ??= this.#acquireResidency('idle');
this.#timer ??= this.#setInterval(() => {
void this.#tickScheduler().catch((error: unknown) => this.#handleSchedulerError(error));
}, SCHEDULER_INTERVAL_MS);
}
#stopScheduler(): void {
+ this.#stopTimer();
+ this.#residency?.release();
+ this.#residency = undefined;
+ }
+
+ #stopTimer(): void {
if (this.#timer !== undefined) {
this.#clearInterval(this.#timer);
this.#timer = undefined;
}
- this.#residency?.release();
- this.#residency = undefined;
}
- async #tickScheduler(): Promise<void> {
- if (!this.#prepared || this.#draining) return;
+ #tickScheduler(): Promise<void> {
+ if (!this.#prepared || this.#draining || this.#handoffHeld) return Promise.resolve();
+ this.#schedulerTask ??= this.#runScheduler().finally(() => {
+ this.#schedulerTask = undefined;
+ });
+ return this.#schedulerTask;
+ }
+
+ async #runScheduler(): Promise<void> {
const { config } = await this.#store.readConfig();
+ if (this.#draining || this.#handoffHeld) return;
this.#reconcileScheduler(config.enabled);
const now = this.#now();
if (!config.enabled || !scheduledTimeHasPassed(now, config.executeTime)) return;
@@ -456,6 +519,7 @@ export class HostDailyReviewCoordinator {
const day = localDayBoundsAt(now, -1);
const archiveId = dailyReviewArchiveId(day, 1);
if (await this.#store.getArchive(archiveId)) return;
+ if (this.#draining || this.#handoffHeld) return;
await this.#run({
range: 1,
offsetDays: -1,
diff --git a/packages/runtime-host/src/server/execution-composition.ts b/packages/runtime-host/src/server/execution-composition.ts
index f098c3ab81..cfb2070c78 100644
--- a/packages/runtime-host/src/server/execution-composition.ts
+++ b/packages/runtime-host/src/server/execution-composition.ts
@@ -671,7 +671,7 @@ export async function createExecutionRuntimeHostComposition(
usage: openedUsageStores,
requestDrain: context.requestDrain,
}),
- acquireResidency: () => context.acquireResidency('daily-review'),
+ acquireResidency: (kind) => context.acquireResidency('daily-review', kind),
requestDrain: context.requestDrain,
});
let poisonFailure: Error | undefined;
@@ -1360,7 +1360,7 @@ export async function createExecutionRuntimeHostComposition(
}),
admitTurn: (sessionId, text, checkpoint, controlLease) =>
goalExecutionCoordinator.admitTurn(sessionId, text, checkpoint, controlLease),
- acquireResidency: () => context.acquireResidency('goal'),
+ acquireResidency: (kind) => context.acquireResidency('goal', kind),
onProjectionChanged: (sessionId) => continuityCoordinator.enqueueCanonicalRefresh(sessionId),
requestDrain: context.requestDrain,
});
@@ -1723,7 +1723,7 @@ export async function createExecutionRuntimeHostComposition(
taskId: string,
) => hostChanges.publishScheduledTask(revision, reason, taskId),
},
- acquireResidency: () => context.acquireResidency('scheduled-task'),
+ acquireResidency: (kind) => context.acquireResidency('scheduled-task', kind),
requestDrain: context.requestDrain,
});
scheduledTaskTool = scheduledTasks.modelTool;
@@ -2127,6 +2127,7 @@ export async function createExecutionRuntimeHostComposition(
if (draining || signal.aborted) return undefined;
const goalHold = goal?.holdForHandoff();
const scheduleHold = scheduledTasks?.holdForHandoff();
+ const dailyReviewHold = dailyReview?.holdForHandoff();
let root: Awaited<ReturnType<RootTurnCoordinator['prepareHandoff']>>;
let detached = false;
const cancel = () => {
@@ -2134,16 +2135,21 @@ export async function createExecutionRuntimeHostComposition(
root?.cancel();
goalHold?.release();
scheduleHold?.release();
+ dailyReviewHold?.release();
signal.removeEventListener('abort', cancel);
};
signal.addEventListener('abort', cancel, { once: true });
try {
- if (!goalHold || !scheduleHold) {
+ if (!goalHold || !scheduleHold || !dailyReviewHold) {
cancel();
return undefined;
}
await waitForHostedExecutionIdleOrAbort(
- Promise.all([goalHold.settled(), scheduleHold.settled()]).then(() => undefined),
+ Promise.all([
+ goalHold.settled(),
+ scheduleHold.settled(),
+ dailyReviewHold.settled(),
+ ]).then(() => undefined),
signal,
);
root = await requireRootCoordinator(coordinator).prepareHandoff(hostEpoch, signal);
@@ -2158,8 +2164,9 @@ export async function createExecutionRuntimeHostComposition(
await waitForHostedExecutionIdleOrAbort(scheduleHold.settled(), signal);
const goals = await goalHold.residencies(prepared.executions);
const roots = await prepared.residencies();
- if (!goals || !roots || signal.aborted || draining) return undefined;
- return [...roots, ...goals, ...scheduleHold.residencies()];
+ const reviews = dailyReviewHold.residencies();
+ if (!goals || !roots || !reviews || signal.aborted || draining) return undefined;
+ return [...roots, ...goals, ...scheduleHold.residencies(), ...reviews];
},
detach: async () => {
detached = true;
diff --git a/packages/runtime-host/src/server/goal-coordinator.ts b/packages/runtime-host/src/server/goal-coordinator.ts
index ff797142a9..65efa58b4b 100644
--- a/packages/runtime-host/src/server/goal-coordinator.ts
+++ b/packages/runtime-host/src/server/goal-coordinator.ts
@@ -58,6 +58,7 @@ import type {
OperationOutcome,
} from '../protocol/index.js';
import type { RuntimeHostResidency } from './host-kernel.js';
+import type { HostResidencyKind } from './host-residency-registry.js';
import type { GoalOperationHandlerMap } from './operation-dispatcher.js';
import { projectGoalState } from './goal-projection.js';
import {
@@ -86,7 +87,7 @@ export interface HostGoalCoordinatorOptions {
checkpoint: GoalCheckpoint,
controlLease: GoalControlLease,
) => GoalTurnAdmission;
- readonly acquireResidency: () => RuntimeHostResidency;
+ readonly acquireResidency: (kind?: HostResidencyKind) => RuntimeHostResidency;
readonly onProjectionChanged: (sessionId: string) => void;
readonly requestDrain: () => void;
readonly now?: () => number;
@@ -116,7 +117,7 @@ export class HostGoalCoordinator {
readonly #onProjectionChanged: (sessionId: string) => void;
readonly #newId: () => string;
readonly #requestDrain: () => void;
- readonly #acquireResidency: () => RuntimeHostResidency;
+ readonly #acquireResidency: HostGoalCoordinatorOptions['acquireResidency'];
readonly #executions: Pick<HostedExecutionAuthority, 'reconcile' | 'subscribe'>;
readonly #authorityBySession = new Map<string, GoalAuthoritySnapshot>();
/**
@@ -156,6 +157,7 @@ export class HostGoalCoordinator {
const tokenCache = this.#tokenCache;
this.continuation = new GoalContinuationCoordinator({
goalManager: this.manager,
+ acquireActivity: () => this.#acquireResidency(),
evaluator: options.evaluator,
getRecentContext: async (sessionId) => {
const messages = await options.readSessionMessages(sessionId);
@@ -579,6 +581,7 @@ export class HostGoalCoordinator {
record,
});
}
+ const residency = this.#acquireResidency();
const commit = this.#persistenceLane.then(async () => {
let result;
try {
@@ -607,10 +610,12 @@ export class HostGoalCoordinator {
throw new Error(`Goal authority changed its committed revision for Session ${sessionId}`);
}
});
- this.#persistenceLane = commit.catch((error) => {
- this.#persistenceFailure ??= error;
- this.#requestDrain();
- });
+ this.#persistenceLane = commit
+ .catch((error) => {
+ this.#persistenceFailure ??= error;
+ this.#requestDrain();
+ })
+ .finally(() => residency.release());
}
async #deleteOrphanedAuthority(snapshot: GoalAuthoritySnapshot): Promise<void> {
@@ -631,10 +636,10 @@ export class HostGoalCoordinator {
if (this.#persistenceFailure !== undefined) throw this.#persistenceFailure;
}
- #syncResidency(goal: GoalState, acquire: () => RuntimeHostResidency): void {
+ #syncResidency(goal: GoalState, acquire: HostGoalCoordinatorOptions['acquireResidency']): void {
const retained = this.#residencies.get(goal.sessionId);
if (!TERMINAL_GOAL_STATUSES.has(goal.status)) {
- if (!retained && !this.#draining) this.#residencies.set(goal.sessionId, acquire());
+ if (!retained && !this.#draining) this.#residencies.set(goal.sessionId, acquire('idle'));
return;
}
retained?.release();
diff --git a/packages/runtime-host/src/server/host-kernel.ts b/packages/runtime-host/src/server/host-kernel.ts
index 84650f1c59..4e7b458a2c 100644
--- a/packages/runtime-host/src/server/host-kernel.ts
+++ b/packages/runtime-host/src/server/host-kernel.ts
@@ -92,7 +92,7 @@ import {
type RuntimeHostListenerSet,
type RuntimeHostListenerSetFactory,
} from './listener-set.js';
-import { HostResidencyRegistry } from './host-residency-registry.js';
+import { HostResidencyRegistry, type HostResidencyKind } from './host-residency-registry.js';
import type { PeerMeshNode } from '../peer-mesh/node.js';
import { createPeerMeshOperationHandlers } from './peer-mesh-authority.js';
import { createHostResourceCollector } from './host-resource-collector.js';
@@ -122,7 +122,8 @@ export class RuntimeHostProcessTerminationRequiredError extends Error {
export interface RuntimeHostCompositionContext {
owner: InteractiveRootOwner;
hostEpoch: string;
- acquireResidency(label: string): RuntimeHostResidency;
+ /** Idle retention keeps schedulers alive without claiming work is in flight. */
+ acquireResidency(label: string, kind?: HostResidencyKind): RuntimeHostResidency;
/** Irreversible fail-stop latch; normal residency still uses acquireResidency(). */
retainUntilProcessExit(): void;
requestDrain(): void;
@@ -388,7 +389,7 @@ export class RuntimeHostKernel {
this.#composition = await this.#options.composition.create({
owner: this.#options.owner,
hostEpoch: this.hostEpoch,
- acquireResidency: (label) => this.#acquireResidency(label),
+ acquireResidency: (label, kind) => this.#acquireResidency(label, kind),
retainUntilProcessExit: () => this.#retainUntilProcessExit(),
requestDrain: () => this.#requestDrain(),
...(this.#options.accessAuthority
@@ -695,8 +696,8 @@ export class RuntimeHostKernel {
this.#settleLifecycleAfterWork();
}
- #acquireResidency(label: string): RuntimeHostResidency {
- const residency = this.#residencies.acquire(label, 'drain', () =>
+ #acquireResidency(label: string, kind: HostResidencyKind = 'drain'): RuntimeHostResidency {
+ const residency = this.#residencies.acquire(label, kind, () =>
this.#settleLifecycleAfterWork(),
);
this.#cancelIdle();
diff --git a/packages/runtime-host/src/server/root-turn-coordinator.ts b/packages/runtime-host/src/server/root-turn-coordinator.ts
index 76a6208b09..6f969f40c3 100644
--- a/packages/runtime-host/src/server/root-turn-coordinator.ts
+++ b/packages/runtime-host/src/server/root-turn-coordinator.ts
@@ -938,7 +938,10 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
),
);
}
- return this.runCommand(async () => {
+ // Admission is active work even while queued behind a Session gate. Its
+ // residency overlaps the execution residency until admission settles.
+ const residency = this.acquireRecoveryResidency();
+ const admission = this.runCommand(async () => {
const activeAtEntry = this.#executions.has(input.sessionId);
let reservation =
preparedReservation ?? (activeAtEntry ? undefined : this.reserveRootTurn(input.sessionId));
@@ -1105,6 +1108,7 @@ export class RootTurnCoordinator implements HostedExecutionAuthority {
if (error instanceof HostedRootAdmissionGateError) throw error.cause;
throw error;
});
+ return admission.finally(() => residency.release());
}
lookup(sessionId: string, turnId: string): Promise<HostedExecutionIdentity | undefined> {
diff --git a/packages/runtime-host/src/server/scheduled-task-coordinator.ts b/packages/runtime-host/src/server/scheduled-task-coordinator.ts
index e4e45cf83f..9df2251876 100644
--- a/packages/runtime-host/src/server/scheduled-task-coordinator.ts
+++ b/packages/runtime-host/src/server/scheduled-task-coordinator.ts
@@ -63,6 +63,7 @@ import {
} from '../protocol/index.js';
import type { ScheduledTaskOperationHandlerMap } from './operation-dispatcher.js';
import type { RuntimeHostResidency } from './host-kernel.js';
+import type { HostResidencyKind } from './host-residency-registry.js';
import type { HostedExecutionAuthority } from './hosted-execution-authority.js';
import type { SessionCreateInput } from '../protocol/session-catalog.js';
@@ -97,7 +98,7 @@ export interface HostScheduledTaskCoordinatorInput {
readonly changes: {
publish(revision: number, reason: ScheduledTaskChangedReason, taskId: string): void;
};
- readonly acquireResidency: () => RuntimeHostResidency;
+ readonly acquireResidency: (kind?: HostResidencyKind) => RuntimeHostResidency;
readonly requestDrain: () => void;
readonly now?: () => number;
readonly newId?: () => string;
@@ -143,7 +144,7 @@ export class HostScheduledTaskCoordinator implements ScheduledTaskToolAuthority
readonly #nativeEffects: ScheduledTaskNativeEffects;
readonly #createSession: HostScheduledTaskCoordinatorInput['createSession'];
readonly #changes: HostScheduledTaskChangeServiceLike;
- readonly #acquireResidency: () => RuntimeHostResidency;
+ readonly #acquireResidency: HostScheduledTaskCoordinatorInput['acquireResidency'];
readonly #requestDrain: () => void;
readonly #now: () => number;
readonly #newId: () => string;
@@ -561,24 +562,32 @@ export class HostScheduledTaskCoordinator implements ScheduledTaskToolAuthority
}
async #refresh(): Promise<void> {
- await this.#exclusive(async () => {
- if (this.#handoffHeld || this.#draining) return;
- for (const claim of await this.#store.listPendingFires()) {
- if (this.#handoffHeld || this.#draining) break;
- if (claim.nativeState === 'waiting_for_provider') {
- await this.#fulfill(claim, true);
+ if (this.#handoffHeld || this.#draining) return;
+ // Cover claim admission, native delivery, and persistence, while an idle
+ // schedule or a read-only catalog query does not claim active work.
+ const residency = this.#acquireResidency();
+ try {
+ await this.#exclusive(async () => {
+ if (this.#handoffHeld || this.#draining) return;
+ for (const claim of await this.#store.listPendingFires()) {
+ if (this.#handoffHeld || this.#draining) break;
+ if (claim.nativeState === 'waiting_for_provider') {
+ await this.#fulfill(claim, true);
+ }
}
- }
- while (!this.#draining && !this.#handoffHeld) {
- const scan = await this.#store.claimNextDue(this.#now());
- for (const expired of scan.expired) this.#publish('updated', expired.id);
- const claim = scan.claim;
- if (!claim) break;
- await this.#refreshResidency();
- await this.#fulfill(claim, false);
- }
- await this.#refreshSchedule();
- });
+ while (!this.#draining && !this.#handoffHeld) {
+ const scan = await this.#store.claimNextDue(this.#now());
+ for (const expired of scan.expired) this.#publish('updated', expired.id);
+ const claim = scan.claim;
+ if (!claim) break;
+ await this.#refreshResidency();
+ await this.#fulfill(claim, false);
+ }
+ await this.#refreshSchedule();
+ });
+ } finally {
+ residency.release();
+ }
}
async #fulfill(
@@ -876,7 +885,7 @@ export class HostScheduledTaskCoordinator implements ScheduledTaskToolAuthority
!this.#draining &&
(claims.length > 0 ||
tasks.some((task) => task.status === 'active' && task.nextFireAt !== null));
- if (shouldHold && !this.#residency) this.#residency = this.#acquireResidency();
+ if (shouldHold && !this.#residency) this.#residency = this.#acquireResidency('idle');
if (!shouldHold) this.#releaseResidency();
}
diff --git a/packages/runtime/src/__tests__/goal-continuation.test.ts b/packages/runtime/src/__tests__/goal-continuation.test.ts
index c4bf6ad923..454fa890e2 100644
--- a/packages/runtime/src/__tests__/goal-continuation.test.ts
+++ b/packages/runtime/src/__tests__/goal-continuation.test.ts
@@ -185,6 +185,41 @@ function setup(opts?: {
};
}
+test('Goal activity covers evaluation through settlement but not a paused durable Goal', async () => {
+ const { manager, coordinator, deps, admitted } = setup();
+ const evaluation = controlledCall<string>();
+ let activities = 0;
+ deps.acquireActivity = () => {
+ activities++;
+ return {
+ release: () => {
+ activities--;
+ },
+ };
+ };
+ deps.evaluator.evaluate = () => evaluation.invoke();
+ manager.create(SESSION, 'ship');
+ assert.equal(activities, 0);
+ const settlement = settleExternal(coordinator, SESSION, { kind: 'completed', turnId: 'turn-1' });
+ try {
+ await evaluation.started;
+ assert.equal(activities, 1);
+ manager.pause(SESSION);
+ assert.equal(activities, 1, 'pausing must not hide an evaluation still settling');
+ evaluation.resolve(
+ '{"met":false,"impossible":false,"progress":true,"waiting":false,"reason":"continue"}',
+ );
+ await settlement;
+ await waitFor(() => activities === 0);
+ assert.equal(manager.get(SESSION)?.status, 'paused');
+ assert.equal(admitted.length, 0);
+ } finally {
+ evaluation.resolve('{}');
+ await settlement;
+ await coordinator.close();
+ }
+});
+
test('handoff hold finishes Goal accounting without admitting a successor; release resumes it', async () => {
const { manager, coordinator, admitted } = setup();
manager.create(SESSION, 'finish the work');
diff --git a/packages/runtime/src/goal-continuation.ts b/packages/runtime/src/goal-continuation.ts
index fb76211b58..8013c010c2 100644
--- a/packages/runtime/src/goal-continuation.ts
+++ b/packages/runtime/src/goal-continuation.ts
@@ -93,6 +93,8 @@ export const volatileGoalDurability: GoalDurabilityPort = Object.freeze({
export interface GoalContinuationDeps {
goalManager: GoalManager;
+ /** Own active evaluation/admission work separately from a durable Goal's lifetime. */
+ acquireActivity?: () => { release(): void };
evaluator: GoalEvaluatorDeps & Partial<Pick<GoalEvaluatorResource, 'close'>>;
/** Summarized recent conversation (last ~5 messages) for the evaluator. */
getRecentContext: (sessionId: string) => Promise<string>;
@@ -598,12 +600,16 @@ export class GoalContinuationCoordinator {
private scheduleDrain(lane: SessionLane): void {
if (!this.isCurrent(lane) || lane.draining) return;
if (this.handoffHeld && lane.queue.length === 0) return;
+ const activity = this.deps.acquireActivity?.();
const task = this.drainLane(lane).catch((error) => {
if (!this.isCurrent(lane)) return;
this.pauseCurrentGoal(lane, `Goal continuation coordinator failed: ${errorMessage(error)}`);
});
this.activeDrains.add(task);
- void task.finally(() => this.activeDrains.delete(task));
+ void task.finally(() => {
+ this.activeDrains.delete(task);
+ activity?.release();
+ });
}
private async drainLane(lane: SessionLane): Promise<void> {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org