diff --git a/packages/command-registry/src/descriptor-timeout-policies.ts b/packages/command-registry/src/descriptor-timeout-policies.ts index 8b52a6748d..47c4979fb9 100644 --- a/packages/command-registry/src/descriptor-timeout-policies.ts +++ b/packages/command-registry/src/descriptor-timeout-policies.ts @@ -3,6 +3,8 @@ import { parseTimeout } from './parse-timeout.ts'; import { DEFAULT_TIMEOUT_POLICY, INSTALL_REQUEST_TIMEOUT_MS, + INSTALL_SOURCE_DAEMON_DEADLINE_MS, + INSTALL_SOURCE_REQUEST_TIMEOUT_MS, LEASE_ALLOCATE_REQUEST_TIMEOUT_MS, MAX_ARMABLE_ALERT_WAIT_WINDOW_MS, } from './timeout-policy.ts'; @@ -24,6 +26,17 @@ export const INSTALL_TIMEOUT_POLICY: CommandTimeoutPolicy = { envelopeMs: INSTALL_REQUEST_TIMEOUT_MS, }; +/** + * The one source-install timeout policy shared by `install-from-source` and `install_source` + * (#4441, decision 6856998913): the 600 s client envelope, with the daemon enforcing the + * envelope less the result margin (570 s) from admission through the descriptor/router path. + */ +export const INSTALL_SOURCE_TIMEOUT_POLICY: CommandTimeoutPolicy = { + ...INSTALL_TIMEOUT_POLICY, + envelopeMs: INSTALL_SOURCE_REQUEST_TIMEOUT_MS, + daemonDeadlineMs: INSTALL_SOURCE_DAEMON_DEADLINE_MS, +}; + // Lease-route commands act on billed cloud sessions the daemon owns; resetting // the daemon on a client timeout would SIGKILL it mid-create/mid-release and // orphan them all (#1774). Allocation also gets an envelope sized for remote diff --git a/packages/command-registry/src/descriptors/device-operations.ts b/packages/command-registry/src/descriptors/device-operations.ts index 40e7066781..0f1125b034 100644 --- a/packages/command-registry/src/descriptors/device-operations.ts +++ b/packages/command-registry/src/descriptors/device-operations.ts @@ -6,11 +6,7 @@ import { settingsRefFrameEffect, NO_PLATFORM_EXECUTION, } from '../descriptor-request-policy.ts'; -import { - DEFAULT_TIMEOUT_POLICY, - FOLD_TIMEOUT_POLICY, - INSTALL_SOURCE_REQUEST_TIMEOUT_MS, -} from '../timeout-policy.ts'; +import { DEFAULT_TIMEOUT_POLICY, FOLD_TIMEOUT_POLICY } from '../timeout-policy.ts'; import { FILL_INTERACTION_RESPONSE_DATA_TRANSFORM, GENERIC_MUTATING_COMMAND_TRAITS, @@ -23,6 +19,7 @@ import { } from '../descriptor-traits.ts'; import { ALERT_TIMEOUT_POLICY, + INSTALL_SOURCE_TIMEOUT_POLICY, PRESERVE_DAEMON_TIMEOUT_POLICY, SETTLE_FLAG_PRESERVE_DAEMON_TIMEOUT_POLICY, postActionObservationTimeoutPolicy, @@ -629,7 +626,7 @@ export const DEVICE_OPERATION_COMMAND_DESCRIPTORS = { recordsSessionAction: true, recordingEffect: 'mutates-app', platformExecution: { kind: 'device-runtime', use: readyMaterializeAndDeployAppUse }, - timeoutPolicy: { ...DEFAULT_TIMEOUT_POLICY, envelopeMs: INSTALL_SOURCE_REQUEST_TIMEOUT_MS }, + timeoutPolicy: INSTALL_SOURCE_TIMEOUT_POLICY, batchable: true, compositeResource: 'none', }, diff --git a/packages/command-registry/src/descriptors/session-operations.ts b/packages/command-registry/src/descriptors/session-operations.ts index 341a6e72dc..593838563b 100644 --- a/packages/command-registry/src/descriptors/session-operations.ts +++ b/packages/command-registry/src/descriptors/session-operations.ts @@ -8,7 +8,6 @@ import { import { COMPOSITE_TIMEOUT_POLICIES, DEFAULT_TIMEOUT_POLICY, - INSTALL_SOURCE_REQUEST_TIMEOUT_MS, PREPARE_REQUEST_TIMEOUT_MS, } from '../timeout-policy.ts'; import { @@ -18,7 +17,10 @@ import { ownerFilesEnabled, type RawCommandDescriptor, } from '../descriptor-traits.ts'; -import { INSTALL_TIMEOUT_POLICY } from '../descriptor-timeout-policies.ts'; +import { + INSTALL_SOURCE_TIMEOUT_POLICY, + INSTALL_TIMEOUT_POLICY, +} from '../descriptor-timeout-policies.ts'; import { deployAppUse, readyMaterializeAndDeployAppUse, @@ -317,7 +319,7 @@ export const SESSION_OPERATION_COMMAND_DESCRIPTORS = [ androidAvdSelection: 'include-stopped', }, platformExecution: { kind: 'device-runtime', use: readyMaterializeAndDeployAppUse }, - timeoutPolicy: { ...INSTALL_TIMEOUT_POLICY, envelopeMs: INSTALL_SOURCE_REQUEST_TIMEOUT_MS }, + timeoutPolicy: INSTALL_SOURCE_TIMEOUT_POLICY, batchable: false, }, { diff --git a/packages/command-registry/src/timeout-policy.ts b/packages/command-registry/src/timeout-policy.ts index 699f85695c..0b3dcd56be 100644 --- a/packages/command-registry/src/timeout-policy.ts +++ b/packages/command-registry/src/timeout-policy.ts @@ -18,6 +18,15 @@ export const INSTALL_SOURCE_REQUEST_TIMEOUT_MS = 600_000; // envelope below the command's declared base. const REQUEST_TIMEOUT_BUDGET_MARGIN_MS = 30_000; +/** + * The source-install work budget the daemon enforces from admission (#4441, + * decisions 6827686874/6856998913): readiness, download, extraction and + * installation share one remaining budget, so the daemon deadline is the + * 600 s client envelope less the result margin. + */ +export const INSTALL_SOURCE_DAEMON_DEADLINE_MS = + INSTALL_SOURCE_REQUEST_TIMEOUT_MS - REQUEST_TIMEOUT_BUDGET_MARGIN_MS; + /** * The longest `alert wait` window the request envelope can be armed for. * diff --git a/packages/daemon/src/core/__tests__/daemon-command-registry.test.ts b/packages/daemon/src/core/__tests__/daemon-command-registry.test.ts index 6923ad850e..c2cb39c007 100644 --- a/packages/daemon/src/core/__tests__/daemon-command-registry.test.ts +++ b/packages/daemon/src/core/__tests__/daemon-command-registry.test.ts @@ -16,6 +16,8 @@ import { shouldPreferExplicitDeviceOverExistingSession, shouldValidateSessionSelector, resolveProviderDeviceResolutionIntent, + resolveDaemonRequestResultDeadlineMs, + resolveDaemonRequestTimeoutMs, usesSessionlessDefaultProviderDevice, } from '../daemon-command-registry.ts'; import type { DaemonRequest } from '../daemon-request.ts'; @@ -328,6 +330,45 @@ function makeRequest(command: string, positionals: string[] = []): DaemonRequest }; } +// #4441 (decision 6856998913): the router's daemon request timeout for both source-install +// commands is the one 570 s source work budget; the admitting transport registers the same +// result deadline (admittedAt + 570 s), and unrelated commands keep no daemon deadline. +test('source-install requests resolve the 570 s daemon deadline and result deadline', () => { + const request = (command: string) => + ({ + token: 't', + session: 'default', + command, + positionals: [], + flags: {}, + }) as DaemonRequest; + for (const command of [PUBLIC_COMMANDS.installFromSource, INTERNAL_COMMANDS.installSource]) { + assert.equal(resolveDaemonRequestTimeoutMs(request(command)), 570_000, command); + const admittedAt = 1_000_000; + assert.equal( + resolveDaemonRequestResultDeadlineMs(request(command), admittedAt), + admittedAt + 570_000, + command, + ); + } + for (const command of [PUBLIC_COMMANDS.install, PUBLIC_COMMANDS.snapshot]) { + assert.equal(resolveDaemonRequestTimeoutMs(request(command)), undefined, command); + } +}); + +test('batch and replay transport deadlines match their resolved execution budgets', () => { + const admittedAt = 1_000_000; + for (const command of [PUBLIC_COMMANDS.batch, PUBLIC_COMMANDS.replay]) { + const request = makeRequest(command); + const executionBudgetMs = resolveDaemonRequestTimeoutMs(request); + assert.notEqual(executionBudgetMs, undefined, command); + assert.equal( + resolveDaemonRequestResultDeadlineMs(request, admittedAt), + admittedAt + executionBudgetMs!, + ); + } +}); + // The fact the transports stamp on each admitted request: only a request with no action in any of // its steps may let a resend loop spend its deadline. test('isReadOnlyRequest marks reads, and never a request that dispatches an action', () => { diff --git a/packages/daemon/src/core/lease-context.ts b/packages/daemon/src/core/lease-context.ts index faabd6b61c..f7a5c71f3c 100644 --- a/packages/daemon/src/core/lease-context.ts +++ b/packages/daemon/src/core/lease-context.ts @@ -4,6 +4,7 @@ import { AppError, BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON, } from '@agent-device/kernel/errors'; +import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; import { resolveCommandStandaloneProjection } from '@agent-device/command-registry/registry'; import type { LeaseBackend } from '@agent-device/kernel/contracts'; import type { DeviceLease } from '@agent-device/contracts/device'; @@ -31,7 +32,14 @@ export function refuseBoundedCompositeResourceOperation(req: DaemonRequest, shap } export function isBoundedCompositeRequest(req: DaemonRequest): boolean { - return getRequestExecutionDeadlineMs(req.meta?.requestId) !== undefined; + if (getRequestExecutionDeadlineMs(req.meta?.requestId) === undefined) return false; + if ( + req.command === INTERNAL_COMMANDS.installSource || + req.command === PUBLIC_COMMANDS.installFromSource + ) { + return req.internal?.executionPlan !== undefined || req.internal?.replayPlanStep === true; + } + return true; } export type SessionLease = { diff --git a/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts b/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts index 27e035ebfe..b5440b72fc 100644 --- a/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts @@ -229,6 +229,26 @@ test('bounded install_source refusal names public install-from-source', async () expect(fs.readFileSync(claimPath)).toEqual(before); }); +test('a top-level source install reaches runtime admission under its own deadline', async () => { + const device = { ...makeIosDevice('SIM-DIRECT-SOURCE-RECOVERY'), appleOs: 'ios' as const }; + seedClaim(device); + const { handler, runtime } = route(device); + const request = openRequest('takeover', { platform: 'ios' }, 'direct-source-recovery'); + const sourcePath = path.join(root('source-recovery-input-'), 'app.ipa'); + fs.writeFileSync(sourcePath, 'owned fixture'); + const response = await handler({ + ...request, + command: 'install_source', + positionals: ['com.example.app'], + meta: { ...request.meta, installSource: { kind: 'path', path: sourcePath } }, + }); + expect(response).toMatchObject({ + ok: false, + error: { details: { reason: 'owner-capability-missing' } }, + }); + expect(runtime.inspectFacts).toHaveBeenCalled(); +}); + test('bounded install preserves the handler selector error before inventory resolution', async () => { const device = { ...makeIosDevice('SIM-NO-SELECTOR'), appleOs: 'ios' as const }; const { handler, runtime, recovery } = route(device, { inventory: [] }); diff --git a/packages/daemon/src/server/__tests__/request-router-install-source-deadline.test.ts b/packages/daemon/src/server/__tests__/request-router-install-source-deadline.test.ts new file mode 100644 index 0000000000..52a52cc778 --- /dev/null +++ b/packages/daemon/src/server/__tests__/request-router-install-source-deadline.test.ts @@ -0,0 +1,586 @@ +import assert from 'node:assert/strict'; +import http from 'node:http'; +import path from 'node:path'; +import { afterEach, test, vi, type Mock } from 'vitest'; +import { createTestDeviceInventoryGateways } from '@agent-device/device-selection/inventory-gateways-fixtures'; +import type { + AppDeploymentResult, + MaterializedAppSource, +} from '@agent-device/contracts/app-deployment-runtime'; +import { + type DeviceBinding, + type DeviceBindingRequest, + type DeviceRuntimeGateway, + type RuntimeFacts, + localRuntimeOwner, +} from '@agent-device/contracts/platform-runtime'; +import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { + closeLoopbackServer, + createTestHostEnvironment, + createUnavailableRuntimeFactsForTest, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { + clearRequestAbortRegistration, + emitRequestProgress, + getRequestSignal, + markRequestCanceled, + registerRequestAbort, +} from '@agent-device/host-kit/request'; +import { fakeCreateCommandSurface } from '../../__tests__/support/command-surface-fake.ts'; +import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; +import { createRequestHandler } from '../../__tests__/support/test-device-runtime-gateway.ts'; +import { LeaseRegistry } from '../../resources/lease-registry.ts'; +import type { DaemonRequest } from '../../core/daemon-request.ts'; +import { startRpcServer } from './http-server-rpc.fixtures.ts'; + +// #4441 (decisions 6827686874/6856998913): the real-route proof for the descriptor candidate — +// a source-install request admitted over loopback HTTP/RPC ingress, routed by the real request +// router, executed through the normal provider-backed source-install path (only the provider +// gateway seam is faked), under a controlled clock. The daemon must enforce the 570 s +// source-install deadline from admission: typed `daemon_request_timeout` error, no late success +// on the wire, cleanup after the answer (including after already-received response headers on +// the streaming route), and refusal of task entry when an earlier registered cutoff has passed. + +const TOKEN = 'install-source-deadline-token'; +const START_MS = 1_800_000_000_000; +/** The descriptor candidate's source-install daemon deadline: 600 s envelope less the 30 s margin. */ +const SOURCE_DEADLINE_MS = 570_000; + +const ANDROID_DEVICE: DeviceInfo = { + platform: 'android', + id: 'emulator-5554', + name: 'Pixel 8', + kind: 'emulator', + booted: true, +}; + +// Captured before any test fakes the clock: loopback socket I/O must never depend on fake timers. +const realSetTimeout = globalThis.setTimeout; +const realClearTimeout = globalThis.clearTimeout; + +function withRealGuard(pending: Promise, ms = 5_000): Promise { + let timer: ReturnType | undefined; + const guard = new Promise((_, reject) => { + timer = realSetTimeout(() => reject(new Error('loopback I/O did not complete in time')), ms); + }); + return Promise.race([pending, guard]).finally(() => { + if (timer !== undefined) realClearTimeout(timer); + }); +} + +async function flushIO(rounds = 25): Promise { + for (let i = 0; i < rounds; i += 1) await new Promise((r) => realSetTimeout(r, 0)); +} + +async function waitFor(cond: () => boolean, what: string): Promise { + for (let i = 0; i < 2_000; i += 1) { + if (cond()) return; + await new Promise((r) => realSetTimeout(r, 1)); + } + throw new Error(`timed out waiting for ${what}`); +} + +async function answeredYet(pending: Promise): Promise { + let answered = false; + void pending.then( + () => { + answered = true; + }, + () => { + answered = true; + }, + ); + await flushIO(); + return answered; +} + +type RpcAnswer = { status: number; body: Record }; + +async function postRpc(port: number, rawBody: string): Promise { + return await withRealGuard( + new Promise((resolve, reject) => { + const req = http.request( + { + host: '127.0.0.1', + port, + method: 'POST', + path: '/rpc', + headers: { 'content-type': 'application/json', authorization: `Bearer ${TOKEN}` }, + }, + (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => + resolve({ + status: res.statusCode ?? 0, + body: JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record, + }), + ); + }, + ); + req.on('error', reject); + req.end(rawBody); + }), + ); +} + +/** A streaming POST whose response headers are observable before the body finishes. */ +function postRpcStream( + port: number, + rawBody: string, +): { + headersReceived: Promise<{ status: number; contentType: string | undefined }>; + bodyDone: Promise<{ bodyText: string }>; +} { + let resolveHeaders!: (headers: { status: number; contentType: string | undefined }) => void; + const headersReceived = new Promise<{ status: number; contentType: string | undefined }>( + (resolve) => { + resolveHeaders = resolve; + }, + ); + const bodyDone = withRealGuard( + new Promise<{ bodyText: string }>((resolve, reject) => { + const req = http.request( + { + host: '127.0.0.1', + port, + method: 'POST', + path: '/rpc', + headers: { 'content-type': 'application/json', authorization: `Bearer ${TOKEN}` }, + }, + (res) => { + resolveHeaders({ + status: res.statusCode ?? 0, + contentType: res.headers['content-type'], + }); + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => resolve({ bodyText: Buffer.concat(chunks).toString('utf8') })); + }, + ); + req.on('error', reject); + req.end(rawBody); + }), + ); + return { headersReceived, bodyDone }; +} + +function installSourceRpcBody(requestId: string, extraMeta: Record = {}): string { + return JSON.stringify({ + jsonrpc: '2.0', + id: requestId, + method: 'agent_device.command', + params: { + command: 'install_source', + session: 'default', + meta: { + requestId, + installSource: { kind: 'url', url: 'https://example.com/app.zip' }, + ...extraMeta, + }, + }, + }); +} + +function installSourceRequest(requestId: string): DaemonRequest { + return { + token: TOKEN, + session: 'default', + command: 'install_source', + positionals: [], + flags: {}, + meta: { requestId, installSource: { kind: 'url', url: 'https://example.com/app.zip' } }, + }; +} + +type ProviderSpies = { + inspectFacts: Mock<(device: DeviceInfo) => Promise>>; + bind: Mock<(request: DeviceBindingRequest) => Promise>>; + ensureReady: Mock; + materializeAppSource: Mock; + deployMaterializedApp: Mock; + /** The request scope's signal, captured when the router binds the device. */ + scopeSignal: AbortSignal | undefined; +}; + +/** + * The provider seam: a device runtime gateway whose binding admits readiness, materialization + * and deployment. Everything else on the gateway is the unavailable-facts fixture, so the only + * mocked seam is the provider/approval boundary the trust policy allows tests to fake. + * The materialization factory receives a getter for the request scope's abort signal, which the + * real bound operation gets through its binding scope. + */ +function makeProviderGateway( + materializeFactory: ( + currentSignal: () => AbortSignal | undefined, + ) => PlatformRuntimeOperations['materializeAppSource'], +): { + gateway: DeviceRuntimeGateway; + spies: ProviderSpies; +} { + const spies: ProviderSpies = { + inspectFacts: vi.fn(), + bind: vi.fn(), + ensureReady: vi.fn(async () => ({ ...ANDROID_DEVICE, booted: true })), + materializeAppSource: vi.fn(materializeFactory(() => spies.scopeSignal)), + deployMaterializedApp: vi.fn(async (): Promise => ({ + packageName: 'com.example.app', + appName: 'Example App', + launchTarget: 'com.example.app', + })), + scopeSignal: undefined, + }; + const admittedFacts = (device: DeviceInfo) => { + const base = createUnavailableRuntimeFactsForTest(device, localRuntimeOwner(device.platform)); + const available = { available: true as const }; + return { + ...base, + operations: { + ...base.operations, + ensureReady: available, + materializeAppSource: available, + deployMaterializedApp: available, + }, + }; + }; + const gateway: DeviceRuntimeGateway = { + inspectFacts: async (device) => { + spies.inspectFacts(device); + return admittedFacts(device); + }, + bind: async (request) => { + const { device, scope } = request; + spies.bind(request); + spies.scopeSignal = scope.signal; + return { + device, + owner: localRuntimeOwner(device.platform), + facts: admittedFacts(device), + operations: { + ensureReady: spies.ensureReady, + materializeAppSource: spies.materializeAppSource, + deployMaterializedApp: spies.deployMaterializedApp, + }, + [Symbol.asyncDispose]: async () => {}, + }; + }, + shutdown: async () => {}, + }; + return { gateway, spies }; +} + +/** A real request router over a session bound to the fixture Android device. */ +function makeRouterHarness(gateway: DeviceRuntimeGateway) { + const sessionStore = makeSessionStore('agent-device-install-source-deadline-'); + sessionStore.publish('default', { + name: 'default', + createdAt: START_MS, + actions: [], + device: ANDROID_DEVICE, + }); + const handler = createRequestHandler({ + host: createTestHostEnvironment(), + createCommandSurface: fakeCreateCommandSurface, + logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'), + token: TOKEN, + sessionStore, + leaseRegistry: new LeaseRegistry(), + deviceInventoryGateways: createTestDeviceInventoryGateways(), + trackDownloadableArtifact: () => 'artifact-id', + deviceRuntimeGateway: gateway, + }); + return { sessionStore, handler }; +} + +/** A provider materialization that observes the request signal, as a real bound operation does. */ +function abortOnSignalMaterialize( + currentSignal: () => AbortSignal | undefined, +): PlatformRuntimeOperations['materializeAppSource'] { + const op: PlatformRuntimeOperations['materializeAppSource'] = (_input) => + new Promise((_resolve, reject) => { + const signal = currentSignal(); + assert.ok(signal, 'the bound materialization must receive the request signal'); + if (signal.aborted) reject(signal.reason); + else signal.addEventListener('abort', () => reject(signal.reason), { once: true }); + }); + return op; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +test('loopback RPC install_source enforces the 570s daemon deadline with a typed error and releases the request', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { gateway, spies } = makeProviderGateway((getSignal) => + abortOnSignalMaterialize(getSignal), + ); + const harness = makeRouterHarness(gateway); + + const { port, server } = await startRpcServer(TOKEN, harness.handler); + try { + vi.useFakeTimers(); + vi.setSystemTime(START_MS); + const requestId = 'req-install-source-570-timeout'; + const answer = postRpc(port, installSourceRpcBody(requestId)); + await waitFor( + () => spies.materializeAppSource.mock.calls.length > 0, + 'the provider materialization to start', + ); + + // One millisecond before the deadline there is still no answer. + await vi.advanceTimersByTimeAsync(SOURCE_DEADLINE_MS - 1); + assert.equal(await answeredYet(answer), false, 'answered before the 570s deadline'); + + // At exactly 570s from admission the router's deadline owner expires the request. + await vi.advanceTimersByTimeAsync(1); + const { status, body } = await withRealGuard(answer); + assert.equal(status, 500); + assert.equal(body.error.data.code, 'COMMAND_FAILED'); + assert.equal(body.error.data.details.reason, 'daemon_request_timeout'); + assert.equal(body.error.data.details.timeoutMs, SOURCE_DEADLINE_MS); + assert.equal(body.error.data.details.requestId, requestId); + assert.equal(body.result, undefined, 'no success result on the wire'); + assert.equal( + spies.deployMaterializedApp.mock.calls.length, + 0, + 'deployment must not run after the timeout', + ); + assert.equal( + getRequestSignal(requestId), + undefined, + 'the request registration must be released once the answer is on the wire', + ); + } finally { + await closeLoopbackServer(server); + vi.useRealTimers(); + } +}); + +test('an install_source whose work crosses the 570s cutoff mid-task gets the typed error, no success, and artifact cleanup', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const cleanupSpy = vi.fn(async () => {}); + let releaseMaterialization!: (value: MaterializedAppSource) => void; + const materialization = new Promise((resolve) => { + releaseMaterialization = resolve; + }); + // Materialization succeeds just before the cutoff; the provider's deployment observes the + // request signal, so the work that crosses the cutoff is aborted, not delivered. + let signalGetter: () => AbortSignal | undefined = () => undefined; + const { gateway, spies } = makeProviderGateway((getSignal) => { + signalGetter = getSignal; + return () => materialization; + }); + // The binding reads the spy at bind time, so replacing it before the request installs the + // signal-observing deployment on the provider seam. + spies.deployMaterializedApp = vi.fn( + () => + new Promise((_resolve, reject) => { + const signal = signalGetter(); + assert.ok(signal, 'the bound deployment must receive the request signal'); + if (signal.aborted) reject(signal.reason); + else signal.addEventListener('abort', () => reject(signal.reason), { once: true }); + }), + ); + const { handler } = makeRouterHarness(gateway); + + const { port, server } = await startRpcServer(TOKEN, handler); + try { + vi.useFakeTimers(); + vi.setSystemTime(START_MS); + const requestId = 'req-install-source-crosses-cutoff'; + const answer = postRpc(port, installSourceRpcBody(requestId)); + await waitFor( + () => spies.materializeAppSource.mock.calls.length > 0, + 'the provider materialization to start', + ); + + // Materialize completes 10s before the deadline; deployment then blocks on the signal. + await vi.advanceTimersByTimeAsync(SOURCE_DEADLINE_MS - 10_000); + releaseMaterialization({ installablePath: '/tmp/materialized/app.apk', cleanup: cleanupSpy }); + await flushIO(); + await waitFor(() => spies.deployMaterializedApp.mock.calls.length > 0, 'deployment to start'); + assert.equal(await answeredYet(answer), false, 'no answer before the 570s deadline'); + + await vi.advanceTimersByTimeAsync(10_000); + const { status, body } = await withRealGuard(answer); + assert.equal(status, 500); + assert.equal(body.error?.data?.details?.reason, 'daemon_request_timeout'); + assert.equal(body.error?.data?.details?.timeoutMs, SOURCE_DEADLINE_MS); + assert.equal(body.result, undefined, 'no late success on the wire'); + assert.equal( + cleanupSpy.mock.calls.length, + 1, + 'the materialized artifact is cleaned up after the cutoff', + ); + assert.equal(getRequestSignal(requestId), undefined, 'registration released after the answer'); + } finally { + await closeLoopbackServer(server); + vi.useRealTimers(); + } +}); + +test('streaming install_source sends response headers first and still answers the 570s expiry in-stream with cleanup', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { gateway, spies } = makeProviderGateway((getSignal) => { + const op = abortOnSignalMaterialize(getSignal); + // A real source download reports progress while it runs; the first progress write is what + // flushes the stream's response headers to the client before the handler's work finishes. + const wrapped: PlatformRuntimeOperations['materializeAppSource'] = (input) => { + emitRequestProgress({ type: 'command', status: 'progress', message: 'downloading app.zip' }); + return op(input); + }; + return wrapped; + }); + const { handler } = makeRouterHarness(gateway); + + const { port, server } = await startRpcServer(TOKEN, handler); + try { + vi.useFakeTimers(); + vi.setSystemTime(START_MS); + const requestId = 'req-install-source-stream-timeout'; + const stream = postRpcStream( + port, + installSourceRpcBody(requestId, { requestProgress: 'command' }), + ); + await waitFor( + () => spies.materializeAppSource.mock.calls.length > 0, + 'the provider materialization to start', + ); + + // The streaming route writes its response headers before the handler's work finishes. + const headers = await withRealGuard(stream.headersReceived); + assert.equal(headers.status, 200); + assert.match(String(headers.contentType), /application\/x-ndjson/); + + await vi.advanceTimersByTimeAsync(SOURCE_DEADLINE_MS); + const { bodyText } = await withRealGuard(stream.bodyDone); + const envelopes = bodyText + .trim() + .split('\n') + .map((line) => JSON.parse(line) as Record); + const final = envelopes.at(-1); + assert.equal(final?.type, 'response'); + assert.equal(final.response.error.data.details.reason, 'daemon_request_timeout'); + assert.equal(final.response.error.data.details.timeoutMs, SOURCE_DEADLINE_MS); + assert.equal(final.response.result, undefined); + assert.equal( + getRequestSignal(requestId), + undefined, + 'the lifetime is released after the streamed answer, even with headers already sent', + ); + } finally { + await closeLoopbackServer(server); + vi.useRealTimers(); + } +}); + +test('an install_source whose earlier registered result deadline already passed is refused before task entry', async () => { + vi.useFakeTimers(); + vi.setSystemTime(START_MS); + const { gateway, spies } = makeProviderGateway(() => async () => ({ + installablePath: '/tmp/materialized/app.apk', + cleanup: async () => {}, + })); + const { handler } = makeRouterHarness(gateway); + const requestId = 'req-install-source-expired-at-admission'; + // The admitting transport's own registration (beginRpcRequestLifetime.admit), standing for a + // request admitted 570s in the past whose result deadline (admittedAt + 570s) has passed. + const registration = registerRequestAbort(requestId, undefined, { + resultDeadlineMs: START_MS - 1, + }); + try { + await vi.advanceTimersByTimeAsync(1); + const response = await handler(installSourceRequest(requestId)); + assert.equal(response.ok, false); + if (response.ok) return; + assert.equal(response.error.code, 'COMMAND_FAILED'); + assert.equal(response.error.details?.reason, 'daemon_request_timeout'); + assert.equal(response.error.details?.timeoutMs, 0); + assert.equal( + spies.inspectFacts.mock.calls.length, + 0, + 'fact inspection must not run when entry is refused', + ); + assert.equal( + spies.materializeAppSource.mock.calls.length, + 0, + 'the provider task must not start when entry is refused', + ); + assert.equal(getRequestSignal(requestId)?.aborted, true); + } finally { + clearRequestAbortRegistration(registration); + vi.useRealTimers(); + } +}); + +test('an earlier result deadline aborts a running source install before deployment', async () => { + vi.useFakeTimers(); + vi.setSystemTime(START_MS); + const resultBudgetMs = 60_000; + const { gateway, spies } = makeProviderGateway((getSignal) => + abortOnSignalMaterialize(getSignal), + ); + const { handler } = makeRouterHarness(gateway); + const requestId = 'req-install-source-earlier-caller'; + const registration = registerRequestAbort(requestId, undefined, { + resultDeadlineMs: START_MS + resultBudgetMs, + }); + const answer = handler(installSourceRequest(requestId)); + try { + await waitFor( + () => spies.materializeAppSource.mock.calls.length === 1, + 'the provider materialization to start', + ); + await vi.advanceTimersByTimeAsync(resultBudgetMs - 1); + assert.equal(spies.scopeSignal?.aborted, false, 'work is still admitted before the cutoff'); + + await vi.advanceTimersByTimeAsync(2); + assert.equal( + spies.scopeSignal?.aborted, + true, + 'the earlier result deadline aborts active work', + ); + const response = await withRealGuard(answer); + assert.equal(response.ok, false); + if (response.ok) return; + assert.equal(response.error.details?.reason, 'daemon_request_timeout'); + assert.equal(response.error.details?.timeoutMs, resultBudgetMs); + assert.equal(spies.deployMaterializedApp.mock.calls.length, 0); + } finally { + markRequestCanceled(requestId); + await withRealGuard(answer).catch(() => {}); + clearRequestAbortRegistration(registration); + vi.useRealTimers(); + } +}); + +test('ordinary install_source over loopback RPC succeeds end to end (benign control)', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const cleanupSpy = vi.fn(async () => {}); + const { gateway, spies } = makeProviderGateway(() => async () => ({ + installablePath: '/tmp/materialized/app.apk', + cleanup: cleanupSpy, + })); + const { handler } = makeRouterHarness(gateway); + const { port, server } = await startRpcServer(TOKEN, handler); + try { + const requestId = 'req-install-source-ok'; + const { status, body } = await postRpc(port, installSourceRpcBody(requestId)); + assert.equal(status, 200); + assert.equal(body.error, undefined); + assert.equal(body.result.ok, true); + assert.equal(body.result.data.packageName, 'com.example.app'); + assert.equal(body.result.data.launchTarget, 'com.example.app'); + assert.equal(spies.materializeAppSource.mock.calls.length, 1); + assert.equal(spies.deployMaterializedApp.mock.calls.length, 1); + assert.equal(cleanupSpy.mock.calls.length, 1); + assert.equal(getRequestSignal(requestId), undefined); + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/packages/host-kit/src/internal/request-cancel.test.ts b/packages/host-kit/src/internal/request-cancel.test.ts index 476c37d579..4268b06bc1 100644 --- a/packages/host-kit/src/internal/request-cancel.test.ts +++ b/packages/host-kit/src/internal/request-cancel.test.ts @@ -533,23 +533,24 @@ test('synchronous execution admission does not adopt a transport result deadline } }); -test('an existing execution owner keeps its cutoff when a transport result cutoff passes first', async () => { +test('an armed request enforces an earlier result cutoff before timer delivery', async () => { vi.useFakeTimers(); - const requestId = 'execution-before-result-adoption'; - const startedAt = Date.now(); - const registration = registerRequestAbort(requestId, undefined, { - resultDeadlineMs: startedAt + 25, - }); + const requestId = 'armed-result-cutoff'; + const resultDeadlineMs = Date.now() + 25; + const registration = registerRequestAbort(requestId, undefined, { resultDeadlineMs }); try { - const result = await withRequestDeadline(requestId, 100, async () => { - vi.setSystemTime(startedAt + 25); - throwIfRequestExecutionDeadlineExceeded(requestId); - assert.equal(getRequestSignal(requestId)?.aborted, false); - assert.equal(getRequestExecutionDeadlineMs(requestId), startedAt + 100); - return { ok: true }; - }); - assert.equal(result.ok, true); - assert.equal(getRequestSignal(requestId)?.aborted, false); + await assert.rejects( + withRequestDeadline(requestId, 100, async () => { + assert.equal(getRequestExecutionDeadlineMs(requestId), resultDeadlineMs); + vi.setSystemTime(resultDeadlineMs); + assert.equal(getRequestSignal(requestId)?.aborted, false); + throwIfRequestExecutionDeadlineExceeded(requestId); + assert.fail('the result cutoff admitted work'); + }), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'daemon_request_timeout', + ); + assert.equal(getRequestSignal(requestId)?.aborted, true); assert.equal(vi.getTimerCount(), 0); } finally { clearRequestAbortRegistration(registration); @@ -762,3 +763,82 @@ test.each([false, true])( } }, ); + +// #4441 (decision 6856998913): withRequestDeadline honors any earlier registered +// execution/result deadline at admission — a source-install request whose result deadline +// (registered by the admitting transport) already passed is refused before task entry. +test('withRequestDeadline refuses task entry when an earlier registered result deadline already expired', async () => { + vi.useFakeTimers(); + const requestId = 'expired-result-deadline-at-entry'; + const registration = registerRequestAbort(requestId, undefined, { + resultDeadlineMs: Date.now() - 1, + }); + try { + let entered = false; + await assert.rejects( + withRequestDeadline(requestId, 570_000, async () => { + entered = true; + return { ok: true }; + }), + (error: unknown) => + error instanceof AppError && + error.details?.reason === 'daemon_request_timeout' && + error.details.timeoutMs === 0 && + error.details.requestId === requestId, + ); + assert.equal(entered, false, 'the expired request entered its task'); + assert.equal(getRequestSignal(requestId)?.aborted, true); + assert.equal(vi.getTimerCount(), 0); + } finally { + clearRequestAbortRegistration(registration); + vi.useRealTimers(); + } +}); + +test('withRequestDeadline admits task entry while an earlier result deadline is still live', async () => { + vi.useFakeTimers(); + const requestId = 'live-result-deadline-at-entry'; + const registration = registerRequestAbort(requestId, undefined, { + resultDeadlineMs: Date.now() + 60_000, + }); + try { + let entered = false; + const result = await withRequestDeadline(requestId, 570_000, async () => { + entered = true; + return { ok: true }; + }); + assert.equal(entered, true); + assert.equal(result.ok, true); + assert.equal(getRequestSignal(requestId)?.aborted, false); + assert.equal(vi.getTimerCount(), 0); + } finally { + clearRequestAbortRegistration(registration); + vi.useRealTimers(); + } +}); + +test('an already-expired result deadline does not relabel an earlier explicit cancellation', async () => { + vi.useFakeTimers(); + const requestId = 'canceled-before-result-deadline-entry'; + const registration = registerRequestAbort(requestId, undefined, { + resultDeadlineMs: Date.now() - 1, + }); + try { + markRequestCanceled(requestId); + let entered = false; + await assert.rejects( + withRequestDeadline(requestId, 570_000, async () => { + entered = true; + return { ok: true }; + }), + (error: unknown) => + isRequestCanceledError(error) && + (error as AppError).details?.reason === 'request_canceled' && + (error as AppError).details?.timeoutMs === undefined, + ); + assert.equal(entered, false); + } finally { + clearRequestAbortRegistration(registration); + vi.useRealTimers(); + } +}); diff --git a/packages/host-kit/src/internal/request-cancel.ts b/packages/host-kit/src/internal/request-cancel.ts index 29a6d63163..70381a7c7e 100644 --- a/packages/host-kit/src/internal/request-cancel.ts +++ b/packages/host-kit/src/internal/request-cancel.ts @@ -290,11 +290,16 @@ export async function withRequestDeadline( : registerRequestAbort(requestId); const controller = requestAbortControllers().get(requestId)!; if (ownedRegistration) controller.deadlineRegistration = ownedRegistration; - const deadlineMs = Date.now() + timeoutMs; + const startedAtMs = Date.now(); + const deadlineMs = Math.min( + startedAtMs + timeoutMs, + controller.resultDeadlineMs ?? Number.POSITIVE_INFINITY, + ); const expire = () => { if (controller.signal.aborted) return; - controller.executionDeadlineCancellation = { timeoutMs, requestId }; - controller.abort(createRequestCanceledError({ timeoutMs, requestId })); + const cancellation = { timeoutMs: Math.max(0, deadlineMs - startedAtMs), requestId }; + controller.executionDeadlineCancellation = cancellation; + controller.abort(createRequestCanceledError(cancellation)); }; const ownedDeadline = { deadlineMs, expire }; const deadlines = (controller.executionDeadlines ??= new Set()); diff --git a/src/__tests__/command-descriptor-timeout-policy.test.ts b/src/__tests__/command-descriptor-timeout-policy.test.ts index aee2e26c7a..5a8aa033b6 100644 --- a/src/__tests__/command-descriptor-timeout-policy.test.ts +++ b/src/__tests__/command-descriptor-timeout-policy.test.ts @@ -13,8 +13,11 @@ import { import { OVERLAY_BUDGET_MS } from '@agent-device/capture-kit/recording-overlay'; import { DEFAULT_TIMEOUT_POLICY, + INSTALL_SOURCE_DAEMON_DEADLINE_MS, + INSTALL_SOURCE_REQUEST_TIMEOUT_MS, MAX_ARMABLE_ALERT_WAIT_WINDOW_MS, resolveCommandDaemonBudgetMs, + resolveCommandDaemonTimeoutMs, resolveCommandRequestTimeoutMs, } from '@agent-device/command-registry/timeout-policy'; @@ -164,6 +167,42 @@ test('request envelopes deviating from the default are bounded, reviewed sets', } }); +// #4441 (decision 6856998913): both source-install commands carry the one source-install +// timeout policy — a 600 s client envelope with a 570 s daemon deadline derived from the +// 30 s result margin — enforced through the descriptor/request-router path. +test('install-from-source and install_source share the one source-install timeout policy', () => { + const base = { positionals: [] as string[], flags: {} }; + assert.equal(INSTALL_SOURCE_REQUEST_TIMEOUT_MS, 600_000); + assert.equal(INSTALL_SOURCE_DAEMON_DEADLINE_MS, 570_000); + assert.equal(INSTALL_SOURCE_REQUEST_TIMEOUT_MS - INSTALL_SOURCE_DAEMON_DEADLINE_MS, 30_000); + for (const command of ['install-from-source', 'install_source']) { + const policy = resolveCommandTimeoutPolicy(command); + assert.equal(policy.envelopeMs, INSTALL_SOURCE_REQUEST_TIMEOUT_MS, command); + assert.equal( + resolveCommandDaemonTimeoutMs(policy, base), + INSTALL_SOURCE_DAEMON_DEADLINE_MS, + command, + ); + assert.equal( + resolveCommandDaemonBudgetMs(policy, base), + INSTALL_SOURCE_DAEMON_DEADLINE_MS, + command, + ); + assert.equal(resolveCommandRequestTimeoutMs(policy, base), 600_000, command); + assert.equal(policy.onTimeout, 'reset-daemon', command); + } + // The normal install route keeps its own ledger-proven envelope and no daemon deadline. + for (const command of ['install', 'reinstall', 'uninstall']) { + const policy = resolveCommandTimeoutPolicy(command); + assert.equal(policy.envelopeMs, 480_000, command); + assert.equal(resolveCommandDaemonTimeoutMs(policy, base), undefined, command); + } + // Unrelated commands keep the default policy untouched. + const fallback = resolveCommandTimeoutPolicy('snapshot'); + assert.equal(fallback.envelopeMs, 90_000); + assert.equal(resolveCommandDaemonTimeoutMs(fallback, base), undefined); +}); + test('commands outside the registry fall back to the explicit default policy', () => { // Matches the deleted hand lists: not listed meant default envelope and a // daemon reset on timeout.