diff --git a/src/contracts/evidenceInputConformance.test.ts b/src/contracts/evidenceInputConformance.test.ts
index a88d5288f5..8ff987aa42 100644
--- a/src/contracts/evidenceInputConformance.test.ts
+++ b/src/contracts/evidenceInputConformance.test.ts
@@ -5,6 +5,7 @@ import { analysisViewSourceSchema } from "../domain/analysisView/analysisViewReq
import { evidenceSchema } from "../domain/evidence.js";
import { evidenceBundleSchema } from "../domain/evidenceBundle.js";
import {
+ declareBorrowedEvidenceInput,
getEvidenceInputContract,
isDeclaredEvidenceInput,
isEvidenceReferenceAlternative,
@@ -248,4 +249,29 @@ describe("public Evidence input declarations", () => {
]);
expect(declarationIssues(choice.prefault(fallback))).toEqual([]);
});
+
+ it("refuses to borrow a declaration that resolves by its parsed union branch", () => {
+ const choice = z.union([
+ z.strictObject({
+ kind: z.literal("source"),
+ source: evidenceInputSchema,
+ }),
+ z.strictObject({ kind: z.literal("none") }),
+ ]);
+ // The borrowing parser never runs the union's branch capture, so its
+ // Evidence would pass through unvisited.
+ expect(() =>
+ getEvidenceInputContract(
+ declareBorrowedEvidenceInput(z.unknown().nonoptional(), choice),
+ ),
+ ).toThrow("cannot select union branches");
+ expect(
+ getEvidenceInputContract(
+ declareBorrowedEvidenceInput(
+ z.unknown().nonoptional(),
+ z.array(evidenceInputSchema),
+ ),
+ ).hasEvidence,
+ ).toBe(true);
+ });
});
diff --git a/src/domain/evidenceInputContract.ts b/src/domain/evidenceInputContract.ts
index 89e44ffac9..6c730f705c 100644
--- a/src/domain/evidenceInputContract.ts
+++ b/src/domain/evidenceInputContract.ts
@@ -118,6 +118,11 @@ export interface EvidenceInputContract {
readonly hasEvidence: boolean;
/** A declared field can replace inline Evidence with a retained reference. */
readonly hasEvidenceReferenceAlternative: boolean;
+ /**
+ * Resolution depends on the union branch this contract's own frame parse
+ * selected, so the frame cannot be replaced by another parser.
+ */
+ readonly selectsParsedBranch: boolean;
resolve(
input: unknown,
visit: Visitor,
@@ -133,6 +138,7 @@ const identity = (
frameSchema: schema,
hasEvidence: false,
hasEvidenceReferenceAlternative,
+ selectsParsedBranch: false,
resolve: (input) => ok(input),
});
@@ -164,6 +170,7 @@ const compile = (schema: z.ZodType): EvidenceInputContract => {
frameSchema: z.unknown().nonoptional(),
hasEvidence: true,
hasEvidenceReferenceAlternative: true,
+ selectsParsedBranch: false,
resolve: (input, visit, path = []) => visit(input, path),
};
if (declared?.kind === "borrowed") {
@@ -171,6 +178,12 @@ const compile = (schema: z.ZodType): EvidenceInputContract => {
if (declaration === undefined)
throw new TypeError("Borrowed Evidence schema has no owning declaration");
const source = getEvidenceInputContract(declaration);
+ // The borrowing parser replaces the frame, so a source that resolves by
+ // the branch its own frame selected would never visit its Evidence.
+ if (source.selectsParsedBranch)
+ throw new TypeError(
+ "Borrowed Evidence declarations cannot select union branches by parsing",
+ );
return { ...source, frameSchema: schema };
}
if (schema instanceof z.ZodObject) return objectContract(schema);
@@ -191,6 +204,7 @@ const compile = (schema: z.ZodType): EvidenceInputContract => {
return {
hasEvidence: true,
hasEvidenceReferenceAlternative: child.hasEvidenceReferenceAlternative,
+ selectsParsedBranch: child.selectsParsedBranch,
frameSchema: replaceWrappedSchema(schema, child.frameSchema),
resolve: (input, visit, path = []) =>
input === undefined ||
@@ -225,6 +239,9 @@ const objectContract = (schema: z.ZodObject): EvidenceInputContract => {
return {
hasEvidence: true,
hasEvidenceReferenceAlternative,
+ selectsParsedBranch: selected.some(
+ ([, child]) => child.selectsParsedBranch,
+ ),
frameSchema: schema.clone(
{
...schema.def,
@@ -257,6 +274,7 @@ const arrayContract = (schema: z.ZodArray): EvidenceInputContract => {
return {
hasEvidence: true,
hasEvidenceReferenceAlternative: child.hasEvidenceReferenceAlternative,
+ selectsParsedBranch: child.selectsParsedBranch,
frameSchema: schema.clone(
{ ...schema.def, element: child.frameSchema },
{ parent: true },
@@ -301,6 +319,7 @@ const unionContract = (schema: z.ZodUnion): EvidenceInputContract => {
return {
hasEvidence: true,
hasEvidenceReferenceAlternative,
+ selectsParsedBranch: true,
frameSchema: frame.clone({
...frame.def,
...(schema.def.error === undefined ? {} : { error: schema.def.error }),
diff --git a/src/domain/immutableJson.test.ts b/src/domain/immutableJson.test.ts
index 49caf837b0..c81a3590f9 100644
--- a/src/domain/immutableJson.test.ts
+++ b/src/domain/immutableJson.test.ts
@@ -3,12 +3,79 @@ import { describe, expect, it, vi } from "vitest";
import type { JsonValue } from "./jsonValue.js";
import {
freezeJsonSnapshot,
+ freezeOwnedJsonTreeSnapshot,
canBorrowParsedJsonSnapshot,
immutableJsonSnapshotMember,
isImmutableJsonSnapshot,
} from "./immutableJson.js";
describe("owned immutable JSON snapshots", () => {
+ it("never borrows a member that sealing did not visit", () => {
+ const hidden = { mutable: true };
+ const named = { mutable: true };
+ const items: JsonValue[] = [1];
+ Object.defineProperty(items, "named", { value: named, enumerable: true });
+ const record: Record = { items };
+ Object.defineProperty(record, "hidden", { value: hidden });
+ const sealed = freezeOwnedJsonTreeSnapshot(record);
+ expect(immutableJsonSnapshotMember(sealed, "hidden")).toBeUndefined();
+ const borrowed = immutableJsonSnapshotMember(sealed, "items");
+ expect(borrowed).toBe(items);
+ expect(immutableJsonSnapshotMember(borrowed, "named")).toBeUndefined();
+ expect(immutableJsonSnapshotMember(borrowed, "0")).toBe(1);
+ expect(isImmutableJsonSnapshot(hidden)).toBe(false);
+ expect(isImmutableJsonSnapshot(named)).toBe(false);
+ expect(Object.isFrozen(named)).toBe(false);
+ });
+
+ it("seals a shared subtree once rather than once per path", () => {
+ // Each level references the next twice: 2^60 paths and 61 objects. The
+ // seal is synchronous, so a lost visited set would expand those paths on
+ // this worker before Vitest can time the test out. The budget is one
+ // descriptor per owned edge of this call.
+ const sharingDepth = 60;
+ let level: JsonValue = { leaf: true };
+ for (let depth = 0; depth < sharingDepth; depth += 1)
+ level = [level, level];
+ const inspectionBudget = sharingDepth * 2 + 1;
+ const describeProperty = Object.getOwnPropertyDescriptor;
+ let inspections = 0;
+ const observed = vi
+ .spyOn(Object, "getOwnPropertyDescriptor")
+ .mockImplementation((target, property) => {
+ inspections += 1;
+ if (inspections > inspectionBudget)
+ throw Object.assign(
+ new Error("Shared JSON sealing exceeded its inspection budget"),
+ {
+ code: "inspection_budget_exceeded" as const,
+ inspections,
+ budget: inspectionBudget,
+ },
+ );
+ return describeProperty(target, property);
+ });
+ let sealed: JsonValue;
+ try {
+ sealed = freezeOwnedJsonTreeSnapshot(level);
+ } finally {
+ observed.mockRestore();
+ }
+ expect(inspections).toBe(inspectionBudget);
+ expect(isImmutableJsonSnapshot(sealed)).toBe(true);
+ let cursor: JsonValue = sealed;
+ for (let depth = 0; depth < sharingDepth; depth += 1) {
+ expect(Array.isArray(cursor)).toBe(true);
+ const pair = cursor as readonly JsonValue[];
+ expect(pair).toHaveLength(2);
+ expect(pair[0]).toBe(pair[1]);
+ expect(Object.isFrozen(pair)).toBe(true);
+ cursor = pair[0] as JsonValue;
+ }
+ expect(cursor).toEqual({ leaf: true });
+ expect(Object.isFrozen(cursor)).toBe(true);
+ });
+
it("borrows only the selected own child of a completed sealed root", () => {
const value = freezeJsonSnapshot({
selected: { values: [1, 2] },
diff --git a/src/domain/immutableJson.ts b/src/domain/immutableJson.ts
index 7ee4f36ed6..a9f3b7bf52 100644
--- a/src/domain/immutableJson.ts
+++ b/src/domain/immutableJson.ts
@@ -16,6 +16,16 @@ export const isImmutableJsonSnapshot = (value: unknown): value is JsonValue =>
(typeof value === "number" && Number.isFinite(value)) ||
(typeof value === "object" && immutableSnapshots.has(value));
+const isArrayIndex = (key: string, length: number): boolean => {
+ const index = Number(key);
+ return (
+ Number.isInteger(index) &&
+ index >= 0 &&
+ index < length &&
+ String(index) === key
+ );
+};
+
/** Borrow one own member of a completed snapshot, carrying its sealing proof. */
export const immutableJsonSnapshotMember = (
snapshot: unknown,
@@ -30,6 +40,13 @@ export const immutableJsonSnapshotMember = (
const descriptor = Object.getOwnPropertyDescriptor(snapshot, key);
if (descriptor === undefined || !Object.hasOwn(descriptor, "value"))
return undefined;
+ // Sealing visits only JSON members: enumerable object keys and array
+ // indices. Any other own property was never checked or frozen beneath it.
+ if (
+ !descriptor.enumerable ||
+ (Array.isArray(snapshot) && !isArrayIndex(key, snapshot.length))
+ )
+ return undefined;
// Completed sealing checked and froze every reachable member. Register only
// the selected child; do not traverse it again or add per-node weak entries.
const member = descriptor.value as JsonValue;
@@ -151,7 +168,8 @@ type OwnedTreeFrame =
/**
* Seal a freshly parsed, exclusively owned JSON tree. Its parser has removed
* aliases, accessors and hidden properties; existing sealed subtrees may be shared.
- * Keep only the active ancestry rather than retaining every completed object.
+ * Completed objects are remembered only for this call, so a subtree shared
+ * along several paths is sealed once instead of once per path.
* Unlike general graph sealing, failure can leave this provisional tree frozen.
*/
export const freezeOwnedJsonTreeSnapshot = (
@@ -159,8 +177,11 @@ export const freezeOwnedJsonTreeSnapshot = (
): T => {
const frames: OwnedTreeFrame[] = [];
const ancestors = new Set