Files
reverse-engineering-anything/src/process/capture/ProcessCaptureRead.ts
T
morluto ab84ba6839 fix(process)!: retain inspection cancellation and cleanup ownership (#10113)
* fix(process): preserve producer-owned inspection cancellation

Prototype the explicit inspection origin and retained file/batch owner protocol. Downstream adapter migration and lease binding remain required before integration.

* fix(process): type inspection ownership handoffs precisely

* fix(process): retain plain inspection preparation cancellation

* fix(process): retain explicit inspection cleanup and cancellation facts

* fix(process): require explicit inspection facts and cleanup scope

* refactor(process): remove redundant cleanup forwarding wrapper

* fix(firmware): retain inspection cancellation and cleanup ownership

* fix(wakaru): retain typed inspection outcomes and caller scope

* fix(ghidra): preserve inspection facts and launch cleanup scope

* fix(providers): preserve typed process inspection outcomes

* refactor(process): remove obsolete inspection cancellation re-export

* fix(native): preserve inspection preparation cleanup and cancellation

* fix(registration): retain typed inspection cleanup during Git discovery

* fix(process): preserve inspection deadline origin in adapter handoff

* fix(process): consume the canonical inspection selector in binding

* fix(native): preserve inspection deadlines and cleanup retry completion

* test(process): narrow the retained Darwin preparation owner

* fix(providers): preserve preparation ownership and timeout policy

Narrow preparation facts through their canonical owner, preserve actual cleanup capabilities and recorded cancellation, and keep enclosing command deadlines authoritative. Retain raw inspection records through Java refusal and configuration projections without changing availability fallback policy.

* refactor(process): use one inspection failure type owner

* fix(providers): retain recorded secondary failures when rebinding

* fix(ghidra): preserve normalized inspection facts through public projection

* fix(process): normalize native process listing cancellation

* docs(development): clarify failure provenance and cleanup verification

* fix(process): preserve direct inspection cancellation facts

* fix(process): retain inspection owners through termination

* fix(process): preserve command inspection cleanup provenance

* fix(desktop): preserve inspection facts after cleanup retry

* refactor(process)!: migrate desktop capture with inspection producers

* fix(desktop)!: preserve capture failure origins and cleanup owners (#10115)

* fix(desktop): preserve capture failure origins and cleanup

* fix(desktop): type keyring cleanup cancellation

* fix(kuna)!: retain copy cleanup before retiring workspaces (#10114)

* fix(kuna): own copy cancellation and descriptor cleanup

* fix(kuna): close copy descriptors before workspace removal

* test(kuna): type copy lifecycle gates for project library

* docs(kuna): explain retained copy-file cleanup and staging ownership

* docs(kuna): separate cache publication, integrity and cleanup guidance

* fix(desktop): retain sampling inspection owners before release

* fix(process): preserve capture file read cancellation origin

* fix(process): retain capture inspection cancellation and cleanup owners

* fix(process): retain sampling inspection failures in capture scope

* fix(process): retain inspection failures through mandatory cleanup

* fix(process): distinguish sampler shutdown from capture cancellation

* fix(browser): retain startup EOF before later cancellation

* fix(process): bind capture inspection cleanup to the owning run

* test(process): migrate cancellation fixtures to typed owners

Record explicit preparation and command cancellation facts, retain exact opaque reasons and physical causes, and guard the mocked version probe from native preparation. Keep the live Wakaru command control while adding a recording equivalent for bounded source verification.

* fix(process): own sampling reads and settle inspection peers

* fix(errors): retain authored recovery through cleanup composition

* fix(process): retain all sampling inspection leaves for final cleanup

* test(browser): report recording cleanup signal outcome

* fix(process): keep inspection error context out of implicit JSON

* fix(desktop): retain normalized sampling cleanup ownership

* test(process): assert tagged startup cancellation
2026-11-11 16:37:48 -05:00

260 lines
8.5 KiB
TypeScript

import type { Dir } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import {
AnalysisCleanupLease,
AnalysisCleanupLeaseGroup,
} from "../../artifacts/AnalysisCleanupLease.js";
import {
ProcessCaptureError,
describeProcessCaptureExecutionFailure,
} from "./ProcessCaptureError.js";
import { OwnedDirectoryHandle } from "../../filesystem/OwnedDirectoryHandle.js";
import { OwnedFileHandle } from "../../filesystem/OwnedFileHandle.js";
import {
OwnedRegularFileOperationFailure,
RegularFileCancelled,
RegularFileCleanupFailure,
withOwnedFileHandle,
type RegularFileOperationOutcome,
} from "../../filesystem/OwnedRegularFile.js";
import { RegularFileOperationCancelled } from "../../filesystem/RegularFile.js";
import { FileReadCancelled } from "../../filesystem/readFileHandleChunks.js";
/** The capture's existing scope retains exact leases without admitting work. */
export interface ProcessCaptureCleanupRetainer {
retain(lease: AnalysisCleanupLease): void;
}
type Cancellation = { readonly reason: unknown };
type CloseRetention = RegularFileCleanupFailure["retention"];
/** One physical read outcome plus any exact descriptor owners still unresolved. */
export class ProcessCaptureReadFailure<
Value = unknown,
> extends ProcessCaptureError {
readonly path: string;
readonly outcome: RegularFileOperationOutcome<Value>;
readonly cleanupLeases: readonly AnalysisCleanupLease[];
readonly cleanupCause: unknown;
readonly operationFailure: OwnedRegularFileOperationFailure | undefined;
readonly retention: CloseRetention;
/** An observed abort is independent of whether cancellation caused the read failure. */
readonly cancellation: Cancellation | undefined;
constructor(options: {
readonly path: string;
readonly outcome: RegularFileOperationOutcome<Value>;
readonly cleanupCause?: unknown;
readonly cleanupLease?: AnalysisCleanupLease;
readonly retention?: CloseRetention;
readonly completionCancellation?: Cancellation | undefined;
readonly operationFailure?: OwnedRegularFileOperationFailure | undefined;
readonly signal: AbortSignal | undefined;
}) {
const operationFailure =
options.operationFailure ??
(options.outcome.kind === "failed" &&
options.outcome.cause instanceof OwnedRegularFileOperationFailure
? options.outcome.cause
: undefined);
const outcome: RegularFileOperationOutcome<Value> =
operationFailure !== undefined && options.outcome.kind === "failed"
? { kind: "failed", cause: operationFailure.operationCause }
: options.outcome;
const cleanupLeases =
options.cleanupLease === undefined ? [] : [options.cleanupLease];
const primaryCancellation =
outcome.kind === "failed"
? operationFailure === undefined
? operationCancellation(outcome.cause)
: undefined
: options.completionCancellation;
const cancellation =
primaryCancellation ??
(options.signal?.aborted === true
? { reason: options.signal.reason }
: undefined);
const primary =
primaryCancellation !== undefined
? primaryCancellation.reason
: outcome.kind === "failed"
? outcome.cause
: options.cleanupCause;
const cleanupCause = options.cleanupCause;
const cleanupReason =
describeProcessCaptureExecutionFailure(cleanupCause) ??
"descriptor close rejected without a value";
const reasons = [
...(outcome.kind === "failed"
? [
describeProcessCaptureExecutionFailure(outcome.cause) ??
"read rejected without a value",
]
: []),
...(options.cleanupLease === undefined
? []
: [`descriptor close failed: ${cleanupReason}`]),
];
super(
`Process capture read failed for ${options.path}${reasons.length === 0 ? "" : `: ${reasons.join("; ")}`}`,
{
cause: primary,
...(primaryCancellation === undefined
? {}
: {
userCategory: "cancelled" as const,
reason: "cancelled" as const,
}),
...(options.cleanupLease === undefined
? {}
: {
cleanup: {
reason: cleanupReason,
resources: options.cleanupLease?.cleanupResources ?? [
options.path,
],
},
}),
},
);
this.path = options.path;
this.outcome = outcome;
this.cleanupLeases = cleanupLeases;
this.cleanupCause = cleanupCause;
this.operationFailure = operationFailure;
this.retention = options.retention ?? { kind: "not_requested" };
this.cancellation = cancellation;
if (cleanupLeases.length > 0)
new AnalysisCleanupLeaseGroup(this, cleanupLeases);
}
}
const operationCancellation = (cause: unknown): Cancellation | undefined => {
if (
cause instanceof RegularFileOperationCancelled ||
cause instanceof FileReadCancelled
)
return { reason: cause.reason };
if (
cause instanceof ProcessCaptureError &&
cause.userCategory === "cancelled"
)
return {
reason: Object.hasOwn(cause, "cause") ? cause.cause : cause,
};
return undefined;
};
/** Keep an admitted file descriptor, its operation result, and close owner together. */
export const withProcessCaptureFile = async <Value>(
path: string,
handle: FileHandle,
signal: AbortSignal | undefined,
retainer: ProcessCaptureCleanupRetainer | undefined,
operation: (file: FileHandle) => Promise<Value>,
): Promise<Value> => {
const owner = new OwnedFileHandle(handle);
const cleanupLease = AnalysisCleanupLease.forCloseOwner(owner, path);
try {
return await withOwnedFileHandle(
path,
owner,
{
...(signal === undefined ? {} : { signal }),
...(retainer === undefined
? {}
: { retainFailedClose: () => retainer.retain(cleanupLease) }),
},
operation,
);
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure)
throw new ProcessCaptureReadFailure({
path,
outcome: cause.outcome as RegularFileOperationOutcome<Value>,
cleanupCause: cause.cleanupCause,
cleanupLease,
retention: cause.retention,
operationFailure: cause.operationFailure,
...(cause.completionCancellation === undefined
? {}
: { completionCancellation: cause.completionCancellation }),
signal,
});
if (cause instanceof RegularFileCancelled)
throw new ProcessCaptureReadFailure({
path,
outcome: cause.outcome,
completionCancellation: { reason: cause.reason },
signal,
});
throw new ProcessCaptureReadFailure({
path,
outcome: { kind: "failed", cause },
signal,
});
}
};
/** Read and close an explicit directory without losing completed entries on close failure. */
export const withProcessCaptureDirectory = async <Value>(
path: string,
directory: Dir,
signal: AbortSignal | undefined,
retainer: ProcessCaptureCleanupRetainer | undefined,
operation: (directory: Dir) => Promise<Value>,
): Promise<Value> => {
const owner = new OwnedDirectoryHandle(directory);
const cleanupLease = AnalysisCleanupLease.forCloseOwner(owner, path);
let outcome: RegularFileOperationOutcome<Value>;
try {
if (signal?.aborted === true)
throw new RegularFileOperationCancelled(signal.reason);
outcome = { kind: "completed", value: await operation(directory) };
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
}
try {
await owner.close();
} catch (cleanupCause: unknown) {
let retention: CloseRetention = { kind: "not_requested" };
if (retainer !== undefined) {
try {
retainer.retain(cleanupLease);
retention = { kind: "callback_returned" };
} catch (cause: unknown) {
retention = { kind: "callback_threw", cause };
}
}
throw new ProcessCaptureReadFailure({
path,
outcome,
cleanupCause,
cleanupLease,
retention,
...(outcome.kind === "completed" && signal?.aborted === true
? { completionCancellation: { reason: signal.reason } }
: {}),
signal,
});
}
if (outcome.kind === "failed") {
throw new ProcessCaptureReadFailure({
path,
outcome,
signal,
});
}
if (signal?.aborted === true)
throw new ProcessCaptureReadFailure({
path,
outcome,
completionCancellation: { reason: signal.reason },
signal,
});
return outcome.value;
};