Skip to content

Commit 414f31d

Browse files
committed
refactor(daemon): enter one runtime store once, at start (#3794)
startDaemonRuntime creates one handle and runs composition, dispatch and close inside it, so every module slot resolves from that runtime without a per-module handle being composed in. DaemonRuntimeDeps.runtimeStates, RuntimeContext and its extend aggregation are gone: the store has nothing left to fold together. Bounded close keeps disposing state only when no work is unfinished, now observed through a slot of the runtime's own store.
1 parent 5c55dc0 commit 414f31d

10 files changed

Lines changed: 49 additions & 112 deletions

‎packages/daemon/src/__tests__/support/daemon-runtime-deps-fixture.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ export function daemonRuntimeDepsFixture(
6060
return async (input) => {
6161
const resolved = typeof overrides === 'function' ? overrides(input) : overrides;
6262
return Object.freeze({
63-
runtimeStates: [],
6463
ownedProcessRecords: createOwnedProcessRecordStore({
6564
stateDir: input.baseDir,
6665
sessionsDir: input.sessionsDir,

‎packages/daemon/src/core/interactor-resolution.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { defineRuntimeSlots, type RuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
1+
import { runtimeSlot } from '@agent-device/host-kit/runtime-slots';
22
import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types';
33
import type { DeviceInfo } from '@agent-device/kernel/device';
44
import { AppError } from '@agent-device/kernel/errors';
@@ -30,17 +30,12 @@ const NO_INTERACTOR_RESOLUTION: InteractorResolution = {
3030

3131
type InteractorResolutionState = { resolution: InteractorResolution };
3232

33-
const interactorResolutionRuntime = defineRuntimeSlots();
3433
const INTERACTOR_RESOLUTION_SLOT = Symbol('interactorResolution');
3534
const interactorResolutionState = (): InteractorResolutionState =>
36-
interactorResolutionRuntime.slot(INTERACTOR_RESOLUTION_SLOT, (): InteractorResolutionState => ({
35+
runtimeSlot(INTERACTOR_RESOLUTION_SLOT, (): InteractorResolutionState => ({
3736
resolution: NO_INTERACTOR_RESOLUTION,
3837
}));
3938

40-
/** The resolution one daemon runtime owns; the runtime installs its composition's into it. */
41-
export const createInteractorResolutionRuntimeState = (): RuntimeStateHandle =>
42-
interactorResolutionRuntime.createHandle();
43-
4439
/**
4540
* Root composition's installation point, beside the provider-device admission that shares the
4641
* same request-scoped provider scope: one change names both. The interactor graph stays behind

‎packages/daemon/src/core/provider-device-admission.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { defineRuntimeSlots, type RuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
1+
import { runtimeSlot } from '@agent-device/host-kit/runtime-slots';
22
import type { DeviceInfo } from '@agent-device/kernel/device';
33

44
/**
@@ -21,17 +21,12 @@ const NO_PROVIDER_DEVICE_ADMISSION: ProviderDeviceAdmission = {
2121

2222
type ProviderAdmissionState = { admission: ProviderDeviceAdmission };
2323

24-
const providerAdmissionRuntime = defineRuntimeSlots();
2524
const PROVIDER_ADMISSION_SLOT = Symbol('providerDeviceAdmission');
2625
const providerAdmissionState = (): ProviderAdmissionState =>
27-
providerAdmissionRuntime.slot(PROVIDER_ADMISSION_SLOT, (): ProviderAdmissionState => ({
26+
runtimeSlot(PROVIDER_ADMISSION_SLOT, (): ProviderAdmissionState => ({
2827
admission: NO_PROVIDER_DEVICE_ADMISSION,
2928
}));
3029

31-
/** The admission one daemon runtime owns; the runtime installs its composition's into it. */
32-
export const createProviderDeviceAdmissionRuntimeState = (): RuntimeStateHandle =>
33-
providerAdmissionRuntime.createHandle();
34-
3530
/**
3631
* Root composition's installation point. The provider runtime scope is ambient per request, so
3732
* this is the one place the daemon names where the fact comes from, and the daemon never reads

‎packages/daemon/src/resources/artifact-tracking.test.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,8 @@ import fs from 'node:fs';
22
import path from 'node:path';
33
import { expect, test } from 'vitest';
44
import { mkdtempForTestSync } from '@agent-device/test-kit';
5-
import {
6-
createArtifactTrackingRuntimeState,
7-
trackDownloadableArtifact,
8-
trackUploadedArtifact,
9-
} from './artifact-tracking.ts';
5+
import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
6+
import { trackDownloadableArtifact, trackUploadedArtifact } from './artifact-tracking.ts';
107

118
test('disposing a runtime removes the temporary files it still tracks', () => {
129
const root = mkdtempForTestSync('agent-device-artifact-dispose-');
@@ -15,7 +12,7 @@ test('disposing a runtime removes the temporary files it still tracks', () => {
1512
fs.writeFileSync(artifactPath, 'artifact');
1613
fs.mkdirSync(uploadDir);
1714
fs.writeFileSync(path.join(uploadDir, 'payload'), 'payload');
18-
const runtime = createArtifactTrackingRuntimeState();
15+
const runtime = createRuntimeStateHandle();
1916

2017
runtime.run(() => {
2118
trackDownloadableArtifact({

‎packages/daemon/src/resources/artifact-tracking.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { defineRuntimeSlots, type RuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
1+
import { runtimeSlot } from '@agent-device/host-kit/runtime-slots';
22
import crypto from 'node:crypto';
33
import fs from 'node:fs';
44
import os from 'node:os';
@@ -50,10 +50,9 @@ type ArtifactTrackingState = {
5050
uploads: Map<string, UploadEntry>;
5151
};
5252

53-
const artifactTrackingRuntime = defineRuntimeSlots();
5453
const ARTIFACT_TRACKING_SLOT = Symbol('artifactTracking');
5554
const artifactTracking = (): ArtifactTrackingState =>
56-
artifactTrackingRuntime.slot(
55+
runtimeSlot(
5756
ARTIFACT_TRACKING_SLOT,
5857
(): ArtifactTrackingState => ({ artifacts: new Map(), uploads: new Map() }),
5958
(state) => {
@@ -71,10 +70,6 @@ const artifactTracking = (): ArtifactTrackingState =>
7170
const pendingArtifacts = () => artifactTracking().artifacts;
7271
const pendingUploads = () => artifactTracking().uploads;
7372

74-
/** The artifacts and uploads one daemon runtime tracks; disposing it stops their expiry timers. */
75-
export const createArtifactTrackingRuntimeState = (): RuntimeStateHandle =>
76-
artifactTrackingRuntime.createHandle();
77-
7873
/** What a finished request registers for each artifact it hands back to the client. */
7974
export type DownloadableArtifactRegistration = {
8075
artifactPath: string;

‎packages/daemon/src/server/http/daemon-runtime-bounded-close.test.ts‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { setTimeout as delay } from 'node:timers/promises';
33
import { lifecycleDeviceRuntimeGateway } from '../../__tests__/support/test-device-runtime-gateway.ts';
44
import { expect, test, vi } from 'vitest';
55
import { createTestDeviceInventoryGateways } from '@agent-device/device-selection/inventory-gateways-fixtures';
6-
import type { RuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
6+
import { runtimeSlot } from '@agent-device/host-kit/runtime-slots';
77
import type { ProviderDeviceRuntime } from '@agent-device/contracts/device';
88
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
99
import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit';
@@ -178,22 +178,27 @@ test('unfinished platform owner shutdown is bounded, reports pending and retains
178178
});
179179
const clearLock = vi.fn(async () => {});
180180
const pluginShutdown = vi.fn(async () => []);
181+
// The slot lives on the runtime's one entered store, so its disposer runs exactly when that
182+
// store is disposed (#3794): it stands in for the per-runtime state the close must not drop
183+
// while work is unfinished.
181184
const disposeState = vi.fn();
182-
const state: RuntimeStateHandle = { run: (fn) => fn(), enter: () => {}, dispose: disposeState };
185+
const heldSlot = Symbol('bounded-close-held-state');
183186
const runtime = await startDaemonRuntime({
184187
host: hostFor(stateDir),
185188
...silent,
186189
shutdownBudgets: { ownerMs: 20 },
187-
composeDeps: daemonRuntimeDepsFixture({
188-
deviceRuntimeGateway: {
189-
...lifecycleDeviceRuntimeGateway,
190-
applicationLifecycle: applicationLifecycleResourceFixture(),
191-
shutdown: () => ownerClosed,
192-
},
193-
ownerLifecycle: platformOwnerLifecycleFixture({ clearDaemonLockConfiguration: clearLock }),
194-
shutdownProviderRuntimes: pluginShutdown,
195-
runtimeStates: [state],
196-
}),
190+
composeDeps: async (input) => {
191+
runtimeSlot(heldSlot, () => ({}), disposeState);
192+
return await daemonRuntimeDepsFixture({
193+
deviceRuntimeGateway: {
194+
...lifecycleDeviceRuntimeGateway,
195+
applicationLifecycle: applicationLifecycleResourceFixture(),
196+
shutdown: () => ownerClosed,
197+
},
198+
ownerLifecycle: platformOwnerLifecycleFixture({ clearDaemonLockConfiguration: clearLock }),
199+
shutdownProviderRuntimes: pluginShutdown,
200+
})(input);
201+
},
197202
});
198203
const closing = runtime.close();
199204
try {

‎packages/daemon/src/server/http/daemon-runtime.ts‎

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,7 @@ import { finalizeDaemonSessionApplicationLifecycle } from '../application-lifecy
4141
import { runtimeHintValues } from '../../sessions/session-runtime.ts';
4242
import {
4343
closeDaemonServers,
44-
createRuntimeContext,
4544
teardownDaemonSessionForShutdown,
46-
type RuntimeContext,
4745
type WritableOutput,
4846
createPluginClose,
4947
createStartupRollback,
@@ -69,7 +67,10 @@ import { createPerfCaptureAdmissionLedger } from '@agent-device/capture-kit/perf
6967
import { createScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger';
7068
import { withCommandHost } from '@agent-device/host-kit/command';
7169
import { cancelAllRequests } from '@agent-device/host-kit/request';
72-
import type { RuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
70+
import {
71+
createRuntimeStateHandle,
72+
type RuntimeStateHandle,
73+
} from '@agent-device/host-kit/runtime-slots';
7374
import { emitDiagnostic, type ResourceDiagnostic } from '@agent-device/host-kit/diagnostics';
7475
import type { HostEnvironment } from '@agent-device/kernel/source-value';
7576
import {
@@ -131,8 +132,6 @@ const DAEMON_RECORDING_REAP_TERM_TIMEOUT_MS = 5_000;
131132
* same factory, so the production assembly is the one every runtime test boots.
132133
*/
133134
export type DaemonRuntimeDeps = Readonly<{
134-
/** State the composition's platform modules keep per daemon runtime (the Apple runner's). */
135-
runtimeStates: readonly RuntimeStateHandle[];
136135
ownedProcessRecords: OwnedProcessRecordStore;
137136
hostDiagnostics: HostDiagnostics;
138137
ownerLifecycle: PlatformOwnerLifecycle;
@@ -244,17 +243,23 @@ export function daemonStartupExitCode(error: unknown): number {
244243
return typeof exitCode === 'number' ? exitCode : 1;
245244
}
246245

246+
/**
247+
* Starts one daemon runtime: the single entered runtime-state store, the command host, then the
248+
* composition and servers built inside both. Every read of per-runtime state (requests, close,
249+
* timers the startup spawns) runs within this handle, so two runtimes in one process never share
250+
* it and no module exposes a store of its own (#3794).
251+
*/
247252
export async function startDaemonRuntime(
248253
options: DaemonRuntimeOptions,
249254
): Promise<DaemonRuntimeController> {
250-
const runtimeContext = createRuntimeContext();
251-
return await runtimeContext.run(
255+
const runtimeState = createRuntimeStateHandle();
256+
return await runtimeState.run(
252257
async () =>
253258
await withCommandHost({ host: options.host, requestEnv: undefined }, async () => {
254259
const rollback = createStartupRollback();
255-
rollback.onRollback(() => runtimeContext.dispose());
260+
rollback.onRollback(() => runtimeState.dispose());
256261
try {
257-
return await startDaemonRuntimeOnHost(options, rollback, runtimeContext);
262+
return await startDaemonRuntimeOnHost(options, rollback, runtimeState);
258263
} catch (error) {
259264
await rollback.run();
260265
throw error;
@@ -266,7 +271,7 @@ export async function startDaemonRuntime(
266271
async function startDaemonRuntimeOnHost(
267272
options: DaemonRuntimeOptions,
268273
rollback: StartupRollback,
269-
runtimeContext: RuntimeContext,
274+
runtimeState: RuntimeStateHandle,
270275
): Promise<DaemonRuntimeController> {
271276
const { host } = options;
272277
const { env } = host;
@@ -306,7 +311,6 @@ async function startDaemonRuntimeOnHost(
306311
}),
307312
openWebSessionNames: () => openWebSessionNames(sessionStore),
308313
});
309-
runtimeContext.extend(deps.runtimeStates);
310314
const appLogAdmissionLedger = createAppLogAdmissionLedger();
311315
const audioProbeAdmissionLedger = createAudioProbeAdmissionLedger();
312316
const perfCaptureAdmissionLedger = createPerfCaptureAdmissionLedger();
@@ -546,7 +550,7 @@ async function startDaemonRuntimeOnHost(
546550
const handleRequest: DaemonInvokeFn = quiesce.admit(async (req) => {
547551
if (shuttingDown) return daemonShuttingDownResponse();
548552
idleReap.cancel();
549-
const dispatch = runtimeContext.run(() => dispatchRequest(req));
553+
const dispatch = runtimeState.run(() => dispatchRequest(req));
550554
inFlightRequests.add(dispatch);
551555
try {
552556
return await dispatch;
@@ -891,7 +895,7 @@ async function startDaemonRuntimeOnHost(
891895
? undefined
892896
: deps.ownerLifecycle.clearDaemonLockConfiguration(),
893897
]);
894-
if (!hasUnfinishedWork()) runtimeContext.dispose();
898+
if (!hasUnfinishedWork()) runtimeState.dispose();
895899
}
896900
};
897901

@@ -907,7 +911,7 @@ async function startDaemonRuntimeOnHost(
907911
closed.catch(() => {});
908912
const close = (closeOptions: { cause?: unknown } = {}): Promise<ShutdownReport> => {
909913
if (!closing) {
910-
closing = runtimeContext.run(() =>
914+
closing = runtimeState.run(() =>
911915
withCommandHost(
912916
{ host, requestEnv: undefined },
913917
async () => await closeOnHost(closeOptions),
@@ -924,7 +928,7 @@ async function startDaemonRuntimeOnHost(
924928
httpPort,
925929
close,
926930
closed,
927-
run: runtimeContext.run,
931+
run: runtimeState.run,
928932
socketPort,
929933
token,
930934
};

‎packages/daemon/src/server/http/server-shutdown.ts‎

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,10 @@ import type {
55
import { normalizeError, type NormalizedError } from '@agent-device/kernel/errors';
66
import type { DaemonServer } from './transport.ts';
77
import { sleep } from '@agent-device/host-kit/retry';
8-
import { createRequestCancelRuntimeState } from '@agent-device/host-kit/request';
9-
import type { RuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
108
import type { RuntimeHintValues } from '@agent-device/contracts/application-lifecycle-runtime';
119
import { SessionStore } from '../../core/session-store.ts';
1210
import type { SessionRef, SessionState } from '../../core/session-state.ts';
1311
import type { PlatformResourceCleanup } from '../../core/platform-resource-cleanup.ts';
14-
import { createProviderDeviceAdmissionRuntimeState } from '../../core/provider-device-admission.ts';
15-
import { createInteractorResolutionRuntimeState } from '../../core/interactor-resolution.ts';
16-
import { createArtifactTrackingRuntimeState } from '../../resources/artifact-tracking.ts';
17-
import { createResumableUploadRuntimeState } from '../resumable-upload.ts';
18-
import { createMaterializedPathRuntimeState } from '../../sessions/materialized-path-registry.ts';
1912
import { stopSessionAppLog, teardownSessionResources } from '../../sessions/session-teardown.ts';
2013
import { resolveDaemonSessionTeardownTimeoutMs } from '../../sessions/session-teardown-budget.ts';
2114
import { runtimeHintValues } from '../../sessions/session-runtime.ts';
@@ -372,39 +365,3 @@ export async function teardownDaemonSessionForShutdown(params: {
372365
sessionStore.retire(ref);
373366
return teardownSucceeded;
374367
}
375-
376-
export type RuntimeContext = Readonly<{
377-
run<T>(fn: () => T): T;
378-
/** Adds state the composition contributed and binds it for the rest of the start. */
379-
extend(handles: readonly RuntimeStateHandle[]): void;
380-
dispose(): void;
381-
}>;
382-
383-
/** The per-runtime state of every module that keeps some, in the order it is entered. */
384-
function createDaemonRuntimeStates(): RuntimeStateHandle[] {
385-
return [
386-
createRequestCancelRuntimeState(),
387-
createProviderDeviceAdmissionRuntimeState(),
388-
createInteractorResolutionRuntimeState(),
389-
createArtifactTrackingRuntimeState(),
390-
createResumableUploadRuntimeState(),
391-
createMaterializedPathRuntimeState(),
392-
];
393-
}
394-
395-
/** The context one daemon runtime enters: every module's per-runtime state, composed in order. */
396-
export function createRuntimeContext(): RuntimeContext {
397-
const states = createDaemonRuntimeStates();
398-
return {
399-
run: (fn) => states.reduceRight((next, state) => () => state.run(next), fn)(),
400-
extend: (handles) => {
401-
for (const handle of handles) {
402-
states.push(handle);
403-
handle.enter();
404-
}
405-
},
406-
dispose: () => {
407-
for (const state of states) state.dispose();
408-
},
409-
};
410-
}

‎packages/daemon/src/server/resumable-upload.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { defineRuntimeSlots, type RuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
1+
import { runtimeSlot } from '@agent-device/host-kit/runtime-slots';
22
import crypto from 'node:crypto';
33
import fs from 'node:fs';
44
import path from 'node:path';
@@ -26,10 +26,9 @@ type ResumableUploadState = {
2626
byKey: Map<string, string>;
2727
};
2828

29-
const resumableUploadRuntime = defineRuntimeSlots();
3029
const RESUMABLE_UPLOAD_SLOT = Symbol('resumableUploads');
3130
const resumableUploads = (): ResumableUploadState =>
32-
resumableUploadRuntime.slot(
31+
runtimeSlot(
3332
RESUMABLE_UPLOAD_SLOT,
3433
(): ResumableUploadState => ({ byId: new Map(), byKey: new Map() }),
3534
(state) => {
@@ -46,10 +45,6 @@ const resumableUploads = (): ResumableUploadState =>
4645
const RESUMABLE_UPLOADS_BY_ID = () => resumableUploads().byId;
4746
const RESUMABLE_UPLOADS_BY_KEY = () => resumableUploads().byKey;
4847

49-
/** The resumable uploads one daemon runtime holds; disposing it stops their expiry timers. */
50-
export const createResumableUploadRuntimeState = (): RuntimeStateHandle =>
51-
resumableUploadRuntime.createHandle();
52-
5348
export type BeginResumableUploadOptions = {
5449
baseUrl: string;
5550
tokenHeaders: Record<string, string>;

‎packages/daemon/src/sessions/materialized-path-registry.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { defineRuntimeSlots, type RuntimeStateHandle } from '@agent-device/host-kit/runtime-slots';
1+
import { runtimeSlot } from '@agent-device/host-kit/runtime-slots';
22
import crypto from 'node:crypto';
33
import { rmSync } from 'node:fs';
44
import fs from 'node:fs/promises';
@@ -35,10 +35,9 @@ export type RetainedMaterializedPaths = {
3535
expiresAt: string;
3636
};
3737

38-
const retainedPathsRuntime = defineRuntimeSlots();
3938
const RETAINED_PATHS_SLOT = Symbol('materializedPaths');
4039
const retainedPaths = (): Map<string, RetainedEntry> =>
41-
retainedPathsRuntime.slot(
40+
runtimeSlot(
4241
RETAINED_PATHS_SLOT,
4342
() => new Map<string, RetainedEntry>(),
4443
(entries) => {
@@ -53,10 +52,6 @@ const retainedPaths = (): Map<string, RetainedEntry> =>
5352
},
5453
);
5554

56-
/** The materialized paths one daemon runtime retains; disposing it stops their expiry timers. */
57-
export const createMaterializedPathRuntimeState = (): RuntimeStateHandle =>
58-
retainedPathsRuntime.createHandle();
59-
6055
export async function retainMaterializedPaths(params: {
6156
installablePath: string;
6257
archivePath?: string;

0 commit comments

Comments
 (0)