Files
rea/src/application/binary/BinarySessionInvestigation.test.ts
T
morluto 1f24b3fa57 feat(evidence)!: name the Evidence subject by its target identity (format revision 2) (#11416)
* feat(evidence)!: name the Evidence subject by its target identity (format revision 2)

The Evidence subject carries subject.identity (kind, sha256, format,
architecture, selection) and the Evidence ID commits to it, so raw/DOL
entry points and ESP flash offsets of the same bytes are different
subjects. Every record declares evidence_format: 2; revision 1 bundles,
standalone records and snapshots are refused with the recreate guidance.
binaryTargetIdentity is the one projection of an open target, used by
Evidence and snapshot comparison.

BREAKING CHANGE: Evidence format revision 2. Evidence IDs commit to the
subject's target identity (subject.identity, including the raw/DOL entry
point or ESP flash offsets), and every record declares evidence_format: 2.
Evidence bundles, records and analysis snapshots from earlier releases are
refused; recreate the observations with this release.

* refactor(analysis-view): read parent subjects through the Evidence identity accessors (#11423)

Analysis views compare their parent's file identity (evidenceFileTarget)
and take path and digest from evidenceSubjectTarget instead of reading
the subject's digest, format and architecture members, which duplicate
subject.identity until they are removed. A counted guard
(evidence-subject-declaration-read) keeps new direct reads out and
records the 20 remaining files.

* fix(evidence): carry format refusals through Evidence readers and bind target selections

- safeParseEvidence/safeParseImmutableEvidence return the format refusal as
  an expected failure; every consumer maps it to the one integrity refusal
  with the recreate guidance. An unmarked object is an earlier record only
  when it has every member records have always carried.
- ArtifactProvider inventory roots and provider subjects that name the
  target's own bytes carry the target's selection (ESP flash offsets).
- Snapshot rows bind only Evidence whose identity, selection included,
  matches the snapshot target.
- Entry-point selections use the raw-binary entry point form.

* fix(evidence): refuse unauthenticated or earlier-format records instead of reading them as absent

- recognizeEvidence (evidenceValidation) replaces tryParseEvidence: input
  without an evidence_id is not Evidence (ok(undefined)); a record that names
  one but fails authentication or is from another format revision is an
  EvidenceIntegrityError carrying the recreate guidance, never undefined.
- Direct analysis retains that refusal as a secondary failure instead of
  silently skipping source capture; cleanup projection, source-closure
  annotation and the flutter, debugger and release-exposure recoveries use
  the same owner (the last three previously read the unauthenticated schema).
- A desktop capture.json from an earlier format is refused with the recreate
  guidance instead of "not desktop application capture Evidence".

* fix(evidence): advertise revision 2 ledger examples and rank delivery omissions by serialized size

- The obligation ledger and reconstruction coverage examples named
  evidence_format 1, which revision 2 refuses; they now use
  EVIDENCE_FORMAT_REVISION.
- MCP delivery chose which unretained recovery to omit by a parsed-storage
  lower bound clipped at the response budget. Once revision 2 subjects made
  the source record's estimate cross the budget, both candidates tied at the
  clip and the smaller source was omitted ahead of the larger completed
  observation. Candidates are now ranked by serialized size, which is what
  the budget counts.

* refactor(native): compare function snapshots by their Evidence target identity (#11450)

Function snapshots carry the subject's file target identity instead of the
duplicated subject declaration. Call paths and function comparisons compare
targets through sameTargetIdentity, so the same bytes opened at a different
raw entry point or ESP flash offset no longer count as one coordinate space:
build_call_path refuses the mix, and compare_functions no longer matches
entries by address across selections. Structural candidates and native
function matching read the architecture and digest through
evidenceFileTarget.

Refs #11417

* refactor(artifacts): compare artifact and WASM summaries by their Evidence target identity (#11461)

Artifact comparison authenticates a summary against its retained inventory
through sameTargetIdentity and rebinds the alias with the whole target,
selection included, so a flash-selected inventory summary taken under an
alias path is no longer refused. WASM comparison, the analysis view
artifact projection and the inventory root check read the digest, format
and display path through the Evidence identity accessors.

Refs #11417

* refactor(evidence): read record subjects through the identity accessors in JS, managed, ledger and bundle readers (#11470)

JavaScript application graphs, runtime reconciliation, managed inspection
and native verification sources, the record summary filter, the ledger's
residual-unknown target and bundle scope selection read the subject digest,
format and display path through evidenceFileTarget and
evidenceSubjectDisplay. No comparison changes: each reader matches one
record's facts against its own payload or a caller filter.

Refs #11417

* refactor(evidence)!: name the Evidence subject only by its target identity (#11497)

* refactor(evidence)!: name the Evidence subject only by its target identity

The subject keeps `identity` and the display facts `name` and `local_path`.
The duplicated `digest`, `format` and `architecture` members are removed; the
format-owned declaration now validates the identity itself. Readers the type
checker found move to the owner accessors; untyped reads in verify scripts,
the efficiency harness and test matchers move to `subject.identity`. The
`evidence-subject-declaration-read` text guard and its baseline are deleted.

Fixes #11473
Refs #11417

BREAKING CHANGE: the Evidence subject no longer has `digest`, `format` or
`architecture`; read `subject.identity.sha256`, `subject.identity.format` and
`subject.identity.architecture`. A record that still carries them is refused.

* test(evidence): give the Flutter verifier fixture the identity subject and check the DOL declaration without the ID

* test(evidence): drop the removed subject members from the declaration matrix and tamper fixtures

* feat(evidence)!: give every Evidence record an explicit subject identity (#11536)

* feat(evidence)!: give every Evidence record an explicit subject identity

A producer that cannot name a file passes an `unknown` target identity
with a closed reason (derived-from-linked-evidence, not-observed,
unsupported-subject) instead of no subject. The subject is non-null;
unknown subjects have no display facts. The generic missing-subject
limitation and `subjectUnavailableReason` are removed; producer-specific
explanations are ordinary limitations. Comparison identity requires the
derived unknown, and null-subject consumers ask the owner accessors.

Refs #11417

BREAKING CHANGE: every Evidence record has a subject. A record without a
file target names `subject.identity` `{ "kind": "unknown", "reason": … }`
with `name` and `local_path` null, instead of `subject: null` and the
limitation "Artifact identity is unavailable for this observation.".
Their Evidence IDs change.

* fix(evidence): name explicit unknown subjects in JavaScript callers and keep a managed graph's file subject

The verification scripts are not type-checked, so five createEvidence
callers still passed undefined (or a missing first target) after the subject
became required. They now pass unknownTarget("not-observed").

A managed application graph chose the first present input subject. Every
subject is now present, so an unknown artifact subject hid a file subject on
the member or boundary Evidence. The graph now takes the first input subject
that names a file.

* test(evidence): assert the subject kind instead of a presence the type now guarantees

Every Evidence record has a subject after this change, so test guards and
assertions that checked it for null always passed. Each now checks that the
fixture subject names a file, or is removed where a later fileIdentity,
fileSubjectTarget or fileSubjectDisplay call already requires that. Non-null
assertions on Evidence subjects are removed; analysis-view inputs, whose
subject is optional, keep an undefined check.

* test(evidence): expect the Evidence subject format under its identity

Two boundary tests still matched subject.format, which slice 2e moved into
subject.identity. toMatchObject is not type-checked against the Evidence
shape, so they failed only when run (the signature test on macOS).
2026-11-16 06:28:01 +08:00

693 lines
25 KiB
TypeScript

import { unknownTarget } from "../../domain/targetIdentity.js";
import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { expect, it, vi } from "vitest";
import { OwnerCancellation } from "../../domain/analysisErrorCore.js";
import { createEvidence } from "../../domain/evidence.js";
import {
createEvidenceBundle,
parseEvidenceBundle,
} from "../../domain/evidenceBundle.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { err, ok } from "../../domain/result.js";
import type { RecordUnknownInput } from "../../domain/residualUnknown.js";
import { OwnedStagedOutput } from "../../filesystem/OwnedStagedOutput.js";
import type { AnalysisProviderCandidate } from "../../ports/AnalysisProvider.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import { BinarySession } from "./BinarySession.js";
import { SessionProviderRouter } from "./SessionProviderRouter.js";
import {
ControllableAnalysisClient,
createBinarySessionTargets,
createCacheProvider,
createDeferred,
createTestBinarySession,
} from "../../../tests/fixtures/binarySession.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { awaitAcknowledgement } from "../../../tests/fixtures/lifecycleAcknowledgement.js";
const observation = (label: string) =>
createEvidence(
unknownTarget("not-observed"),
{ id: "fixture", name: "Lifecycle fixture", version: "1" },
{ operation: label, parameters: {}, result: { fixture: label } },
);
const unknownRequirements: Omit<RecordUnknownInput, "question" | "domain"> = {
severity: "medium",
supporting_evidence_ids: [],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [],
relationships: [],
};
const unknownInput: RecordUnknownInput = {
...unknownRequirements,
question: "Which source revision produced this lifecycle fixture?",
domain: "provenance",
};
const seed = (session: ReturnType<typeof createTestBinarySession>) => {
expect(session.recordEvidence(observation("retained_fixture")).ok).toBe(true);
const recorded = session.recordUnknown(unknownInput);
if (!recorded.ok) throw recorded.error;
expect(
session.updateUnknown({
...unknownRequirements,
unknown_id: recorded.value.unknown_id,
expected_revision: 1,
status: "investigating",
resolution: null,
}).ok,
).toBe(true);
return session.exportEvidenceBundle();
};
it("publishes engine retirement with its pending cleanup owner already visible", async () => {
const [target] = await createBinarySessionTargets();
const entered = createDeferred<void>();
const release = createDeferred<void>();
const provider = createCacheProvider([]);
const session = createTestBinarySession({
...provider,
createClient: (...arguments_) => ({
...provider.createClient(...arguments_),
close: async () => {
entered.resolve();
await release.promise;
return ok(null);
},
}),
});
const notifications: ReturnType<typeof session.status>[] = [];
const pending: Promise<unknown>[] = [];
let unsubscribe: () => void = () => undefined;
try {
expect((await session.open(target)).ok).toBe(true);
expect(
(
await session.execute("address_name", {
address: "0x1000",
document: "fixture",
})
).ok,
).toBe(true);
unsubscribe = session.onAnalysisSnapshotChanged(() => {
notifications.push(session.status());
});
const closing = session.close();
pending.push(closing);
await awaitAcknowledgement(entered.promise, closing, "engine close entry");
expect(notifications.length).toBeGreaterThan(0);
for (const status of await Promise.all(notifications)) {
expect(status).toMatchObject({ open: false, cleanup_pending: true });
expect(status).not.toHaveProperty("cleanup_retry");
}
release.resolve();
expect((await closing).ok).toBe(true);
expect(await session.status()).toMatchObject({
open: false,
cleanup_pending: false,
});
} finally {
unsubscribe();
release.resolve();
await Promise.allSettled(pending);
await session.close();
}
});
it("preserves metadata invalidation across reset until the mutated engine is retired", async () => {
const [target] = await createBinarySessionTargets();
const calls: string[] = [];
const base = createCacheProvider(calls);
const createClient = vi.fn(base.createClient);
const session = createTestBinarySession({ ...base, createClient });
const parameters = { address: "0x1000", document: "fixture" };
try {
expect((await session.open(target)).ok).toBe(true);
expect((await session.execute("address_name", parameters)).ok).toBe(true);
const replay = session.exportAnalysisSnapshot();
if (!replay.ok) throw replay.error;
expect(replay.value.entries).toHaveLength(1);
// The fixture declares this operation as a metadata mutation. No real
// provider or target bytes are changed by the simulated observation.
expect(
(
await session.execute("set_address_name", {
...parameters,
name: "renamed",
})
).ok,
).toBe(true);
expect(session.exportAnalysisSnapshot()).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
const before = session.exportEvidenceBundle();
expect(await session.resetInvestigation()).toEqual({
ok: true,
value: {
cleared_evidence_records: before.records.length,
cleared_unknown_revisions: 0,
cleared_unknown_heads: 0,
retained_target: true,
},
});
expect(session.activeTarget()?.path).toBe(target);
expect(createClient).toHaveBeenCalledTimes(1);
expect(session.exportAnalysisSnapshot()).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
expect(session.importAnalysisSnapshot(replay.value)).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
expect((await session.execute("address_name", parameters)).ok).toBe(true);
expect((await session.execute("address_name", parameters)).ok).toBe(true);
expect(
calls.filter((operation) => operation === "address_name"),
).toHaveLength(3);
expect((await session.close()).ok).toBe(true);
expect((await session.open(target)).ok).toBe(true);
expect(session.exportAnalysisSnapshot().ok).toBe(true);
} finally {
await session.dispose();
}
});
it("preserves records through failed disposal and clears them only after its owned cleanup succeeds", async () => {
const [target] = await createBinarySessionTargets();
const client = new ControllableAnalysisClient();
const realClose = client.close.bind(client);
const failure = new ProviderCleanupError(
"fixture",
["fixture-owned-engine"],
{ reason: "Controlled disposal cleanup refusal" },
);
let allowed = false;
const close = vi
.spyOn(client, "close")
.mockImplementation(() =>
allowed ? realClose() : Promise.resolve(err(failure)),
);
const createClient = vi.fn(() => client);
const session = createTestBinarySession(createClient);
try {
expect((await session.open(target)).ok).toBe(true);
expect(
(
await session.execute("address_name", {
address: "0x1000",
document: "fixture",
})
).ok,
).toBe(true);
const before = seed(session);
for (let attempt = 0; attempt < 2; attempt += 1) {
expect(await session.dispose()).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(session.exportEvidenceBundle()).toEqual(before);
expect(session.listUnknowns()[0]?.revision).toBe(2);
expect(session.activeTarget()).toBeUndefined();
}
expect((await session.open(target)).ok).toBe(false);
expect(createClient).toHaveBeenCalledTimes(1);
allowed = true;
expect(await session.dispose()).toEqual(ok(null));
expect(session.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
expect(session.listUnknowns()).toEqual([]);
const closeCalls = close.mock.calls.length;
expect(await session.dispose()).toEqual(ok(null));
expect(close).toHaveBeenCalledTimes(closeCalls);
} finally {
allowed = true;
close.mockRestore();
await session.dispose();
}
});
it.each(["retired", "healthy"] as const)(
"refuses reset while separate candidate cleanup is pending with a %s engine",
async (engineState) => {
const [target] = await createBinarySessionTargets();
const root = await createTestTempDirectory("rea-reset-candidate-cleanup-");
const ownedRoot = join(root, "candidate-owned-inspection");
const checkpoint = join(root, "checkpoint.json");
const originalCheckpoint = Buffer.from("caller-owned checkpoint");
await writeFile(checkpoint, originalCheckpoint);
const providerCalls: string[] = [];
const provider = createCacheProvider(providerCalls);
let pending = false;
let cleanupAllowed = false;
const acquireCandidateOwner = async () => {
await mkdir(ownedRoot);
await writeFile(join(ownedRoot, "observation"), "candidate-owned facts");
pending = true;
};
const failure = new ProviderCleanupError("fixture", [ownedRoot], {
reason: "Controlled registry-owned inspection cleanup refusal",
});
const closeClient = vi.fn(async () => {
if (engineState === "retired") await acquireCandidateOwner();
return ok(null);
});
const createClient = vi.fn<typeof provider.createClient>(
(...arguments_) => ({
...provider.createClient(...arguments_),
close: closeClient,
}),
);
const closeOwnedResources = vi.fn(async () => {
if (!pending) return ok(null);
if (!cleanupAllowed) return err(failure);
await rm(ownedRoot, { recursive: true, force: true });
pending = false;
return ok(null);
});
const candidate: AnalysisProviderCandidate = {
identity: provider.identity,
capabilities: provider.capabilities,
createClient,
resolveAnalysisProfile: (selected, options) => {
if (provider.resolveAnalysisProfile === undefined)
throw new Error("The fixture requires its declared profile resolver");
return provider.resolveAnalysisProfile(selected, options);
},
inspectAvailability: () => ({
status: "available",
code: null,
reason: null,
diagnostics: {},
}),
inspectTargetSupport: () => ({
status: "supported",
code: null,
reason: null,
diagnostics: {},
}),
hasPendingOwnedResources: () => pending,
closeOwnedResources,
};
// The real registry owns this candidate predicate and cleanup callback;
// only the candidate's resource failure and native execution are simulated.
const registry = new AnalysisProviderRegistry([candidate]);
const session = new BinarySession(
SessionProviderRouter.selectable(registry, []),
);
const parameters = { address: "0x1000", document: "fixture" };
try {
expect((await session.open(target)).ok).toBe(true);
expect((await session.execute("address_name", parameters)).ok).toBe(true);
expect(createClient).toHaveBeenCalledTimes(1);
expect(registry.hasPendingOwnedResources()).toBe(false);
if (engineState === "healthy") {
const callsBefore = closeOwnedResources.mock.calls.length;
expect((await session.resetInvestigation()).ok).toBe(true);
expect(closeOwnedResources).toHaveBeenCalledTimes(callsBefore);
expect(closeClient).not.toHaveBeenCalled();
}
const before = seed(session);
if (engineState === "retired") {
expect(await session.close()).toEqual(err(failure));
expect(closeClient).toHaveBeenCalledTimes(1);
expect(session.activeTarget()).toBeUndefined();
} else {
await acquireCandidateOwner();
expect(session.activeTarget()?.path).toBe(target);
}
expect(registry.hasPendingOwnedResources()).toBe(true);
const cleanupCallsBefore = closeOwnedResources.mock.calls.length;
expect(
await session.resetInvestigation({
savePath: checkpoint,
overwrite: true,
}),
).toEqual(err(failure));
expect(closeOwnedResources).toHaveBeenCalledTimes(cleanupCallsBefore + 1);
expect((await readFile(checkpoint)).equals(originalCheckpoint)).toBe(
true,
);
expect(await readFile(join(ownedRoot, "observation"), "utf8")).toBe(
"candidate-owned facts",
);
expect(session.exportEvidenceBundle()).toEqual(before);
expect(session.listUnknowns()[0]?.revision).toBe(2);
expect(registry.hasPendingOwnedResources()).toBe(true);
expect(closeClient).toHaveBeenCalledTimes(
engineState === "retired" ? 1 : 0,
);
cleanupAllowed = true;
const reset = await session.resetInvestigation({
savePath: checkpoint,
overwrite: true,
});
expect(reset).toMatchObject({
ok: true,
value: {
cleared_evidence_records: before.records.length,
cleared_unknown_revisions: before.unknowns.length,
cleared_unknown_heads: 1,
retained_target: engineState === "healthy",
},
});
expect(closeOwnedResources).toHaveBeenCalledTimes(cleanupCallsBefore + 2);
expect(registry.hasPendingOwnedResources()).toBe(false);
await expect(access(ownedRoot)).rejects.toMatchObject({ code: "ENOENT" });
expect(
parseEvidenceBundle(JSON.parse(await readFile(checkpoint, "utf8"))),
).toEqual(before);
expect(session.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
expect(createClient).toHaveBeenCalledTimes(1);
expect(closeClient).toHaveBeenCalledTimes(
engineState === "retired" ? 1 : 0,
);
if (engineState === "healthy") {
expect(session.activeTarget()?.path).toBe(target);
expect((await session.execute("address_name", parameters)).ok).toBe(
true,
);
expect(createClient).toHaveBeenCalledTimes(1);
expect(
providerCalls.filter((operation) => operation === "address_name"),
).toHaveLength(2);
}
} finally {
cleanupAllowed = true;
await session.dispose();
}
},
);
it("drains prior metadata writes and refuses later admissions and direct writes after disposal", async () => {
const [target] = await createBinarySessionTargets();
const calls: string[] = [];
const session = createTestBinarySession(createCacheProvider(calls));
const entered = createDeferred<void>();
const release = createDeferred<void>();
let committedBeforeClear = false;
const pending: Promise<unknown>[] = [];
try {
expect((await session.open(target)).ok).toBe(true);
expect(
(
await session.execute("address_name", {
address: "0x1000",
document: "fixture",
})
).ok,
).toBe(true);
const snapshot = session.exportAnalysisSnapshot();
if (!snapshot.ok) throw snapshot.error;
const before = session.withAdmittedAnalysis(
"before_dispose",
undefined,
async () => {
entered.resolve();
await release.promise;
const record = observation("admitted_before_disposal");
const written = session.recordEvidence(record);
committedBeforeClear =
written.ok && session.hasEvidence(record.evidence_id);
return written;
},
);
pending.push(before);
await awaitAcknowledgement(entered.promise, before, "metadata write entry");
const disposing = session.dispose();
pending.push(disposing);
const late = vi.fn(async () =>
session.importEvidenceBundle(
createEvidenceBundle([observation("late_import")]),
),
);
const after = session.withAdmittedAnalysis(
"import_evidence_bundle",
undefined,
late,
);
pending.push(after);
release.resolve();
expect((await before).ok).toBe(true);
expect(committedBeforeClear).toBe(true);
expect(await disposing).toEqual(ok(null));
expect((await after).ok).toBe(false);
expect(late).not.toHaveBeenCalled();
const afterSettled = vi.fn(async () => session.recordUnknown(unknownInput));
expect(
(
await session.withAdmittedAnalysis(
"record_unknown",
undefined,
afterSettled,
)
).ok,
).toBe(false);
expect(afterSettled).not.toHaveBeenCalled();
expect(session.recordEvidence(observation("after_dispose")).ok).toBe(false);
expect(
session.importEvidenceBundle(
createEvidenceBundle([observation("after_dispose_import")]),
).ok,
).toBe(false);
expect(session.importAnalysisSnapshot(snapshot.value).ok).toBe(false);
expect(session.recordUnknown(unknownInput).ok).toBe(false);
expect(
session.recordEvidenceWithUnknown(
observation("after_dispose_unknown"),
unknownInput,
).ok,
).toBe(false);
expect((await session.open(target)).ok).toBe(false);
expect((await session.openBundleResources(target)).ok).toBe(false);
expect(session.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
} finally {
release.resolve();
await Promise.allSettled(pending);
await session.dispose();
}
});
it.each(["preaborted", "queued"] as const)(
"preserves exact reset cancellation reason when %s",
async (phase) => {
const root = await createTestTempDirectory("rea-reset-cancel-reason-");
const session = createTestBinarySession(
() => new ControllableAnalysisClient(),
);
const before = seed(session);
const entered = createDeferred<void>();
const release = createDeferred<void>();
const reason = { caller: "explicit reset cancellation", phase };
const controller = new AbortController();
const path = join(root, "must-not-publish.json");
let blocker: Promise<unknown> | undefined;
try {
if (phase === "queued") {
blocker = session.withAdmittedAnalysis(
"before_reset",
undefined,
async () => {
entered.resolve();
await release.promise;
},
);
await awaitAcknowledgement(
entered.promise,
blocker,
"reset blocker entry",
);
} else controller.abort(reason);
const resetting = session.resetInvestigation({
savePath: path,
signal: controller.signal,
});
if (phase === "queued") controller.abort(reason);
release.resolve();
await blocker;
const result = await resetting;
if (result.ok) throw new Error("Cancelled reset reported success");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cause).toBe(reason);
expect(session.exportEvidenceBundle()).toEqual(before);
await expect(access(path)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
release.resolve();
await blocker;
await session.dispose();
}
},
);
it("retains exact cancellation reason and a complete checkpoint during final cleanup", async () => {
const root = await createTestTempDirectory("rea-reset-final-cancel-");
const path = join(root, "published.json");
const session = createTestBinarySession(
() => new ControllableAnalysisClient(),
);
const before = seed(session);
const reason = { caller: "cancel reset after actual staged-output cleanup" };
const controller = new AbortController();
const original = OwnedStagedOutput.prototype.close;
let interrupted = false;
const seam = vi
.spyOn(OwnedStagedOutput.prototype, "close")
.mockImplementation(async function (this: OwnedStagedOutput) {
await original.call(this);
if (dirname(this.directory) === root && !interrupted) {
interrupted = true;
controller.abort(reason);
}
});
try {
const result = await session.resetInvestigation({
savePath: path,
signal: controller.signal,
});
if (result.ok) throw new Error("Cancelled reset reported success");
expect(interrupted).toBe(true);
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cause).toBe(reason);
const saved = await readFile(path);
expect(parseEvidenceBundle(JSON.parse(saved.toString("utf8")))).toEqual(
before,
);
expect(result.error.diagnostics?.saved_bundle).toEqual({
path,
bytes: saved.length,
records: before.records.length,
unknowns: before.unknowns.length,
});
expect(session.exportEvidenceBundle()).toEqual(before);
expect((await session.resetInvestigation()).ok).toBe(true);
expect(session.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
} finally {
seam.mockRestore();
await session.dispose();
}
});
it.each(
(
[
"execute",
"direct observation",
"external mutation",
"composed analysis",
"reset",
"open binary",
"open resources",
] as const
).flatMap((entrypoint) =>
[false, true].map((aborted) => ({ entrypoint, aborted })),
),
)(
"seals new $entrypoint admission at shutdown with caller aborted=$aborted",
async ({ entrypoint, aborted }) => {
const [target] = await createBinarySessionTargets();
const calls: string[] = [];
const session = createTestBinarySession(createCacheProvider(calls));
const entered = createDeferred<void>();
const release = createDeferred<void>();
const parameters = { address: "0x1000", document: "fixture" };
const mutation = vi.fn(async () => ok(null));
let earlier: Promise<unknown> | undefined;
try {
const opened = await session.open(target);
if (!opened.ok) throw opened.error;
earlier = session.withAdmittedAnalysis(
"earlier",
undefined,
async (analysis) => {
entered.resolve();
await release.promise;
return analysis.execute("address_name", parameters);
},
);
await awaitAcknowledgement(
entered.promise,
earlier,
"earlier analysis admission",
);
const controller = new AbortController();
const reason = { caller: "opaque shutdown cancellation", entrypoint };
if (aborted) controller.abort(reason);
session.beginShutdown();
const options = { signal: controller.signal };
const late = {
execute: () => session.execute("address_name", parameters, options),
"direct observation": () =>
session.executeForDirectObservation(
"address_name",
parameters,
parameters,
options,
),
"external mutation": () =>
session.withAdmittedExternalMutation(
undefined,
controller.signal,
mutation,
(_value, error) => error,
),
"composed analysis": () =>
session.withAdmittedAnalysis("late", controller.signal, mutation),
reset: () => session.resetInvestigation(options),
"open binary": () => session.open(target, options),
"open resources": () => session.openBundleResources(target, options),
}[entrypoint]();
release.resolve();
const result = await late;
if (result.ok) throw new Error("Expected shutdown admission refusal");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cause).toBe(
aborted ? reason : OwnerCancellation.ownerClosed,
);
expect(mutation).not.toHaveBeenCalled();
expect(await earlier).toMatchObject({ ok: true, value: { ok: true } });
expect(calls.filter((name) => name === "address_name")).toHaveLength(1);
} finally {
release.resolve();
await earlier;
await session.dispose();
}
},
);
it("stops prompt completion dispatch as soon as shutdown seals admission", async () => {
const [target] = await createBinarySessionTargets();
const calls: string[] = [];
const base = createCacheProvider(calls);
const session = createTestBinarySession({
...base,
createClient: (...arguments_) => {
const client = base.createClient(...arguments_);
return { ...client, executeIfReady: client.execute.bind(client) };
},
});
try {
const opened = await session.open(target);
if (!opened.ok) throw opened.error;
// Instantiate the real composite's child before exercising its ready path.
const initial = await session.execute("address_name", {});
if (!initial.ok) throw initial.error;
expect(
await session.executeIfProviderReady("address_name", {}),
).toMatchObject({ ok: true });
const before = calls.length;
session.beginShutdown();
expect(
await session.executeIfProviderReady("address_name", {}),
).toBeUndefined();
expect(calls).toHaveLength(before);
} finally {
await session.dispose();
}
});