refactor(coverage): evaluate inline without workspaces
This commit is contained in:
@@ -18,7 +18,6 @@ import type {
|
||||
UnknownStatus,
|
||||
UpdateUnknownInput,
|
||||
} from "../domain/residualUnknown.js";
|
||||
import type { ReconstructionCoverageWorkspace } from "../domain/reconstructionCoverage.js";
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
@@ -57,14 +56,6 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
importAnalysisSnapshot(
|
||||
snapshot: AnalysisSnapshot,
|
||||
): Result<number, AnalysisError>;
|
||||
retainReconstructionCoverageWorkspace(
|
||||
workspace: ReconstructionCoverageWorkspace,
|
||||
): "added" | "duplicate";
|
||||
reconstructionCoverageWorkspace(
|
||||
workspaceId: string,
|
||||
revision: number,
|
||||
): ReconstructionCoverageWorkspace | undefined;
|
||||
reconstructionCoverageWorkspaces(): readonly ReconstructionCoverageWorkspace[];
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
|
||||
@@ -10,10 +10,6 @@ import {
|
||||
type AnalysisError,
|
||||
type UnknownRegistryError,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
parseReconstructionCoverageWorkspace,
|
||||
type ReconstructionCoverageWorkspace,
|
||||
} from "../domain/reconstructionCoverage.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
ResidualUnknown,
|
||||
@@ -45,10 +41,6 @@ export abstract class BinarySessionRecords {
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
});
|
||||
readonly #snapshot = new AnalysisSnapshotCache();
|
||||
readonly #coverageWorkspaces = new Map<
|
||||
string,
|
||||
ReconstructionCoverageWorkspace
|
||||
>();
|
||||
#snapshotInvalidated = false;
|
||||
readonly #snapshotListeners = new Set<() => void | Promise<void>>();
|
||||
|
||||
@@ -211,30 +203,6 @@ export abstract class BinarySessionRecords {
|
||||
}
|
||||
}
|
||||
|
||||
retainReconstructionCoverageWorkspace(
|
||||
workspace: ReconstructionCoverageWorkspace,
|
||||
): "added" | "duplicate" {
|
||||
const parsed = parseReconstructionCoverageWorkspace(workspace);
|
||||
const key = workspaceKey(parsed.workspace_id, parsed.revision);
|
||||
if (this.#coverageWorkspaces.has(key)) return "duplicate";
|
||||
this.#coverageWorkspaces.set(key, parsed);
|
||||
return "added";
|
||||
}
|
||||
|
||||
reconstructionCoverageWorkspace(
|
||||
workspaceId: string,
|
||||
revision: number,
|
||||
): ReconstructionCoverageWorkspace | undefined {
|
||||
const workspace = this.#coverageWorkspaces.get(
|
||||
workspaceKey(workspaceId, revision),
|
||||
);
|
||||
return workspace === undefined ? undefined : structuredClone(workspace);
|
||||
}
|
||||
|
||||
reconstructionCoverageWorkspaces(): readonly ReconstructionCoverageWorkspace[] {
|
||||
return sortedWorkspaces(this.#coverageWorkspaces.values());
|
||||
}
|
||||
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError> {
|
||||
@@ -305,19 +273,3 @@ export abstract class BinarySessionRecords {
|
||||
return this.#evidence.verifyUnknownResolution(unknownId);
|
||||
}
|
||||
}
|
||||
|
||||
const workspaceKey = (workspaceId: string, revision: number): string =>
|
||||
`${workspaceId}:${String(revision)}`;
|
||||
|
||||
const sortedWorkspaces = <
|
||||
T extends { readonly workspace_id: string; readonly revision: number },
|
||||
>(
|
||||
workspaces: Iterable<T>,
|
||||
): readonly T[] =>
|
||||
[...workspaces]
|
||||
.sort(
|
||||
(left, right) =>
|
||||
left.workspace_id.localeCompare(right.workspace_id) ||
|
||||
left.revision - right.revision,
|
||||
)
|
||||
.map((workspace) => structuredClone(workspace));
|
||||
|
||||
@@ -1,121 +1,44 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { AnalysisInputError, type AnalysisError } from "../domain/errors.js";
|
||||
import {
|
||||
evaluateReconstructionClosure,
|
||||
reconstructionCoverageWorkspaceSchema,
|
||||
reconstructionCoverageDataSchema,
|
||||
} from "../domain/reconstructionCoverage.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import {
|
||||
readReconstructionCoverageWorkspace,
|
||||
writeReconstructionCoverageWorkspace,
|
||||
} from "./ReconstructionCoverageWorkspaceStore.js";
|
||||
|
||||
const COMMIT_OPERATION = "commit_reconstruction_coverage" as const;
|
||||
const QUERY_OPERATION = "query_reconstruction_coverage" as const;
|
||||
const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
export const reconstructionCoverageCommitInputSchema = z.strictObject({
|
||||
approved: z.literal(true),
|
||||
workspace_path: z.string().min(1).max(4_096),
|
||||
expected_revision: z.number().int().min(1).nullable(),
|
||||
workspace: reconstructionCoverageWorkspaceSchema,
|
||||
});
|
||||
|
||||
export const reconstructionCoverageQueryInputSchema = z.strictObject({
|
||||
workspace_path: z.string().min(1).max(4_096),
|
||||
export const reconstructionCoverageEvaluationInputSchema = z.strictObject({
|
||||
coverage: reconstructionCoverageDataSchema,
|
||||
boundary_id: z.string().min(1).max(200),
|
||||
});
|
||||
|
||||
export const reconstructionCoverageCommitOutputSchema = z.strictObject({
|
||||
workspace_path: z.string(),
|
||||
bytes: z.number().int().min(0),
|
||||
workspace_id: z.string().regex(/^rcw_[a-f0-9]{64}$/u),
|
||||
revision: z.number().int().min(1),
|
||||
revision_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
evidence_records: z.number().int().min(0),
|
||||
});
|
||||
|
||||
/** Commit one caller-approved canonical reconstruction coverage CAS revision. */
|
||||
export const commitReconstructionCoverage = async (
|
||||
/** Evaluate inline reconstruction coverage against a named boundary. */
|
||||
export const evaluateReconstructionCoverage = (
|
||||
rawInput: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const parsed = reconstructionCoverageCommitInputSchema.safeParse(rawInput);
|
||||
nowEpochMs = Date.now(),
|
||||
): Result<JsonValue, AnalysisError> => {
|
||||
const parsed =
|
||||
reconstructionCoverageEvaluationInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError(COMMIT_OPERATION, { cause: parsed.error }),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(COMMIT_OPERATION));
|
||||
const written = await writeReconstructionCoverageWorkspace(
|
||||
parsed.data.workspace,
|
||||
parsed.data.workspace_path,
|
||||
parsed.data.expected_revision,
|
||||
policy,
|
||||
);
|
||||
if (!written.ok) return written;
|
||||
return ok(
|
||||
jsonValueSchema.parse({
|
||||
workspace_path: written.value.path,
|
||||
bytes: written.value.bytes,
|
||||
workspace_id: parsed.data.workspace.workspace_id,
|
||||
revision: parsed.data.workspace.revision,
|
||||
revision_sha256: parsed.data.workspace.revision_sha256,
|
||||
evidence_records: parsed.data.workspace.evidence_bundle.records.length,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
/** Read one coverage revision and evaluate a named fail-closed boundary. */
|
||||
export const queryReconstructionCoverage = async (
|
||||
rawInput: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
nowEpochMs: number,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const parsed = reconstructionCoverageQueryInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError(QUERY_OPERATION, { cause: parsed.error }),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(QUERY_OPERATION));
|
||||
const loaded = await readReconstructionCoverageWorkspace(
|
||||
parsed.data.workspace_path,
|
||||
policy,
|
||||
);
|
||||
if (!loaded.ok) return loaded;
|
||||
if (loaded.value === null)
|
||||
return err(
|
||||
new AnalysisInputError(QUERY_OPERATION, {
|
||||
cause: new TypeError(
|
||||
"Reconstruction coverage workspace does not exist",
|
||||
),
|
||||
new AnalysisInputError("evaluate_reconstruction_coverage", {
|
||||
cause: parsed.error,
|
||||
}),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(QUERY_OPERATION));
|
||||
try {
|
||||
return ok(
|
||||
jsonValueSchema.parse(
|
||||
evaluateReconstructionClosure(
|
||||
loaded.value,
|
||||
parsed.data.coverage,
|
||||
parsed.data.boundary_id,
|
||||
nowEpochMs,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(new AnalysisInputError(QUERY_OPERATION, { cause }));
|
||||
return err(
|
||||
new AnalysisInputError("evaluate_reconstruction_coverage", { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { WorkspaceStorageError } from "../domain/errors.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
parseReconstructionCoverageWorkspace,
|
||||
serializeReconstructionCoverageWorkspace,
|
||||
type ReconstructionCoverageWorkspace,
|
||||
} from "../domain/reconstructionCoverage.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
readRevisionedWorkspace,
|
||||
writeRevisionedWorkspace,
|
||||
type RevisionedWorkspaceCodec,
|
||||
} from "./RevisionedWorkspaceStore.js";
|
||||
|
||||
const codec: RevisionedWorkspaceCodec<ReconstructionCoverageWorkspace> = {
|
||||
parse: parseReconstructionCoverageWorkspace,
|
||||
serialize: serializeReconstructionCoverageWorkspace,
|
||||
validateNext: (current, next, expectedRevision) => {
|
||||
if ((current?.revision ?? null) !== expectedRevision)
|
||||
return err(new WorkspaceStorageError("update", "revision-conflict"));
|
||||
if (current === null)
|
||||
return next.revision === 1 && next.previous_revision_sha256 === null
|
||||
? ok(null)
|
||||
: err(new WorkspaceStorageError("update", "revision-conflict"));
|
||||
if (
|
||||
current.name !== next.name ||
|
||||
current.workspace_id !== next.workspace_id
|
||||
)
|
||||
return err(new WorkspaceStorageError("update", "name-conflict"));
|
||||
return next.revision === current.revision + 1 &&
|
||||
next.previous_revision_sha256 === current.revision_sha256
|
||||
? ok(null)
|
||||
: err(new WorkspaceStorageError("update", "revision-conflict"));
|
||||
},
|
||||
};
|
||||
|
||||
/** Read a validated reconstruction coverage workspace revision. */
|
||||
export const readReconstructionCoverageWorkspace = (
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
Result<ReconstructionCoverageWorkspace | null, WorkspaceStorageError>
|
||||
> => readRevisionedWorkspace(path, policy, codec);
|
||||
|
||||
/** Atomically append one reconstruction coverage workspace CAS revision. */
|
||||
export const writeReconstructionCoverageWorkspace = (
|
||||
workspace: ReconstructionCoverageWorkspace,
|
||||
path: string,
|
||||
expectedRevision: number | null,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
Result<
|
||||
{ readonly path: string; readonly bytes: number },
|
||||
WorkspaceStorageError
|
||||
>
|
||||
> =>
|
||||
writeRevisionedWorkspace(path, policy, {
|
||||
document: workspace,
|
||||
expectedRevision,
|
||||
codec,
|
||||
});
|
||||
@@ -1,190 +0,0 @@
|
||||
import {
|
||||
createStoreFileLock,
|
||||
removeStaleStoreFileLock,
|
||||
type StoreFileLock,
|
||||
} from "./StoreFileLock.js";
|
||||
import { lstat, readFile, realpath } from "node:fs/promises";
|
||||
import { basename, dirname, resolve } from "node:path";
|
||||
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { isJsonWithinLimits } from "../domain/jsonLimits.js";
|
||||
import { WorkspaceStorageError } from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
|
||||
|
||||
type WorkspaceResult<Value> = Result<Value, WorkspaceStorageError>;
|
||||
|
||||
/** Parser, serializer, and CAS transition owned by one revisioned workspace. */
|
||||
export interface RevisionedWorkspaceCodec<Document> {
|
||||
readonly parse: (input: unknown) => Document;
|
||||
readonly serialize: (document: Document) => string;
|
||||
readonly validateNext: (
|
||||
current: Document | null,
|
||||
next: Document,
|
||||
expectedRevision: number | null,
|
||||
) => WorkspaceResult<null>;
|
||||
}
|
||||
|
||||
/** Read one root-confined, owner-only revisioned workspace document. */
|
||||
export const readRevisionedWorkspace = async <Document>(
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
codec: RevisionedWorkspaceCodec<Document>,
|
||||
): Promise<WorkspaceResult<Document | null>> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new WorkspaceStorageError("read", "disabled"));
|
||||
try {
|
||||
const destination = await resolveDestination(path, policy.roots);
|
||||
if (destination === null)
|
||||
return err(new WorkspaceStorageError("read", "outside-root"));
|
||||
return await readWorkspaceFile(destination, policy, codec);
|
||||
} catch (cause: unknown) {
|
||||
return err(new WorkspaceStorageError("read", "io", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
export interface RevisionedWorkspaceWriteInput<Document> {
|
||||
readonly document: Document;
|
||||
readonly expectedRevision: number | null;
|
||||
readonly codec: RevisionedWorkspaceCodec<Document>;
|
||||
}
|
||||
|
||||
/** Atomically append one validated CAS-linked revision under an exclusive lock. */
|
||||
export const writeRevisionedWorkspace = async <Document>(
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
input: RevisionedWorkspaceWriteInput<Document>,
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
|
||||
> => {
|
||||
const { document, expectedRevision, codec } = input;
|
||||
if (policy.roots.length === 0)
|
||||
return err(new WorkspaceStorageError("update", "disabled"));
|
||||
let encoded: string;
|
||||
try {
|
||||
encoded = codec.serialize(document);
|
||||
} catch (cause: unknown) {
|
||||
return err(new WorkspaceStorageError("update", "integrity", { cause }));
|
||||
}
|
||||
const bytes = Buffer.byteLength(encoded, "utf8");
|
||||
if (bytes > policy.maxBytes)
|
||||
return err(new WorkspaceStorageError("update", "too-large"));
|
||||
let lock: StoreFileLock | undefined;
|
||||
try {
|
||||
const destination = await resolveDestination(path, policy.roots);
|
||||
if (destination === null)
|
||||
return err(new WorkspaceStorageError("update", "outside-root"));
|
||||
const acquired = await acquireLock(destination);
|
||||
if (!acquired.ok) return acquired;
|
||||
lock = acquired.value;
|
||||
const current = await readWorkspaceFile(destination, policy, codec);
|
||||
if (!current.ok) return current;
|
||||
const checked = codec.validateNext(
|
||||
current.value,
|
||||
document,
|
||||
expectedRevision,
|
||||
);
|
||||
if (!checked.ok) return checked;
|
||||
await writeFileAtomic(destination, encoded, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
fsync: true,
|
||||
});
|
||||
return ok({ path: resolve(path), bytes });
|
||||
} catch (cause: unknown) {
|
||||
return err(new WorkspaceStorageError("update", "io", { cause }));
|
||||
} finally {
|
||||
if (lock !== undefined) await lock.release();
|
||||
}
|
||||
};
|
||||
|
||||
const resolveDestination = async (
|
||||
path: string,
|
||||
roots: readonly string[],
|
||||
): Promise<string | null> => {
|
||||
const requested = resolve(path);
|
||||
const canonicalParent = await realpath(dirname(requested));
|
||||
const destination = resolve(canonicalParent, basename(requested));
|
||||
for (const root of await canonicalizeConfiguredRoots(
|
||||
roots.map((configuredRoot) => resolve(configuredRoot)),
|
||||
)) {
|
||||
if (isPathWithinRoot(root, destination)) return destination;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const readWorkspaceFile = async <Document>(
|
||||
destination: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
codec: RevisionedWorkspaceCodec<Document>,
|
||||
): Promise<WorkspaceResult<Document | null>> => {
|
||||
const stats = await lstat(destination).catch((cause: unknown) => {
|
||||
if (isFileNotFound(cause)) return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (stats === undefined) return ok(null);
|
||||
if (!stats.isFile() || stats.isSymbolicLink())
|
||||
return err(new WorkspaceStorageError("read", "not-file"));
|
||||
if (stats.size > policy.maxBytes)
|
||||
return err(new WorkspaceStorageError("read", "too-large"));
|
||||
const encoded = await readFile(destination);
|
||||
if (encoded.byteLength > policy.maxBytes)
|
||||
return err(new WorkspaceStorageError("read", "too-large"));
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(encoded.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(new WorkspaceStorageError("read", "invalid-json", { cause }));
|
||||
}
|
||||
if (!isJsonWithinLimits(decoded, policy))
|
||||
return err(new WorkspaceStorageError("read", "too-large"));
|
||||
try {
|
||||
return ok(codec.parse(decoded));
|
||||
} catch (cause: unknown) {
|
||||
return err(new WorkspaceStorageError("read", "integrity", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
const acquireLock = async (
|
||||
destination: string,
|
||||
): Promise<WorkspaceResult<StoreFileLock>> => {
|
||||
const path = `${destination}.lock`;
|
||||
try {
|
||||
return ok(await createStoreFileLock(path));
|
||||
} catch (cause: unknown) {
|
||||
if (isAlreadyExists(cause) && (await removeStaleStoreFileLock(path))) {
|
||||
try {
|
||||
return ok(await createStoreFileLock(path));
|
||||
} catch (retryCause: unknown) {
|
||||
return err(
|
||||
new WorkspaceStorageError(
|
||||
"update",
|
||||
isAlreadyExists(retryCause) ? "locked" : "io",
|
||||
{ cause: retryCause },
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return err(
|
||||
new WorkspaceStorageError(
|
||||
"update",
|
||||
isAlreadyExists(cause) ? "locked" : "io",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "ENOENT";
|
||||
|
||||
const isAlreadyExists = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "EEXIST";
|
||||
|
||||
const errorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
Reference in New Issue
Block a user