From b4190b95bea74b06b5403f00df0a57541b9c3f06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 19:01:40 +0100 Subject: [PATCH 1/9] fix(daemon): cancel artifact preparation on client disconnect --- .../src/resources/artifact-tracking.test.ts | 82 +++++++++++++ .../daemon/src/resources/artifact-tracking.ts | 15 ++- .../request-diagnostics-http.test.ts | 31 ++++- .../server/downloadable-artifact-http.test.ts | 112 +++++++++++------- .../src/server/downloadable-artifact-http.ts | 24 ++-- packages/daemon/src/server/http-errors.ts | 11 +- .../src/server/request-diagnostics-http.ts | 2 +- website/docs/docs/remote-proxy.md | 3 + 8 files changed, 214 insertions(+), 66 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 84a3170300..f5c8273d83 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -84,6 +84,88 @@ test('cancelling the archive builder preserves a second download waiting for its } }); +test.each(['deadline-aborted', 'failed'] as const)( + 'a live artifact starts a fresh archive while a %s build is settling', + async (failure) => { + const root = mkdtempForTestSync('fu-art-retry-build-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + const expected = Buffer.from('fresh archive payload'); + fs.writeFileSync(path.join(artifactPath, 'payload'), expected); + const runtime = createRuntimeStateHandle(); + let finishAborted!: () => void; + const settling = new Promise((resolve) => { + finishAborted = resolve; + }); + let aborted!: () => void; + const cancelled = new Promise((resolve) => { + aborted = resolve; + }); + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + if (failure === 'failed') throw new Error('tar failed'); + args[2]?.signal?.addEventListener('abort', aborted, { once: true }); + await settling; + return await runCmd(...args); + }); + const openings: Array> = []; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const timers = vi.spyOn(globalThis, 'setTimeout'); + const first = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(first); + void first.catch(() => {}); + const deadline = timers.mock.calls.find(([, delay]) => delay === 15 * 60 * 1000)?.[0]; + timers.mockRestore(); + if (failure === 'deadline-aborted') { + expect(deadline).toBeTypeOf('function'); + runtime.run(() => deadline!()); + await cancelled; + } else { + await Promise.resolve(); + } + const second = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(second); + void second.catch(() => {}); + finishAborted(); + await expect(first).rejects.toMatchObject( + failure === 'deadline-aborted' + ? { details: { reason: 'RESOURCE_EXPIRED' } } + : { + code: 'COMMAND_FAILED', + message: `Failed to archive downloadable artifact: ${artifactPath}`, + }, + ); + const download = await second; + const closed = once(download.stream, 'close'); + const bytes = await buffer(download.stream); + await closed; + download.release(); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + expect(archive).toHaveBeenCalledTimes(2); + runtime.run(() => cleanupDownloadableArtifact(id)); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(path.dirname(String(download.stream.path)))).toBe(false); + } finally { + finishAborted(); + for (const result of await Promise.allSettled(openings)) { + if (result.status !== 'fulfilled') continue; + const download = result.value; + if (!download.stream.closed) { + const closed = once(download.stream, 'close'); + download.stream.destroy(); + await closed; + } + download.release(); + } + runtime.dispose(); + archive.mockRestore(); + } + }, +); + test('disposing every archive waiter aborts the shared build and removes its temporary directory', async () => { const root = mkdtempForTestSync('fu-art-cancel-all-'); const artifactPath = path.join(root, 'capture.trace'); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 4bc868a76f..db2602efc1 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -176,7 +176,9 @@ export async function openDownloadableArtifact( artifactId: string, tenantId: string | undefined, hostEnv: NodeJS.ProcessEnv, + signal?: AbortSignal, ): Promise { + signal?.throwIfAborted(); const artifacts = pendingArtifacts(); const { entry, stat } = readDownloadableArtifactEntry(artifactId, tenantId); const download: ArtifactDownload = { @@ -184,6 +186,7 @@ export async function openDownloadableArtifact( release: () => { if (!entry.activeDownloads.delete(download)) return; clearTimeout(deadline); + signal?.removeEventListener('abort', cancel); if (entry.cleanupRequested) requestArtifactCleanup(artifacts, artifactId, entry); }, }; @@ -193,7 +196,11 @@ export async function openDownloadableArtifact( ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS, ); deadline.unref(); + const cancel = () => cancelArtifactDownload(artifactId, entry, download, signal?.reason); + signal?.addEventListener('abort', cancel, { once: true }); + if (signal?.aborted) cancel(); try { + download.controller.signal.throwIfAborted(); const payload = await prepareArtifactPayload(artifactId, entry, stat, hostEnv); download.controller.signal.throwIfAborted(); if (!payload) { @@ -215,9 +222,9 @@ function cancelArtifactDownload( artifactId: string, entry: ArtifactEntry, download: ArtifactDownload, + reason: unknown = expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId), ): void { if (!entry.activeDownloads.has(download)) return; - const reason = expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); download.controller.abort(reason); if (!download.stream) { if ([...entry.activeDownloads].every(({ controller }) => controller.signal.aborted)) { @@ -331,7 +338,7 @@ async function ensureDirectoryArchive( if (entry.directoryArchive && fs.existsSync(entry.directoryArchive.archivePath)) { return entry.directoryArchive; } - if (entry.directoryArchivePromise) { + if (entry.directoryArchivePromise && entry.archiveAbortController?.signal.aborted === false) { return await entry.directoryArchivePromise; } @@ -391,10 +398,6 @@ async function createDirectoryArchive( fileName, sizeBytes: fs.statSync(archivePath).size, }; - // Inventory can expire while tar is still archiving. - if (entry.cleanupRequested && entry.activeDownloads.size === 0) { - throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); - } entry.directoryArchive = archive; return archive; } catch (error) { diff --git a/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts b/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts index d8a9352e83..6d61ece741 100644 --- a/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts +++ b/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts @@ -1,6 +1,6 @@ import { resolveSessionRequestLogPath } from '@agent-device/daemon-contracts/session-artifact-paths'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { test } from 'vitest'; +import { expect, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import http from 'node:http'; @@ -94,6 +94,35 @@ test('request diagnostics route serves one record as ndjson to an authorized cal }); }); +test('request diagnostics returns complete JSON when its stream fails before headers', async () => { + await withDiagnosticsServer(async ({ baseUrl, sessionsDir }) => { + writeRecord(sessionsDir, 'default', 'abc123'); + const createReadStream = fs.createReadStream; + const streams = vi.spyOn(fs, 'createReadStream').mockImplementation((file, options) => + createReadStream(file, { + ...(typeof options === 'object' ? options : {}), + fs: { + ...fs, + open: (_file, _flags, _mode, callback) => callback(new Error('record read failed')), + }, + }), + ); + let response: Response | undefined; + try { + response = await fetch(diagnosticsUrl(baseUrl, 'default', 'abc123'), { + headers: { authorization: 'Bearer daemon-secret' }, + }); + expect(response.status).toBe(500); + expect(response.headers.get('content-type')).toBe('application/json'); + expect(response.headers.get('content-length')).toBeNull(); + expect(await response.json()).toMatchObject({ ok: false, error: 'record read failed' }); + } finally { + await response?.body?.cancel().catch(() => {}); + streams.mockRestore(); + } + }); +}); + test('request diagnostics route refuses an unauthenticated caller', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts index aa8e14bccc..047d1ab43a 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.test.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -28,6 +28,7 @@ type DownloadFixture = { failResponse(): void; outcome(): 'pending' | 'complete' | 'failed'; cleanupCount(): number; + closedResponses(): number; expire(): void; expiryPending(): boolean; fireDeadlines(): void; @@ -52,8 +53,10 @@ async function withDownloadFixture( ); const port = await listenOnLoopback(server); let activeResponse: http.ServerResponse | undefined; + let closedResponses = 0; server.on('request', (_request, response) => { activeResponse = response; + response.once('close', () => closedResponses++); }); const timers = vi.spyOn(globalThis, 'setTimeout'); const clearedTimers = vi.spyOn(globalThis, 'clearTimeout'); @@ -107,6 +110,7 @@ async function withDownloadFixture( abortClient: () => request?.destroy(), failResponse: () => activeResponse?.destroy(new Error('injected response failure')), outcome: () => outcome, + closedResponses: () => closedResponses, cleanupCount: () => removed.mock.calls.filter(([target]) => target === source).length, expire: () => runtime.run(expire), expiryPending: () => !clearedTimers.mock.calls.some(([timer]) => timer === expiryTimer), @@ -140,49 +144,71 @@ async function withDownloadFixture( } } -test('a client abort during a shared archive build preserves the other HTTP download', async () => { - const started = deferred(); - const proceed = deferred(); - const runCmd = command.runCmd; - const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { - started.resolve(); - await proceed.promise; - return await runCmd(...args); - }); - const opens = vi.spyOn(artifactTracking, 'openDownloadableArtifact'); - try { - await withDownloadFixture( - async (fixture) => { - const expected = fs.readFileSync(path.join(fixture.source, 'payload')); - fixture.start(); - await started.promise; - const second = fetch(fixture.url, { headers: { authorization: 'Bearer fu-art-secret' } }); - void second.catch(() => {}); - try { - await vi.waitFor(() => expect(opens).toHaveBeenCalledTimes(2)); - fixture.abortClient(); - await vi.waitFor(() => expect(fixture.outcome()).toBe('failed')); - proceed.resolve(); - const response = await second; - expect(response.status).toBe(200); - const bytes = Buffer.from(await response.arrayBuffer()); - expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); - expect(gunzipSync(bytes).includes(expected)).toBe(true); - expect(archive).toHaveBeenCalledTimes(1); - await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); - } finally { - proceed.resolve(); - await Promise.allSettled([second]); - } - }, - () => {}, - ); - } finally { - proceed.resolve(); - opens.mockRestore(); - archive.mockRestore(); - } -}); +test.each(['lone', 'shared'] as const)( + 'a client abort cancels its preparation during a %s archive build', + async (kind) => { + const started = deferred(); + const proceed = deferred(); + let archiveSignal: AbortSignal | undefined; + let archiveDir = ''; + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + archiveSignal = args[2]?.signal; + archiveDir = path.dirname(String(args[1]?.[1])); + started.resolve(); + await proceed.promise; + return await runCmd(...args); + }); + try { + await withDownloadFixture( + async (fixture) => { + const expected = fs.readFileSync(path.join(fixture.source, 'payload')); + const statSync = fs.statSync; + let admissions = 0; + const stats = vi.spyOn(fs, 'statSync').mockImplementation((...args) => { + if (args[0] === fixture.source) admissions++; + return statSync(...args); + }); + let second: Promise | undefined; + try { + fixture.start(); + await started.promise; + if (kind === 'shared') { + second = fetch(fixture.url, { headers: { authorization: 'Bearer fu-art-secret' } }); + void second.catch(() => {}); + await vi.waitFor(() => expect(admissions).toBe(2)); + } + fixture.abortClient(); + await vi.waitFor(() => expect(fixture.closedResponses()).toBe(1)); + expect(archiveSignal?.aborted).toBe(kind === 'lone'); + proceed.resolve(); + if (second) { + const response = await second; + expect(response.status).toBe(200); + const bytes = Buffer.from(await response.arrayBuffer()); + expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + } else { + await vi.waitFor(() => expect(fs.existsSync(archiveDir)).toBe(false)); + expect(fs.existsSync(fixture.source)).toBe(true); + } + expect(fixture.streams).toHaveLength(kind === 'shared' ? 1 : 0); + expect(archive).toHaveBeenCalledTimes(1); + } finally { + proceed.resolve(); + await Promise.allSettled(second ? [second] : []); + stats.mockRestore(); + } + }, + () => {}, + ); + } finally { + proceed.resolve(); + archive.mockRestore(); + } + }, +); test.each(['destroyed', 'truncated', 'errored'] as const)( 'a %s artifact read terminates the HTTP response', diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index c6b4238783..3fea5b63cf 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -9,7 +9,7 @@ import { listDownloadableArtifacts, openDownloadableArtifact, } from '../resources/artifact-tracking.ts'; -import { sendRestJsonError } from './http-errors.ts'; +import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts'; import { decodeUriSegment } from './http-request-target.ts'; type DownloadableArtifactHttpRoute = @@ -83,6 +83,10 @@ async function handleArtifactDownload( return; } + const controller = new AbortController(); + const cancel = () => controller.abort(); + res.once('close', cancel); + if (res.destroyed) cancel(); try { const auth = await authorize({ req, @@ -94,7 +98,12 @@ async function handleArtifactDownload( }); if (!auth) return; - const artifact = await openDownloadableArtifact(artifactId, auth.tenantId, options.hostEnv); + const artifact = await openDownloadableArtifact( + artifactId, + auth.tenantId, + options.hostEnv, + controller.signal, + ); const { stream } = artifact; const closed = finished(stream, { cleanup: true }).catch(() => {}); try { @@ -141,14 +150,9 @@ async function handleArtifactDownload( artifact.release(); } } catch (error) { - if (res.destroyed) return; - if (res.headersSent) { - res.destroy(error instanceof Error ? error : undefined); - return; - } - res.removeHeader('content-length'); - res.removeHeader('content-disposition'); - sendRestJsonError(res, normalizeError(error)); + failStreamedHttpResponse(res, error); + } finally { + res.removeListener('close', cancel); } } diff --git a/packages/daemon/src/server/http-errors.ts b/packages/daemon/src/server/http-errors.ts index 60c264aba0..ea1726178f 100644 --- a/packages/daemon/src/server/http-errors.ts +++ b/packages/daemon/src/server/http-errors.ts @@ -50,12 +50,13 @@ export function sendRestJsonError(res: http.ServerResponse, normalized: Normaliz * destroying the connection, so the client sees a truncated body rather than a * complete one. */ -export function failStreamedHttpResponse(res: http.ServerResponse, error: Error): void { +export function failStreamedHttpResponse(res: http.ServerResponse, error: unknown): void { + if (res.destroyed) return; if (res.headersSent) { - res.destroy(error); + res.destroy(error instanceof Error ? error : undefined); return; } - const normalized = normalizeError(error); - res.statusCode = statusCodeForNormalizedError(normalized); - res.end(normalized.message); + res.removeHeader('content-length'); + res.removeHeader('content-disposition'); + sendRestJsonError(res, normalizeError(error)); } diff --git a/packages/daemon/src/server/request-diagnostics-http.ts b/packages/daemon/src/server/request-diagnostics-http.ts index 4261cc4922..84540ad98d 100644 --- a/packages/daemon/src/server/request-diagnostics-http.ts +++ b/packages/daemon/src/server/request-diagnostics-http.ts @@ -161,7 +161,7 @@ async function handleRequestDiagnostics( }); stream.pipe(res); } catch (error) { - sendRestJsonError(res, normalizeError(error)); + failStreamedHttpResponse(res, error); } } diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 43d3a764f6..4f7819c217 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -90,6 +90,9 @@ destination on your machine. Direct RPC callers receive artifact IDs and downloa By default, artifacts leave the inventory after download or after 15 minutes. `AGENT_DEVICE_RETAIN_ARTIFACTS` keeps downloaded artifacts in inventory until expiry. Downloads already in progress can finish before their files are removed, including overlapping downloads of a directory archive. +Closing the HTTP connection cancels that download, including directory archive preparation. +Other downloads waiting for the same archive can still finish. You can retry a cancelled download +while the artifact remains in inventory. Each download has a 15-minute maximum lifetime. When it reaches that limit, the daemon cancels it and cleans up after its pipeline stops. From 3e079476de2a84b55c8544802a884cbbecd851f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 19:06:54 +0100 Subject: [PATCH 2/9] chore(gates): acknowledge compatible artifact HTTP lifecycle fixes --- test/wire-compat/ledger.json | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index cb7b48b017..38b96e24f1 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,20 +71,20 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:df174d1ccf73851ca58bd75533fb4660424003b98bd9e41fe942cf3ab3698e5f", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:54b5a8817237d38502f8ae56d8e754217c811520110deb3f2637264e68534f98", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:ac4268cba9ffdfee7e92429b1a49e48570154d735eed62bfca36d1e2759cec43", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", "packages/daemon/src/server/downloadable-artifact-http.ts#resolveDownloadableArtifactHttpRoute": "sha256:9fcdc9619e8d378e8f04ef7b3584863af446e855702ddce83a16ec194a6d98af", "packages/daemon/src/server/http-errors.ts#NormalizedHttpError": "sha256:2c2111802fe5f193acbeacc454de9cfab82bc8e4274b896f485e19a14f5518cf", - "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse": "sha256:e4f4dbb80a2213395220dfe448ff4453cc0402a755a66fe4203a7adf6fda4948", + "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse": "sha256:3e6b642cb41b88ab1e6f3269ebd14918f912cbecf09f40e9b591fdd28a2ba489", "packages/daemon/src/server/http-errors.ts#sendRestJsonError": "sha256:aef588e77ea73eb3cf6e94ec2f2c98a434fcaaeb96de6973a43c442b704694ad", "packages/daemon/src/server/http-errors.ts#statusCodeForNormalizedError": "sha256:39aa61eed8459527d7077e31e23be4fe0275021ed99c70ad692538091db91125", "packages/daemon/src/server/http-request-target.ts#decodeUriSegment": "sha256:b37622771ea4e61d1a9820169dbdc5809b5c38889bfad79277d7b22f3c3f1ef1", "packages/daemon/src/server/request-diagnostics-http.ts#REQUEST_DIAGNOSTICS_CONTENT_TYPE": "sha256:16bbd9ae7eaeaaa8c8cbd6e65c4ce786a6c5230c5351288228bbf1a6f11bdcdc", "packages/daemon/src/server/request-diagnostics-http.ts#RequestDiagnosticsHttpAuthorizer": "sha256:24b0fa6b1d965e5cf6503a4665148dc6360c56bf5a0ae710eeaa76a73a62c52a", "packages/daemon/src/server/request-diagnostics-http.ts#RequestDiagnosticsHttpOptions": "sha256:cd2c0dda77d2bc434857aea07206a5491ce5f0b82cb86628569f607d6c2cebcf", - "packages/daemon/src/server/request-diagnostics-http.ts#handleRequestDiagnostics": "sha256:32c3d100176dd99ecbb61f8050d05b1cda64b7be1944a2cd16633e83fa78660b", + "packages/daemon/src/server/request-diagnostics-http.ts#handleRequestDiagnostics": "sha256:08d3fd203cd7e47814cf8c50f710e86bee28ac2818dbf93910ae49725b97468a", "packages/daemon/src/server/request-diagnostics-http.ts#resolveRequestDiagnosticsHttpRoute": "sha256:4ff07623b27a6f7461e1addb87aabd149904da63f7462149ae4114d14336cde0", "packages/daemon-contracts/src/request-progress-protocol.ts#DaemonProgressEnvelope": "sha256:16162d01cfc43fc6a0198dbba3358981c1a278a70f7494ebe70d051f517cfb22", "packages/daemon-contracts/src/request-progress-protocol.ts#DaemonResponseEnvelope": "sha256:202ae64836af890549a1d95963903f9a506294b80bd0862c1b708e72d7f286d0", @@ -257,8 +257,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:54b5a8817237d38502f8ae56d8e754217c811520110deb3f2637264e68534f98", - "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field." + "digest": "sha256:ac4268cba9ffdfee7e92429b1a49e48570154d735eed62bfca36d1e2759cec43", + "rationale": "Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", @@ -297,8 +297,8 @@ }, { "declaration": "packages/daemon/src/server/request-diagnostics-http.ts#handleRequestDiagnostics", - "digest": "sha256:32c3d100176dd99ecbb61f8050d05b1cda64b7be1944a2cd16633e83fa78660b", - "rationale": "#2198 context: asks isTenantAddressableSessionName instead of applying the prefix rule locally. Same UNAUTHORIZED code, same 'Session is outside this tenant' message and same 401 body for the attested-tenant case the rule still refuses; the only difference a peer can observe is that an unattested tenant now gets the 200 + ndjson record it already knows how to read instead of a 401 it could not act on." + "digest": "sha256:08d3fd203cd7e47814cf8c50f710e86bee28ac2818dbf93910ae49725b97468a", + "rationale": "Implementation-only HTTP error repair under ADR 0006: setup failures use the shared streamed failure helper. Before headers, it emits the existing REST JSON error shape with an error status; after headers, it destroys the incomplete transfer. Successful diagnostics remain 200 with the same NDJSON bytes. Released clients reject error statuses before reading diagnostic records, so no successful response parser or request requirement changes." }, { "declaration": "packages/kernel/src/contracts.ts#LEASE_BACKENDS", @@ -497,8 +497,8 @@ }, { "declaration": "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse", - "digest": "sha256:e4f4dbb80a2213395220dfe448ff4453cc0402a755a66fe4203a7adf6fda4948", - "rationale": "Passes the whole normalized error to the details-aware status mapper instead of its code; the plain-text body is unchanged. A gone resource now answers 404 instead of 500: COMMAND_FAILED with details.reason RESOURCE_EXPIRED (an artifact, upload ticket, uploaded artifact or materialized path id the TTL registry no longer holds) maps to 404. The mapper also takes over the DEVICE_IN_USE human_control_active 423 rule, which statusCodeForDaemonError applied only to a failed response a /rpc handler returned. The rule now also reaches the REST routes and thrown /rpc failures, which answered 500: a PUT /admin/leases/ refused during a human-control hold, or a non-streamed /rpc call whose handler throws human_control_active, now answers 423. /admin/* is host-only on the loopback port and the proxy never forwards it, and the host already reads 423 for the same refusal on a returned /rpc failure. No released client branches on 404 versus 500 for these routes: downloadRemoteArtifactFromUrl treats any status >= 400 alike, the upload client fails any non-2xx and decides retries from a typed stream detail rather than the status, the /rpc client parses the JSON-RPC error envelope whatever the status and only special-cases 409, and the proxy passes the status through. The error code, message and JSON-RPC error data a peer parses are unchanged, so a protocol 2 peer reports the same failure it did before." + "digest": "sha256:3e6b642cb41b88ab1e6f3269ebd14918f912cbecf09f40e9b591fdd28a2ba489", + "rationale": "Compatible HTTP error repair under ADR 0006: both streamed routes use the existing REST JSON error shape before headers, removing stale length and attachment headers. Previously a diagnostics stream open failure could retain its successful-response length and leave the error body incomplete. The helper ignores closed responses and still destroys incomplete transfers after headers. Released artifact and diagnostics clients reject non-success status codes before treating a body as downloaded bytes; routes, successful responses and authorization are unchanged, so older peers still fail clearly without a protocol bump." } ] } From 3f1f5c1b215d5ed250cdc5ca1b2c0b79744528e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 19:25:59 +0100 Subject: [PATCH 3/9] fix(daemon): preserve successful artifact download completion --- .../src/resources/artifact-tracking.test.ts | 125 +++++++++++++++++- .../daemon/src/resources/artifact-tracking.ts | 86 +++++++----- .../request-diagnostics-http.test.ts | 4 +- .../server/downloadable-artifact-http.test.ts | 51 +++++-- .../src/server/downloadable-artifact-http.ts | 4 +- 5 files changed, 219 insertions(+), 51 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index f5c8273d83..04fabe5687 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -5,6 +5,7 @@ import { buffer } from 'node:stream/consumers'; import { gunzipSync } from 'node:zlib'; import { expect, test, vi } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { AppError, isRequestCanceledError, normalizeError } from '@agent-device/kernel/errors'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import * as command from '@agent-device/host-kit/command'; import { @@ -84,7 +85,7 @@ test('cancelling the archive builder preserves a second download waiting for its } }); -test.each(['deadline-aborted', 'failed'] as const)( +test.each(['deadline-aborted', 'failed', 'late-aborted'] as const)( 'a live artifact starts a fresh archive while a %s build is settling', async (failure) => { const root = mkdtempForTestSync('fu-art-retry-build-'); @@ -101,10 +102,22 @@ test.each(['deadline-aborted', 'failed'] as const)( const cancelled = new Promise((resolve) => { aborted = resolve; }); + let tarSucceeded!: () => void; + const succeeded = new Promise((resolve) => { + tarSucceeded = resolve; + }); + let firstArchiveDir = ''; const runCmd = command.runCmd; const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + firstArchiveDir = path.dirname(String(args[1]?.[1])); if (failure === 'failed') throw new Error('tar failed'); args[2]?.signal?.addEventListener('abort', aborted, { once: true }); + if (failure === 'late-aborted') { + const result = await runCmd(...args); + tarSucceeded(); + await settling; + return result; + } await settling; return await runCmd(...args); }); @@ -119,7 +132,8 @@ test.each(['deadline-aborted', 'failed'] as const)( void first.catch(() => {}); const deadline = timers.mock.calls.find(([, delay]) => delay === 15 * 60 * 1000)?.[0]; timers.mockRestore(); - if (failure === 'deadline-aborted') { + if (failure !== 'failed') { + if (failure === 'late-aborted') await succeeded; expect(deadline).toBeTypeOf('function'); runtime.run(() => deadline!()); await cancelled; @@ -131,13 +145,14 @@ test.each(['deadline-aborted', 'failed'] as const)( void second.catch(() => {}); finishAborted(); await expect(first).rejects.toMatchObject( - failure === 'deadline-aborted' + failure !== 'failed' ? { details: { reason: 'RESOURCE_EXPIRED' } } : { code: 'COMMAND_FAILED', message: `Failed to archive downloadable artifact: ${artifactPath}`, }, ); + expect(fs.existsSync(firstArchiveDir)).toBe(false); const download = await second; const closed = once(download.stream, 'close'); const bytes = await buffer(download.stream); @@ -145,7 +160,8 @@ test.each(['deadline-aborted', 'failed'] as const)( download.release(); expect(gunzipSync(bytes).includes(expected)).toBe(true); expect(archive).toHaveBeenCalledTimes(2); - runtime.run(() => cleanupDownloadableArtifact(id)); + if (failure === 'late-aborted') runtime.dispose(); + else runtime.run(() => cleanupDownloadableArtifact(id)); expect(fs.existsSync(artifactPath)).toBe(false); expect(fs.existsSync(path.dirname(String(download.stream.path)))).toBe(false); } finally { @@ -166,6 +182,107 @@ test.each(['deadline-aborted', 'failed'] as const)( }, ); +test('an archive setup failure does not poison a simultaneous retry', async () => { + const root = mkdtempForTestSync('fu-art-setup-retry-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'retry after setup failure'); + const runtime = createRuntimeStateHandle(); + const directories = vi.spyOn(fs, 'mkdtempSync').mockImplementationOnce(() => { + throw new AppError('COMMAND_FAILED', 'archive setup failed'); + }); + const openings: Array> = []; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const first = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(first); + void first.catch(() => {}); + const second = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + openings.push(second); + void second.catch(() => {}); + await expect(first).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + message: 'archive setup failed', + }); + const download = await second; + const closed = once(download.stream, 'close'); + expect( + gunzipSync(await buffer(download.stream)).includes(Buffer.from('retry after setup failure')), + ).toBe(true); + await closed; + download.release(); + runtime.run(() => cleanupDownloadableArtifact(id)); + expect(fs.existsSync(artifactPath)).toBe(false); + } finally { + for (const result of await Promise.allSettled(openings)) { + if (result.status !== 'fulfilled') continue; + const download = result.value; + if (!download.stream.closed) { + const closed = once(download.stream, 'close'); + download.stream.destroy(); + await closed; + } + download.release(); + } + directories.mockRestore(); + runtime.dispose(); + } +}); + +test.each(['before opening', 'while archiving'] as const)( + 'caller cancellation %s has a typed reason without forwarding caller data', + async (phase) => { + const root = mkdtempForTestSync('fu-art-client-cancel-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'cancelled payload'); + const runtime = createRuntimeStateHandle(); + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + const signal = args[2]!.signal!; + await new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(signal.reason), { once: true }); + }); + throw new Error('aborted tar cannot complete'); + }); + const caller = new AbortController(); + const reason = new AppError('COMMAND_FAILED', 'private caller cancellation data', { + reason: 'RESOURCE_EXPIRED', + }); + let opening: Promise | undefined; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + if (phase === 'before opening') caller.abort(reason); + opening = runtime.run(() => + openDownloadableArtifact(id, undefined, process.env, caller.signal), + ); + void opening.catch(() => {}); + if (phase === 'while archiving') caller.abort(reason); + const error = await opening.catch((error: unknown) => error); + expect(isRequestCanceledError(error)).toBe(true); + const normalized = normalizeError(error); + expect(normalized).toMatchObject({ + code: 'COMMAND_FAILED', + message: 'request canceled', + details: { reason: 'request_canceled' }, + }); + expect(JSON.stringify(normalized)).not.toContain('private caller cancellation data'); + expect(JSON.stringify(normalized)).not.toContain('RESOURCE_EXPIRED'); + expect(fs.existsSync(artifactPath)).toBe(true); + runtime.run(() => cleanupDownloadableArtifact(id)); + expect(fs.existsSync(artifactPath)).toBe(false); + } finally { + caller.abort(); + if (opening) await Promise.allSettled([opening]); + runtime.dispose(); + archive.mockRestore(); + } + }, +); + test('disposing every archive waiter aborts the shared build and removes its temporary directory', async () => { const root = mkdtempForTestSync('fu-art-cancel-all-'); const artifactPath = path.join(root, 'capture.trace'); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index db2602efc1..39064e9152 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -4,7 +4,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { finished } from 'node:stream/promises'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors'; import type { DaemonArtifactType } from '@agent-device/kernel/contracts'; import type { DeviceRotation } from '@agent-device/contracts/device'; import type { DaemonArtifactInventoryEntry } from '@agent-device/contracts/observability'; @@ -34,6 +34,11 @@ type DirectoryArchive = { sizeBytes: number; }; +type DirectoryArchiveBuild = { + promise: Promise; + controller: AbortController; +}; + type ArtifactSourceCleanup = { remainingEntries: number; deleteAfterDownload: boolean; @@ -55,8 +60,7 @@ type ArtifactEntry = { sourceCleanup: ArtifactSourceCleanup; createdAt: number; directoryArchive?: DirectoryArchive; - directoryArchivePromise?: Promise; - archiveAbortController?: AbortController; + directoryArchiveBuild?: DirectoryArchiveBuild; activeDownloads: Set; cleanupRequested: boolean; timer: ReturnType; @@ -178,7 +182,7 @@ export async function openDownloadableArtifact( hostEnv: NodeJS.ProcessEnv, signal?: AbortSignal, ): Promise { - signal?.throwIfAborted(); + if (signal?.aborted) throw createRequestCanceledError(); const artifacts = pendingArtifacts(); const { entry, stat } = readDownloadableArtifactEntry(artifactId, tenantId); const download: ArtifactDownload = { @@ -196,7 +200,8 @@ export async function openDownloadableArtifact( ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS, ); deadline.unref(); - const cancel = () => cancelArtifactDownload(artifactId, entry, download, signal?.reason); + const cancel = () => + cancelArtifactDownload(artifactId, entry, download, createRequestCanceledError()); signal?.addEventListener('abort', cancel, { once: true }); if (signal?.aborted) cancel(); try { @@ -228,7 +233,7 @@ function cancelArtifactDownload( download.controller.abort(reason); if (!download.stream) { if ([...entry.activeDownloads].every(({ controller }) => controller.signal.aborted)) { - entry.archiveAbortController?.abort(reason); + entry.directoryArchiveBuild?.controller.abort(reason); } return; } @@ -338,17 +343,20 @@ async function ensureDirectoryArchive( if (entry.directoryArchive && fs.existsSync(entry.directoryArchive.archivePath)) { return entry.directoryArchive; } - if (entry.directoryArchivePromise && entry.archiveAbortController?.signal.aborted === false) { - return await entry.directoryArchivePromise; + const currentBuild = entry.directoryArchiveBuild; + if (currentBuild && !currentBuild.controller.signal.aborted) { + return await currentBuild.promise; } - const archivePromise = createDirectoryArchive(artifactId, entry, hostEnv); - entry.directoryArchivePromise = archivePromise; + const controller = new AbortController(); + const archivePromise = createDirectoryArchive(artifactId, entry, hostEnv, controller); + const build = { promise: archivePromise, controller }; + entry.directoryArchiveBuild = build; try { return await archivePromise; } finally { - if (entry.directoryArchivePromise === archivePromise) { - entry.directoryArchivePromise = undefined; + if (entry.directoryArchiveBuild === build) { + entry.directoryArchiveBuild = undefined; } } } @@ -357,21 +365,21 @@ async function createDirectoryArchive( artifactId: string, entry: ArtifactEntry, hostEnv: NodeJS.ProcessEnv, + controller: AbortController, ): Promise { - cleanupDirectoryArchive(entry); - - const sourceName = safeArtifactFilename( - entry.fileName, - path.basename(entry.artifactPath) || artifactId, - ); - const fileName = archiveFilename(sourceName); - const tempDir = fs.mkdtempSync( - path.join(os.tmpdir(), `agent-device-download-${crypto.randomUUID()}-`), - ); - const archivePath = path.join(tempDir, fileName); - const controller = new AbortController(); - entry.archiveAbortController = controller; + let tempDir: string | undefined; try { + cleanupDirectoryArchive(entry); + + const sourceName = safeArtifactFilename( + entry.fileName, + path.basename(entry.artifactPath) || artifactId, + ); + const fileName = archiveFilename(sourceName); + tempDir = fs.mkdtempSync( + path.join(os.tmpdir(), `agent-device-download-${crypto.randomUUID()}-`), + ); + const archivePath = path.join(tempDir, fileName); await runCmd( 'tar', [ @@ -401,17 +409,23 @@ async function createDirectoryArchive( entry.directoryArchive = archive; return archive; } catch (error) { - fs.rmSync(tempDir, { recursive: true, force: true }); - if (controller.signal.aborted) throw controller.signal.reason; - if (error instanceof AppError) throw error; - throw new AppError( - 'COMMAND_FAILED', - `Failed to archive downloadable artifact: ${entry.artifactPath}`, - { artifactPath: entry.artifactPath }, - error instanceof Error ? error : undefined, - ); + const failure = controller.signal.aborted + ? controller.signal.reason + : error instanceof AppError + ? error + : new AppError( + 'COMMAND_FAILED', + `Failed to archive downloadable artifact: ${entry.artifactPath}`, + { artifactPath: entry.artifactPath }, + error instanceof Error ? error : undefined, + ); + controller.abort(failure); + if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true }); + throw failure; } finally { - if (entry.archiveAbortController === controller) entry.archiveAbortController = undefined; + if (entry.directoryArchiveBuild?.controller === controller) { + entry.directoryArchiveBuild = undefined; + } } } @@ -455,7 +469,7 @@ function requestArtifactCleanup( entry.cleanupRequested = true; clearTimeout(entry.timer); if (entry.activeDownloads.size > 0 || artifacts.get(artifactId) !== entry) return; - entry.archiveAbortController?.abort( + entry.directoryArchiveBuild?.controller.abort( expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId), ); artifacts.delete(artifactId); diff --git a/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts b/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts index 6d61ece741..e546f319dc 100644 --- a/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts +++ b/packages/daemon/src/server/__tests__/request-diagnostics-http.test.ts @@ -94,7 +94,9 @@ test('request diagnostics route serves one record as ndjson to an authorized cal }); }); -test('request diagnostics returns complete JSON when its stream fails before headers', async () => { +test('request diagnostics returns complete JSON when its stream fails before headers', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + await withDiagnosticsServer(async ({ baseUrl, sessionsDir }) => { writeRecord(sessionsDir, 'default', 'abc123'); const createReadStream = fs.createReadStream; diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts index 047d1ab43a..75bee4d82b 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.test.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -1,15 +1,23 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import http from 'node:http'; +import * as streamPromises from 'node:stream/promises'; import path from 'node:path'; import { gunzipSync } from 'node:zlib'; import { expect, test, vi } from 'vitest'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import * as command from '@agent-device/host-kit/command'; -import { closeLoopbackServer, listenOnLoopback, mkdtempForTestSync } from '@agent-device/test-kit'; +import { + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; import * as artifactTracking from '../resources/artifact-tracking.ts'; import { createDaemonHttpServer } from './http/http-server.ts'; +vi.mock('node:stream/promises', { spy: true }); + function deferred() { let resolve!: () => void; const promise = new Promise((done) => { @@ -29,6 +37,7 @@ type DownloadFixture = { outcome(): 'pending' | 'complete' | 'failed'; cleanupCount(): number; closedResponses(): number; + receivedRequests(): number; expire(): void; expiryPending(): boolean; fireDeadlines(): void; @@ -54,7 +63,9 @@ async function withDownloadFixture( const port = await listenOnLoopback(server); let activeResponse: http.ServerResponse | undefined; let closedResponses = 0; + let receivedRequests = 0; server.on('request', (_request, response) => { + receivedRequests++; activeResponse = response; response.once('close', () => closedResponses++); }); @@ -111,6 +122,7 @@ async function withDownloadFixture( failResponse: () => activeResponse?.destroy(new Error('injected response failure')), outcome: () => outcome, closedResponses: () => closedResponses, + receivedRequests: () => receivedRequests, cleanupCount: () => removed.mock.calls.filter(([target]) => target === source).length, expire: () => runtime.run(expire), expiryPending: () => !clearedTimers.mock.calls.some(([timer]) => timer === expiryTimer), @@ -144,6 +156,34 @@ async function withDownloadFixture( } } +test('a completed download finishes its pipeline without aborting', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + const pipelines = vi.spyOn(streamPromises, 'pipeline'); + try { + await withDownloadFixture( + async (fixture) => { + const expected = fs.readFileSync(path.join(fixture.source, 'payload')); + const response = await fetch(fixture.url, { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(response.status).toBe(200); + const bytes = Buffer.from(await response.arrayBuffer()); + expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + await vi.waitFor(() => expect(fixture.closedResponses()).toBe(1)); + expect(pipelines).toHaveBeenCalledTimes(1); + await expect(pipelines.mock.results[0]!.value).resolves.toBeUndefined(); + expect(pipelines.mock.calls[0]!.at(-1)).toMatchObject({ signal: { aborted: false } }); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + }, + () => {}, + ); + } finally { + pipelines.mockRestore(); + } +}); + test.each(['lone', 'shared'] as const)( 'a client abort cancels its preparation during a %s archive build', async (kind) => { @@ -163,12 +203,6 @@ test.each(['lone', 'shared'] as const)( await withDownloadFixture( async (fixture) => { const expected = fs.readFileSync(path.join(fixture.source, 'payload')); - const statSync = fs.statSync; - let admissions = 0; - const stats = vi.spyOn(fs, 'statSync').mockImplementation((...args) => { - if (args[0] === fixture.source) admissions++; - return statSync(...args); - }); let second: Promise | undefined; try { fixture.start(); @@ -176,7 +210,7 @@ test.each(['lone', 'shared'] as const)( if (kind === 'shared') { second = fetch(fixture.url, { headers: { authorization: 'Bearer fu-art-secret' } }); void second.catch(() => {}); - await vi.waitFor(() => expect(admissions).toBe(2)); + await vi.waitFor(() => expect(fixture.receivedRequests()).toBe(2)); } fixture.abortClient(); await vi.waitFor(() => expect(fixture.closedResponses()).toBe(1)); @@ -198,7 +232,6 @@ test.each(['lone', 'shared'] as const)( } finally { proceed.resolve(); await Promise.allSettled(second ? [second] : []); - stats.mockRestore(); } }, () => {}, diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 3fea5b63cf..56446875ab 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -84,7 +84,9 @@ async function handleArtifactDownload( } const controller = new AbortController(); - const cancel = () => controller.abort(); + const cancel = () => { + if (!res.writableFinished) controller.abort(); + }; res.once('close', cancel); if (res.destroyed) cancel(); try { From 57f7ab526c42c70cf657ae269425564969221e86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 19:25:59 +0100 Subject: [PATCH 4/9] chore(gates): retain diagnostics tenant compatibility rationale --- test/wire-compat/ledger.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 38b96e24f1..b907f2f363 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:df174d1ccf73851ca58bd75533fb4660424003b98bd9e41fe942cf3ab3698e5f", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:ac4268cba9ffdfee7e92429b1a49e48570154d735eed62bfca36d1e2759cec43", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:b3c5b170c70dcd3bd8d8c9aa15873482e0aec88466b385bb00624f35001f63af", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", @@ -257,8 +257,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:ac4268cba9ffdfee7e92429b1a49e48570154d735eed62bfca36d1e2759cec43", - "rationale": "Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload." + "digest": "sha256:b3c5b170c70dcd3bd8d8c9aa15873482e0aec88466b385bb00624f35001f63af", + "rationale": "Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. The disconnected HTTP response is already closed and receives no new payload; artifact expiry and download deadlines keep their existing reasons." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", @@ -298,7 +298,7 @@ { "declaration": "packages/daemon/src/server/request-diagnostics-http.ts#handleRequestDiagnostics", "digest": "sha256:08d3fd203cd7e47814cf8c50f710e86bee28ac2818dbf93910ae49725b97468a", - "rationale": "Implementation-only HTTP error repair under ADR 0006: setup failures use the shared streamed failure helper. Before headers, it emits the existing REST JSON error shape with an error status; after headers, it destroys the incomplete transfer. Successful diagnostics remain 200 with the same NDJSON bytes. Released clients reject error statuses before reading diagnostic records, so no successful response parser or request requirement changes." + "rationale": "#2198 context: asks isTenantAddressableSessionName instead of applying the prefix rule locally. Same UNAUTHORIZED code, same 'Session is outside this tenant' message and same 401 body for the attested-tenant case the rule still refuses; the only difference a peer can observe is that an unattested tenant now gets the 200 + ndjson record it already knows how to read instead of a 401 it could not act on. Implementation-only HTTP error repair under ADR 0006: setup failures use the shared streamed failure helper. Before headers, it emits the existing REST JSON error shape with an error status; after headers, it destroys the incomplete transfer. Successful diagnostics remain 200 with the same NDJSON bytes. Released clients reject error statuses before reading diagnostic records, so no successful response parser or request requirement changes." }, { "declaration": "packages/kernel/src/contracts.ts#LEASE_BACKENDS", From 3fb1f44b052b067eed5552ec230b8ae677842c70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 19:50:06 +0100 Subject: [PATCH 5/9] docs(wire-compat): keep earlier artifact error rationales in the ledger --- test/wire-compat/ledger.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index b907f2f363..97980d246b 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -258,7 +258,7 @@ { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", "digest": "sha256:b3c5b170c70dcd3bd8d8c9aa15873482e0aec88466b385bb00624f35001f63af", - "rationale": "Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. The disconnected HTTP response is already closed and receives no new payload; artifact expiry and download deadlines keep their existing reasons." + "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field. Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. The disconnected HTTP response is already closed and receives no new payload; artifact expiry and download deadlines keep their existing reasons." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", @@ -498,7 +498,7 @@ { "declaration": "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse", "digest": "sha256:3e6b642cb41b88ab1e6f3269ebd14918f912cbecf09f40e9b591fdd28a2ba489", - "rationale": "Compatible HTTP error repair under ADR 0006: both streamed routes use the existing REST JSON error shape before headers, removing stale length and attachment headers. Previously a diagnostics stream open failure could retain its successful-response length and leave the error body incomplete. The helper ignores closed responses and still destroys incomplete transfers after headers. Released artifact and diagnostics clients reject non-success status codes before treating a body as downloaded bytes; routes, successful responses and authorization are unchanged, so older peers still fail clearly without a protocol bump." + "rationale": "Passes the whole normalized error to the details-aware status mapper instead of its code; the plain-text body is unchanged. A gone resource now answers 404 instead of 500: COMMAND_FAILED with details.reason RESOURCE_EXPIRED (an artifact, upload ticket, uploaded artifact or materialized path id the TTL registry no longer holds) maps to 404. The mapper also takes over the DEVICE_IN_USE human_control_active 423 rule, which statusCodeForDaemonError applied only to a failed response a /rpc handler returned. The rule now also reaches the REST routes and thrown /rpc failures, which answered 500: a PUT /admin/leases/ refused during a human-control hold, or a non-streamed /rpc call whose handler throws human_control_active, now answers 423. /admin/* is host-only on the loopback port and the proxy never forwards it, and the host already reads 423 for the same refusal on a returned /rpc failure. No released client branches on 404 versus 500 for these routes: downloadRemoteArtifactFromUrl treats any status >= 400 alike, the upload client fails any non-2xx and decides retries from a typed stream detail rather than the status, the /rpc client parses the JSON-RPC error envelope whatever the status and only special-cases 409, and the proxy passes the status through. The error code, message and JSON-RPC error data a peer parses are unchanged, so a protocol 2 peer reports the same failure it did before. Compatible HTTP error repair under ADR 0006: both streamed routes use the existing REST JSON error shape before headers, removing stale length and attachment headers. Previously a diagnostics stream open failure could retain its successful-response length and leave the error body incomplete. The helper ignores closed responses and still destroys incomplete transfers after headers. Released artifact and diagnostics clients reject non-success status codes before treating a body as downloaded bytes; routes, successful responses and authorization are unchanged, so older peers still fail clearly without a protocol bump." } ] } From 3d9cacf0bb1f102b4863c10b3225c49ab8626f3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 19:54:10 +0100 Subject: [PATCH 6/9] docs(wire-compat): describe the JSON error body in the streamed failure rationale --- test/wire-compat/ledger.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index 97980d246b..f82fa10f5b 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -498,7 +498,7 @@ { "declaration": "packages/daemon/src/server/http-errors.ts#failStreamedHttpResponse", "digest": "sha256:3e6b642cb41b88ab1e6f3269ebd14918f912cbecf09f40e9b591fdd28a2ba489", - "rationale": "Passes the whole normalized error to the details-aware status mapper instead of its code; the plain-text body is unchanged. A gone resource now answers 404 instead of 500: COMMAND_FAILED with details.reason RESOURCE_EXPIRED (an artifact, upload ticket, uploaded artifact or materialized path id the TTL registry no longer holds) maps to 404. The mapper also takes over the DEVICE_IN_USE human_control_active 423 rule, which statusCodeForDaemonError applied only to a failed response a /rpc handler returned. The rule now also reaches the REST routes and thrown /rpc failures, which answered 500: a PUT /admin/leases/ refused during a human-control hold, or a non-streamed /rpc call whose handler throws human_control_active, now answers 423. /admin/* is host-only on the loopback port and the proxy never forwards it, and the host already reads 423 for the same refusal on a returned /rpc failure. No released client branches on 404 versus 500 for these routes: downloadRemoteArtifactFromUrl treats any status >= 400 alike, the upload client fails any non-2xx and decides retries from a typed stream detail rather than the status, the /rpc client parses the JSON-RPC error envelope whatever the status and only special-cases 409, and the proxy passes the status through. The error code, message and JSON-RPC error data a peer parses are unchanged, so a protocol 2 peer reports the same failure it did before. Compatible HTTP error repair under ADR 0006: both streamed routes use the existing REST JSON error shape before headers, removing stale length and attachment headers. Previously a diagnostics stream open failure could retain its successful-response length and leave the error body incomplete. The helper ignores closed responses and still destroys incomplete transfers after headers. Released artifact and diagnostics clients reject non-success status codes before treating a body as downloaded bytes; routes, successful responses and authorization are unchanged, so older peers still fail clearly without a protocol bump." + "rationale": "Compatible HTTP error repair under ADR 0006. Status: the helper passes the whole normalized error to the details-aware status mapper instead of its code. A gone resource now answers 404 instead of 500: COMMAND_FAILED with details.reason RESOURCE_EXPIRED (an artifact, upload ticket, uploaded artifact or materialized path id the TTL registry no longer holds) maps to 404. The mapper also takes over the DEVICE_IN_USE human_control_active 423 rule, which statusCodeForDaemonError applied only to a failed response a /rpc handler returned. The rule now also reaches the REST routes and thrown /rpc failures, which answered 500: a PUT /admin/leases/ refused during a human-control hold, or a non-streamed /rpc call whose handler throws human_control_active, now answers 423. /admin/* is host-only on the loopback port and the proxy never forwards it, and the host already reads 423 for the same refusal on a returned /rpc failure. Body: before headers, the helper no longer writes the plain-text error message. It removes stale content-length and content-disposition headers and sends the existing REST JSON error shape ({ ok: false, error, code, reason?, hint? }) that the other REST routes already use. Previously a diagnostics stream open failure could keep its successful-response length and leave the error body incomplete. After headers, it still destroys the incomplete transfer, and it ignores an already destroyed response. No released client branches on 404 versus 500 or parses this body: downloadRemoteArtifactFromUrl treats any status >= 400 alike and keeps the body only as an opaque details.body string, the diagnostics client rejects non-success statuses before reading records, the upload client fails any non-2xx and decides retries from a typed stream detail rather than the status, the /rpc client parses the JSON-RPC error envelope whatever the status and only special-cases 409, and the proxy passes the status through. Routes, successful responses and authorization are unchanged, so a protocol 2 peer reports the same failure it did before." } ] } From 6a835090fc05337e4084f352ed4af0fb2ecff12f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 21:08:19 +0100 Subject: [PATCH 7/9] fix(daemon): count inventory callers as archive waiters --- .../src/resources/artifact-tracking.test.ts | 75 ++---------- .../daemon/src/resources/artifact-tracking.ts | 76 +++++++----- .../server/downloadable-artifact-http.test.ts | 115 ++++++++++++------ .../src/server/downloadable-artifact-http.ts | 12 +- .../daemon/src/server/http/http-server.ts | 17 +-- .../http/response-disconnect-signal.test.ts | 59 +++++++++ .../server/http/response-disconnect-signal.ts | 19 +++ .../daemon/src/server/human-control-http.ts | 27 +--- 8 files changed, 232 insertions(+), 168 deletions(-) create mode 100644 packages/daemon/src/server/http/response-disconnect-signal.test.ts create mode 100644 packages/daemon/src/server/http/response-disconnect-signal.ts diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 04fabe5687..68386040c8 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -85,7 +85,7 @@ test('cancelling the archive builder preserves a second download waiting for its } }); -test.each(['deadline-aborted', 'failed', 'late-aborted'] as const)( +test.each(['deadline-aborted', 'late-aborted'] as const)( 'a live artifact starts a fresh archive while a %s build is settling', async (failure) => { const root = mkdtempForTestSync('fu-art-retry-build-'); @@ -110,7 +110,6 @@ test.each(['deadline-aborted', 'failed', 'late-aborted'] as const)( const runCmd = command.runCmd; const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { firstArchiveDir = path.dirname(String(args[1]?.[1])); - if (failure === 'failed') throw new Error('tar failed'); args[2]?.signal?.addEventListener('abort', aborted, { once: true }); if (failure === 'late-aborted') { const result = await runCmd(...args); @@ -132,26 +131,15 @@ test.each(['deadline-aborted', 'failed', 'late-aborted'] as const)( void first.catch(() => {}); const deadline = timers.mock.calls.find(([, delay]) => delay === 15 * 60 * 1000)?.[0]; timers.mockRestore(); - if (failure !== 'failed') { - if (failure === 'late-aborted') await succeeded; - expect(deadline).toBeTypeOf('function'); - runtime.run(() => deadline!()); - await cancelled; - } else { - await Promise.resolve(); - } + if (failure === 'late-aborted') await succeeded; + expect(deadline).toBeTypeOf('function'); + runtime.run(() => deadline!()); + await cancelled; const second = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); openings.push(second); void second.catch(() => {}); finishAborted(); - await expect(first).rejects.toMatchObject( - failure !== 'failed' - ? { details: { reason: 'RESOURCE_EXPIRED' } } - : { - code: 'COMMAND_FAILED', - message: `Failed to archive downloadable artifact: ${artifactPath}`, - }, - ); + await expect(first).rejects.toMatchObject({ details: { reason: 'RESOURCE_EXPIRED' } }); expect(fs.existsSync(firstArchiveDir)).toBe(false); const download = await second; const closed = once(download.stream, 'close'); @@ -182,55 +170,6 @@ test.each(['deadline-aborted', 'failed', 'late-aborted'] as const)( }, ); -test('an archive setup failure does not poison a simultaneous retry', async () => { - const root = mkdtempForTestSync('fu-art-setup-retry-'); - const artifactPath = path.join(root, 'capture.trace'); - fs.mkdirSync(artifactPath); - fs.writeFileSync(path.join(artifactPath, 'payload'), 'retry after setup failure'); - const runtime = createRuntimeStateHandle(); - const directories = vi.spyOn(fs, 'mkdtempSync').mockImplementationOnce(() => { - throw new AppError('COMMAND_FAILED', 'archive setup failed'); - }); - const openings: Array> = []; - try { - const id = runtime.run(() => - trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), - ); - const first = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); - openings.push(first); - void first.catch(() => {}); - const second = runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); - openings.push(second); - void second.catch(() => {}); - await expect(first).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - message: 'archive setup failed', - }); - const download = await second; - const closed = once(download.stream, 'close'); - expect( - gunzipSync(await buffer(download.stream)).includes(Buffer.from('retry after setup failure')), - ).toBe(true); - await closed; - download.release(); - runtime.run(() => cleanupDownloadableArtifact(id)); - expect(fs.existsSync(artifactPath)).toBe(false); - } finally { - for (const result of await Promise.allSettled(openings)) { - if (result.status !== 'fulfilled') continue; - const download = result.value; - if (!download.stream.closed) { - const closed = once(download.stream, 'close'); - download.stream.destroy(); - await closed; - } - download.release(); - } - directories.mockRestore(); - runtime.dispose(); - } -}); - test.each(['before opening', 'while archiving'] as const)( 'caller cancellation %s has a typed reason without forwarding caller data', async (phase) => { @@ -317,7 +256,7 @@ test('disposing every archive waiter aborts the shared build and removes its tem openings.push(runtime.run(() => openDownloadableArtifact(id, undefined, process.env))); for (const opening of openings) void opening.catch(() => {}); runtime.dispose(); - expect(archiveSignal?.aborted).toBe(true); + await vi.waitFor(() => expect(archiveSignal?.aborted).toBe(true)); expect(fs.existsSync(artifactPath)).toBe(true); expect(fs.existsSync(archiveDir)).toBe(true); continueArchive(); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 39064e9152..d862fb403e 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -37,6 +37,7 @@ type DirectoryArchive = { type DirectoryArchiveBuild = { promise: Promise; controller: AbortController; + waiters: number; }; type ArtifactSourceCleanup = { @@ -206,7 +207,13 @@ export async function openDownloadableArtifact( if (signal?.aborted) cancel(); try { download.controller.signal.throwIfAborted(); - const payload = await prepareArtifactPayload(artifactId, entry, stat, hostEnv); + const payload = await prepareArtifactPayload( + artifactId, + entry, + stat, + hostEnv, + download.controller.signal, + ); download.controller.signal.throwIfAborted(); if (!payload) { throw new AppError( @@ -231,12 +238,7 @@ function cancelArtifactDownload( ): void { if (!entry.activeDownloads.has(download)) return; download.controller.abort(reason); - if (!download.stream) { - if ([...entry.activeDownloads].every(({ controller }) => controller.signal.aborted)) { - entry.directoryArchiveBuild?.controller.abort(reason); - } - return; - } + if (!download.stream) return; const closed = finished(download.stream, { cleanup: true }).catch(() => {}); download.stream.destroy(); void closed.then(download.release); @@ -315,6 +317,7 @@ async function prepareArtifactPayload( entry: ArtifactEntry, stat: fs.Stats, hostEnv: NodeJS.ProcessEnv, + signal?: AbortSignal, ): Promise { if (stat.isFile()) { return { @@ -326,7 +329,7 @@ async function prepareArtifactPayload( } if (!stat.isDirectory()) return null; - const directoryArchive = await ensureDirectoryArchive(artifactId, entry, hostEnv); + const directoryArchive = await ensureDirectoryArchive(artifactId, entry, hostEnv, signal); return { artifactPath: directoryArchive.archivePath, fileName: directoryArchive.fileName, @@ -339,24 +342,44 @@ async function ensureDirectoryArchive( artifactId: string, entry: ArtifactEntry, hostEnv: NodeJS.ProcessEnv, + signal?: AbortSignal, ): Promise { + signal?.throwIfAborted(); if (entry.directoryArchive && fs.existsSync(entry.directoryArchive.archivePath)) { return entry.directoryArchive; } - const currentBuild = entry.directoryArchiveBuild; - if (currentBuild && !currentBuild.controller.signal.aborted) { - return await currentBuild.promise; + const artifacts = pendingArtifacts(); + let build = entry.directoryArchiveBuild; + if (!build || build.controller.signal.aborted) { + const controller = new AbortController(); + build = { + promise: createDirectoryArchive(artifactId, entry, hostEnv, controller), + controller, + waiters: 0, + }; + entry.directoryArchiveBuild = build; } - - const controller = new AbortController(); - const archivePromise = createDirectoryArchive(artifactId, entry, hostEnv, controller); - const build = { promise: archivePromise, controller }; - entry.directoryArchiveBuild = build; + build.waiters += 1; + let onAbort: (() => void) | undefined; + const aborted = + signal && + new Promise((_resolve, reject) => { + onAbort = () => reject(signal.reason); + signal.addEventListener('abort', onAbort, { once: true }); + if (signal.aborted) onAbort(); + }); try { - return await archivePromise; + return await (aborted ? Promise.race([build.promise, aborted]) : build.promise); } finally { - if (entry.directoryArchiveBuild === build) { - entry.directoryArchiveBuild = undefined; + if (signal && onAbort) signal.removeEventListener('abort', onAbort); + build.waiters -= 1; + if (build.waiters === 0) { + if (signal?.aborted) { + build.controller.abort(signal.reason); + await build.promise.catch(() => {}); + } + if (entry.directoryArchiveBuild === build) entry.directoryArchiveBuild = undefined; + if (entry.cleanupRequested) requestArtifactCleanup(artifacts, artifactId, entry); } } } @@ -419,13 +442,8 @@ async function createDirectoryArchive( { artifactPath: entry.artifactPath }, error instanceof Error ? error : undefined, ); - controller.abort(failure); if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true }); throw failure; - } finally { - if (entry.directoryArchiveBuild?.controller === controller) { - entry.directoryArchiveBuild = undefined; - } } } @@ -468,10 +486,12 @@ function requestArtifactCleanup( ): void { entry.cleanupRequested = true; clearTimeout(entry.timer); - if (entry.activeDownloads.size > 0 || artifacts.get(artifactId) !== entry) return; - entry.directoryArchiveBuild?.controller.abort( - expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId), - ); + if ( + entry.activeDownloads.size > 0 || + entry.directoryArchiveBuild || + artifacts.get(artifactId) !== entry + ) + return; artifacts.delete(artifactId); cleanupDirectoryArchive(entry); entry.sourceCleanup.remainingEntries -= 1; diff --git a/packages/daemon/src/server/downloadable-artifact-http.test.ts b/packages/daemon/src/server/downloadable-artifact-http.test.ts index 75bee4d82b..b4453b9c25 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.test.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.test.ts @@ -1,10 +1,9 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; import http from 'node:http'; -import * as streamPromises from 'node:stream/promises'; import path from 'node:path'; import { gunzipSync } from 'node:zlib'; -import { expect, test, vi } from 'vitest'; +import { expect, test, vi, type MockInstance } from 'vitest'; import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import * as command from '@agent-device/host-kit/command'; import { @@ -16,8 +15,6 @@ import { import * as artifactTracking from '../resources/artifact-tracking.ts'; import { createDaemonHttpServer } from './http/http-server.ts'; -vi.mock('node:stream/promises', { spy: true }); - function deferred() { let resolve!: () => void; const promise = new Promise((done) => { @@ -38,6 +35,7 @@ type DownloadFixture = { cleanupCount(): number; closedResponses(): number; receivedRequests(): number; + responseDestroys(): number; expire(): void; expiryPending(): boolean; fireDeadlines(): void; @@ -64,7 +62,9 @@ async function withDownloadFixture( let activeResponse: http.ServerResponse | undefined; let closedResponses = 0; let receivedRequests = 0; + const responseDestroySpies: Array> = []; server.on('request', (_request, response) => { + responseDestroySpies.push(vi.spyOn(response, 'destroy')); receivedRequests++; activeResponse = response; response.once('close', () => closedResponses++); @@ -123,6 +123,8 @@ async function withDownloadFixture( outcome: () => outcome, closedResponses: () => closedResponses, receivedRequests: () => receivedRequests, + responseDestroys: () => + responseDestroySpies.reduce((count, spy) => count + spy.mock.calls.length, 0), cleanupCount: () => removed.mock.calls.filter(([target]) => target === source).length, expire: () => runtime.run(expire), expiryPending: () => !clearedTimers.mock.calls.some(([timer]) => timer === expiryTimer), @@ -153,38 +155,37 @@ async function withDownloadFixture( await closeLoopbackServer(server); runtime.dispose(); removed.mockRestore(); + for (const spy of responseDestroySpies) spy.mockRestore(); } } -test('a completed download finishes its pipeline without aborting', async (t) => { +test('a completed download is not destroyed or cleaned up twice after its 200 response', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; - const pipelines = vi.spyOn(streamPromises, 'pipeline'); - try { - await withDownloadFixture( - async (fixture) => { - const expected = fs.readFileSync(path.join(fixture.source, 'payload')); - const response = await fetch(fixture.url, { - headers: { authorization: 'Bearer fu-art-secret' }, - }); - expect(response.status).toBe(200); - const bytes = Buffer.from(await response.arrayBuffer()); - expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); - expect(gunzipSync(bytes).includes(expected)).toBe(true); - await vi.waitFor(() => expect(fixture.closedResponses()).toBe(1)); - expect(pipelines).toHaveBeenCalledTimes(1); - await expect(pipelines.mock.results[0]!.value).resolves.toBeUndefined(); - expect(pipelines.mock.calls[0]!.at(-1)).toMatchObject({ signal: { aborted: false } }); - await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); - }, - () => {}, - ); - } finally { - pipelines.mockRestore(); - } + await withDownloadFixture( + async (fixture) => { + const expected = fs.readFileSync(path.join(fixture.source, 'payload')); + const response = await fetch(fixture.url, { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(response.status).toBe(200); + const bytes = Buffer.from(await response.arrayBuffer()); + expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + await vi.waitFor(() => expect(fixture.closedResponses()).toBe(1)); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + expect(fixture.responseDestroys()).toBe(0); + expect(fixture.cleanupCount()).toBe(1); + fixture.expire(); + fixture.runtime.dispose(); + expect(fixture.cleanupCount()).toBe(1); + expect(fixture.responseDestroys()).toBe(0); + }, + () => {}, + ); }); -test.each(['lone', 'shared'] as const)( +test.each(['lone', 'shared', 'inventory'] as const)( 'a client abort cancels its preparation during a %s archive build', async (kind) => { const started = deferred(); @@ -207,18 +208,35 @@ test.each(['lone', 'shared'] as const)( try { fixture.start(); await started.promise; - if (kind === 'shared') { - second = fetch(fixture.url, { headers: { authorization: 'Bearer fu-art-secret' } }); + if (kind !== 'lone') { + const url = + kind === 'inventory' + ? fixture.url.slice(0, fixture.url.lastIndexOf('/')) + : fixture.url; + second = fetch(url, { headers: { authorization: 'Bearer fu-art-secret' } }); void second.catch(() => {}); await vi.waitFor(() => expect(fixture.receivedRequests()).toBe(2)); } fixture.abortClient(); await vi.waitFor(() => expect(fixture.closedResponses()).toBe(1)); - expect(archiveSignal?.aborted).toBe(kind === 'lone'); + if (kind !== 'inventory') expect(archiveSignal?.aborted).toBe(kind === 'lone'); proceed.resolve(); if (second) { - const response = await second; + let response = await second; expect(response.status).toBe(200); + if (kind === 'inventory') { + expect(await response.json()).toMatchObject({ + artifacts: [ + { id: fixture.url.split('/').at(-1), filename: 'capture.trace.tar.gz' }, + ], + }); + expect(archiveSignal?.aborted).toBe(false); + expect(fs.existsSync(fixture.source)).toBe(true); + response = await fetch(fixture.url, { + headers: { authorization: 'Bearer fu-art-secret' }, + }); + expect(response.status).toBe(200); + } const bytes = Buffer.from(await response.arrayBuffer()); expect(bytes).toHaveLength(Number(response.headers.get('content-length'))); expect(gunzipSync(bytes).includes(expected)).toBe(true); @@ -227,7 +245,7 @@ test.each(['lone', 'shared'] as const)( await vi.waitFor(() => expect(fs.existsSync(archiveDir)).toBe(false)); expect(fs.existsSync(fixture.source)).toBe(true); } - expect(fixture.streams).toHaveLength(kind === 'shared' ? 1 : 0); + expect(fixture.streams).toHaveLength(kind !== 'lone' ? 1 : 0); expect(archive).toHaveBeenCalledTimes(1); } finally { proceed.resolve(); @@ -243,6 +261,35 @@ test.each(['lone', 'shared'] as const)( }, ); +test('a failed archive build permits a later HTTP download to retry', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + const archive = vi + .spyOn(command, 'runCmd') + .mockRejectedValueOnce(new Error('injected tar failure')); + try { + await withDownloadFixture( + async (fixture) => { + const headers = { authorization: 'Bearer fu-art-secret' }; + const failed = await fetch(fixture.url, { headers }); + expect(failed.status).toBe(500); + expect(await failed.json()).toMatchObject({ ok: false, code: 'COMMAND_FAILED' }); + expect(fs.existsSync(fixture.source)).toBe(true); + const expected = fs.readFileSync(path.join(fixture.source, 'payload')); + const response = await fetch(fixture.url, { headers }); + expect(response.status).toBe(200); + const bytes = Buffer.from(await response.arrayBuffer()); + expect(gunzipSync(bytes).includes(expected)).toBe(true); + expect(archive).toHaveBeenCalledTimes(2); + await vi.waitFor(() => expect(fs.existsSync(fixture.source)).toBe(false)); + }, + () => {}, + ); + } finally { + archive.mockRestore(); + } +}); + test.each(['destroyed', 'truncated', 'errored'] as const)( 'a %s artifact read terminates the HTTP response', async (failure) => { diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 56446875ab..59fce82a46 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -11,6 +11,7 @@ import { } from '../resources/artifact-tracking.ts'; import { failStreamedHttpResponse, sendRestJsonError } from './http-errors.ts'; import { decodeUriSegment } from './http-request-target.ts'; +import { responseDisconnectSignal } from './http/response-disconnect-signal.ts'; type DownloadableArtifactHttpRoute = | { kind: 'inventory' } @@ -83,12 +84,7 @@ async function handleArtifactDownload( return; } - const controller = new AbortController(); - const cancel = () => { - if (!res.writableFinished) controller.abort(); - }; - res.once('close', cancel); - if (res.destroyed) cancel(); + const signal = responseDisconnectSignal(req, res); try { const auth = await authorize({ req, @@ -104,7 +100,7 @@ async function handleArtifactDownload( artifactId, auth.tenantId, options.hostEnv, - controller.signal, + signal, ); const { stream } = artifact; const closed = finished(stream, { cleanup: true }).catch(() => {}); @@ -153,8 +149,6 @@ async function handleArtifactDownload( } } catch (error) { failStreamedHttpResponse(res, error); - } finally { - res.removeListener('close', cancel); } } diff --git a/packages/daemon/src/server/http/http-server.ts b/packages/daemon/src/server/http/http-server.ts index 12d7893ff1..2856a340c6 100644 --- a/packages/daemon/src/server/http/http-server.ts +++ b/packages/daemon/src/server/http/http-server.ts @@ -5,6 +5,7 @@ // request's cancellation lifetime, and invocation. The envelope framing lives // in `http-rpc-envelope.ts`, the authorization decisions in // `http-authorization.ts`, and the RPC method vocabulary in `http-rpc-methods.ts`. +import { responseDisconnectSignal } from './response-disconnect-signal.ts'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { AsyncResource } from 'node:async_hooks'; import http from 'node:http'; @@ -453,12 +454,11 @@ function beginRpcRequestLifetime(params: { let abortRegistration: ReturnType; let handlerCompleted = false; let canceledInFlight = false; + let disconnectSignal: AbortSignal | undefined; + let onClientGone: (() => void) | undefined; - // `res` close fires for a finished response too, so the completion guard is what separates a - // real disconnect from an ordinary end. `markRequestCanceled` aborts only this request's - // signal, leaving other requests, other devices, and non-Apple work alone. const markCanceledIfResponseIncomplete = () => { - if (handlerCompleted || res.writableFinished || canceledInFlight) return; + if (handlerCompleted || canceledInFlight) return; canceledInFlight = true; markRequestCanceled(requestId); emitDiagnostic({ @@ -482,10 +482,10 @@ function beginRpcRequestLifetime(params: { }; }, watchForClientDisconnect() { - const onClientGone = AsyncResource.bind(markCanceledIfResponseIncomplete); - req.on('aborted', onClientGone); - res.on('close', onClientGone); - if (req.aborted || res.destroyed) { + onClientGone = AsyncResource.bind(markCanceledIfResponseIncomplete); + disconnectSignal = responseDisconnectSignal(req, res); + disconnectSignal.addEventListener('abort', onClientGone, { once: true }); + if (disconnectSignal.aborted) { markCanceledIfResponseIncomplete(); } }, @@ -493,6 +493,7 @@ function beginRpcRequestLifetime(params: { handlerCompleted = true; }, release() { + if (onClientGone) disconnectSignal?.removeEventListener('abort', onClientGone); clearRequestAbortRegistration(abortRegistration); }, }; diff --git a/packages/daemon/src/server/http/response-disconnect-signal.test.ts b/packages/daemon/src/server/http/response-disconnect-signal.test.ts new file mode 100644 index 0000000000..050f1b6ddb --- /dev/null +++ b/packages/daemon/src/server/http/response-disconnect-signal.test.ts @@ -0,0 +1,59 @@ +import http from 'node:http'; +import net from 'node:net'; +import { expect, test } from 'vitest'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { isRequestCanceledError } from '@agent-device/kernel/errors'; +import { responseDisconnectSignal } from './response-disconnect-signal.ts'; + +test.each(['request abort', 'response close', 'already aborted', 'already destroyed'] as const)( + '%s produces a typed disconnect signal and removes its listeners', + (event) => { + const socket = new net.Socket(); + const req = new http.IncomingMessage(socket); + const res = new http.ServerResponse(req); + try { + if (event === 'already aborted') req.destroy(); + if (event === 'already destroyed') res.destroy(); + const signal = responseDisconnectSignal(req, res); + if (event === 'request abort') req.destroy(); + if (event === 'response close') res.emit('close'); + expect(signal.aborted).toBe(true); + expect(isRequestCanceledError(signal.reason)).toBe(true); + expect(req.listenerCount('aborted')).toBe(0); + expect(res.listenerCount('close')).toBe(0); + } finally { + req.destroy(); + res.destroy(); + socket.destroy(); + } + }, +); + +test('a completed response does not abort its disconnect signal', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + + let signal: AbortSignal | undefined; + let responseClosed!: () => void; + const closed = new Promise((resolve) => { + responseClosed = resolve; + }); + const server = http.createServer((req, res) => { + signal = responseDisconnectSignal(req, res); + res.once('close', responseClosed); + res.end('complete'); + }); + try { + const port = await listenOnLoopback(server); + const response = await fetch(`http://127.0.0.1:${port}`); + expect(response.status).toBe(200); + expect(await response.text()).toBe('complete'); + await closed; + expect(signal?.aborted).toBe(false); + } finally { + await closeLoopbackServer(server); + } +}); diff --git a/packages/daemon/src/server/http/response-disconnect-signal.ts b/packages/daemon/src/server/http/response-disconnect-signal.ts new file mode 100644 index 0000000000..c7d2d07a5c --- /dev/null +++ b/packages/daemon/src/server/http/response-disconnect-signal.ts @@ -0,0 +1,19 @@ +import type http from 'node:http'; +import { createRequestCanceledError } from '@agent-device/kernel/errors'; + +/** Cancels work when the HTTP client abandons an unfinished response. */ +export function responseDisconnectSignal( + req: http.IncomingMessage, + res: http.ServerResponse, +): AbortSignal { + const controller = new AbortController(); + function cancelIfDisconnected(): void { + if (!res.writableFinished) controller.abort(createRequestCanceledError()); + req.off('aborted', cancelIfDisconnected); + res.off('close', cancelIfDisconnected); + } + req.once('aborted', cancelIfDisconnected); + res.once('close', cancelIfDisconnected); + if (req.aborted || res.destroyed) cancelIfDisconnected(); + return controller.signal; +} diff --git a/packages/daemon/src/server/human-control-http.ts b/packages/daemon/src/server/human-control-http.ts index 60a701b582..f668997596 100644 --- a/packages/daemon/src/server/human-control-http.ts +++ b/packages/daemon/src/server/human-control-http.ts @@ -1,7 +1,8 @@ import type http from 'node:http'; -import { AppError, createRequestCanceledError, normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { readNodeHttpRequestBody, timingSafeStringEqual } from '@agent-device/host-kit/transport'; import { sendRestJsonError } from './http-errors.ts'; +import { responseDisconnectSignal } from './http/response-disconnect-signal.ts'; import { HUMAN_CONTROL_HTTP_PREFIX, parseHumanControlHoldInput, @@ -75,26 +76,10 @@ async function upsertHumanControlHold( params: HumanControlHttpParams, ): Promise { const { req, res } = params; - const controller = new AbortController(); - const cancelIfDisconnected = () => { - if (!res.writableFinished) controller.abort(createRequestCanceledError()); - }; - req.once('aborted', cancelIfDisconnected); - res.once('close', cancelIfDisconnected); - if (req.aborted || res.destroyed) cancelIfDisconnected(); - try { - const input = await readHoldInput(req); - const hold = await params.registry.putHumanControlHold( - { kind: 'host' }, - holdId, - input, - controller.signal, - ); - sendJson(res, { ok: true, hold, state: 'active' }); - } finally { - req.off('aborted', cancelIfDisconnected); - res.off('close', cancelIfDisconnected); - } + const signal = responseDisconnectSignal(req, res); + const input = await readHoldInput(req); + const hold = await params.registry.putHumanControlHold({ kind: 'host' }, holdId, input, signal); + sendJson(res, { ok: true, hold, state: 'active' }); } function removeHumanControlHold(holdId: string, params: HumanControlHttpParams): void { From 47d1ac7e0a76b1c35690b0d3b126b6a05257c2a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 21:08:20 +0100 Subject: [PATCH 8/9] chore(gates): acknowledge shared HTTP disconnect handling --- test/wire-compat/ledger.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index f82fa10f5b..b1c1bda441 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -71,7 +71,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:df174d1ccf73851ca58bd75533fb4660424003b98bd9e41fe942cf3ab3698e5f", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:b3c5b170c70dcd3bd8d8c9aa15873482e0aec88466b385bb00624f35001f63af", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:fbb1ffa587ffb8b2975936fd35113c1970da16c58a713014df2c6ba885eecdd5", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:651806eabbd78d51d4bb21dab0b8a28847fb6087941f73dee735c24d9c2a79fa", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", @@ -257,8 +257,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:b3c5b170c70dcd3bd8d8c9aa15873482e0aec88466b385bb00624f35001f63af", - "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field. Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. The disconnected HTTP response is already closed and receives no new payload; artifact expiry and download deadlines keep their existing reasons." + "digest": "sha256:fbb1ffa587ffb8b2975936fd35113c1970da16c58a713014df2c6ba885eecdd5", + "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field. Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. Artifact expiry and download deadlines keep their existing reasons. The shared HTTP disconnect helper preserves typed cancellation on aborted requests and unfinished response closes. Directory preparation counts inventory and download callers together, so one disconnected download cannot abort an inventory caller's build; successful response fields and authorization stay unchanged." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", From 9e4deaeb4d816fb00023755c5006295839bee11e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 21:32:25 +0100 Subject: [PATCH 9/9] fix(daemon): abort inventory archive builds on cleanup --- .../src/resources/artifact-tracking.test.ts | 111 ++++++++++++++++++ .../daemon/src/resources/artifact-tracking.ts | 12 +- .../server/http/response-disconnect-signal.ts | 1 + 3 files changed, 118 insertions(+), 6 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.test.ts b/packages/daemon/src/resources/artifact-tracking.test.ts index 68386040c8..ba2b80e738 100644 --- a/packages/daemon/src/resources/artifact-tracking.test.ts +++ b/packages/daemon/src/resources/artifact-tracking.test.ts @@ -10,12 +10,123 @@ import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; import * as command from '@agent-device/host-kit/command'; import { cleanupDownloadableArtifact, + listDownloadableArtifacts, openDownloadableArtifact, trackDownloadableArtifact, trackUploadedArtifact, type OpenedDownloadableArtifact, } from './artifact-tracking.ts'; +test.each(['cleanup', 'expiry'] as const)( + '%s aborts an inventory-only archive and removes its source after tar settles', + async (trigger) => { + const root = mkdtempForTestSync('fu-art-inventory-expiry-'); + const artifactPath = path.join(root, 'capture.trace'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), 'pending inventory archive'); + const runtime = createRuntimeStateHandle(); + let start!: () => void; + const started = new Promise((resolve) => { + start = resolve; + }); + let finish!: () => void; + const stopped = new Promise((resolve) => { + finish = resolve; + }); + let archivePath = ''; + let signal: AbortSignal | undefined; + const runCmd = command.runCmd; + const archive = vi.spyOn(command, 'runCmd').mockImplementationOnce(async (...args) => { + archivePath = String(args[1]?.[1]); + signal = args[2]?.signal; + fs.writeFileSync(archivePath, 'partial tar output'); + start(); + await stopped; + return await runCmd(...args); + }); + let listing: ReturnType | undefined; + try { + const timers = vi.spyOn(globalThis, 'setTimeout'); + let id: string; + let expire: (() => void) | undefined; + try { + id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + expire = timers.mock.calls.find(([, delay]) => delay === 15 * 60 * 1000)?.[0]; + } finally { + timers.mockRestore(); + } + listing = runtime.run(() => listDownloadableArtifacts(undefined, process.env)); + await started; + expect(fs.existsSync(archivePath)).toBe(true); + if (trigger === 'expiry') { + expect(expire).toBeTypeOf('function'); + runtime.run(() => expire!()); + } else { + runtime.run(() => cleanupDownloadableArtifact(id)); + } + expect(signal?.aborted).toBe(true); + expect(signal?.reason).toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: 'RESOURCE_EXPIRED' }, + }); + expect(fs.existsSync(artifactPath)).toBe(true); + expect(fs.existsSync(archivePath)).toBe(true); + finish(); + expect(await listing).toEqual([]); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(path.dirname(archivePath))).toBe(false); + expect(archive).toHaveBeenCalledTimes(1); + } finally { + finish(); + if (listing) await listing; + runtime.dispose(); + archive.mockRestore(); + } + }, +); + +test('a missing cached directory archive is rebuilt from the live source', async () => { + const root = mkdtempForTestSync('fu-art-cache-rebuild-'); + const artifactPath = path.join(root, 'capture.trace'); + const expected = Buffer.from('live source after cached archive disappears'); + fs.mkdirSync(artifactPath); + fs.writeFileSync(path.join(artifactPath, 'payload'), expected); + const runtime = createRuntimeStateHandle(); + const downloads: OpenedDownloadableArtifact[] = []; + try { + const id = runtime.run(() => + trackDownloadableArtifact({ artifactPath, artifactType: 'trace-log' }), + ); + const first = await runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + downloads.push(first); + expect(gunzipSync(await buffer(first.stream)).includes(expected)).toBe(true); + await vi.waitFor(() => expect(first.stream.closed).toBe(true)); + first.release(); + const oldArchive = String(first.stream.path); + fs.unlinkSync(oldArchive); + expect(fs.existsSync(artifactPath)).toBe(true); + const second = await runtime.run(() => openDownloadableArtifact(id, undefined, process.env)); + downloads.push(second); + expect(gunzipSync(await buffer(second.stream)).includes(expected)).toBe(true); + await vi.waitFor(() => expect(second.stream.closed).toBe(true)); + second.release(); + expect(String(second.stream.path)).not.toBe(oldArchive); + expect(fs.existsSync(path.dirname(oldArchive))).toBe(false); + runtime.run(() => cleanupDownloadableArtifact(id)); + expect(fs.existsSync(artifactPath)).toBe(false); + expect(fs.existsSync(path.dirname(String(second.stream.path)))).toBe(false); + } finally { + for (const download of downloads) { + download.stream.destroy(); + await vi.waitFor(() => expect(download.stream.closed).toBe(true)); + download.release(); + } + runtime.dispose(); + } +}); + test('cancelling the archive builder preserves a second download waiting for its full archive', async () => { const root = mkdtempForTestSync('fu-art-shared-build-'); const artifactPath = path.join(root, 'capture.trace'); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index d862fb403e..4af16a65a2 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -204,7 +204,6 @@ export async function openDownloadableArtifact( const cancel = () => cancelArtifactDownload(artifactId, entry, download, createRequestCanceledError()); signal?.addEventListener('abort', cancel, { once: true }); - if (signal?.aborted) cancel(); try { download.controller.signal.throwIfAborted(); const payload = await prepareArtifactPayload( @@ -486,12 +485,13 @@ function requestArtifactCleanup( ): void { entry.cleanupRequested = true; clearTimeout(entry.timer); - if ( - entry.activeDownloads.size > 0 || - entry.directoryArchiveBuild || - artifacts.get(artifactId) !== entry - ) + if (entry.activeDownloads.size > 0 || artifacts.get(artifactId) !== entry) return; + if (entry.directoryArchiveBuild) { + entry.directoryArchiveBuild.controller.abort( + expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId), + ); return; + } artifacts.delete(artifactId); cleanupDirectoryArchive(entry); entry.sourceCleanup.remainingEntries -= 1; diff --git a/packages/daemon/src/server/http/response-disconnect-signal.ts b/packages/daemon/src/server/http/response-disconnect-signal.ts index c7d2d07a5c..23f1e842df 100644 --- a/packages/daemon/src/server/http/response-disconnect-signal.ts +++ b/packages/daemon/src/server/http/response-disconnect-signal.ts @@ -8,6 +8,7 @@ export function responseDisconnectSignal( ): AbortSignal { const controller = new AbortController(); function cancelIfDisconnected(): void { + // A finished response also emits close. if (!res.writableFinished) controller.abort(createRequestCanceledError()); req.off('aborted', cancelIfDisconnected); res.off('close', cancelIfDisconnected);