From 16624f1324e156d14025b2c346596c9781c07488 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:29:22 +0800 Subject: [PATCH] fix(evidence): cancel exports before atomic publication --- docs/mcp-contracts.md | 2 + src/application/EvidenceBundleFiles.ts | 12 +- src/application/JsonFiles.ts | 92 ++++++++++++--- src/server/registerSessionRecordTools.ts | 3 +- .../filesystem/evidenceBundleFiles.test.ts | 106 +++++++++++++++++ .../mcp/evidenceExportCancellation.test.ts | 109 ++++++++++++++++++ 6 files changed, 308 insertions(+), 16 deletions(-) create mode 100644 tests/boundary/mcp/evidenceExportCancellation.test.ts diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index e2b0c5eac..8a5cc6cf9 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -195,6 +195,8 @@ workflow, or call `export_evidence_bundle` with a destination path. Complete bundle exports stream canonical JSON into an atomically published file. A broad follow-up or `get_evidence_bundle` can also exceed the response budget; exporting preserves the complete session without sending it through a single MCP frame. +Cancelling an export stops further serialization and removes its staging file. +The destination changes only when a complete export is atomically published. Clients that explicitly configure a larger receive buffer can set the REA server's `REA_MCP_MAX_RESPONSE_BYTES` environment variable to the same byte diff --git a/src/application/EvidenceBundleFiles.ts b/src/application/EvidenceBundleFiles.ts index 57eeb1397..c6edd156f 100644 --- a/src/application/EvidenceBundleFiles.ts +++ b/src/application/EvidenceBundleFiles.ts @@ -9,6 +9,7 @@ import { EvidenceIntegrityError, } from "../domain/evidenceErrors.js"; import { err, ok, type Result } from "../domain/result.js"; +import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; import { parseProcessCapture } from "../domain/process/processCapture.js"; import { bufferedJsonParts, @@ -17,7 +18,10 @@ import { import { readJsonFile, writeTextParts } from "./JsonFiles.js"; type EvidenceReadFailure = EvidenceFileError | EvidenceIntegrityError; -type EvidenceWriteFailure = EvidenceFileError | EvidenceIntegrityError; +type EvidenceWriteFailure = + | EvidenceFileError + | EvidenceIntegrityError + | AnalysisCancelledError; /** Read and validate an evidence bundle at the caller-supplied path. */ export const readEvidenceBundle = async ( @@ -57,12 +61,15 @@ export const writeEvidenceBundle = async ( bundle: EvidenceBundle, path: string, overwrite: boolean, + signal?: AbortSignal, ): Promise< Result< { readonly path: string; readonly bytes: number }, EvidenceWriteFailure > > => { + if (signal?.aborted === true) + return err(new AnalysisCancelledError("export_evidence_bundle")); let checked: EvidenceBundle; try { checked = parseEvidenceBundle(bundle); @@ -77,5 +84,8 @@ export const writeEvidenceBundle = async ( bufferedJsonParts(canonicalJsonParts(checked)), path, overwrite, + signal === undefined + ? undefined + : { signal, operation: "export_evidence_bundle" }, ); }; diff --git a/src/application/JsonFiles.ts b/src/application/JsonFiles.ts index 079d2c9d1..cdf80d7e8 100644 --- a/src/application/JsonFiles.ts +++ b/src/application/JsonFiles.ts @@ -7,12 +7,23 @@ import { realpath, rename, rm, + type FileHandle, } from "node:fs/promises"; import { basename, dirname, resolve } from "node:path"; import { EvidenceFileError } from "../domain/evidenceErrors.js"; +import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; import { err, ok, type Result } from "../domain/result.js"; +/** Request control and its owning operation for an interruptible atomic write. */ +export interface TextWriteCancellation { + readonly signal: AbortSignal; + readonly operation: string; +} + +type TextWriteResult = + Result<{ readonly path: string; readonly bytes: number }, Failure>; + /** Read JSON data from a regular file at the caller-supplied path. */ export const readJsonFile = async ( path: string, @@ -57,20 +68,31 @@ export const writeTextFile = async ( encoded: string, path: string, overwrite: boolean, -): Promise< - Result<{ readonly path: string; readonly bytes: number }, EvidenceFileError> -> => writeTextParts([encoded], path, overwrite); +): Promise> => + writeTextParts([encoded], path, overwrite); -/** Publish complete streamed text atomically, keeping only one encoded part in memory. */ -export const writeTextParts = async ( +/** Publish streamed text atomically unless cancellation wins before publication. */ +export function writeTextParts( parts: Iterable, path: string, overwrite: boolean, -): Promise< - Result<{ readonly path: string; readonly bytes: number }, EvidenceFileError> -> => { +): Promise>; +/** Pass request control to stop streamed generation before atomic publication. */ +export function writeTextParts( + parts: Iterable, + path: string, + overwrite: boolean, + cancellation: TextWriteCancellation | undefined, +): Promise; +export async function writeTextParts( + parts: Iterable, + path: string, + overwrite: boolean, + cancellation?: TextWriteCancellation, +): Promise { const requestedPath = resolve(path); try { + assertWriteActive(cancellation); const canonicalParent = await realpath(dirname(requestedPath)); const destination = resolve(canonicalParent, basename(requestedPath)); const existing = await lstat(destination).catch((cause: unknown) => { @@ -87,9 +109,21 @@ export const writeTextParts = async ( new EvidenceFileError("write", "not-file", { path: requestedPath }), ); } - const bytes = await publishFile(destination, parts, overwrite); + assertWriteActive(cancellation); + const bytes = await publishFile( + destination, + parts, + overwrite, + cancellation, + ); return ok({ path: requestedPath, bytes }); } catch (cause: unknown) { + if ( + cancellation?.signal.aborted === true && + cause instanceof AnalysisCancelledError && + cause.operation === cancellation.operation + ) + return err(cause); if (!overwrite && fileErrorCode(cause) === "EEXIST") return err( new EvidenceFileError("write", "exists", { @@ -104,7 +138,7 @@ export const writeTextParts = async ( }), ); } -}; +} /** A missing path or parent is a selection error, not a permission failure. */ const missingOrIo = (cause: unknown): "missing" | "io" => { @@ -116,6 +150,7 @@ const publishFile = async ( destination: string, parts: Iterable, overwrite: boolean, + cancellation?: TextWriteCancellation, ): Promise => { const stagingDirectory = await mkdtemp( resolve(dirname(destination), ".rea-write-"), @@ -125,14 +160,14 @@ const publishFile = async ( const file = await open(staged, "wx", 0o600); let bytes = 0; try { - for (const part of parts) { - await file.writeFile(part, { encoding: "utf8" }); - bytes += Buffer.byteLength(part, "utf8"); - } + bytes = await writeStagedParts(file, parts, cancellation); + assertWriteActive(cancellation); await file.sync(); } finally { await file.close(); } + // Once submitted, the atomic publication can win a later cancellation race. + assertWriteActive(cancellation); if (overwrite) await rename(staged, destination); // A hard link publishes complete bytes atomically and cannot replace an existing name. else await link(staged, destination); @@ -142,6 +177,35 @@ const publishFile = async ( } }; +const writeStagedParts = async ( + file: FileHandle, + parts: Iterable, + cancellation?: TextWriteCancellation, +): Promise => { + assertWriteActive(cancellation); + const iterator = parts[Symbol.iterator](); + let exhausted = false; + let bytes = 0; + try { + for (;;) { + assertWriteActive(cancellation); + const part = iterator.next(); + if (part.done) exhausted = true; + assertWriteActive(cancellation); + if (part.done) return bytes; + await file.writeFile(part.value, { encoding: "utf8" }); + bytes += Buffer.byteLength(part.value, "utf8"); + } + } finally { + if (!exhausted) iterator.return?.(); + } +}; + +const assertWriteActive = (cancellation?: TextWriteCancellation): void => { + if (cancellation?.signal.aborted === true) + throw new AnalysisCancelledError(cancellation.operation); +}; + const fileErrorCode = (cause: unknown): unknown => typeof cause === "object" && cause !== null && "code" in cause ? cause.code diff --git a/src/server/registerSessionRecordTools.ts b/src/server/registerSessionRecordTools.ts index 8e777a64f..d88d4edf9 100644 --- a/src/server/registerSessionRecordTools.ts +++ b/src/server/registerSessionRecordTools.ts @@ -42,12 +42,13 @@ const registerExportEvidenceTool = ({ server.registerTool( exportContract.name, toolRegistrationOptions(exportContract), - async (input) => { + async (input, context) => { const bundle = bundleForSerialization(session); const written = await writeEvidenceBundle( bundle, input.path, input.overwrite, + context.mcpReq.signal, ); return written.ok ? toCallToolResult( diff --git a/tests/boundary/filesystem/evidenceBundleFiles.test.ts b/tests/boundary/filesystem/evidenceBundleFiles.test.ts index 716c65880..11216b671 100644 --- a/tests/boundary/filesystem/evidenceBundleFiles.test.ts +++ b/tests/boundary/filesystem/evidenceBundleFiles.test.ts @@ -34,6 +34,112 @@ const bundle = (result = true) => ), ]); +describe("evidence bundle export cancellation", () => { + it("does not inspect the path or advance a source cancelled before writing", async () => { + const root = await createTestTempDirectory("rea-export-pre-cancel-"); + const controller = new AbortController(); + controller.abort(); + let advanced = false; + function* parts() { + advanced = true; + yield "unused"; + } + expect( + await writeTextParts( + parts(), + join(root, "missing", "bundle.json"), + false, + { + signal: controller.signal, + operation: "export_evidence_bundle", + }, + ), + ).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisCancelledError", + operation: "export_evidence_bundle", + }, + }); + expect(advanced).toBe(false); + expect(await readdir(root)).toEqual([]); + expect( + await writeEvidenceBundle( + bundle(), + join(root, "bundle.json"), + false, + controller.signal, + ), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } }); + expect(await readdir(root)).toEqual([]); + }); + + it.each([false, true])( + "closes a cancelled source and preserves the destination (overwrite: %s)", + async (overwrite) => { + const root = await createTestTempDirectory("rea-export-cancel-"); + const path = join(root, "bundle.json"); + if (overwrite) await writeFile(path, "original"); + const controller = new AbortController(); + let closed = false; + let continued = false; + function* parts() { + try { + yield "staged partial data"; + controller.abort(); + yield "cancelled data"; + continued = true; + yield "unreachable"; + } finally { + closed = true; + } + } + expect( + await writeTextParts(parts(), path, overwrite, { + signal: controller.signal, + operation: "export_evidence_bundle", + }), + ).toMatchObject({ + ok: false, + error: { + _tag: "AnalysisCancelledError", + operation: "export_evidence_bundle", + }, + }); + expect(closed).toBe(true); + expect(continued).toBe(false); + expect(await readdir(root)).toEqual(overwrite ? ["bundle.json"] : []); + if (overwrite) expect(await readFile(path, "utf8")).toBe("original"); + expect( + await writeEvidenceBundle(bundle(), path, overwrite), + ).toMatchObject({ ok: true }); + expect(await readEvidenceBundle(path)).toEqual({ + ok: true, + value: bundle(), + }); + }, + ); + + it("does not publish when cancellation arrives at source exhaustion", async () => { + const root = await createTestTempDirectory("rea-export-final-cancel-"); + const path = join(root, "bundle.json"); + await writeFile(path, "original"); + const controller = new AbortController(); + function* parts() { + yield "complete replacement"; + controller.abort(); + } + expect( + await writeTextParts(parts(), path, true, { + signal: controller.signal, + operation: "export_evidence_bundle", + }), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } }); + expect(await readFile(path, "utf8")).toBe("original"); + expect(await readdir(root)).toEqual(["bundle.json"]); + }); +}); + describe("evidence bundle publication", () => { it.each([false, true])( "never publishes a partial streamed file (overwrite: %s)", diff --git a/tests/boundary/mcp/evidenceExportCancellation.test.ts b/tests/boundary/mcp/evidenceExportCancellation.test.ts new file mode 100644 index 000000000..2a7e2c40b --- /dev/null +++ b/tests/boundary/mcp/evidenceExportCancellation.test.ts @@ -0,0 +1,109 @@ +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { readdir, readFile, stat, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { setImmediate } from "node:timers/promises"; +import { expect, it, onTestFinished } from "vitest"; +import { readEvidenceBundle } from "../../../src/application/EvidenceBundleFiles.js"; +import { createEvidence } from "../../../src/domain/evidence.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +it.each([false, true])( + "stops an SDK export cancellation before publication and keeps the same session usable (overwrite: %s)", + async (overwrite) => { + const root = await createTestTempDirectory("rea-mcp-export-cancel-"); + const path = join(root, "bundle.json"); + if (overwrite) await writeFile(path, "original destination"); + const session = createTestBinarySession(() => { + throw new Error("Evidence export must not start a binary provider"); + }); + const evidence = createEvidence( + undefined, + { id: "fixture", name: "Fixture", version: "1" }, + { + operation: "large_observation", + parameters: {}, + result: { observed: "雪😀".repeat(1024 * 1024) }, + }, + ); + expect(session.recordEvidence(evidence).ok).toBe(true); + const server = createServer(session, session); + const client = new Client({ + name: "evidence-export-cancellation", + version: "1", + }); + const controller = new AbortController(); + onTestFinished(async () => { + controller.abort(); + await client.close(); + await server.close(); + await session.close(); + }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + const cancellation = client + .callTool( + { name: "export_evidence_bundle", arguments: { path, overwrite } }, + { signal: controller.signal }, + ) + .then( + () => "completed", + (error: unknown) => error, + ); + // Observe actual staged bytes, rather than only a locally rejected promise. + const deadline = performance.now() + 5000; + let stagedBytes = 0; + while (stagedBytes === 0 && performance.now() < deadline) { + const staging = (await readdir(root)).find((name) => + name.startsWith(".rea-write-"), + ); + if (staging !== undefined) { + const staged = await stat(join(root, staging, "content")).catch( + (cause: unknown) => { + if ( + cause instanceof Error && + "code" in cause && + cause.code === "ENOENT" + ) + return undefined; + throw cause; + }, + ); + stagedBytes = staged?.size ?? 0; + } + await setImmediate(); + } + expect(stagedBytes).toBeGreaterThan(0); + controller.abort(new Error("SDK export cancellation verification")); + expect(await cancellation).toMatchObject({ + message: expect.stringContaining("SDK export cancellation verification"), + }); + await expect + .poll(() => readdir(root), { timeout: 5000 }) + .toEqual(overwrite ? ["bundle.json"] : []); + if (overwrite) + expect(await readFile(path, "utf8")).toBe("original destination"); + expect(session.hasEvidence(evidence.evidence_id)).toBe(true); + await client.ping(); + const next = await client.callTool({ + name: "export_evidence_bundle", + arguments: { path, overwrite }, + }); + expect(next.isError, JSON.stringify(next)).not.toBe(true); + expect(await readEvidenceBundle(path)).toMatchObject({ + ok: true, + value: { + records: [ + { + evidence_id: evidence.evidence_id, + normalized_result: evidence.normalized_result, + }, + ], + }, + }); + await client.ping(); + }, +);