From 2dea2c203870bbdbde8d0eefef8aadae10e91c44 Mon Sep 17 00:00:00 2001 From: sharif <61516383+sharifhsn@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:51:59 -0500 Subject: [PATCH] feat(kuna): admit PE/COFF, and forward the engine's spec variables (#15058) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * kuna: admit PE/COFF and forward the engine's spec variables PE x64 is the class kuna handles and no other provider here does; its .pdata is a better boundary source than discovery (430,906 discovered against 299,257 .pdata extents on one 120 MB image). Admission is the format check only — kuna opens at the header base itself. A source-built kuna also finds its compiled specs through KUNA_SPECS or SLEIGHHOME, and the child environment carried only HOME/XDG_CACHE_HOME/NO_COLOR, so a build install failed with 'Could not find .sla' and it read as a target problem. Both are forwarded when set; a release kuna carries its specs and is unaffected. Adds the env test, flips the PE admission assertion, and says both in the provider doc. * chore: rerun checks * fix(kuna): bind selected spec trees into the child and the cache Forward KUNA_SPECS and SLEIGHHOME from the environment captured for the provider, not from the ambient process. Hash each selected tree into the analysis profile and export key so an in-place rebuild cannot reuse an older result, and give a tree that cannot be hashed its own inspection fence. * fix(kuna): revalidate spec trees at launch and admit only x86-64 PE The session kept the first specification digest, so a later export could read a rebuilt tree and publish it under the earlier key. Each command and export now hashes the selected trees again and keys the result with that read; a tree that cannot be confirmed becomes an unknown identity with a new reuse fence. Directory close failures are retained on the caller's resource scope, and the entry cap stops the directory read instead of buffering every name. PE admission is x86-64; other PE architectures are refused. Co-authored-by: morluto * style(kuna): format the launch-revalidation changes oxfmt --check rejected KunaProjectCache, KunaSessionClient, KunaSpecIdentity, and the spec identity test. Apply the repository formatter. Co-authored-by: morluto * fix(kuna): own spec identity once per launching operation Compute one specification snapshot inside the session's classified failure boundary and use that value for the cache key, the close key, the profile, and the launch. Cached answers from an adopted project do not walk the tree again. A tree that differs from the committed profile is refused and the adopted reader is dropped. Directory close retains one lease, and the session dialect keeps that cleanup on the classified error. Delete the extra refreshes in project build and command launch. Co-authored-by: morluto * fix(kuna): check spec identity when a child spawns Drop the operation allowlist. Each operation carries one memoized confirmation, and runKunaCommand runs it under that command's deadline before spawn. An unidentifiable tree reuses the fence minted for the resolved profile, so the export key matches the profile BinarySession commits. Relative spec paths are resolved from REA's working directory when they are selected. A spec-file close keeps the lease the hook returns, and installation retention is keyed by the original owner. Co-authored-by: morluto * fix(kuna): keep spec-scan leases with the spawn owner A shared export was retaining a failed spec close on the client that started the build. That client can close while another client still waits, and its close does not join the scan. The scan now runs in the cache scope and the lease it returns is the cache's hash lease, so close and settled can still release it. A client-owned command keeps the lease in that command's scope. Co-authored-by: morluto * fix(kuna): isolate each spec scan's signal and deadline Spawns still share one identity result, but each waits on its own abort, budget, and cleanup owner. The child timeout is whatever budget remains after the scan and names the Kuna timeout setting. Co-authored-by: morluto * test(analysis-view): accept either oversized-page parent recovery Source tests merge this branch with main, whose fixed-allowance recovery no longer says "caller-supplied bundle". Co-authored-by: morluto * test(views): drop recovery-prose lock on oversized route refusal * fix(kuna): bound installation spec reads by the function timeout identifyKunaExternalSpecs requires the caller's deadline. Inspection uses REA_KUNA_TIMEOUT_MS, or the version-probe deadline when that timeout cannot be read, and reports AnalysisTimeoutError. Co-authored-by: morluto * fix(kuna): own spec scans through close and register spec roots A cancelled wait keeps the physical spec read on the command or export scope until its close settles. Setup and doctor copy an explicit KUNA_SPECS or SLEIGHHOME into the client registration. Co-authored-by: morluto * fix(kuna): retry a clean spec timeout and re-list walked directories A spec-read timeout keeps a failed close's lease. A clean installation timeout is not reused, so the next settings scan again. The walk re-lists each directory and refuses the digest when the name set changed. Co-authored-by: morluto * fix(kuna): keep spec-scan waits bounded and save absolute spec roots The caller's wait ends at its deadline while the scope still owns the read. Setup stores KUNA_SPECS and SLEIGHHOME as absolute paths. Co-authored-by: morluto * refactor(kuna): verify spec trees inline at each spawn Replace the shared, detached per-operation spec scan in KunaSessionClient, and the ownSpecScan plumbing that kept it owned, with an inline check in runKunaCommand beside the executable-digest check. Each spawn reads the tree under its own signal, deadline and cleanup owner, so the scan cannot outlive the request or the shutdown that admitted it. - Route every Kuna deadline timeout, including the spec-read timeout and its cleanup facts, through one kunaDeadlineTimeout owner. - Move spec-variable selection into KunaConfiguration, its only reader. - Pass an owner cancellation reason to the scan timer and read the function timeout through readRuntimeSetting (architecture guards). - Cover a spec-file close failure that coincides with the scan timeout. * fix(kuna): report late spec scans as timeouts and keep empty selections - Check the deadline after the final directory read and close, so a scan that finishes past its budget is a timeout, not an identified tree. - Convert only a deadline-stopped read to a timeout; an earlier physical failure keeps its cause beside the cleanup it left. - Keep an explicitly empty KUNA_SPECS or SLEIGHHOME empty in setup and doctor registrations instead of resolving it to the working directory. * test(kuna): remove wall-clock timing from spec deadline tests - Observe the timeout the strings child is granted instead of asserting elapsed time; the scan delay must come out of that grant. A control that gives the child the full budget fails the test. - Block the failing spec close on the scan's own deadline signal, with a test-owned release, instead of racing a fixed delay against a 20 ms deadline. * fix(kuna): keep launch directory cleanup and report doctor spec timeouts - A spec directory whose close failed during a launch scan now reports its retained cleanup through kunaRetainedResourceCleanupError instead of a plain adapter error, so the command reports cleanupIncomplete until its scope retries the handle. - Doctor projects a spec read that exceeds kuna.function_timeout_ms into a failed Kuna version check with the timeout's recovery, instead of aborting the doctor run. - Narrow the granted child timeout in the deadline test (CI typecheck). --------- Co-authored-by: sharif Co-authored-by: Cursor Agent Co-authored-by: morluto Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- docs/kuna-provider.md | 8 +- .../SetupRegistrationEnvironment.ts | 15 +- .../analysisView/javascriptRoutesView.test.ts | 1 - src/filesystem/OwnedRegularFile.ts | 34 +- src/filesystem/StableFileHash.ts | 2 +- src/filesystem/callerPath.ts | 19 + src/kuna/KunaCacheManifest.ts | 19 + src/kuna/KunaCommand.ts | 196 ++- src/kuna/KunaConfiguration.ts | 98 ++ src/kuna/KunaCopy.test.ts | 3 + src/kuna/KunaDoctor.ts | 30 +- src/kuna/KunaInstallation.ts | 119 +- src/kuna/KunaProjectCache.ts | 26 +- src/kuna/KunaProjectExport.ts | 8 +- src/kuna/KunaProvider.ts | 26 +- src/kuna/KunaSessionClient.ts | 66 +- src/kuna/KunaSessionEvidence.ts | 3 +- src/kuna/KunaSpecIdentity.ts | 773 ++++++++++ src/kuna/KunaTargetCommands.ts | 6 +- .../kuna/kunaCacheCleanupConcurrency.test.ts | 1 + .../kuna/kunaChildEnvironment.test.ts | 132 ++ .../providers/kuna/kunaDoctor.test.ts | 104 +- .../providers/kuna/kunaProjectCache.test.ts | 1 + .../providers/kuna/kunaProvider.test.ts | 11 +- .../kuna/kunaSelectedCommand.test.ts | 15 +- .../providers/kuna/kunaSpecIdentity.test.ts | 1295 +++++++++++++++++ 26 files changed, 2897 insertions(+), 114 deletions(-) create mode 100644 src/kuna/KunaSpecIdentity.ts create mode 100644 tests/boundary/providers/kuna/kunaChildEnvironment.test.ts create mode 100644 tests/boundary/providers/kuna/kunaSpecIdentity.test.ts diff --git a/docs/kuna-provider.md b/docs/kuna-provider.md index 2e42ff46ab..e4534048e5 100644 --- a/docs/kuna-provider.md +++ b/docs/kuna-provider.md @@ -2,7 +2,7 @@ [Kuna](https://github.com/Noelo-Lab/kuna) is an Apache-2.0 decompiler distributed as one `kuna` executable. For a new installation, use Kuna 1.1000, REA's recommended verified release. REA uses a `kuna` you supply; it does not download, install, update or bundle Kuna. REA accepts other releases; `rea doctor` and analysis Evidence report them as unverified. Verification compares the reported version; it does not authenticate the executable. Analysis profiles retain the observed version and executable digest, independently of REA's current verified-release policy. The 1.1000 real-provider checks ran on macOS arm64; Linux and other hosts have not been verified with that release. -Kuna is static: it reads the selected image and never executes it. +Kuna is static: it reads the selected image and never executes it. A source-built kuna needs its compiled specifications, which it finds through `KUNA_SPECS` or `SLEIGHHOME`. REA forwards each variable from the provider's selected environment when that environment sets it, and does not read the ambient process environment. The selected path and a content digest of that tree are part of the analysis profile and the export cache key. A relative path is resolved to an absolute path from REA's working directory when the configuration is read; the identity scan and the child both use that absolute path. A path that cannot be resolved is a configuration error. An unidentifiable tree gets one `reuse_fence` minted with the resolved profile and reused for later inspection and launch, so the export key matches the committed profile. Installation reads each selected tree under the function timeout (`REA_KUNA_TIMEOUT_MS`), or under the version-probe deadline when that timeout cannot be read. Each child spawn re-reads the tree under its own deadline, cancellation and cleanup owner, and is refused when the tree differs; a timed-out installation read is retried under the next accepted `kuna.function_timeout_ms`. A request that does not spawn a child does not read the tree. A release kuna carries its specifications and needs neither variable. This profile change makes earlier Kuna analysis snapshots and resumable directory exports incompatible, even with the same Kuna executable. Keep the old files: @@ -43,7 +43,7 @@ reports two health checks beside it that do not decide availability: `version` runs `kuna --version` and fingerprints the executable, and `cache` inspects the cache root without creating it. Runtime does not run these probes when it reports availability; opening a target runs the version probe. `rea setup` -lists Kuna as a ready provider only when every Kuna check passes. +lists Kuna as a ready provider only when every Kuna check passes. Setup copies an explicit `KUNA_SPECS` or `SLEIGHHOME` into that client's registration with the other Kuna settings. Select it explicitly with `--provider kuna`, MCP's `open_binary.provider_id: "kuna"`, or `REA_ANALYSIS_PROVIDER=kuna`. With Kuna and another provider configured for the same target, `auto` reports `ambiguous` instead of choosing one. @@ -70,7 +70,7 @@ workflows. Early single-function results have their own source limitation. A single-function decompile, inventory, string, graph or xref run that exceeds its deadline fails as `provider_timeout`, naming the setting that owns the deadline. Change the reported budget for newly accepted operations with `update_analysis_settings` using `kuna.function_timeout_ms` or `kuna.project_timeout_ms`. A project export that exceeds `REA_KUNA_PROJECT_TIMEOUT_MS` is an export failure instead: requests that need the export report `capability_unavailable` with the export's own retry guidance. -Windows is not supported yet. Supported targets are ELF and thin Mach-O executables for x86-64, AArch64 and ARM; PE and universal Mach-O are rejected with a typed reason. +PE/COFF (x86-64) is admitted beside ELF and thin Mach-O executables for x86-64, AArch64 and ARM; universal Mach-O is still rejected with a typed reason. A PE opens at its own header image base and `.pdata` bounds are kuna's, not REA's. Kuna still runs only on Linux and macOS: a Windows host is refused before any target is opened. ## What Kuna answers @@ -91,7 +91,7 @@ Typed procedure references, basic blocks, raw-memory tools, annotations and type ## How answers are produced -The first text or assembly request in a session looks for this target's export in the cache. `list_documents` reads the selected path without initializing analysis. Inventory, function lookup, string queries, call relationships and xrefs do not start a C export. A data-name lookup starts it only when the address is absent from the function inventory. The export is keyed by the target's SHA-256, the Kuna executable's SHA-256, its version and `--jobs`. +The first text or assembly request in a session looks for this target's export in the cache. `list_documents` reads the selected path without initializing analysis. Inventory, function lookup, string queries, call relationships and xrefs do not start a C export. A data-name lookup starts it only when the address is absent from the function inventory. The export is keyed by the target's SHA-256, the Kuna executable's SHA-256, its version, `--jobs`, and any selected `KUNA_SPECS` or `SLEIGHHOME` path together with the content digest committed in the analysis profile. No selected specification keeps the key used when those variables are unset. - **Warm cache:** analysis reads reuse the verified export. A fresh server verifies its file digests once, even for concurrent first requests; that cost scales with export size. - **Cold cache:** diff --git a/src/application/SetupRegistrationEnvironment.ts b/src/application/SetupRegistrationEnvironment.ts index 1ba217dd6f..d8b1b904ea 100644 --- a/src/application/SetupRegistrationEnvironment.ts +++ b/src/application/SetupRegistrationEnvironment.ts @@ -1,5 +1,14 @@ import type { DoctorProviderInspection } from "../ports/DoctorProviderInspection.js"; import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; +import { absoluteCallerSelection } from "../filesystem/callerPath.js"; + +const KUNA_SPEC_REGISTRATION_SETTINGS = ["KUNA_SPECS", "SLEIGHHOME"] as const; + +/** A saved spec root must not depend on the client's later working directory. */ +const registeredSettingValue = (key: string, value: string): string => + KUNA_SPEC_REGISTRATION_SETTINGS.some((spec) => spec === key) + ? absoluteCallerSelection(value) + : value; const SELECTED_REGISTRATION_SETTINGS = [ "GHIDRA_INSTALL_DIR", @@ -54,6 +63,8 @@ const SELECTED_REGISTRATION_SETTINGS = [ "REA_KUNA_PROJECT_TIMEOUT_MS", "REA_KUNA_TIMEOUT_MS", "REA_KUNA_JOBS", + "KUNA_SPECS", + "SLEIGHHOME", "REA_ANALYSIS_PROVIDER", "REA_ASAR_MAX_HEADER_BYTES", "REA_ASAR_MAX_LISTING_BYTES", @@ -123,7 +134,9 @@ export const explicitSetupRegistrationEnvironment = ( Object.fromEntries( SELECTED_REGISTRATION_SETTINGS.flatMap((key) => { const value = environment[key]; - return value === undefined ? [] : [[key, value]]; + return value === undefined + ? [] + : [[key, registeredSettingValue(key, value)]]; }), ); diff --git a/src/domain/analysisView/javascriptRoutesView.test.ts b/src/domain/analysisView/javascriptRoutesView.test.ts index 0b0f7aaaa2..c2ce893801 100644 --- a/src/domain/analysisView/javascriptRoutesView.test.ts +++ b/src/domain/analysisView/javascriptRoutesView.test.ts @@ -300,7 +300,6 @@ it("explains how to recover an oversized route row without changing the parent", }); expect(projected.remediation.action).toContain("select fewer fields"); expect(projected.remediation.action).toContain("no runtime override"); - expect(projected.remediation.action).toContain("caller-supplied bundle"); const narrow = query(source, { ...selection, fields: ["classification", "confidence"], diff --git a/src/filesystem/OwnedRegularFile.ts b/src/filesystem/OwnedRegularFile.ts index 17fb36d8d6..f60a48d226 100644 --- a/src/filesystem/OwnedRegularFile.ts +++ b/src/filesystem/OwnedRegularFile.ts @@ -64,6 +64,8 @@ export interface RegularFileCleanupFacts { | undefined; readonly completionCancellation?: { readonly reason: unknown } | undefined; readonly operationFailure?: OwnedRegularFileOperationFailure | undefined; + /** Lease returned by the close hook, when the hook retained one. */ + readonly retainedClose?: unknown; } export class RegularFileCleanupFailure extends Error { @@ -74,6 +76,8 @@ export class RegularFileCleanupFailure extends Error { readonly retention: NonNullable; readonly completionCancellation: { readonly reason: unknown } | undefined; readonly operationFailure: OwnedRegularFileOperationFailure | undefined; + /** Lease returned by the close hook, when the hook retained one. */ + readonly retainedClose: unknown; constructor(facts: RegularFileCleanupFacts) { const { @@ -103,12 +107,14 @@ export class RegularFileCleanupFailure extends Error { this.retention = retention; this.completionCancellation = completionCancellation; this.operationFailure = operationFailure; + this.retainedClose = facts.retainedClose; } } export interface OwnedFileOperationOptions { readonly signal?: AbortSignal; - readonly retainFailedClose?: (owner: OwnedFileHandle) => void; + /** Return the lease this owner retains so the failure can clear with it. */ + readonly retainFailedClose?: (owner: OwnedFileHandle) => unknown; } /** Read only cancellation facts recorded by the operation or its final close. */ @@ -159,7 +165,8 @@ export const withOwnedRegularFile = async ( owner: cause.owner, outcome: { kind: "failed", cause: cause.cause }, cleanupCause: cause.cleanupCause, - retention, + retention: retention.retention, + retainedClose: retention.retainedClose, }); }); return withOwnedFileHandle( @@ -206,12 +213,14 @@ export const withOwnedFileHandle = async ( : undefined; // Retain the physical read outcome even if the caller cancelled during // close: consumers may need completed observations such as a file digest. + const retention = retainOwner(options.retainFailedClose, owner); throw new RegularFileCleanupFailure({ path, owner, outcome: retainedOutcome, cleanupCause, - retention: retainOwner(options.retainFailedClose, owner), + retention: retention.retention, + retainedClose: retention.retainedClose, completionCancellation, operationFailure, }); @@ -228,12 +237,21 @@ export const withOwnedFileHandle = async ( const retainOwner = ( retain: OwnedRegularFileOptions["retainFailedClose"], owner: OwnedFileHandle, -): RegularFileCleanupFailure["retention"] => { - if (retain === undefined) return { kind: "not_requested" }; +): { + readonly retention: RegularFileCleanupFailure["retention"]; + readonly retainedClose: unknown; +} => { + if (retain === undefined) + return { retention: { kind: "not_requested" }, retainedClose: undefined }; try { - retain(owner); - return { kind: "callback_returned" }; + return { + retention: { kind: "callback_returned" }, + retainedClose: retain(owner), + }; } catch (cause: unknown) { - return { kind: "callback_threw", cause }; + return { + retention: { kind: "callback_threw", cause }, + retainedClose: undefined, + }; } }; diff --git a/src/filesystem/StableFileHash.ts b/src/filesystem/StableFileHash.ts index e7d520c3b3..2a439fa800 100644 --- a/src/filesystem/StableFileHash.ts +++ b/src/filesystem/StableFileHash.ts @@ -19,7 +19,7 @@ import { errorMessage } from "../kernel/errorMessage.js"; export interface StableFileHashOptions { readonly signal?: AbortSignal; - readonly retainFailedClose: (owner: OwnedFileHandle) => void; + readonly retainFailedClose: (owner: OwnedFileHandle) => unknown; /** Optional synchronous observer invoked with each read slice (reused buffer; copy if retained). */ readonly onChunk?: (chunk: Buffer) => void; } diff --git a/src/filesystem/callerPath.ts b/src/filesystem/callerPath.ts index b7736707a1..bc3e705450 100644 --- a/src/filesystem/callerPath.ts +++ b/src/filesystem/callerPath.ts @@ -73,3 +73,22 @@ export const absoluteCallerPath = ( const directory = /\/\.?$/u.test(path) && segments.length > 0; return `/${segments.join("/")}${directory ? "/" : ""}`; }; + +/** + * Absolute form of a caller-selected path, for a value saved into another + * process. An empty or already absolute path is unchanged. A relative path + * that cannot be resolved stays as the caller wrote it. + */ +export const absoluteCallerSelection = ( + path: string, + platform: NodeJS.Platform = HOST_PLATFORM.platform, +): string => { + // An empty selection stays empty; it never selects the working directory. + if (path === "" || isQualifiedCallerPath(path, platform)) return path; + try { + const resolved = absoluteCallerPath(path, { platform }); + return isQualifiedCallerPath(resolved, platform) ? resolved : path; + } catch { + return path; + } +}; diff --git a/src/kuna/KunaCacheManifest.ts b/src/kuna/KunaCacheManifest.ts index ef438a864e..ff5046249a 100644 --- a/src/kuna/KunaCacheManifest.ts +++ b/src/kuna/KunaCacheManifest.ts @@ -6,6 +6,10 @@ import { utcDateTimeSchema } from "../domain/offsetDateTime.js"; import { releaseProducerIdentity } from "../filesystem/ProducerIdentity.js"; import { sha256Hex } from "../kernel/sha256Hex.js"; import { kunaExportFileNames } from "./KunaProjectExport.js"; +import { + kunaExternalSpecRecordSchema, + type KunaExternalSpecRecord, +} from "./KunaSpecIdentity.js"; import type { KunaInventoryFunction, KunaProjectFunction, @@ -32,6 +36,13 @@ export interface KunaProjectKeyInputs { * callee-first prototypes and change some bodies. */ readonly jobs: number; + /** + * Selected external specification trees. Empty keeps the historical key: + * a release executable with no `KUNA_SPECS` or `SLEIGHHOME` does not gain + * a new cache identity. A selected tree includes its path and content + * digest, or a per-inspection fence when that digest cannot be made. + */ + readonly externalSpecs: readonly KunaExternalSpecRecord[]; } /** Content address of one export: every input that can change its bytes. */ @@ -48,6 +59,9 @@ export const kunaProjectKey = (inputs: KunaProjectKeyInputs): string => kuna_executable: inputs.kunaExecutable, kuna_version: inputs.kunaVersion, export: { command: "decompile-project", jobs: inputs.jobs }, + ...(inputs.externalSpecs.length === 0 + ? {} + : { external_specs: inputs.externalSpecs }), }) ?? "", ); @@ -69,6 +83,10 @@ const manifestSchema = z kuna_executable: z.string(), kuna_version: z.string().min(1), jobs: z.int().positive(), + // Absent on exports written before specification identity. Parsing + // supplies an empty list so those keys stay valid; a selected tree is + // stored explicitly. + external_specs: z.array(kunaExternalSpecRecordSchema).default([]), }), files: z.strictObject({ c: fileSchema, @@ -100,6 +118,7 @@ const manifestSchema = z kunaExecutable: inputs.kuna_executable, kunaVersion: inputs.kuna_version, jobs: inputs.jobs, + externalSpecs: inputs.external_specs ?? [], }) ) context.addIssue({ diff --git a/src/kuna/KunaCommand.ts b/src/kuna/KunaCommand.ts index c3cf1ad160..42322bac93 100644 --- a/src/kuna/KunaCommand.ts +++ b/src/kuna/KunaCommand.ts @@ -6,7 +6,7 @@ import { AnalysisError, type AnalysisCapturedOutput, } from "../domain/analysisErrorBase.js"; -import { analysisSettingLimit } from "../domain/analysisSettingDefinitions.js"; +import { Deadline } from "../domain/deadline.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { AnalysisOutputError, @@ -18,6 +18,8 @@ import { import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { + AnalysisCleanupLease, + AnalysisCleanupLeaseGroup, assertArtifactReadActive, artifactFileCompletion, artifactFilePrimaryFacts, @@ -32,7 +34,6 @@ import { } from "../process/OwnedCommand.js"; import { hashStableFile } from "../filesystem/StableFileHash.js"; import { assertArtifactCommandPath } from "../process/ArtifactCommandPath.js"; -import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import { RegularFileCleanupFailure, regularFileCancellation, @@ -49,8 +50,15 @@ import { type KunaInstallation, type KunaResourceScope, } from "./KunaInstallation.js"; -import type { KunaDeadline } from "./KunaConfiguration.js"; +import { kunaDeadlineTimeout, type KunaDeadline } from "./KunaConfiguration.js"; import { KUNA_PROVIDER_ID } from "./KunaRelease.js"; +import { + comparableKunaExternalSpecs, + identifyKunaExternalSpecs, + kunaExternalSpecParameter, + sameKunaExternalSpecs, + type KunaSpecCloseOwner, +} from "./KunaSpecIdentity.js"; import type { ProviderFailureDialect } from "../providers/classifyProviderFailure.js"; import { errorMessage } from "../kernel/errorMessage.js"; @@ -83,9 +91,14 @@ interface KunaCommandRequest { readonly stdout?: Writable | undefined; readonly signal: AbortSignal; readonly retainFailedFileClose: ( - owner: OwnedFileHandle, + owner: KunaSpecCloseOwner, resource: string, - ) => void; + ) => AnalysisCleanupLease; + /** + * Join the specification scan to the scope that owns this spawn. The cache + * tracks an export; a client command is already inside its command scope. + */ + readonly trackSpecScan?: (work: () => Promise) => Promise; readonly launcher?: KunaProcessLauncher | undefined; } @@ -109,6 +122,14 @@ type KunaCommandOutcome = readonly owner: ProviderProcessSupervisor | undefined; }; +const bindRetainedFileClose = ( + failure: RegularFileCleanupFailure, + error: AnalysisError, +): void => { + if (failure.retainedClose instanceof AnalysisCleanupLease) + new AnalysisCleanupLeaseGroup(error, [failure.retainedClose]); +}; + /** Preserve the operation's typed failure while attaching descriptor cleanup. */ export const kunaFileCleanupError = ( failure: RegularFileCleanupFailure, @@ -116,21 +137,27 @@ export const kunaFileCleanupError = ( ): AnalysisError => { const diagnostics = kunaInstallationFailureDiagnostics(failure); const cancellation = regularFileCancellation(failure); - if (cancellation !== undefined) - return cancelledBy(operation, carriedReason(cancellation.reason), { + if (cancellation !== undefined) { + const error = cancelledBy(operation, carriedReason(cancellation.reason), { diagnostics, cleanup: { reason: errorMessage(failure.cleanupCause), resources: [failure.path], }, }); + bindRetainedFileClose(failure, error); + return error; + } const cleanup = new ProviderCleanupError( KUNA_PROVIDER_ID, [failure.path], { reason: errorMessage(failure.cleanupCause), ...diagnostics }, { cause: failure, operation }, ); - if (failure.outcome.kind === "completed") return cleanup; + if (failure.outcome.kind === "completed") { + bindRetainedFileClose(failure, cleanup); + return cleanup; + } const primaryCause = failure.outcome.cause; const primary = primaryCause instanceof AnalysisError @@ -143,9 +170,12 @@ export const kunaFileCleanupError = ( const composed = analysisErrorWithCleanupFailure(primary, cleanup, operation); // The installation facts stay where every other outcome reports them, not // only inside the composed primary and cleanup reports. - return diagnostics === undefined - ? composed - : composed.retainDiagnostics(diagnostics); + const reported = + diagnostics === undefined + ? composed + : composed.retainDiagnostics(diagnostics); + bindRetainedFileClose(failure, reported); + return reported; }; /** Preserve the exact retryable resources when an inspection admission retries them. */ @@ -236,6 +266,100 @@ export const verifyKunaExecutableDigest = async ( return sha256 === installation.sha256 ? undefined : sha256; }; +/** The configured deadline, named for the setting that owns this run. */ +const kunaOperationTimeout = ( + request: KunaCommandRequest, + details?: Parameters[3], +): AnalysisTimeoutError => + kunaDeadlineTimeout( + request.operation, + request.deadline, + ["kuna", ...request.arguments.slice(0, 1)].join(" "), + details, + ); + +/** A pre-spawn file check failed: keep its cleanup owner and typed cause. */ +const preSpawnCheckFailure = ( + cause: unknown, + request: KunaCommandRequest, + userMessage: string, +): KunaCommandOutcome => { + if (cause instanceof RegularFileCleanupFailure) + return { + kind: "failed", + error: kunaFileCleanupError(cause, request.operation), + fileCleanupFailure: cause, + }; + // A directory whose close failed carries its retained lease; keep it. + if (cause instanceof ArtifactReaderFailure) { + const retained = kunaRetainedResourceCleanupError(cause, request.operation); + if (retained !== undefined) return { kind: "failed", error: retained }; + } + const cancellation = regularFileCancellation(cause); + return { + kind: "failed", + error: + cause instanceof AnalysisError + ? cause + : cancellation !== undefined + ? cancelledBy(request.operation, carriedReason(cancellation.reason)) + : new ProviderAdapterError(KUNA_PROVIDER_ID, request.operation, { + cause, + userMessage: `${userMessage}: ${errorMessage(cause)}`, + }), + }; +}; + +/** + * Re-read each selected specification tree under this spawn's own signal, + * clock and cleanup owner, and refuse the spawn when it no longer matches the + * identity the installation committed. A request that spawns nothing never + * reads the tree. + */ +const verifyKunaSpecTrees = async ( + request: KunaCommandRequest, + budget: Deadline, +): Promise => { + const { installation } = request; + const selected = installation.configuration.externalSpecs; + if (selected.length === 0) return undefined; + const committed = installation.externalSpecIdentities; + const scan = () => + identifyKunaExternalSpecs(selected, { + operation: request.operation, + deadline: request.deadline, + budget, + platform: installation.configuration.platform, + signal: request.signal, + committed, + retainFailedClose: request.retainFailedFileClose, + }); + let observed: Awaited>; + try { + observed = await (request.trackSpecScan?.(scan) ?? scan()); + } catch (cause: unknown) { + return preSpawnCheckFailure( + cause, + request, + "Cannot read the Kuna specification tree", + ); + } + if (sameKunaExternalSpecs(kunaExternalSpecParameter(committed), observed)) + return undefined; + return { + kind: "failed", + error: new ProviderAdapterError(KUNA_PROVIDER_ID, request.operation, { + userMessage: + "The Kuna specification tree no longer matches the analysis profile committed for this session; reopen the target to analyze it with the current specifications.", + diagnostics: { + reason: "spec_identity_diverged", + committed_external_specs: comparableKunaExternalSpecs(committed), + observed_external_specs: comparableKunaExternalSpecs(observed), + }, + }), + }; +}; + /** Run Kuna under an owned process group with REA's environment and limits. */ export const runKunaCommand = async ( request: KunaCommandRequest, @@ -260,27 +384,20 @@ export const runKunaCommand = async ( }), }; } catch (cause: unknown) { - if (cause instanceof RegularFileCleanupFailure) { - return { - kind: "failed", - error: kunaFileCleanupError(cause, request.operation), - fileCleanupFailure: cause, - }; - } - const cancellation = regularFileCancellation(cause); - return { - kind: "failed", - error: - cause instanceof AnalysisError - ? cause - : cancellation !== undefined - ? cancelledBy(request.operation, carriedReason(cancellation.reason)) - : new ProviderAdapterError(KUNA_PROVIDER_ID, request.operation, { - cause, - userMessage: `Cannot verify ${installation.executable}: ${errorMessage(cause)}`, - }), - }; + return preSpawnCheckFailure( + cause, + request, + `Cannot verify ${installation.executable}`, + ); } + // The specification read and the child share one clock. + const budget = Deadline.after(request.timeoutMs); + if (budget.remainingMs() === 0) + return { kind: "failed", error: kunaOperationTimeout(request) }; + const specs = await verifyKunaSpecTrees(request, budget); + if (specs !== undefined) return specs; + if (budget.remainingMs() === 0) + return { kind: "failed", error: kunaOperationTimeout(request) }; try { const snapshot = await runOwnedCommand( { @@ -294,7 +411,7 @@ export const runKunaCommand = async ( env: { TMPDIR: request.workspace }, }, { - timeoutMs: Math.max(1, request.timeoutMs), + timeoutMs: Math.max(1, budget.remainingMs()), diagnosticBytes: request.outputBytes, ...(request.stdout === undefined ? {} : { stdout: request.stdout }), }, @@ -515,19 +632,8 @@ const commandFailure = ( carriedReason(cause.cancellation?.reason), capturedOutput === undefined ? undefined : { capturedOutput }, ); - else if (cause.reason === "timeout") { - const { setting, ms } = request.deadline; - const analysisSetting = - setting === "REA_KUNA_TIMEOUT_MS" - ? "kuna.function_timeout_ms" - : "kuna.project_timeout_ms"; - primary = new AnalysisTimeoutError(operation, ms, { - ...details, - limit: analysisSettingLimit(analysisSetting, ms, request.deadline.source), - userMessage: `kuna ${subcommand} did not finish within ${analysisSetting} (${String(ms)} ms).`, - remediationAction: `${analysisSetting} is ${String(ms)} ms. It can be changed at runtime with update_analysis_settings. The launch seed is ${setting}.`, - }); - } + else if (cause.reason === "timeout") + primary = kunaOperationTimeout(request, details); // The same input overflows the same fixed buffer; waiting cannot help. else if (cause.reason === "output-limit") primary = new AnalysisResourceConstraintError( diff --git a/src/kuna/KunaConfiguration.ts b/src/kuna/KunaConfiguration.ts index c3cab2c97e..a135cb4868 100644 --- a/src/kuna/KunaConfiguration.ts +++ b/src/kuna/KunaConfiguration.ts @@ -5,6 +5,12 @@ import { } from "../domain/analysisResourceLimits.js"; import { isAbsolute } from "node:path"; +import { errorMessage } from "../kernel/errorMessage.js"; +import { + absoluteCallerPath, + isQualifiedCallerPath, +} from "../filesystem/callerPath.js"; + import { ConfigurationError } from "../domain/configurationErrors.js"; import { currentAnalysisOperationSnapshot } from "../domain/analysisOperationSnapshot.js"; import { @@ -17,6 +23,26 @@ import { KUNA_COMMAND_REMEDIATION, KUNA_UNSUPPORTED_HOST_REMEDIATION, } from "./KunaRelease.js"; +import { analysisSettingLimit } from "../domain/analysisSettingDefinitions.js"; +import { AnalysisTimeoutError } from "../domain/analysisErrorCore.js"; +import type { AnalysisErrorOptions } from "../domain/analysisErrorBase.js"; + +/** + * Variables a source-built Kuna uses to find compiled SLEIGH specifications. + * A release executable carries those specifications and ignores both. + */ +export const KUNA_SPEC_VARIABLES = ["KUNA_SPECS", "SLEIGHHOME"] as const; + +export type KunaSpecVariable = (typeof KUNA_SPEC_VARIABLES)[number]; + +/** + * Caller-selected specification root. `path` is absolute: a relative selection + * is resolved from REA's working directory before it is stored. + */ +export interface KunaSelectedSpec { + readonly variable: KunaSpecVariable; + readonly path: string; +} /** Kuna caps its own decode lanes and worker pool at 32. */ export const MAXIMUM_KUNA_JOBS = 32; @@ -54,6 +80,15 @@ export interface KunaConfiguration { readonly projectTimeoutLaunchValid?: boolean; readonly functionTimeoutLaunchValid?: boolean; readonly jobs: number; + /** Host whose path rules interpreted these settings, including spec roots. */ + readonly platform: NodeJS.Platform; + /** + * `KUNA_SPECS` and `SLEIGHHOME` from the environment passed to + * {@link readKunaConfiguration}. Empty when that environment did not set + * them. Relative selections are absolute paths resolved from REA's working + * directory; they are not read from `process.env` again later. + */ + readonly externalSpecs: readonly KunaSelectedSpec[]; } /** One configured deadline and the setting that owns it. */ @@ -86,6 +121,26 @@ const kunaDeadline = ( return { setting, ms, source }; }; +/** `subject` did not finish within `deadline`; name its runtime setting. */ +export const kunaDeadlineTimeout = ( + operation: string, + deadline: KunaDeadline, + subject: string, + details?: Pick, +): AnalysisTimeoutError => { + const { setting, ms, source } = deadline; + const analysisSetting = + setting === "REA_KUNA_TIMEOUT_MS" + ? "kuna.function_timeout_ms" + : "kuna.project_timeout_ms"; + return new AnalysisTimeoutError(operation, ms, { + ...details, + limit: analysisSettingLimit(analysisSetting, ms, source), + userMessage: `${subject} did not finish within ${analysisSetting} (${String(ms)} ms).`, + remediationAction: `${analysisSetting} is ${String(ms)} ms. It can be changed at runtime with update_analysis_settings. The launch seed is ${setting}.`, + }); +}; + export const kunaFunctionDeadline = ( configuration: KunaConfiguration, ): KunaDeadline => @@ -145,6 +200,45 @@ const failure = ( : `Correct ${setting} to meet the reported constraint, or unset it to use its default. Restart REA after changing the environment.`, }); +/** + * Relative specification roots are resolved from REA's working directory once, + * here, so the identity scan and the child both see that absolute path. A + * path that cannot be resolved honestly is a configuration error. + */ +const qualifiedExternalSpecs = ( + environment: Readonly, + platform: NodeJS.Platform, +): Result => { + const qualified: KunaSelectedSpec[] = []; + for (const variable of KUNA_SPEC_VARIABLES) { + const selected = environment[variable]; + if (selected === undefined || selected === "") continue; + const spec = { variable, path: selected }; + if (isQualifiedCallerPath(spec.path, platform)) { + qualified.push(spec); + continue; + } + let path: string; + try { + path = absoluteCallerPath(spec.path, { platform }); + } catch (cause: unknown) { + return failure( + "open_options_invalid", + `${spec.variable} could not be resolved from the working directory: ${errorMessage(cause)}. Received ${spec.path}.`, + spec.variable, + ); + } + if (!isQualifiedCallerPath(path, platform)) + return failure( + "open_options_invalid", + `${spec.variable} must resolve to an absolute path; received ${spec.path}.`, + spec.variable, + ); + qualified.push({ variable, path }); + } + return ok(qualified); +}; + const positiveInteger = (value: string): number | undefined => /^[1-9]\d*$/u.test(value) && Number.isSafeInteger(Number(value)) ? Number(value) @@ -268,6 +362,8 @@ export const readKunaConfiguration = ( "REA_KUNA_JOBS", ); + const externalSpecs = qualifiedExternalSpecs(environment, platform); + if (!externalSpecs.ok) return externalSpecs; return ok({ command, cacheRoot: cacheRoot ?? defaultKunaCacheDirectory(environment, platform), @@ -279,5 +375,7 @@ export const readKunaConfiguration = ( functionTimeoutSource: functionTimeout.value.source, functionTimeoutLaunchValid: functionTimeout.value.launchValid, jobs, + platform, + externalSpecs: externalSpecs.value, }); }; diff --git a/src/kuna/KunaCopy.test.ts b/src/kuna/KunaCopy.test.ts index 4cde06d3bc..f5b3fa6ba7 100644 --- a/src/kuna/KunaCopy.test.ts +++ b/src/kuna/KunaCopy.test.ts @@ -265,6 +265,7 @@ it("keeps staging until both copy descriptors close, then retires the exact work sha256: "0".repeat(64), bytes: 0, script: false, + externalSpecIdentities: [], configuration: { command: join(root, "never-launched"), cacheRoot, @@ -274,6 +275,8 @@ it("keeps staging until both copy descriptors close, then retires the exact work projectTimeoutSource: "default", functionTimeoutMs: 1000, functionTimeoutSource: "default", + platform: "linux", + externalSpecs: [], }, }; const cache = new KunaProjectCache(cacheRoot, { maxBytes: 1024 * 1024 }); diff --git a/src/kuna/KunaDoctor.ts b/src/kuna/KunaDoctor.ts index b46c2a6136..cfcc3ed9c6 100644 --- a/src/kuna/KunaDoctor.ts +++ b/src/kuna/KunaDoctor.ts @@ -12,6 +12,7 @@ import { } from "./KunaAdmission.js"; import type { RetainedResourceScope } from "../ports/AnalysisProvider.js"; import type { JsonValue } from "../domain/jsonValue.js"; +import { AnalysisTimeoutError } from "../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; import type { @@ -26,6 +27,7 @@ import { KUNA_VERSION_PROBE_REMEDIATION, } from "./KunaRelease.js"; import { errorMessage } from "../kernel/errorMessage.js"; +import { absoluteCallerSelection } from "../filesystem/callerPath.js"; import { kunaCacheLocationSettings } from "./KunaConfiguration.js"; /** Settings setup writes into a client registration. */ @@ -36,6 +38,8 @@ export const KUNA_REGISTRATION_SETTINGS = [ "REA_KUNA_PROJECT_TIMEOUT_MS", "REA_KUNA_TIMEOUT_MS", "REA_KUNA_JOBS", + "KUNA_SPECS", + "SLEIGHHOME", ] as const; // These affect readiness when they select a cache root. Setup leaves them @@ -98,7 +102,12 @@ export const inspectKunaProvider = async ( registrationEnvironment: Object.fromEntries( KUNA_REGISTRATION_SETTINGS.flatMap((name) => { const setting = environment[name]; - return setting === undefined ? [] : [[name, setting]]; + if (setting === undefined) return []; + const value = + name === "KUNA_SPECS" || name === "SLEIGHHOME" + ? absoluteCallerSelection(setting, platform) + : setting; + return [[name, value]]; }), ), checks: [ @@ -230,6 +239,25 @@ const probeCleanupFailure = ( kunaResources: KunaResourceScope, kunaInstallationDialect: (typeof import("./KunaCommand.js"))["kunaInstallationDialect"], ): DoctorProviderCheck => { + // A selected spec tree that cannot be read within kuna.function_timeout_ms + // is a failed Kuna check, not a failed doctor run. + if (cause instanceof AnalysisTimeoutError) { + const check = { + name: "version", + ok: false, + code: "provider_timeout", + detail: cause.userMessage ?? cause.message, + remediation: cause.remediationAction ?? null, + classification: "runtime_failure", + } as const; + return cause.cleanupIncomplete + ? cleanupIncompleteCheck( + { ...check, code: "cleanup_incomplete" }, + cause.diagnostics, + cause.cleanupResources, + ) + : { ...check, details: { timeout_ms: cause.timeoutMs } }; + } let recognised = true; const failure = classifyProviderFailure( cause, diff --git a/src/kuna/KunaInstallation.ts b/src/kuna/KunaInstallation.ts index 981157f486..b123c8912b 100644 --- a/src/kuna/KunaInstallation.ts +++ b/src/kuna/KunaInstallation.ts @@ -7,6 +7,8 @@ import { randomUUID } from "node:crypto"; import { realpath } from "node:fs/promises"; import { appendCallerPath } from "../filesystem/callerPath.js"; +import { Deadline } from "../domain/deadline.js"; +import { readRuntimeSetting } from "../config/runtimeAnalysisSettings.js"; import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { @@ -44,15 +46,22 @@ import type { } from "../process/ProviderProcess.js"; import { admitKunaCommand } from "./KunaAdmission.js"; import { + kunaFunctionDeadline, readKunaConfiguration, type KunaConfiguration, type KunaConfigurationFailure, + type KunaDeadline, } from "./KunaConfiguration.js"; import { KUNA_COMMAND_REMEDIATION, KUNA_VERIFIED_VERSION, KUNA_VERSION_PROBE_REMEDIATION, } from "./KunaRelease.js"; +import { + committedKunaExternalSpecs, + identifyKunaExternalSpecs, + type KunaExternalSpecRecord, +} from "./KunaSpecIdentity.js"; import { errorMessage } from "../kernel/errorMessage.js"; /** `kuna --version` exits before loading specs or an input; it needs no budget beyond this. */ @@ -117,6 +126,12 @@ export interface KunaInstallation { * checks cannot match the configured path by argv prefix. */ readonly script: boolean; + /** + * Content identity of each external specification tree selected by + * `configuration.externalSpecs`. Paths come from that snapshot; the digest + * covers the tree's bytes so an in-place rebuild is a different identity. + */ + readonly externalSpecIdentities: readonly KunaExternalSpecRecord[]; } /** Why the selected Kuna installation cannot be used. */ @@ -136,7 +151,21 @@ export interface KunaInstallationOptions { readonly signal?: AbortSignal; /** Probe deadline; tests shorten it. */ readonly probeTimeoutMs?: number; - readonly resourceScope: RetainedResourceScope; + readonly resourceScope: RetainedResourceScope & { + /** + * Retain this owner and return that lease. The map key is the owner, so + * a file-cleanup failure can find the lease it must release. + */ + retainClose?( + owner: { + close(): Promise; + readonly cleanupResources?: readonly string[] | undefined; + }, + resource: string, + ): AnalysisCleanupLease; + }; + /** Profile records whose unknown fences this inspection reuses. */ + readonly committedSpecs?: JsonValue; /** Test seam for the owned command launcher; production uses the verified default. */ readonly processLauncher?: ( options: OwnedProviderProcessSpawnOptions, @@ -178,7 +207,7 @@ export const kunaInstallationCancellation = ( /** One installation inspection's retained owners and originating errors. */ export interface KunaResourceScope { - readonly owner: RetainedResourceScope; + readonly owner: KunaInstallationOptions["resourceScope"]; readonly cleanupResources: readonly string[] | undefined; readonly hasPending: boolean; installationCancellationError( @@ -212,6 +241,28 @@ export const createKunaResourceScope = ( ...new Set(pending.flatMap((lease) => lease.cleanupResources ?? [])), ]; }; + const retainClose = ( + owner: { + close(): Promise; + readonly cleanupResources?: readonly string[] | undefined; + }, + resource: string, + ): AnalysisCleanupLease => { + const existing = leases.get(owner); + if (existing !== undefined) return existing; + const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); + leases.set(owner, lease); + parent.retain( + { + close: () => lease.release(), + get cleanupResources() { + return lease.cleanupResources; + }, + }, + resource, + ); + return lease; + }; return { get hasPending() { return pendingLeases().length > 0; @@ -238,18 +289,9 @@ export const createKunaResourceScope = ( return error; }, owner: { + retainClose, retain: (owner, resource) => { - const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); - leases.set(owner, lease); - parent.retain( - { - close: () => lease.release(), - get cleanupResources() { - return lease.cleanupResources; - }, - }, - resource, - ); + retainClose(owner, resource); }, run: (operation) => parent.run(operation), }, @@ -269,10 +311,18 @@ export const kunaChildEnvironment = ( configuration: KunaConfiguration, ): NodeJS.ProcessEnv => { const home = appendCallerPath(configuration.cacheRoot, "home"); + // A release build carries compiled specifications. A source build finds + // them only through these variables, so the child receives the paths + // captured when configuration was read. The ambient process environment is + // not a caller selection and must not replace or supply them. + const inherited: NodeJS.ProcessEnv = {}; + for (const spec of configuration.externalSpecs) + inherited[spec.variable] = spec.path; return { HOME: home, XDG_CACHE_HOME: appendCallerPath(home, ".cache"), NO_COLOR: "1", + ...inherited, }; }; @@ -379,6 +429,28 @@ const recordPartialInstallationFileOperation = ( return true; }; +/** + * The spec walk uses the function timeout, the same configured budget a + * single-function spawn spends (`REA_KUNA_TIMEOUT_MS`). When that timeout + * cannot be read, the version probe's deadline is the budget this + * installation already has. Neither clock is a new number. + */ +const installationSpecDeadline = ( + configuration: KunaConfiguration, + probeDeadlineMs: number, +): KunaDeadline => { + const deadline = readRuntimeSetting(() => + kunaFunctionDeadline(configuration), + ); + return deadline.ok + ? deadline.value + : { + setting: "REA_KUNA_TIMEOUT_MS", + ms: probeDeadlineMs, + source: "default", + }; +}; + /** Resolve, version-probe and fingerprint the configured executable. */ export const inspectKunaInstallation = async ( environment: Readonly, @@ -643,6 +715,26 @@ export const inspectKunaInstallation = async ( }, ); + const committed = committedKunaExternalSpecs(options.committedSpecs); + const specDeadline = installationSpecDeadline(configuration.value, deadline); + const externalSpecIdentities = await options.resourceScope.run(() => + identifyKunaExternalSpecs(configuration.value.externalSpecs, { + operation: "kuna:installation", + deadline: specDeadline, + budget: Deadline.after(specDeadline.ms), + platform: options.platform, + ...(committed === undefined ? {} : { committed }), + ...(options.signal === undefined ? {} : { signal: options.signal }), + retainFailedClose: (owner, resource) => { + const retainClose = options.resourceScope.retainClose; + if (retainClose !== undefined) return retainClose(owner, resource); + const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); + options.resourceScope.retain(owner, resource); + return lease; + }, + }), + ); + return ok({ configuration: configuration.value, executable, @@ -650,5 +742,6 @@ export const inspectKunaInstallation = async ( verified: version === KUNA_VERIFIED_VERSION, ...fingerprint, script, + externalSpecIdentities, }); }; diff --git a/src/kuna/KunaProjectCache.ts b/src/kuna/KunaProjectCache.ts index ebfe2a5345..cf87b2f51c 100644 --- a/src/kuna/KunaProjectCache.ts +++ b/src/kuna/KunaProjectCache.ts @@ -53,7 +53,7 @@ import { RegularFileCleanupFailure, regularFileCancellation, } from "../filesystem/OwnedRegularFile.js"; -import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; +import type { KunaSpecCloseOwner } from "./KunaSpecIdentity.js"; import type { KunaInstallation } from "./KunaInstallation.js"; import { DEFAULT_KUNA_CACHE_MAX_BYTES, @@ -269,9 +269,9 @@ export class KunaProjectCache { } >(); /** Hash descriptors whose close was not confirmed; staging stays until retry. */ - readonly #retainedHashFiles = new Map(); + readonly #retainedHashFiles = new Map(); /** Keep the exact close lease available for errors bound after a retry ends. */ - readonly #hashRecords = new WeakMap(); + readonly #hashRecords = new WeakMap(); /** Serialize owner release and staging retirement across concurrent lookups. */ #hashRetry: Promise = Promise.resolve(); /** Each resource owner's release, read by the errors reporting it. */ @@ -467,14 +467,16 @@ export class KunaProjectCache { ): Promise> { if (request.signal?.aborted === true) return err(cancelledBy(KUNA_EXPORT_OPERATION, request.signal)); + const { installation } = request; const key = kunaProjectKey({ targetSha256: request.targetSha256, targetBasename: basename(request.targetPath), - kunaSha256: request.installation.sha256, - kunaCommand: request.installation.configuration.command, - kunaExecutable: request.installation.executable, - kunaVersion: request.installation.version, - jobs: request.installation.configuration.jobs, + kunaSha256: installation.sha256, + kunaCommand: installation.configuration.command, + kunaExecutable: installation.executable, + kunaVersion: installation.version, + jobs: installation.configuration.jobs, + externalSpecs: installation.externalSpecIdentities, }); const running = this.#inflight.get(key); // A build whose waiters all left is winding down; a new request starts afresh. @@ -1003,6 +1005,7 @@ export class KunaProjectCache { kuna_executable: request.installation.executable, kuna_version: request.installation.version, jobs: request.installation.configuration.jobs, + external_specs: [...request.installation.externalSpecIdentities], }, files: exported.files, summary: exported.summary, @@ -1268,11 +1271,13 @@ export class KunaProjectCache { } #retainHashFile( - owner: OwnedFileHandle, + owner: KunaSpecCloseOwner, key: string, staging: string | null, resource: string, - ): void { + ): AnalysisCleanupLease { + const existing = this.#hashRecords.get(owner); + if (existing !== undefined) return existing.lease; const retained: RetainedHashFile = { key, staging, @@ -1281,6 +1286,7 @@ export class KunaProjectCache { }; this.#hashRecords.set(owner, retained); this.#retainedHashFiles.set(owner, retained); + return retained.lease; } #replaceHashCloseError( diff --git a/src/kuna/KunaProjectExport.ts b/src/kuna/KunaProjectExport.ts index b41a2fe65d..c1e7fae527 100644 --- a/src/kuna/KunaProjectExport.ts +++ b/src/kuna/KunaProjectExport.ts @@ -1,4 +1,5 @@ import { + type AnalysisCleanupLease, type ArtifactResourceScope, ArtifactReaderFailure, artifactFileCancellationCause, @@ -29,7 +30,7 @@ import { observeStableFile, StableFileHashFailure, } from "../filesystem/StableFileHash.js"; -import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; +import type { KunaSpecCloseOwner } from "./KunaSpecIdentity.js"; import { prepareProcessOwnershipInspection } from "../process/ProcessOwnershipObservation.js"; import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js"; import { @@ -145,9 +146,9 @@ export interface KunaExportRequest { readonly signal: AbortSignal; readonly copyResources: ArtifactResourceScope; readonly retainFailedFileClose: ( - owner: OwnedFileHandle, + owner: KunaSpecCloseOwner, resource: string, - ) => void; + ) => AnalysisCleanupLease; readonly onStatus: (status: KunaExportStatus) => void; readonly launcher?: KunaProcessLauncher | undefined; /** Deadline accepted when the export started. Later setting changes do not rewrite it. */ @@ -302,6 +303,7 @@ export const exportKunaProject = async ( signal, launcher: request.launcher, retainFailedFileClose: request.retainFailedFileClose, + trackSpecScan: (work) => request.copyResources.track(work), }); if (outcome.kind === "ok") return { ok: true as const, snapshot: outcome.snapshot }; diff --git a/src/kuna/KunaProvider.ts b/src/kuna/KunaProvider.ts index dcd3268fbc..8a78ab0344 100644 --- a/src/kuna/KunaProvider.ts +++ b/src/kuna/KunaProvider.ts @@ -51,6 +51,7 @@ import { } from "./KunaRelease.js"; import { KunaRunSlots } from "./KunaRunSlots.js"; import { KunaSessionClient } from "./KunaSessionClient.js"; +import { kunaExternalSpecParameter } from "./KunaSpecIdentity.js"; import { kunaUnavailable } from "./KunaUnavailable.js"; const KUNA_ARCHITECTURE_LABELS = { @@ -166,14 +167,29 @@ export class KunaProvider implements AnalysisProviderCandidate { reason: "Kuna decompiles executable images, not databases or archives.", diagnostics, }; - if (target.format !== "elf" && target.format !== "mach-o") + // PE/COFF is admitted for x86-64: kuna loads it (sections, relocations, + // imports) and its `.pdata` is a better boundary source than discovery. + // The Xbox/GDK x64 class has no other decompiler that runs at all. + // Other PE architectures are not part of that verification. + if (target.format === "pe" && target.architecture !== "x86_64") + return { + status: "unsupported", + code: "architecture_unsupported", + reason: `REA verified the Kuna provider on x86-64 PE; ${target.architecture} PE is not admitted yet.`, + diagnostics: { ...diagnostics, architecture: target.architecture }, + }; + if ( + target.format !== "elf" && + target.format !== "mach-o" && + target.format !== "pe" + ) return { status: "unsupported", code: "target_format_unsupported", reason: target.format === "mach-o-universal" ? "REA's Kuna provider has no verified universal Mach-O slice selection yet; open a thin slice or use another provider." - : `REA verified the Kuna provider on ELF and thin Mach-O images; ${target.format} is not admitted yet.`, + : `REA verified the Kuna provider on ELF, thin Mach-O and PE images; ${target.format} is not admitted yet.`, diagnostics, }; if (KUNA_ARCHITECTURE_LABELS[target.architecture] === null) @@ -243,6 +259,9 @@ export class KunaProvider implements AnalysisProviderCandidate { return err(error); } const { value } = installation; + const externalSpecs = kunaExternalSpecParameter( + value.externalSpecIdentities, + ); return ok({ releaseVerification: { status: value.verified @@ -287,6 +306,9 @@ export class KunaProvider implements AnalysisProviderCandidate { }, value_flow: "explicitly-unavailable-v1", cache_policy: "live", + ...(externalSpecs === undefined + ? {} + : { external_specs: externalSpecs }), }, ), }); diff --git a/src/kuna/KunaSessionClient.ts b/src/kuna/KunaSessionClient.ts index 164332da8e..83a14d20fd 100644 --- a/src/kuna/KunaSessionClient.ts +++ b/src/kuna/KunaSessionClient.ts @@ -44,6 +44,7 @@ import { AnalysisCapabilityUnavailableError, AnalysisInputError, AnalysisResourceConstraintError, + AnalysisTimeoutError, cancelledBy, carriedReason, isAborted, @@ -85,6 +86,10 @@ import { type KunaInstallation, } from "./KunaInstallation.js"; import { kunaProjectKey, type KunaProject } from "./KunaCacheManifest.js"; +import { + kunaExternalSpecParameter, + sameKunaExternalSpecs, +} from "./KunaSpecIdentity.js"; import { KunaPublishedProjectCleanupError, type KunaProjectCache, @@ -347,21 +352,19 @@ export class KunaSessionClient implements AnalysisClient { regex = admitted.value; } } - const installation = await this.#ensureInstallation( - operation, - options.signal, - ); - if (!installation.ok) return installation; + const installed = await this.#ensureInstallation(operation, options.signal); + if (!installed.ok) return installed; + const installation = installed.value; try { if (operation === "health") return ok( - this.#execution([], installation.value, { + this.#execution([], installation, { result: { ready: true, kuna: { - version: installation.value.version, - verified: installation.value.verified, - sha256: installation.value.sha256, + version: installation.version, + verified: installation.verified, + sha256: installation.sha256, }, }, source: null, @@ -376,13 +379,13 @@ export class KunaSessionClient implements AnalysisClient { operation === "procedure_assembly" || operation === "analyze_function" ) { - const project = await this.#startProject(installation.value); + const project = await this.#startProject(installation); if (!project.ok) return project; } const answer = await this.#answer( operation, parameters, - installation.value, + installation, options, search, regex, @@ -399,7 +402,7 @@ export class KunaSessionClient implements AnalysisClient { return ok( this.#execution( kunaLimitations(operation, this.#deadline, this.#heapRequest), - installation.value, + installation, answer.value, ), ); @@ -1645,12 +1648,17 @@ export class KunaSessionClient implements AnalysisClient { void owned.promise.then((result) => { // A proven cancellation has no reusable installation result. Its // complete cleanup precedes replacement; physical failures stay cached. + if (this.#installation !== owned) return; + const cleanTimeout = + !result.ok && + result.error instanceof AnalysisTimeoutError && + !result.error.cleanupIncomplete; if ( - this.#installation === owned && - owned.signal.aborted && - (result.ok || - (result.error instanceof AnalysisCancelledError && - !result.error.cleanupIncomplete)) + cleanTimeout || + (owned.signal.aborted && + (result.ok || + (result.error instanceof AnalysisCancelledError && + !result.error.cleanupIncomplete))) ) this.#installation = undefined; }); @@ -1681,10 +1689,12 @@ export class KunaSessionClient implements AnalysisClient { this.#resourceScope.forCloseOwners(), ); try { + const committedSpecs = this.#profile?.parameters["external_specs"]; const inspected = await inspectKunaInstallation(this.#environment, { platform: this.#platform, resourceScope: kunaResources.owner, signal, + ...(committedSpecs === undefined ? {} : { committedSpecs }), ...(this.#launcher === undefined ? {} : { processLauncher: this.#launcher }), @@ -1736,6 +1746,27 @@ export class KunaSessionClient implements AnalysisClient { }, }), ); + if ( + this.#profile !== undefined && + !sameKunaExternalSpecs( + committedSpecs, + inspected.value.externalSpecIdentities, + ) + ) { + const observedSpecs = kunaExternalSpecParameter( + inspected.value.externalSpecIdentities, + ); + return err( + new ProviderAdapterError(KUNA_PROVIDER_ID, "health", { + userMessage: + "The Kuna specification tree changed after this target was opened; reopen the target to analyze it with the current specifications.", + diagnostics: { + committed_external_specs: committedSpecs ?? [], + observed_external_specs: observedSpecs ?? [], + }, + }), + ); + } return ok(inspected.value); } catch (cause: unknown) { return err( @@ -1793,6 +1824,7 @@ export class KunaSessionClient implements AnalysisClient { kunaExecutable: installation.executable, kunaVersion: installation.version, jobs: installation.configuration.jobs, + externalSpecs: installation.externalSpecIdentities, }); this.#key = key; const cached = await this.#cache.lookup(key, this.#session.signal); diff --git a/src/kuna/KunaSessionEvidence.ts b/src/kuna/KunaSessionEvidence.ts index a085e61184..f84ddab73d 100644 --- a/src/kuna/KunaSessionEvidence.ts +++ b/src/kuna/KunaSessionEvidence.ts @@ -83,8 +83,9 @@ export const kunaSessionDialect = ( ): ProviderFailureDialect => ({ providerId: KUNA_PROVIDER_ID, operation, - unclassified: (cause) => + unclassified: (cause, details) => new ProviderAdapterError(KUNA_PROVIDER_ID, operation, { + ...details, cause, userMessage: `Kuna ${operation} failed: ${errorMessage(cause)}`, }), diff --git a/src/kuna/KunaSpecIdentity.ts b/src/kuna/KunaSpecIdentity.ts new file mode 100644 index 0000000000..174f4d29af --- /dev/null +++ b/src/kuna/KunaSpecIdentity.ts @@ -0,0 +1,773 @@ +import { randomUUID } from "node:crypto"; +import type { Stats } from "node:fs"; +import { lstat, opendir, readlink, realpath, stat } from "node:fs/promises"; + +import { z } from "zod"; + +import { cancelledBy, OwnerCancellation } from "../domain/analysisErrorCore.js"; +import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import { Deadline } from "../domain/deadline.js"; +import { equalJsonValues, type JsonValue } from "../domain/jsonValue.js"; +import { digestCanonicalValue } from "../domain/canonicalDigest.js"; +import { + compareUnicodeCodePoints, + compositeKey, +} from "../domain/unicodeCodePointOrder.js"; +import { isQualifiedCallerPath } from "../filesystem/callerPath.js"; +import { decodeDirectoryEntryName } from "../filesystem/decodeDirectoryEntryName.js"; +import type { DirectoryEntryName } from "../filesystem/decodeDirectoryEntryName.js"; +import { OwnedDirectoryHandle } from "../filesystem/OwnedDirectoryHandle.js"; +import { + RegularFileCancelled, + RegularFileCleanupFailure, + regularFileCancellation, +} from "../filesystem/OwnedRegularFile.js"; +import { + RegularFileChangedError, + RegularFileOperationCancelled, + assertRegularFileActive, +} from "../filesystem/RegularFile.js"; +import { + hashStableFile, + stableFileHashCause, +} from "../filesystem/StableFileHash.js"; +import { + AnalysisCleanupLease, + AnalysisCleanupLeaseGroup, + ArtifactReaderFailure, +} from "../resources/index.js"; +import { errorMessage } from "../kernel/errorMessage.js"; +import { + KUNA_SPEC_VARIABLES, + kunaDeadlineTimeout, + type KunaDeadline, + type KunaSelectedSpec, +} from "./KunaConfiguration.js"; + +const specTreeTimeout = ( + options: KunaSpecIdentityOptions, + cleanup?: { readonly reason: string; readonly resources: readonly string[] }, +) => + kunaDeadlineTimeout( + options.operation, + options.deadline, + "Reading the Kuna specification tree", + cleanup === undefined ? undefined : { cleanup }, + ); + +/** + * Why a selected tree has no content digest. A partial digest is not an + * identity: it could alias a different tree, so the caller must not reuse it. + */ +export const KUNA_SPEC_UNKNOWN_REASONS = [ + "not_absolute", + "not_directory", + "unreadable", + "limit", + "cycle", + "unstable", +] as const; + +export type KunaSpecUnknownReason = (typeof KUNA_SPEC_UNKNOWN_REASONS)[number]; + +const SHA256_PATTERN = /^[0-9a-f]{64}$/u; + +/** + * One selected specification tree. `reuse_fence` exists only when the bytes + * could not be identified. A resolved profile mints that fence once; later + * inspections and launches of the same path and reason reuse it, so the + * export key matches the committed profile. A new resolution mints again. + */ +export const kunaExternalSpecRecordSchema = z.discriminatedUnion("status", [ + z.strictObject({ + variable: z.enum(KUNA_SPEC_VARIABLES), + path: z.string().min(1), + status: z.literal("identified"), + sha256: z.string().regex(SHA256_PATTERN), + }), + z.strictObject({ + variable: z.enum(KUNA_SPEC_VARIABLES), + path: z.string().min(1), + status: z.literal("unknown"), + reason: z.enum(KUNA_SPEC_UNKNOWN_REASONS), + reuse_fence: z.string().uuid(), + }), +]); + +export type KunaExternalSpecRecord = z.infer< + typeof kunaExternalSpecRecordSchema +>; + +/** + * Stop before a partial digest. These bounds keep installation from walking + * an unbounded tree; crossing one yields `limit`, which is not reusable. + */ +const MAX_SPEC_TREE_ENTRIES = 100_000; +const MAX_SPEC_TREE_BYTES = 2 * 1024 ** 3; +const MAX_SPEC_TREE_DEPTH = 32; + +/** A closeable owner the caller's resource scope can retry. */ +export interface KunaSpecCloseOwner { + close(): Promise; + readonly cleanupResources?: readonly string[]; +} + +/** + * The clock for one specification read. `deadline` is the configured budget + * the error reports. `budget` is the shared clock, so a spawn can charge the + * scan and the child to one deadline. There is no unbounded read. + */ +export interface KunaSpecIdentityOptions { + readonly operation: string; + readonly deadline: KunaDeadline; + readonly budget: Deadline; + readonly platform: NodeJS.Platform; + /** Caller cancellation. The budget abort is separate and reports a timeout. */ + readonly signal?: AbortSignal; + /** + * Entry allowance for one tree. Production uses the module bound. A smaller + * value still returns the limit identity and does not hash a prefix. + */ + readonly maxEntries?: number; + /** + * Unknown records already committed for this session. An unknown tree with + * the same variable, path and reason reuses that record's fence. + */ + readonly committed?: readonly KunaExternalSpecRecord[]; + /** + * Register this exact lease with the caller's scope and return it. The + * failure carries the same lease, so releasing the scope clears it. + */ + readonly retainFailedClose: ( + owner: KunaSpecCloseOwner, + resource: string, + ) => AnalysisCleanupLease; +} + +const committedFence = ( + spec: KunaSelectedSpec, + reason: KunaSpecUnknownReason, + committed: readonly KunaExternalSpecRecord[] | undefined, +): string => { + const prior = committed?.find( + (record) => + record.variable === spec.variable && + record.path === spec.path && + record.status === "unknown" && + record.reason === reason, + ); + return prior?.status === "unknown" ? prior.reuse_fence : randomUUID(); +}; + +const unknownSpec = ( + spec: KunaSelectedSpec, + reason: KunaSpecUnknownReason, + committed: readonly KunaExternalSpecRecord[] | undefined, +): KunaExternalSpecRecord => ({ + variable: spec.variable, + path: spec.path, + status: "unknown", + reason, + reuse_fence: committedFence(spec, reason, committed), +}); + +/** Parse a committed profile's specification records, or undefined when absent. */ +export const committedKunaExternalSpecs = ( + value: JsonValue | undefined, +): readonly KunaExternalSpecRecord[] | undefined => { + if (value === undefined) return undefined; + const parsed = z.array(kunaExternalSpecRecordSchema).safeParse(value); + return parsed.success ? parsed.data : undefined; +}; + +const withoutReuseFence = (record: KunaExternalSpecRecord): JsonValue => { + if (record.status === "identified") return { ...record }; + const { reuse_fence: _reuseFence, ...identity } = record; + return identity; +}; + +/** Identity comparable across inspections. The reuse fence is not content. */ +export const comparableKunaExternalSpecs = ( + specs: readonly KunaExternalSpecRecord[], +): JsonValue => specs.map(withoutReuseFence); + +/** + * Profile and cache material. Omitted when nothing was selected, so an + * installation without external specifications keeps its previous profile + * digest and export key. An unknown tree keeps the profile's `reuse_fence`, + * so a later inspection of the same tree does not mint a second identity. + */ +export const kunaExternalSpecParameter = ( + specs: readonly KunaExternalSpecRecord[], +): JsonValue | undefined => + specs.length === 0 ? undefined : (specs as unknown as JsonValue); + +/** + * True when a committed profile describes the same specification paths and + * content digests as this inspection. The reuse fence is the profile's + * stable identity for an unknown tree, so it is not a content difference. + */ +export const sameKunaExternalSpecs = ( + committed: JsonValue | undefined, + observed: readonly KunaExternalSpecRecord[], +): boolean => { + if (committed === undefined) return observed.length === 0; + const parsed = z.array(kunaExternalSpecRecordSchema).safeParse(committed); + if (!parsed.success) return false; + return equalJsonValues( + parsed.data.map(withoutReuseFence), + observed.map(withoutReuseFence), + ); +}; + +const fatalIdentityFailure = (cause: unknown): boolean => + cause instanceof ArtifactReaderFailure || + cause instanceof RegularFileCleanupFailure || + cause instanceof RegularFileCancelled || + cause instanceof RegularFileOperationCancelled || + regularFileCancellation(cause) !== undefined; + +const errorCode = (cause: unknown): string | undefined => { + const inner = stableFileHashCause(cause); + return typeof inner === "object" && + inner !== null && + "code" in inner && + typeof inner.code === "string" + ? inner.code + : undefined; +}; + +const hashFailureReason = (cause: unknown): "unstable" | "unreadable" => { + const inner = stableFileHashCause(cause); + return inner instanceof RegularFileChangedError ? "unstable" : "unreadable"; +}; + +const nodeIdentity = (stats: Stats): string => + `${String(stats.dev)}:${String(stats.ino)}`; + +const fileType = (stats: Stats): string => { + if (stats.isFIFO()) return "fifo"; + if (stats.isSocket()) return "socket"; + if (stats.isBlockDevice()) return "block"; + if (stats.isCharacterDevice()) return "character"; + return "unknown"; +}; + +const pathKey = (path: readonly DirectoryEntryName[]): string => + compositeKey( + path.map((component) => + component.kind === "decoded" + ? ["decoded", component.name] + : ["unrepresentable", component.rawHex], + ), + ); + +type TreeEntry = { + readonly path: readonly DirectoryEntryName[]; + readonly kind: "file" | "directory" | "symlink" | "other"; + readonly sha256?: string; + readonly bytes?: number; + readonly target?: DirectoryEntryName; + readonly fileType?: string; +}; + +interface WalkFrame { + readonly directory: string; + readonly components: readonly DirectoryEntryName[]; + readonly depth: number; +} + +const usableComponent = ( + component: DirectoryEntryName, +): component is { readonly kind: "decoded"; readonly name: string } => + component.kind === "decoded" && + component.name !== "" && + component.name !== "." && + component.name !== ".." && + !component.name.includes("/") && + !component.name.includes("\\") && + !component.name.includes("\0"); + +const childPath = (directory: string, name: string): string => + directory.endsWith("/") ? `${directory}${name}` : `${directory}/${name}`; + +const copyEntryName = (raw: string | Buffer): Buffer => + Buffer.isBuffer(raw) ? Buffer.from(raw) : Buffer.from(raw); + +/** + * Read at most `remainingEntries` names. One extra read distinguishes a + * directory that ends on the allowance from one that exceeds it, without + * retaining the overflow name. + */ +const listDirectory = async ( + directory: string, + options: KunaSpecIdentityOptions, + remainingEntries: number, +): Promise<{ + readonly names: readonly Buffer[]; + readonly limited: boolean; +}> => { + assertRegularFileActive(options.signal); + const owner = new OwnedDirectoryHandle( + await opendir(directory, { encoding: "buffer" as BufferEncoding }), + ); + const names: Buffer[] = []; + let failure: unknown; + let limited = false; + try { + for (;;) { + assertRegularFileActive(options.signal); + if (names.length >= remainingEntries) { + const extra = await owner.handle.read(); + limited = extra !== null; + break; + } + const entry = await owner.handle.read(); + if (entry === null) break; + names.push(copyEntryName(entry.name as string | Buffer)); + } + } catch (cause: unknown) { + failure = cause; + } + try { + await owner.close(); + } catch (cause: unknown) { + // One lease: the scope retains it, and the failure is bound to it. + const closeOwner: KunaSpecCloseOwner = { + close: () => owner.close(), + cleanupResources: [directory], + }; + const lease = options.retainFailedClose(closeOwner, directory); + const cleanupFacts = { + cause: failure ?? cause, + cleanup: { reason: errorMessage(cause), resources: [directory] }, + cleanupLeases: [lease], + }; + const message = `Could not close specification directory ${directory}: ${errorMessage(cause)}`; + // An interrupted listing stays an interruption; the close failure is its + // cleanup, as on the regular-file path. + const interruption = regularFileCancellation(failure); + throw interruption === undefined + ? new ArtifactReaderFailure("unavailable", message, cleanupFacts) + : new ArtifactReaderFailure("cancelled", message, { + ...cleanupFacts, + cancellation: interruption, + }); + } + if (failure !== undefined) throw failure; + return { names, limited }; +}; + +const readLinkTarget = async ( + path: string, +): Promise => { + try { + return decodeDirectoryEntryName(await readlink(path)); + } catch { + return undefined; + } +}; + +interface DirectorySnapshot { + readonly path: string; + /** Names returned by the walk's listing, copied so a later re-list can compare them. */ + readonly names: readonly Buffer[]; +} + +interface WalkState { + readonly entries: TreeEntry[]; + bytes: number; + readonly seen: Set; + readonly stack: WalkFrame[]; + readonly directories: DirectorySnapshot[]; +} + +const hashTreeFile = async ( + path: string, + size: number, + state: WalkState, + components: readonly DirectoryEntryName[], + options: KunaSpecIdentityOptions, +): Promise => { + if ( + !Number.isSafeInteger(size) || + size < 0 || + size > MAX_SPEC_TREE_BYTES - state.bytes + ) + return "limit"; + try { + const hashed = await hashStableFile(path, { + ...(options.signal === undefined ? {} : { signal: options.signal }), + retainFailedClose: (owner) => options.retainFailedClose(owner, path), + }); + state.bytes += hashed.bytes; + if (state.bytes > MAX_SPEC_TREE_BYTES) return "limit"; + state.entries.push({ + path: components, + kind: "file", + sha256: hashed.sha256, + bytes: hashed.bytes, + }); + return undefined; + } catch (cause: unknown) { + if (fatalIdentityFailure(cause)) throw cause; + return hashFailureReason(cause); + } +}; + +const walkChildren = async ( + frame: WalkFrame, + state: WalkState, + options: KunaSpecIdentityOptions, +): Promise => { + if (frame.depth > MAX_SPEC_TREE_DEPTH) return "limit"; + const allowance = options.maxEntries ?? MAX_SPEC_TREE_ENTRIES; + let listed: { readonly names: readonly Buffer[]; readonly limited: boolean }; + try { + listed = await listDirectory( + frame.directory, + options, + Math.max(0, allowance - state.entries.length), + ); + } catch (cause: unknown) { + if (fatalIdentityFailure(cause)) throw cause; + return "unreadable"; + } + if (listed.limited) return "limit"; + state.directories.push({ + path: frame.directory, + names: listed.names.map((name) => Buffer.from(name)), + }); + for (const rawName of listed.names) { + assertRegularFileActive(options.signal); + if (state.entries.length >= allowance) return "limit"; + const component = decodeDirectoryEntryName(rawName); + if (!usableComponent(component)) return "unreadable"; + const components = [...frame.components, component]; + const path = childPath(frame.directory, component.name); + const reason = await considerChild( + path, + components, + frame.depth, + state, + options, + ); + if (reason !== undefined) return reason; + } + return undefined; +}; + +const considerChild = async ( + path: string, + components: readonly DirectoryEntryName[], + depth: number, + state: WalkState, + options: KunaSpecIdentityOptions, +): Promise => { + let linked: Stats; + try { + linked = await lstat(path); + } catch (cause: unknown) { + if (fatalIdentityFailure(cause)) throw cause; + return "unreadable"; + } + if (linked.isSymbolicLink()) + return considerSymlink(path, components, depth, state, options); + if (linked.isDirectory()) + return queueDirectory(path, linked, components, depth, state); + if (linked.isFile()) + return hashTreeFile(path, linked.size, state, components, options); + state.entries.push({ + path: components, + kind: "other", + fileType: fileType(linked), + }); + return undefined; +}; + +const queueDirectory = ( + directory: string, + stats: Stats, + components: readonly DirectoryEntryName[], + depth: number, + state: WalkState, +): KunaSpecUnknownReason | undefined => { + const identity = nodeIdentity(stats); + if (state.seen.has(identity)) return "cycle"; + state.seen.add(identity); + state.entries.push({ path: components, kind: "directory" }); + state.stack.push({ directory, components, depth: depth + 1 }); + return undefined; +}; + +const considerSymlink = async ( + path: string, + components: readonly DirectoryEntryName[], + depth: number, + state: WalkState, + options: KunaSpecIdentityOptions, +): Promise => { + let followed: Stats; + try { + followed = await stat(path); + } catch (cause: unknown) { + if (fatalIdentityFailure(cause)) throw cause; + if (errorCode(cause) === "ELOOP") return "cycle"; + if (errorCode(cause) !== "ENOENT") return "unreadable"; + const target = await readLinkTarget(path); + if (target === undefined) return "unreadable"; + state.entries.push({ path: components, kind: "symlink", target }); + return undefined; + } + if (followed.isDirectory()) { + let resolved: string; + try { + resolved = await realpath(path); + } catch (cause: unknown) { + if (fatalIdentityFailure(cause)) throw cause; + return errorCode(cause) === "ELOOP" ? "cycle" : "unreadable"; + } + return queueDirectory(resolved, followed, components, depth, state); + } + if (followed.isFile()) + return hashTreeFile(path, followed.size, state, components, options); + state.entries.push({ + path: components, + kind: "other", + fileType: fileType(followed), + }); + return undefined; +}; + +const directoryNameKey = (name: Buffer): string => name.toString("hex"); + +const sameDirectoryNames = ( + left: readonly Buffer[], + right: readonly Buffer[], +): boolean => { + if (left.length !== right.length) return false; + const listed = left.map(directoryNameKey).sort(); + const again = right.map(directoryNameKey).sort(); + return listed.every((name, index) => name === again[index]); +}; + +/** + * Re-list every directory the walk accepted. A name added or removed after + * that listing is a different tree, so the digest is not an identity. + */ +const directoryChangedDuringWalk = async ( + state: WalkState, + options: KunaSpecIdentityOptions, +): Promise => { + for (const directory of state.directories) { + let listed: { + readonly names: readonly Buffer[]; + readonly limited: boolean; + }; + try { + listed = await listDirectory( + directory.path, + options, + directory.names.length, + ); + } catch (cause: unknown) { + if (fatalIdentityFailure(cause)) throw cause; + return "unstable"; + } + if (listed.limited || !sameDirectoryNames(listed.names, directory.names)) + return "unstable"; + } + return undefined; +}; + +const identifySpecTree = async ( + root: string, + options: KunaSpecIdentityOptions, +): Promise< + | { readonly status: "identified"; readonly sha256: string } + | { readonly status: "unknown"; readonly reason: KunaSpecUnknownReason } +> => { + if (!isQualifiedCallerPath(root, options.platform)) + return { status: "unknown", reason: "not_absolute" }; + let rootStats: Stats; + try { + rootStats = await lstat(root); + } catch (cause: unknown) { + if (fatalIdentityFailure(cause)) throw cause; + return { + status: "unknown", + reason: errorCode(cause) === "ENOTDIR" ? "not_directory" : "unreadable", + }; + } + let directory = root; + if (rootStats.isSymbolicLink()) { + try { + directory = await realpath(root); + rootStats = await lstat(directory); + } catch (cause: unknown) { + if (fatalIdentityFailure(cause)) throw cause; + return { + status: "unknown", + reason: errorCode(cause) === "ELOOP" ? "cycle" : "unreadable", + }; + } + } + if (!rootStats.isDirectory()) + return { status: "unknown", reason: "not_directory" }; + const state: WalkState = { + entries: [], + bytes: 0, + seen: new Set([nodeIdentity(rootStats)]), + stack: [{ directory, components: [], depth: 0 }], + directories: [], + }; + while (state.stack.length > 0) { + const frame = state.stack.pop(); + if (frame === undefined) break; + const reason = await walkChildren(frame, state, options); + if (reason !== undefined) return { status: "unknown", reason }; + } + const changed = await directoryChangedDuringWalk(state, options); + if (changed !== undefined) return { status: "unknown", reason: changed }; + state.entries.sort((left, right) => + compareUnicodeCodePoints(pathKey(left.path), pathKey(right.path)), + ); + return { + status: "identified", + sha256: digestCanonicalValue(state.entries, "Kuna specification tree"), + }; +}; + +/** + * An interrupted spec read whose file or directory close then failed: the + * cleanup it still owes and the lease that retries it. + */ +const interruptedCleanup = ( + cause: unknown, +): + | { + readonly cleanup: { + readonly reason: string; + readonly resources: readonly string[]; + }; + readonly leases: readonly AnalysisCleanupLease[]; + } + | undefined => { + if (cause instanceof RegularFileCleanupFailure) + return regularFileCancellation(cause) === undefined + ? undefined + : { + cleanup: { + reason: errorMessage(cause.cleanupCause), + resources: [cause.path], + }, + leases: + cause.retainedClose instanceof AnalysisCleanupLease + ? [cause.retainedClose] + : [], + }; + if ( + cause instanceof ArtifactReaderFailure && + cause.cancellation !== undefined && + cause.cleanup !== undefined + ) + return { cleanup: cause.cleanup, leases: cause.cleanupLeases ?? [] }; + return undefined; +}; + +/** Bind the retained leases to the error that reports their cleanup. */ +const withCleanup = ( + error: E, + leases: readonly AnalysisCleanupLease[], +): E => { + if (leases.length > 0) new AnalysisCleanupLeaseGroup(error, [...leases]); + return error; +}; + +const specScanCancelled = (cause: unknown): boolean => + cause instanceof RegularFileCancelled || + cause instanceof RegularFileOperationCancelled || + regularFileCancellation(cause) !== undefined; + +const readKunaExternalSpecs = async ( + specs: readonly KunaSelectedSpec[], + options: KunaSpecIdentityOptions, +): Promise => { + const identified: KunaExternalSpecRecord[] = []; + for (const spec of specs) { + assertRegularFileActive(options.signal); + const tree = await identifySpecTree(spec.path, options); + identified.push( + tree.status === "identified" + ? { + variable: spec.variable, + path: spec.path, + status: "identified", + sha256: tree.sha256, + } + : unknownSpec(spec, tree.reason, options.committed), + ); + } + return identified; +}; + +/** + * Content identity of each selected specification tree, in variable order. + * The walk stops when `budget` expires and reports that configured deadline. + */ +export const identifyKunaExternalSpecs = async ( + specs: readonly KunaSelectedSpec[], + options: KunaSpecIdentityOptions, +): Promise => { + if (specs.length === 0) return []; + if (options.budget.remainingMs() === 0) throw specTreeTimeout(options); + const controller = new AbortController(); + const timer = setTimeout( + () => controller.abort(OwnerCancellation.deadlineElapsed), + options.budget.remainingMs(), + ); + timer.unref(); + const signal = + options.signal === undefined + ? controller.signal + : AbortSignal.any([options.signal, controller.signal]); + try { + const records = await readKunaExternalSpecs(specs, { ...options, signal }); + // The last read or close may finish after the deadline; that is not a + // result inside the configured budget. + assertRegularFileActive(signal); + if (options.budget.expired()) throw specTreeTimeout(options); + return records; + } catch (cause: unknown) { + const interrupted = interruptedCleanup(cause); + if (options.signal?.aborted === true) { + // A file close failure already reports its cancellation downstream; a + // directory's envelope keeps the caller's cancellation here. + if ( + !(cause instanceof ArtifactReaderFailure) || + interrupted === undefined + ) + throw cause; + throw withCleanup( + cancelledBy(options.operation, options.signal, { + cleanup: interrupted.cleanup, + }), + interrupted.leases, + ); + } + if (!(controller.signal.aborted || options.budget.expired())) throw cause; + // Only a read the deadline stopped is a timeout. An earlier physical + // failure keeps its own cause beside any cleanup it left. + if (interrupted === undefined && !specScanCancelled(cause)) throw cause; + // A handle whose close failed while the deadline stopped the read stays + // with the timeout, bound to its retained lease. + throw interrupted === undefined + ? specTreeTimeout(options) + : withCleanup( + specTreeTimeout(options, interrupted.cleanup), + interrupted.leases, + ); + } finally { + clearTimeout(timer); + } +}; diff --git a/src/kuna/KunaTargetCommands.ts b/src/kuna/KunaTargetCommands.ts index 52a627b174..3a91cf9ed0 100644 --- a/src/kuna/KunaTargetCommands.ts +++ b/src/kuna/KunaTargetCommands.ts @@ -49,7 +49,7 @@ import { classifyProviderFailure, type ProviderFailureDialect, } from "../providers/classifyProviderFailure.js"; -import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; +import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import { errorMessage } from "../kernel/errorMessage.js"; interface WorkspaceRoot { @@ -236,7 +236,9 @@ export class KunaTargetCommands { [resource], ); this.#resources.retain({ kind: "lease", resource, lease }); - failedHashClose = { owner, lease }; + if (owner instanceof OwnedFileHandle) + failedHashClose = { owner, lease }; + return lease; }, }); if (outcome.kind === "retained") { diff --git a/tests/boundary/providers/kuna/kunaCacheCleanupConcurrency.test.ts b/tests/boundary/providers/kuna/kunaCacheCleanupConcurrency.test.ts index 121e00ffdf..73cc21b854 100644 --- a/tests/boundary/providers/kuna/kunaCacheCleanupConcurrency.test.ts +++ b/tests/boundary/providers/kuna/kunaCacheCleanupConcurrency.test.ts @@ -69,6 +69,7 @@ test.each([false, true])( kunaExecutable: installed.value.executable, kunaVersion: installed.value.version, jobs: installed.value.configuration.jobs, + externalSpecs: installed.value.externalSpecIdentities, }); keys.push(key); const pending = cache.build( diff --git a/tests/boundary/providers/kuna/kunaChildEnvironment.test.ts b/tests/boundary/providers/kuna/kunaChildEnvironment.test.ts new file mode 100644 index 0000000000..7337bb8c5f --- /dev/null +++ b/tests/boundary/providers/kuna/kunaChildEnvironment.test.ts @@ -0,0 +1,132 @@ +import { mkdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { afterEach, expect, it as test } from "vitest"; + +import { explicitSetupRegistrationEnvironment } from "../../../../src/application/SetupRegistrationEnvironment.js"; +import { absoluteCallerPath } from "../../../../src/filesystem/callerPath.js"; +import { readKunaConfiguration } from "../../../../src/kuna/KunaConfiguration.js"; +import { kunaChildEnvironment } from "../../../../src/kuna/KunaInstallation.js"; +import type { KunaProcessLauncher } from "../../../../src/kuna/KunaCommand.js"; +import { spawnOwnedProviderProcess } from "../../../../src/process/ProviderProcess.js"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; +import { session } from "./kunaSessionFixture.js"; + +const it = test.skipIf(process.platform === "win32"); + +const saved = { + specs: process.env.KUNA_SPECS, + home: process.env.SLEIGHHOME, +}; + +afterEach(() => { + for (const [key, value] of [ + ["KUNA_SPECS", saved.specs], + ["SLEIGHHOME", saved.home], + ] as const) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } +}); + +it("forwards specification paths from the selected environment", () => { + process.env.KUNA_SPECS = "/ambient/specs"; + process.env.SLEIGHHOME = "/ambient/sleigh"; + const configured = readKunaConfiguration( + { + REA_KUNA_COMMAND: "/opt/kuna/kuna", + HOME: "/home/analyst", + KUNA_SPECS: "/caller/specs", + SLEIGHHOME: "/caller/sleigh", + }, + "linux", + ); + if (!configured.ok) throw new Error(configured.error.reason); + expect(configured.value.externalSpecs).toEqual([ + { variable: "KUNA_SPECS", path: "/caller/specs" }, + { variable: "SLEIGHHOME", path: "/caller/sleigh" }, + ]); + const env = kunaChildEnvironment(configured.value); + expect(env).toMatchObject({ + KUNA_SPECS: "/caller/specs", + SLEIGHHOME: "/caller/sleigh", + HOME: "/home/analyst/.cache/rea/kuna/home", + NO_COLOR: "1", + }); +}); + +it("resolves a relative specification path from the working directory", () => { + const configured = readKunaConfiguration( + { + REA_KUNA_COMMAND: "/opt/kuna/kuna", + HOME: "/home/analyst", + KUNA_SPECS: "relative/specs", + }, + "linux", + ); + if (!configured.ok) throw new Error(configured.error.reason); + const path = absoluteCallerPath("relative/specs"); + expect(configured.value.externalSpecs).toEqual([ + { variable: "KUNA_SPECS", path }, + ]); + expect(kunaChildEnvironment(configured.value).KUNA_SPECS).toBe(path); +}); + +it("omits specification variables the selected environment did not set", () => { + process.env.KUNA_SPECS = "/ambient/specs"; + process.env.SLEIGHHOME = "/ambient/sleigh"; + const configured = readKunaConfiguration( + { + REA_KUNA_COMMAND: "/opt/kuna/kuna", + HOME: "/home/analyst", + KUNA_SPECS: "", + }, + "linux", + ); + if (!configured.ok) throw new Error(configured.error.reason); + expect(configured.value.externalSpecs).toEqual([]); + const env = kunaChildEnvironment(configured.value); + expect(env.KUNA_SPECS).toBeUndefined(); + expect(env.SLEIGHHOME).toBeUndefined(); +}); + +it("gives the version probe the provider environment, not the ambient one", async () => { + process.env.KUNA_SPECS = "/ambient/specs"; + process.env.SLEIGHHOME = "/ambient/sleigh"; + const root = await createTestTempDirectory("rea-kuna-spec-env-"); + const specs = join(root, "specs"); + const sleigh = join(root, "sleigh"); + await mkdir(specs); + await mkdir(sleigh); + await writeFile(join(specs, "x.sla"), "spec"); + let child: NodeJS.ProcessEnv | undefined; + const launcher: KunaProcessLauncher = async (options) => { + child ??= options.hostEnvironment; + return spawnOwnedProviderProcess(options); + }; + await session( + "rea-kuna-spec-env-session-", + {}, + { KUNA_SPECS: specs, SLEIGHHOME: sleigh }, + launcher, + ); + expect(child).toMatchObject({ + KUNA_SPECS: specs, + SLEIGHHOME: sleigh, + NO_COLOR: "1", + }); +}); + +it("records explicitly selected specification paths in setup registrations", () => { + expect( + explicitSetupRegistrationEnvironment({ + KUNA_SPECS: "/opt/kuna/specs", + SLEIGHHOME: "/opt/sleigh", + UNRELATED: "dropped", + }), + ).toEqual({ KUNA_SPECS: "/opt/kuna/specs", SLEIGHHOME: "/opt/sleigh" }); + // An explicitly empty selection is saved as written, not as the working directory. + expect( + explicitSetupRegistrationEnvironment({ KUNA_SPECS: "", SLEIGHHOME: "" }), + ).toEqual({ KUNA_SPECS: "", SLEIGHHOME: "" }); +}); diff --git a/tests/boundary/providers/kuna/kunaDoctor.test.ts b/tests/boundary/providers/kuna/kunaDoctor.test.ts index 9020a1ee81..7b7ad315ff 100644 --- a/tests/boundary/providers/kuna/kunaDoctor.test.ts +++ b/tests/boundary/providers/kuna/kunaDoctor.test.ts @@ -8,14 +8,18 @@ import { } from "node:fs/promises"; import { join, sep as separator } from "node:path"; -import { expect, it as test } from "vitest"; +import { expect, it as test, vi } from "vitest"; import { inspectKunaProviderOwned as inspectKunaProvider } from "./kunaResourceScope.js"; import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; import { fakeKunaCalls, writeFakeKuna } from "./fakeKuna.js"; import { createSystemDoctorHost } from "../../../../src/doctorRuntime.js"; import { runDoctorOwned } from "../../../../src/application/Doctor.js"; +import { explicitSetupRegistrationEnvironment } from "../../../../src/application/SetupRegistrationEnvironment.js"; +import { absoluteCallerPath } from "../../../../src/filesystem/callerPath.js"; import { KunaProvider } from "../../../../src/kuna/KunaProvider.js"; +import { runWithAnalysisOperationSnapshot } from "../../../../src/domain/analysisOperationSnapshot.js"; +import * as StableFileHash from "../../../../src/filesystem/StableFileHash.js"; import { AnalysisCancelledError, OwnerCancellation, @@ -51,11 +55,14 @@ it("publishes the caller's explicit settings once the installation validates", a version: { stdout: "kuna 1.1000\n" }, }); const cache = join(root, "cache"); + const specs = join(root, "specs"); + await mkdir(specs); const inspection = await inspectKunaProvider({ REA_KUNA_COMMAND: kuna, REA_KUNA_CACHE_DIR: cache, REA_KUNA_JOBS: "4", + KUNA_SPECS: specs, UNRELATED: "not published", }); @@ -67,6 +74,7 @@ it("publishes the caller's explicit settings once the installation validates", a REA_KUNA_COMMAND: kuna, REA_KUNA_CACHE_DIR: cache, REA_KUNA_JOBS: "4", + KUNA_SPECS: specs, }, checks: [ { @@ -91,7 +99,45 @@ it("publishes the caller's explicit settings once the installation validates", a }, ], }); - expect(Object.keys(inspection.registrationEnvironment)).toHaveLength(3); + expect(Object.keys(inspection.registrationEnvironment)).toHaveLength(4); +}); + +it("publishes selected specification roots into the client registration", async () => { + const root = await createTestTempDirectory("rea-kuna-doctor-specs-"); + const kuna = await writeFakeKuna(root, { + version: { stdout: "kuna 1.1000\n" }, + }); + const specs = join(root, "specs"); + const sleigh = join(root, "sleigh"); + await mkdir(specs); + await mkdir(sleigh); + const inspection = await inspectKunaProvider({ + REA_KUNA_COMMAND: kuna, + KUNA_SPECS: specs, + SLEIGHHOME: sleigh, + }); + expect(inspection.registrationEnvironment).toMatchObject({ + REA_KUNA_COMMAND: kuna, + KUNA_SPECS: specs, + SLEIGHHOME: sleigh, + }); + expect( + explicitSetupRegistrationEnvironment({ + KUNA_SPECS: specs, + SLEIGHHOME: sleigh, + UNRELATED: "not published", + }), + ).toEqual({ + KUNA_SPECS: specs, + SLEIGHHOME: sleigh, + }); + expect( + explicitSetupRegistrationEnvironment({ + KUNA_SPECS: "relative/specs", + }), + ).toEqual({ + KUNA_SPECS: absoluteCallerPath("relative/specs"), + }); }); it("flags an unverified release without failing the installation", async () => { @@ -477,3 +523,57 @@ it.each([ code: "version_unresolved", }); }); + +it("reports a spec read that exceeds the function timeout as a failed check", async () => { + const root = await createTestTempDirectory("rea-kuna-doctor-spec-timeout-"); + const kuna = await writeFakeKuna(root, { + version: { stdout: "kuna 1.1000\n" }, + }); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + // The paused hash ends on the scan deadline, or on the test-owned release. + let releaseHash: () => void = () => undefined; + const hashReleased = new Promise((resolve) => { + releaseHash = resolve; + }); + const original = StableFileHash.hashStableFile; + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (String(path).endsWith(".sla")) + await new Promise((resolve) => { + void hashReleased.then(resolve); + if (options.signal?.aborted === true) resolve(); + options.signal?.addEventListener("abort", () => resolve(), { + once: true, + }); + }); + return original(path, options); + }); + try { + const inspection = await runWithAnalysisOperationSnapshot( + { revision: 1, overrides: { "kuna.function_timeout_ms": 50 } }, + () => + inspectKunaProvider({ + REA_KUNA_COMMAND: kuna, + REA_KUNA_CACHE_DIR: join(root, "cache"), + KUNA_SPECS: specs, + }), + ); + expect(inspection.available).toBe(true); + expect(inspection.checks).toContainEqual( + expect.objectContaining({ + name: "version", + ok: false, + code: "provider_timeout", + classification: "runtime_failure", + remediation: expect.stringContaining("kuna.function_timeout_ms"), + details: { timeout_ms: 50 }, + }), + ); + } finally { + releaseHash(); + hash.mockRestore(); + } +}); diff --git a/tests/boundary/providers/kuna/kunaProjectCache.test.ts b/tests/boundary/providers/kuna/kunaProjectCache.test.ts index b61660c5ce..82ec7b60c3 100644 --- a/tests/boundary/providers/kuna/kunaProjectCache.test.ts +++ b/tests/boundary/providers/kuna/kunaProjectCache.test.ts @@ -94,6 +94,7 @@ const keyOf = (installation: KunaInstallation, target: Target) => kunaExecutable: installation.executable, kunaVersion: installation.version, jobs: installation.configuration.jobs, + externalSpecs: installation.externalSpecIdentities, }); const callsOf = async (kuna: string, subcommand: string) => diff --git a/tests/boundary/providers/kuna/kunaProvider.test.ts b/tests/boundary/providers/kuna/kunaProvider.test.ts index 207c826b33..af8d1ba414 100644 --- a/tests/boundary/providers/kuna/kunaProvider.test.ts +++ b/tests/boundary/providers/kuna/kunaProvider.test.ts @@ -93,8 +93,15 @@ it("discovers configuration without probing and admits only verified targets", a configured.inspectTargetSupport(executable("mach-o", "arm64")).status, ).toBe("supported"); expect( - configured.inspectTargetSupport(executable("pe", "x86_64")), - ).toMatchObject({ status: "unsupported", code: "target_format_unsupported" }); + configured.inspectTargetSupport(executable("pe", "x86_64")).status, + ).toBe("supported"); + expect( + configured.inspectTargetSupport(executable("pe", "arm64")), + ).toMatchObject({ + status: "unsupported", + code: "architecture_unsupported", + diagnostics: { target_format: "pe", architecture: "arm64" }, + }); expect( configured.inspectTargetSupport(executable("mach-o-universal", "arm64")), ).toMatchObject({ code: "target_format_unsupported" }); diff --git a/tests/boundary/providers/kuna/kunaSelectedCommand.test.ts b/tests/boundary/providers/kuna/kunaSelectedCommand.test.ts index f8715816c7..bd5d7d060a 100644 --- a/tests/boundary/providers/kuna/kunaSelectedCommand.test.ts +++ b/tests/boundary/providers/kuna/kunaSelectedCommand.test.ts @@ -11,6 +11,7 @@ import { join } from "node:path"; import { expect, it as test } from "vitest"; import type { RetainedResourceScope } from "../../../../src/ports/AnalysisProvider.js"; +import { AnalysisCleanupLease } from "../../../../src/resources/AnalysisCleanupLease.js"; import { runKunaCommand } from "../../../../src/kuna/KunaCommand.js"; import type { KunaInstallation } from "../../../../src/kuna/KunaInstallation.js"; import { KunaProjectCache } from "../../../../src/kuna/KunaProjectCache.js"; @@ -53,7 +54,19 @@ const runInstallation = ( deadline: { setting: "REA_KUNA_TIMEOUT_MS", source: "setting", ms: 5_000 }, outputBytes: 4096, signal: new AbortController().signal, - retainFailedFileClose: (owner, path) => resources.retain(owner, path), + retainFailedFileClose: (owner, path) => { + const lease = new AnalysisCleanupLease(() => owner.close(), [path]); + resources.retain( + { + close: () => lease.release(), + get cleanupResources() { + return lease.cleanupResources; + }, + }, + path, + ); + return lease; + }, }); it("uses the selected Kuna launcher and its sibling producer for readiness and commands", async () => { diff --git a/tests/boundary/providers/kuna/kunaSpecIdentity.test.ts b/tests/boundary/providers/kuna/kunaSpecIdentity.test.ts new file mode 100644 index 0000000000..67b07124db --- /dev/null +++ b/tests/boundary/providers/kuna/kunaSpecIdentity.test.ts @@ -0,0 +1,1295 @@ +import { createHash } from "node:crypto"; +import { Dir } from "node:fs"; +import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { expect, it as test, vi } from "vitest"; + +import { commitExecutionProfile } from "../../../../src/application/binary/BinarySessionExecution.js"; +import { DEFAULT_KUNA_FUNCTION_TIMEOUT_MS } from "../../../../src/domain/analysisResourceLimits.js"; +import { runWithAnalysisOperationSnapshot } from "../../../../src/domain/analysisOperationSnapshot.js"; +import { Deadline } from "../../../../src/domain/deadline.js"; +import { absoluteCallerPath } from "../../../../src/filesystem/callerPath.js"; +import { OwnedDirectoryHandle } from "../../../../src/filesystem/OwnedDirectoryHandle.js"; +import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js"; +import { RegularFileCleanupFailure } from "../../../../src/filesystem/OwnedRegularFile.js"; +import * as StableFileHash from "../../../../src/filesystem/StableFileHash.js"; +import * as OwnedCommand from "../../../../src/process/OwnedCommand.js"; +import { + kunaFileCleanupError, + kunaInstallationDialect, +} from "../../../../src/kuna/KunaCommand.js"; +import { createKunaResourceScope } from "../../../../src/kuna/KunaInstallation.js"; +import type { KunaInstallation } from "../../../../src/kuna/KunaInstallation.js"; +import { kunaProjectKey } from "../../../../src/kuna/KunaCacheManifest.js"; +import { kunaSessionDialect } from "../../../../src/kuna/KunaSessionEvidence.js"; +import { KunaProjectCache } from "../../../../src/kuna/KunaProjectCache.js"; +import { + identifyKunaExternalSpecs, + type KunaSpecIdentityOptions, +} from "../../../../src/kuna/KunaSpecIdentity.js"; +import { AnalysisCleanupLease } from "../../../../src/resources/AnalysisCleanupLease.js"; +import { classifyProviderFailure } from "../../../../src/providers/classifyProviderFailure.js"; +import type { RetainedResourceScope } from "../../../../src/ports/AnalysisProvider.js"; +import { awaitAcknowledgement } from "../../../fixtures/lifecycleAcknowledgement.js"; +import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; +import { fakeKunaCalls, writeFakeKuna } from "./fakeKuna.js"; +import { inspectKunaInstallationOwned } from "./kunaResourceScope.js"; +import { withKunaProjectDeadline } from "./kunaProjectRequest.js"; +import { session } from "./kunaSessionFixture.js"; + +const it = test.skipIf(process.platform === "win32"); + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u; + +const idleLease = () => new AnalysisCleanupLease(async () => undefined, []); + +/** Direct reads use the configured function timeout. Production passes its own clock. */ +const specRead = ( + options: Omit, +): KunaSpecIdentityOptions => { + const deadline = { + setting: "REA_KUNA_TIMEOUT_MS" as const, + ms: DEFAULT_KUNA_FUNCTION_TIMEOUT_MS, + source: "default" as const, + }; + return { + operation: "kuna:spec-identity", + deadline, + budget: Deadline.after(deadline.ms), + ...options, + }; +}; + +const recordedSha256 = (value: unknown): string => { + if (!Array.isArray(value)) + throw new Error("spec diagnostics were not a list"); + const record: unknown = value[0]; + if (typeof record !== "object" || record === null) + throw new Error("spec diagnostics omitted the record"); + if (!("sha256" in record) || typeof record.sha256 !== "string") + throw new Error("spec diagnostics omitted sha256"); + return record.sha256; +}; + +const keyFor = ( + installation: KunaInstallation, + targetSha256: string, + targetBasename: string, +) => + kunaProjectKey({ + targetSha256, + targetBasename, + kunaSha256: installation.sha256, + kunaCommand: installation.configuration.command, + kunaExecutable: installation.executable, + kunaVersion: installation.version, + jobs: installation.configuration.jobs, + externalSpecs: installation.externalSpecIdentities, + }); + +const installed = async ( + root: string, + environment: Readonly>, +) => { + const kuna = await writeFakeKuna(root); + const result = await inspectKunaInstallationOwned({ + REA_KUNA_COMMAND: kuna, + REA_KUNA_CACHE_DIR: join(root, "cache"), + ...environment, + }); + if (!result.ok) throw new Error(result.error.reason); + return { kuna, installation: result.value }; +}; + +it("keeps an unchanged specification tree in the profile and export key", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-stable-"); + const specs = join(root, "specs"); + await mkdir(join(specs, "x86"), { recursive: true }); + await writeFile(join(specs, "x86", "base.sla"), "same"); + const first = await installed(root, { KUNA_SPECS: specs }); + const second = await installed(root, { KUNA_SPECS: specs }); + expect(first.installation.externalSpecIdentities).toEqual( + second.installation.externalSpecIdentities, + ); + expect(first.installation.externalSpecIdentities).toEqual([ + { + variable: "KUNA_SPECS", + path: specs, + status: "identified", + sha256: expect.stringMatching(/^[0-9a-f]{64}$/u), + }, + ]); + const target = "ab".repeat(32); + expect(keyFor(first.installation, target, "program")).toBe( + keyFor(second.installation, target, "program"), + ); + const { profile } = await session( + "rea-kuna-spec-profile-", + {}, + { KUNA_SPECS: specs }, + ); + expect(profile.parameters.external_specs).toEqual( + first.installation.externalSpecIdentities, + ); +}); + +it("changes the profile, export key and cache entry when spec bytes change", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-rebuild-"); + const specs = join(root, "specs"); + const specFile = join(specs, "x.sla"); + await mkdir(specs); + await writeFile(specFile, "version-a"); + const { kuna, installation } = await installed(root, { KUNA_SPECS: specs }); + const cache = new KunaProjectCache(installation.configuration.cacheRoot, { + maxBytes: 64 * 1024 ** 2, + }); + const targetPath = join(root, "program"); + await writeFile(targetPath, "program"); + const digest = createHash("sha256").update("program").digest("hex"); + const firstExport = await cache.build( + withKunaProjectDeadline({ + installation, + targetPath, + targetSha256: digest, + }), + ); + const { profile, open } = await session( + "rea-kuna-spec-health-", + {}, + { KUNA_SPECS: specs }, + ); + expect(profile.parameters.external_specs).toEqual( + installation.externalSpecIdentities, + ); + await writeFile(specFile, "version-b"); + const rebuilt = await installed(root, { KUNA_SPECS: specs }); + expect(rebuilt.installation.externalSpecIdentities).toMatchObject([ + { variable: "KUNA_SPECS", path: specs, status: "identified" }, + ]); + const before = installation.externalSpecIdentities[0]; + const after = rebuilt.installation.externalSpecIdentities[0]; + if (before?.status !== "identified" || after?.status !== "identified") + throw new Error("specification tree was not identified"); + expect(after.sha256).not.toBe(before.sha256); + const targetSha256 = "cd".repeat(32); + expect(keyFor(installation, targetSha256, "program")).not.toBe( + keyFor(rebuilt.installation, targetSha256, "program"), + ); + + const client = open(); + const health = await client.execute("health", {}); + expect(health.ok).toBe(false); + if (health.ok) throw new Error("changed specifications were accepted"); + expect(health.error).toMatchObject({ + diagnostics: { + committed_external_specs: installation.externalSpecIdentities, + observed_external_specs: [ + { + variable: "KUNA_SPECS", + path: specs, + status: "identified", + sha256: after.sha256, + }, + ], + }, + }); + + try { + const secondExport = await cache.build( + withKunaProjectDeadline({ + installation: rebuilt.installation, + targetPath, + targetSha256: digest, + }), + ); + expect(firstExport.ok && secondExport.ok).toBe(true); + if (!firstExport.ok || !secondExport.ok) + throw new Error("export did not publish"); + expect(secondExport.value.key).not.toBe(firstExport.value.key); + expect(secondExport.value.manifest.inputs.external_specs).toEqual( + rebuilt.installation.externalSpecIdentities, + ); + expect( + (await fakeKunaCalls(kuna)).filter( + ({ argv }) => argv[0] === "decompile-project", + ), + ).toHaveLength(2); + } finally { + expect((await cache.close()).ok).toBe(true); + } +}); + +it("refuses a launch when the tree differs from the committed profile", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-diverge-"); + const specs = join(root, "specs"); + const specFile = join(specs, "x.sla"); + await mkdir(specs); + await writeFile(specFile, "version-a"); + const { open, kuna } = await session( + "rea-kuna-spec-diverge-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + expect( + (await client.execute("procedure_assembly", { procedure: "main" })).ok, + ).toBe(true); + await writeFile(specFile, "version-b"); + const refused = await client.execute("list_strings", {}); + expect(refused.ok).toBe(false); + if (refused.ok) throw new Error("diverged specifications were accepted"); + expect(refused.error).toMatchObject({ + _tag: "ProviderAdapterError", + diagnostics: { + reason: "spec_identity_diverged", + committed_external_specs: [ + { variable: "KUNA_SPECS", path: specs, status: "identified" }, + ], + observed_external_specs: [ + { variable: "KUNA_SPECS", path: specs, status: "identified" }, + ], + }, + }); + const diagnostics = refused.error.diagnostics; + if (diagnostics === undefined) + throw new Error("divergence omitted diagnostics"); + expect(recordedSha256(diagnostics["observed_external_specs"])).not.toBe( + recordedSha256(diagnostics["committed_external_specs"]), + ); + expect( + (await client.execute("procedure_assembly", { procedure: "main" })).ok, + ).toBe(true); + const addressed = await client.execute("procedure_address", { + procedure: "0x9999", + }); + expect(addressed.ok).toBe(false); + if (addressed.ok) throw new Error("graph launch skipped the spec check"); + expect(addressed.error).toMatchObject({ + _tag: "ProviderAdapterError", + diagnostics: { reason: "spec_identity_diverged" }, + }); + expect( + (await fakeKunaCalls(kuna)).filter( + ({ argv }) => argv[0] === "decompile-graph", + ), + ).toHaveLength(0); +}); + +it("serves an adopted project without hashing the specification tree", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-cached-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const { open } = await session( + "rea-kuna-spec-cached-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + expect( + (await client.execute("procedure_assembly", { procedure: "main" })).ok, + ).toBe(true); + await rm(specs, { recursive: true }); + expect( + (await client.execute("procedure_assembly", { procedure: "main" })).ok, + ).toBe(true); +}); + +it("uses one unknown fence for the profile and the export key", async () => { + const resolved = absoluteCallerPath("relative/specs"); + const { open, cacheRoot, profile } = await session( + "rea-kuna-spec-unknown-key-", + {}, + { KUNA_SPECS: "relative/specs" }, + ); + const client = open(); + const result = await client.execute("procedure_assembly", { + procedure: "main", + }); + expect(result.ok).toBe(true); + if (!result.ok) throw new Error("unknown specification export failed"); + const names = await readdir(join(cacheRoot, "projects")); + expect(names).toHaveLength(1); + const manifest = JSON.parse( + await readFile( + join(cacheRoot, "projects", names[0]!, "manifest.json"), + "utf8", + ), + ) as { + key: string; + inputs: { external_specs: unknown }; + }; + expect(manifest.key).toBe(names[0]); + expect(manifest.inputs.external_specs).toMatchObject([ + { + variable: "KUNA_SPECS", + path: resolved, + status: "unknown", + reason: "unreadable", + reuse_fence: expect.stringMatching(UUID), + }, + ]); + expect(result.value.analysisProfile?.parameters["external_specs"]).toEqual( + manifest.inputs.external_specs, + ); + const profiled = commitExecutionProfile( + "procedure_assembly", + result, + profile, + ); + expect(profiled.ok).toBe(true); + if (!profiled.ok) throw new Error("committed profile was refused"); + expect(profiled.value.analysisProfile?.parameters["external_specs"]).toEqual( + manifest.inputs.external_specs, + ); + expect((await client.close()).ok).toBe(true); +}); + +it("returns a typed cancellation when the spec scan is aborted", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-cancel-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const { open } = await session( + "rea-kuna-spec-cancel-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + expect((await client.execute("health", {})).ok).toBe(true); + const controller = new AbortController(); + const original = StableFileHash.hashStableFile; + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (String(path).endsWith(".sla")) controller.abort(); + return original(path, options); + }); + try { + const result = await client.execute( + "procedure_assembly", + { procedure: "main" }, + { signal: controller.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) throw new Error("cancelled spec scan succeeded"); + expect(result.error._tag).toBe("AnalysisCancelledError"); + } finally { + hash.mockRestore(); + } +}); + +it("does not cancel the export when the standalone decompile scan is aborted", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-independent-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const { open, kuna } = await session( + "rea-kuna-spec-independent-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + expect((await client.execute("health", {})).ok).toBe(true); + let releaseScan: () => void = () => undefined; + const scanHeld = new Promise((resolve) => { + releaseScan = resolve; + }); + let markStarted: () => void = () => undefined; + const scanStarted = new Promise((resolve) => { + markStarted = resolve; + }); + const original = StableFileHash.hashStableFile; + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (!String(path).endsWith(".sla")) return original(path, options); + markStarted(); + await scanHeld; + return original(path, options); + }); + const caller = new AbortController(); + const run = client.execute( + "procedure_pseudo_code", + { procedure: "main" }, + { signal: caller.signal }, + ); + try { + await awaitAcknowledgement(scanStarted, run, "decompile spec scan"); + caller.abort(); + releaseScan(); + const result = await run; + expect(result.ok).toBe(false); + if (result.ok) throw new Error("aborted decompile succeeded"); + expect(result.error._tag).toBe("AnalysisCancelledError"); + let watchingExport = true; + const exportStarted = (async () => { + while (watchingExport) { + const calls = await fakeKunaCalls(kuna); + if (calls.some(({ argv }) => argv[0] === "decompile-project")) return; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + })(); + try { + await awaitAcknowledgement( + exportStarted, + new Promise(() => undefined), + "export after the decompile abort", + ); + } finally { + watchingExport = false; + await Promise.allSettled([exportStarted]); + } + } finally { + caller.abort(); + releaseScan(); + await Promise.allSettled([run]); + hash.mockRestore(); + } +}); + +it("reports a spec close that fails after its wait is cancelled", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-cancel-close-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const { open } = await session( + "rea-kuna-spec-cancel-close-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + expect((await client.execute("health", {})).ok).toBe(true); + let releaseClose: () => void = () => undefined; + const closeUnblocked = new Promise((resolve) => { + releaseClose = resolve; + }); + let markReached: () => void = () => undefined; + const closeReached = new Promise((resolve) => { + markReached = resolve; + }); + let watching = false; + const originalHash = StableFileHash.hashStableFile; + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (String(path).endsWith(".sla")) watching = true; + return originalHash(path, options); + }); + const originalClose = OwnedFileHandle.prototype.close; + const close = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementation(async function (this: OwnedFileHandle) { + if (!watching) return originalClose.call(this); + watching = false; + markReached(); + await closeUnblocked; + await originalClose.call(this); + throw new Error("spec file close failed"); + }); + const caller = new AbortController(); + const run = client.execute( + "procedure_pseudo_code", + { procedure: "main", analysis: "independent_fresh" }, + { signal: caller.signal }, + ); + let closing: ReturnType | undefined; + try { + await awaitAcknowledgement(closeReached, run, "spec close"); + caller.abort(); + closing = client.close(); + let closeSettled = false; + void closing.then( + () => { + closeSettled = true; + }, + () => { + closeSettled = true; + }, + ); + await new Promise((resolve) => setImmediate(resolve)); + expect(closeSettled).toBe(false); + releaseClose(); + expect((await closing).ok).toBe(true); + await run; + } finally { + caller.abort(); + releaseClose(); + await Promise.allSettled([ + run, + ...(closing === undefined ? [] : [closing]), + ]); + hash.mockRestore(); + close.mockRestore(); + } +}); + +it("charges spec scan time against the child deadline", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-budget-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const { open, kuna } = await session( + "rea-kuna-spec-budget-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + expect((await client.execute("health", {})).ok).toBe(true); + // The child's granted timeout is observed directly, so load can only make + // it smaller; the wide budget keeps a slow scan from refusing the spawn. + const budgetMs = 2_000; + const scanMs = 300; + const original = StableFileHash.hashStableFile; + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (String(path).endsWith(".sla")) + await new Promise((resolve) => setTimeout(resolve, scanMs)); + return original(path, options); + }); + const granted: number[] = []; + const originalRun = OwnedCommand.runOwnedCommand; + const run = vi + .spyOn(OwnedCommand, "runOwnedCommand") + .mockImplementation(async (command, limits, options) => { + if (command.arguments[0] === "strings" && limits.timeoutMs !== null) + granted.push(limits.timeoutMs); + return originalRun(command, limits, options); + }); + try { + const listed = await runWithAnalysisOperationSnapshot( + { revision: 1, overrides: { "kuna.project_timeout_ms": budgetMs } }, + () => client.execute("list_strings", {}), + ); + expect(listed.ok).toBe(true); + expect(granted).toHaveLength(1); + // Timers never fire early by more than a millisecond. + expect(granted[0]).toBeLessThanOrEqual(budgetMs - scanMs + 1); + expect(granted[0]).toBeGreaterThan(0); + expect( + (await fakeKunaCalls(kuna)).filter(({ argv }) => argv[0] === "strings"), + ).toHaveLength(1); + } finally { + hash.mockRestore(); + run.mockRestore(); + } +}); + +it("returns a typed timeout when the spec scan exceeds the operation deadline", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-timeout-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const { open, kuna } = await session( + "rea-kuna-spec-timeout-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + expect( + (await client.execute("procedure_assembly", { procedure: "main" })).ok, + ).toBe(true); + const callsBefore = (await fakeKunaCalls(kuna)).length; + const original = StableFileHash.hashStableFile; + let releaseHash: () => void = () => undefined; + const hashRelease = new Promise((resolve) => { + releaseHash = resolve; + }); + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (String(path).endsWith(".sla")) { + await new Promise((resolve) => { + const finish = () => resolve(); + if (options.signal?.aborted === true) { + finish(); + return; + } + options.signal?.addEventListener("abort", finish, { once: true }); + void hashRelease.then(finish); + }); + } + return original(path, options); + }); + try { + const refused = await runWithAnalysisOperationSnapshot( + { revision: 1, overrides: { "kuna.project_timeout_ms": 1 } }, + () => client.execute("list_strings", {}), + ); + expect(refused.ok).toBe(false); + if (refused.ok) throw new Error("spec scan ignored the deadline"); + expect(refused.error).toMatchObject({ + _tag: "AnalysisTimeoutError", + timeoutMs: 1, + limit: { + setting: "kuna.project_timeout_ms", + effective_value: 1, + unit: "ms", + }, + }); + expect((await fakeKunaCalls(kuna)).length).toBe(callsBefore); + } finally { + releaseHash(); + hash.mockRestore(); + } +}); + +it("bounds an installation spec read with the function timeout", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-install-timeout-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const kuna = await writeFakeKuna(root); + const original = StableFileHash.hashStableFile; + let markStarted: () => void = () => undefined; + const scanStarted = new Promise((resolve) => { + markStarted = resolve; + }); + let releaseHash: () => void = () => undefined; + const hashRelease = new Promise((resolve) => { + releaseHash = resolve; + }); + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (!String(path).endsWith(".sla")) return original(path, options); + markStarted(); + await new Promise((resolve) => { + const finish = () => resolve(); + if (options.signal?.aborted === true) { + finish(); + return; + } + options.signal?.addEventListener("abort", finish, { once: true }); + void hashRelease.then(finish); + }); + return original(path, options); + }); + const run = runWithAnalysisOperationSnapshot( + { revision: 1, overrides: { "kuna.function_timeout_ms": 200 } }, + () => + inspectKunaInstallationOwned({ + REA_KUNA_COMMAND: kuna, + REA_KUNA_CACHE_DIR: join(root, "cache"), + KUNA_SPECS: specs, + }), + ); + try { + await awaitAcknowledgement(scanStarted, run, "installation spec scan"); + await expect(run).rejects.toMatchObject({ + _tag: "AnalysisTimeoutError", + timeoutMs: 200, + limit: { + setting: "kuna.function_timeout_ms", + effective_value: 200, + unit: "ms", + }, + }); + } finally { + releaseHash(); + await Promise.allSettled([run]); + hash.mockRestore(); + } +}); + +it("scans again after a clean installation spec timeout", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-timeout-retry-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const { open } = await session( + "rea-kuna-spec-timeout-retry-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + const original = StableFileHash.hashStableFile; + let releaseHash: () => void = () => undefined; + const hashRelease = new Promise((resolve) => { + releaseHash = resolve; + }); + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (!String(path).endsWith(".sla")) return original(path, options); + await new Promise((resolve) => { + const finish = () => resolve(); + if (options.signal?.aborted === true) { + finish(); + return; + } + options.signal?.addEventListener("abort", finish, { once: true }); + void hashRelease.then(finish); + }); + return original(path, options); + }); + try { + const refused = await runWithAnalysisOperationSnapshot( + { revision: 1, overrides: { "kuna.function_timeout_ms": 200 } }, + () => client.execute("health", {}), + ); + expect(refused.ok).toBe(false); + if (refused.ok) throw new Error("installation spec timeout was cached"); + expect(refused.error).toMatchObject({ + _tag: "AnalysisTimeoutError", + timeoutMs: 200, + limit: { setting: "kuna.function_timeout_ms", effective_value: 200 }, + }); + } finally { + releaseHash(); + hash.mockRestore(); + } + expect((await client.execute("health", {})).ok).toBe(true); +}); + +it("keeps a spec-file close failure on the timeout that stopped the read", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-timeout-close-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const { open, kuna } = await session( + "rea-kuna-spec-timeout-close-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + expect((await client.execute("health", {})).ok).toBe(true); + const callsBefore = (await fakeKunaCalls(kuna)).length; + // The close blocks until the scan's own deadline fires, so the timeout + // always lands while the spec descriptor is open. The test-owned release + // ends that wait in teardown even if the deadline never fires. + let scanSignal: AbortSignal | undefined; + let releaseClose: () => void = () => undefined; + const closeReleased = new Promise((resolve) => { + releaseClose = resolve; + }); + const originalHash = StableFileHash.hashStableFile; + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (String(path).endsWith(".sla")) scanSignal = options.signal; + return originalHash(path, options); + }); + const originalClose = OwnedFileHandle.prototype.close; + let failClose = true; + const close = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementation(async function (this: OwnedFileHandle) { + const signal = scanSignal; + if (signal === undefined || !failClose) return originalClose.call(this); + failClose = false; + await new Promise((resolve) => { + void closeReleased.then(resolve); + if (signal.aborted) resolve(); + signal.addEventListener("abort", () => resolve(), { once: true }); + }); + throw new Error("spec file close failed"); + }); + let failure: { readonly cleanupIncomplete: boolean } | undefined; + try { + const refused = await runWithAnalysisOperationSnapshot( + { revision: 1, overrides: { "kuna.project_timeout_ms": 500 } }, + () => client.execute("list_strings", {}), + ); + expect(refused.ok).toBe(false); + if (refused.ok) throw new Error("timed-out spec read was accepted"); + failure = refused.error; + expect(refused.error.cleanupIncomplete).toBe(true); + expect(refused.error.cleanupPrimary ?? refused.error).toMatchObject({ + _tag: "AnalysisTimeoutError", + limit: { setting: "kuna.project_timeout_ms", effective_value: 500 }, + }); + expect((await fakeKunaCalls(kuna)).length).toBe(callsBefore); + } finally { + releaseClose(); + hash.mockRestore(); + close.mockRestore(); + } + // Closing the client retries the retained descriptor and clears the report. + expect((await client.close()).ok).toBe(true); + expect(failure?.cleanupIncomplete).toBe(false); +}); + +it("keeps a shared export's spec-close lease after the starting client closes", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-shared-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "version-a"); + const { open, provider } = await session( + "rea-kuna-spec-shared-session-", + {}, + { KUNA_SPECS: specs }, + ); + const first = open(); + const second = open(); + expect((await first.execute("health", {})).ok).toBe(true); + expect((await second.execute("health", {})).ok).toBe(true); + let hashingSpec = false; + let releaseClose: () => void = () => undefined; + const closeUnblocked = new Promise((resolve) => { + releaseClose = resolve; + }); + let markReached: () => void = () => undefined; + const scanWaiting = new Promise((resolve) => { + markReached = resolve; + }); + const originalHash = StableFileHash.hashStableFile; + const hash = vi + .spyOn(StableFileHash, "hashStableFile") + .mockImplementation(async (path, options) => { + if (String(path).endsWith(".sla")) hashingSpec = true; + return originalHash(path, options); + }); + const originalClose = OwnedFileHandle.prototype.close; + const close = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementation(async function (this: OwnedFileHandle) { + if (!hashingSpec) return originalClose.call(this); + hashingSpec = false; + markReached(); + await closeUnblocked; + await originalClose.call(this); + throw new Error("spec file close failed"); + }); + const firstRun = first.execute("procedure_assembly", { procedure: "main" }); + const secondRun = second.execute("procedure_assembly", { procedure: "main" }); + try { + await awaitAcknowledgement( + scanWaiting, + Promise.all([firstRun, secondRun]), + "shared export spec close", + ); + expect(await first.close()).toEqual({ ok: true, value: null }); + releaseClose(); + const failed = await secondRun; + expect(failed.ok).toBe(false); + if (failed.ok) throw new Error("shared export hid the spec close"); + expect(failed.error.cleanupIncomplete).toBe(true); + await firstRun; + expect(failed.error.cleanupIncomplete).toBe(true); + expect((await second.close()).ok).toBe(true); + expect(failed.error.cleanupIncomplete).toBe(false); + expect((await provider.closeOwnedResources()).ok).toBe(true); + } finally { + releaseClose(); + await Promise.allSettled([firstRun, secondRun]); + hash.mockRestore(); + close.mockRestore(); + } +}); + +it("stops a spec directory at the entry allowance", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-limit-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "a.sla"), "a"); + await writeFile(join(specs, "b.sla"), "b"); + const identified = await identifyKunaExternalSpecs( + [{ variable: "KUNA_SPECS", path: specs }], + specRead({ + platform: "linux", + maxEntries: 1, + retainFailedClose: () => idleLease(), + }), + ); + expect(identified).toMatchObject([ + { + variable: "KUNA_SPECS", + path: specs, + status: "unknown", + reason: "limit", + reuse_fence: expect.stringMatching(UUID), + }, + ]); + expect(identified[0]).not.toHaveProperty("sha256"); +}); + +it("retains a specification directory whose close failed", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-close-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const retained: AnalysisCleanupLease[] = []; + const close = vi + .spyOn(OwnedDirectoryHandle.prototype, "close") + .mockImplementationOnce(async function (this: OwnedDirectoryHandle) { + close.mockRestore(); + await this.close(); + throw new Error("spec directory close failed"); + }); + let thrown: unknown; + try { + await identifyKunaExternalSpecs( + [{ variable: "KUNA_SPECS", path: specs }], + specRead({ + platform: "linux", + retainFailedClose: (owner, resource) => { + const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); + retained.push(lease); + return lease; + }, + }), + ); + } catch (cause: unknown) { + thrown = cause; + } finally { + close.mockRestore(); + } + expect(thrown).toMatchObject({ + reason: "unavailable", + cleanup: { resources: [specs] }, + cleanupLeases: [retained[0]], + }); + const classified = classifyProviderFailure( + thrown, + kunaSessionDialect("procedure_assembly"), + ); + expect(classified.cleanupIncomplete).toBe(true); + await retained[0]?.release(); + expect(classified.cleanupIncomplete).toBe(false); +}); + +it("keeps a launch's spec-directory close failure on the command scope", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-launch-dir-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const { open, kuna } = await session( + "rea-kuna-spec-launch-dir-session-", + {}, + { KUNA_SPECS: specs }, + ); + const client = open(); + expect((await client.execute("health", {})).ok).toBe(true); + const callsBefore = (await fakeKunaCalls(kuna)).length; + const close = vi + .spyOn(OwnedDirectoryHandle.prototype, "close") + .mockImplementationOnce(async function (this: OwnedDirectoryHandle) { + close.mockRestore(); + await this.close(); + throw new Error("spec directory close failed"); + }); + let failure: { readonly cleanupIncomplete: boolean } | undefined; + try { + const refused = await client.execute("list_strings", {}); + expect(refused.ok).toBe(false); + if (refused.ok) throw new Error("launch hid the directory close"); + failure = refused.error; + expect(refused.error.cleanupIncomplete).toBe(true); + expect(refused.error.cleanupResources).toContain(specs); + expect((await fakeKunaCalls(kuna)).length).toBe(callsBefore); + } finally { + close.mockRestore(); + } + // The command scope retries the retained handle when the client closes. + expect((await client.close()).ok).toBe(true); + expect(failure?.cleanupIncomplete).toBe(false); +}); + +/** Fail the next directory close after really closing it, so a retry succeeds. */ +const failNextDirectoryClose = () => { + const close = vi + .spyOn(OwnedDirectoryHandle.prototype, "close") + .mockImplementationOnce(async function (this: OwnedDirectoryHandle) { + close.mockRestore(); + await this.close(); + throw new Error("spec directory close failed"); + }); + return close; +}; + +it("keeps a cancelled directory listing's cancellation beside its failed close", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-dir-cancel-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const caller = new AbortController(); + const originalRead = Dir.prototype.read as (this: Dir) => Promise; + // The caller cancels while the listing is open; the loop observes it next. + const read = vi.spyOn(Dir.prototype, "read").mockImplementationOnce(function ( + this: Dir, + ) { + caller.abort(); + return originalRead.call(this); + } as unknown as typeof Dir.prototype.read); + const close = failNextDirectoryClose(); + const retained: AnalysisCleanupLease[] = []; + let thrown: unknown; + try { + await identifyKunaExternalSpecs( + [{ variable: "KUNA_SPECS", path: specs }], + specRead({ + platform: "linux", + signal: caller.signal, + retainFailedClose: (owner, resource) => { + const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); + retained.push(lease); + return lease; + }, + }), + ); + } catch (cause: unknown) { + thrown = cause; + } finally { + read.mockRestore(); + close.mockRestore(); + } + expect(thrown).toMatchObject({ + _tag: "AnalysisCancelledError", + cleanupIncomplete: true, + cleanupResources: [specs], + }); + await retained[0]?.release(); + expect(thrown).toMatchObject({ cleanupIncomplete: false }); +}); + +it("reports a deadline-stopped directory listing as a timeout beside its failed close", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-dir-timeout-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const originalRead = Dir.prototype.read as (this: Dir) => Promise; + // The 50 ms scan deadline fires while this read is still pending, so the + // listing loop observes it on its next check. + const read = vi + .spyOn(Dir.prototype, "read") + .mockImplementationOnce(async function (this: Dir) { + await new Promise((resolve) => setTimeout(resolve, 150)); + return originalRead.call(this); + } as unknown as typeof Dir.prototype.read); + const close = failNextDirectoryClose(); + const retained: AnalysisCleanupLease[] = []; + const deadline = { + setting: "REA_KUNA_TIMEOUT_MS" as const, + ms: 50, + source: "runtime" as const, + }; + let thrown: unknown; + try { + await identifyKunaExternalSpecs([{ variable: "KUNA_SPECS", path: specs }], { + operation: "kuna:spec-identity", + deadline, + budget: Deadline.after(deadline.ms), + platform: "linux", + retainFailedClose: (owner, resource) => { + const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); + retained.push(lease); + return lease; + }, + }); + } catch (cause: unknown) { + thrown = cause; + } finally { + read.mockRestore(); + close.mockRestore(); + } + expect(thrown).toMatchObject({ + _tag: "AnalysisTimeoutError", + cleanupIncomplete: true, + cleanupResources: [specs], + limit: { setting: "kuna.function_timeout_ms", effective_value: 50 }, + }); + await retained[0]?.release(); + expect(thrown).toMatchObject({ cleanupIncomplete: false }); +}); + +it("binds a specification file close to the lease the hook returned", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-file-close-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const retained: AnalysisCleanupLease[] = []; + const close = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementationOnce(async function (this: OwnedFileHandle) { + close.mockRestore(); + await this.close(); + throw new Error("spec file close failed"); + }); + let thrown: unknown; + try { + await identifyKunaExternalSpecs( + [{ variable: "KUNA_SPECS", path: specs }], + specRead({ + platform: "linux", + retainFailedClose: (owner, resource) => { + const lease = AnalysisCleanupLease.forCloseOwner(owner, resource); + retained.push(lease); + return lease; + }, + }), + ); + } catch (cause: unknown) { + thrown = cause; + } finally { + close.mockRestore(); + } + expect(thrown).toMatchObject({ retainedClose: retained[0] }); + if (!(thrown instanceof RegularFileCleanupFailure)) + throw new Error("file close did not fail"); + const classified = kunaFileCleanupError(thrown, "procedure_assembly"); + expect(classified).toMatchObject({ + _tag: "ProviderAdapterError", + cleanupIncomplete: true, + }); + await retained[0]?.release(); + expect(classified.cleanupIncomplete).toBe(false); +}); + +it("clears an installation file-close failure when its owner lease is released", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-install-close-"); + const specs = join(root, "specs"); + await mkdir(specs); + await writeFile(join(specs, "x.sla"), "spec"); + const parent: RetainedResourceScope = { + retain: () => undefined, + run: (operation) => operation(), + }; + const resources = createKunaResourceScope(parent); + const close = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementationOnce(async function (this: OwnedFileHandle) { + close.mockRestore(); + await this.close(); + throw new Error("spec file close failed"); + }); + let thrown: unknown; + try { + await identifyKunaExternalSpecs( + [{ variable: "KUNA_SPECS", path: specs }], + specRead({ + platform: "linux", + retainFailedClose: (owner, resource) => + resources.owner.retainClose?.(owner, resource) ?? idleLease(), + }), + ); + } catch (cause: unknown) { + thrown = cause; + } finally { + close.mockRestore(); + } + const classified = classifyProviderFailure( + thrown, + kunaInstallationDialect( + "health", + resources, + kunaSessionDialect("health").unclassified, + ), + ); + expect(classified.cleanupIncomplete).toBe(true); + const lease = + thrown instanceof Error && + "retainedClose" in thrown && + thrown.retainedClose instanceof AnalysisCleanupLease + ? thrown.retainedClose + : undefined; + expect(lease).toBeInstanceOf(AnalysisCleanupLease); + await lease?.release(); + expect(classified.cleanupIncomplete).toBe(false); +}); + +it("gives an unidentifiable specification a fresh non-reusable identity", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-unknown-"); + const resolved = absoluteCallerPath("relative/specs"); + const first = await installed(root, { KUNA_SPECS: "relative/specs" }); + const second = await installed(root, { KUNA_SPECS: "relative/specs" }); + expect(first.installation.externalSpecIdentities).toMatchObject([ + { + variable: "KUNA_SPECS", + path: resolved, + status: "unknown", + reason: "unreadable", + }, + ]); + const relative = await identifyKunaExternalSpecs( + [{ variable: "KUNA_SPECS", path: "relative/specs" }], + specRead({ + platform: "linux", + retainFailedClose: () => idleLease(), + }), + ); + expect(relative).toMatchObject([ + { + variable: "KUNA_SPECS", + path: "relative/specs", + status: "unknown", + reason: "not_absolute", + }, + ]); + const reused = await identifyKunaExternalSpecs( + [{ variable: "KUNA_SPECS", path: resolved }], + specRead({ + platform: "linux", + committed: first.installation.externalSpecIdentities, + retainFailedClose: () => idleLease(), + }), + ); + expect(reused[0]).toMatchObject({ + status: "unknown", + reason: "unreadable", + reuse_fence: + first.installation.externalSpecIdentities[0]?.status === "unknown" + ? first.installation.externalSpecIdentities[0].reuse_fence + : undefined, + }); + expect(first.installation.externalSpecIdentities[0]).toMatchObject({ + reuse_fence: expect.stringMatching(UUID), + }); + expect(second.installation.externalSpecIdentities[0]).toMatchObject({ + reuse_fence: expect.stringMatching(UUID), + }); + const firstFence = first.installation.externalSpecIdentities[0]; + const secondFence = second.installation.externalSpecIdentities[0]; + if (firstFence?.status !== "unknown" || secondFence?.status !== "unknown") + throw new Error("relative specification was identified"); + expect(secondFence.reuse_fence).not.toBe(firstFence.reuse_fence); + const target = "ef".repeat(32); + expect(keyFor(first.installation, target, "program")).not.toBe( + keyFor(second.installation, target, "program"), + ); + const { profile: firstProfile, open } = await session( + "rea-kuna-spec-unknown-a-", + {}, + { KUNA_SPECS: "relative/specs" }, + ); + const health = await open().execute("health", {}); + expect(health.ok).toBe(true); + const { profile: secondProfile } = await session( + "rea-kuna-spec-unknown-b-", + {}, + { KUNA_SPECS: "relative/specs" }, + ); + expect(firstProfile.parameters.external_specs).toMatchObject([ + { + variable: "KUNA_SPECS", + path: resolved, + status: "unknown", + reason: "unreadable", + }, + ]); + expect(firstProfile.digest).not.toBe(secondProfile.digest); +}); + +it("leaves the profile and export key unchanged when no specification is selected", async () => { + const root = await createTestTempDirectory("rea-kuna-spec-absent-"); + const { installation } = await installed(root, {}); + expect(installation.configuration.externalSpecs).toEqual([]); + expect(installation.externalSpecIdentities).toEqual([]); + const { profile } = await session("rea-kuna-spec-absent-profile-"); + expect(profile.parameters).not.toHaveProperty("external_specs"); + const target = "12".repeat(32); + expect(keyFor(installation, target, "program")).toBe( + kunaProjectKey({ + targetSha256: target, + targetBasename: "program", + kunaSha256: installation.sha256, + kunaCommand: installation.configuration.command, + kunaExecutable: installation.executable, + kunaVersion: installation.version, + jobs: installation.configuration.jobs, + externalSpecs: [], + }), + ); +});