From 96a603117d71b83b0a304d2a94f9dc8e4dc63f42 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 14 Sep 2026 21:55:03 -0600 Subject: [PATCH] reference: record F-NoOwnExecution instead of sampling it (#178) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The property is closure: for a file whose verdict is `fold`, what executes is a closed set the rule names. A CPU profile is the wrong instrument for that. It has a sampling floor, so chant's "0 MB of definition-library code on the path" means everything the profiler could see rather than nothing ran (#177), and something does run — revival constructs entities through real host classes. So this counts, and it counts twice. packages/reference/src/trace.ts is a ledger: every site in the package that invokes code it did not write records the invocation and the rule admitting it. The harness also wraps every callable the host publishes in a counting Proxy, which knows nothing about rules and only sees that it was called. An invocation one observer sees and the other does not is an unmapped frame and fails the build. Three panels, from the committed fixtures: A data-host, 19 fixtures, zero invocations on both observers. F-Profile-DataHost made visible rather than measured. B full, 29 fully folding estates, 24 invocations, both counts agreeing. C full, 32 estates that do not fold completely, 21 invocations. chant's harness fails unless every file folds, so it has never recorded one of these. F-Succ/forward-into-imports is the exemplar and its verdicts and taint edges are held to the fixture's own expectation. Arm coverage is asserted too, so a rule F-NoOwnExecution lists that nothing exercises fails. F-Eval-CallMethod is reached only by an expression fixture, which is why the sweep folds those as well. Mutation-tested rather than assumed: removing F-Val-Fate from the allowlist produces 23 failures, and deleting one record() call from revive.ts produces the unmapped-frame failure the two-observer design exists to catch. The artifact is JSON and not a markdown report. #190 is the bug that habit produced on corpus-report.md, so sync-spec.mjs reads this one with JSON.parse and it has no table to drift from. Also here: spec/rationale.md's claim that 2.1 made the 0 MB row "a property the specification requires" conflated the property with the instrument. 2.1 requires the thinness the row reflects; the row is still a profiler sample. packages/reference/src/no-own-execution.test.ts is untouched and complementary: it asserts a folded file's own statements never run, where this asserts closure over what does. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01AzfJnYw9p6rAxhJqXK3CPv --- docs/content/what-it-enables/no-execution.md | 13 + docs/scripts/sync-spec.mjs | 20 +- packages/reference/no-own-execution.json | 65 ++++ packages/reference/src/fold.ts | 9 +- packages/reference/src/index.ts | 1 + packages/reference/src/project.ts | 3 + packages/reference/src/recording.test.ts | 157 ++++++++++ packages/reference/src/recording.ts | 312 +++++++++++++++++++ packages/reference/src/revive.ts | 32 +- packages/reference/src/trace.ts | 52 ++++ scripts/record-no-own-execution.mjs | 40 +++ spec/fixtures/UNCOVERED.md | 2 +- spec/rationale.md | 8 +- 13 files changed, 702 insertions(+), 12 deletions(-) create mode 100644 packages/reference/no-own-execution.json create mode 100644 packages/reference/src/recording.test.ts create mode 100644 packages/reference/src/recording.ts create mode 100644 packages/reference/src/trace.ts create mode 100644 scripts/record-no-own-execution.mjs diff --git a/docs/content/what-it-enables/no-execution.md b/docs/content/what-it-enables/no-execution.md index ad8f50a..37c4e60 100644 --- a/docs/content/what-it-enables/no-execution.md +++ b/docs/content/what-it-enables/no-execution.md @@ -44,6 +44,19 @@ chant folds every file it can and measures that it executed nothing. Its `test/l Both profiler recordings are readable in the browser. [The `cdk synth` recording](https://spicypath.intentius.workers.dev/leftness-cdk) carries a marker on the moment the app starts, and stays lit from there. [The `chant build` recording](https://spicypath.intentius.workers.dev/leftness-chant) answers the same search with no matches. [Flame graphing the leftness of infra tooling](https://lex00.github.io/posts/flame-graphing-the-leftness-of-infra-tooling/) walks through both, and the harness that regenerates them is [`test/leftness`](https://github.com/INTENTIUS/chant/tree/main/test/leftness). +A profile is the wrong instrument for the claim, because the claim is closure rather than volume. A `--cpu-prof` figure has a sampling floor, so 0 MB means everything the profiler could see. So the reference counts instead. Every site in it that invokes code it did not write records the invocation and the rule that admits it, and a counting proxy around the host's callables counts the same invocations without being told what they are. Across {{< figure "execution.foldingFixtures" >}} fully folding whole-build fixtures the ledger holds {{< figure "execution.foldingInvocations" >}} invocations and the two counts agree. Each one names an arm of `F-NoOwnExecution`. An invocation either observer sees and the other does not is an unmapped frame and fails the build. There are {{< figure "execution.unmapped" >}}. + +The arms are the rule's own closed list: + +- revival of an envelope (`F-Val-Fate`) +- an eager intrinsic (`F-Eval-CallEager`) +- a method on a real receiver (`F-Eval-CallMethod`) +- a package's factory at `F-Call` step 6 + +Nothing reached any other, and a listed arm that nothing reaches fails too, so the list has no dead entry. + +Two things the profile cannot show, and this does. Under `data-host` the count is zero across {{< figure "execution.dataHostFixtures" >}} fixtures, which is `F-Profile-DataHost` made visible rather than measured. And {{< figure "execution.mixedFixtures" >}} fixtures are estates that do not fold completely, where a file that folds sits beside one that runs. chant's harness fails unless every file folds, so it has never recorded one. + The reference implementation folds with no runtime at all. At spec {{< figure "specVersion" >}} it agrees with chant {{< figure "chantPin" >}} on every one of {{< figure "corpus.comparable" >}} comparable corpus files, and on the {{< figure "corpus.bothFold" >}} that fold on both sides the export namespaces are identical. ## Where the rule lives diff --git a/docs/scripts/sync-spec.mjs b/docs/scripts/sync-spec.mjs index 6ee26e1..9d8280d 100644 --- a/docs/scripts/sync-spec.mjs +++ b/docs/scripts/sync-spec.mjs @@ -98,6 +98,24 @@ mkdirSync(dataDir, { recursive: true }); // The evaluator's WebAssembly module, when scripts/build-wasm.sh has run: its size in kilobytes, so the page that loads it can say what it is asking the reader to download. let wasmKB = null; try { wasmKB = Math.round(statSync(join(root, "docs", "static", "tsad-eval", "tsad-eval.wasm")).size / 1024); } catch {} -const figures = { specVersion, chantPin, referenceVersion, conformanceVersion, rulesWithFixture, rulesTotal, fixtures, wholeBuildFixtures, corpus, wasmKB }; +// The F-NoOwnExecution recording (#178): an exact ledger of everything the +// reference invokes while folding, with the rule that admits each one. Read +// as JSON rather than slurped out of a report, which is #190's lesson. +let execution = null; +try { + const r = json(join(root, "packages", "reference", "no-own-execution.json")); + const panel = (id) => r.panels.find((p) => p.id === id); + execution = { + dataHostFixtures: panel("A").fixtures, + foldingFixtures: panel("B").fixtures, + foldingInvocations: panel("B").invocations, + mixedFixtures: panel("C").fixtures, + mixedInvocations: panel("C").invocations, + invocations: r.panels.reduce((n, p) => n + p.invocations, 0), + arms: Object.keys(r.arms.reached).length, + unmapped: r.panels.reduce((n, p) => n + p.failures.length, 0), + }; +} catch {} +const figures = { specVersion, chantPin, referenceVersion, conformanceVersion, rulesWithFixture, rulesTotal, fixtures, wholeBuildFixtures, corpus, execution, wasmKB }; writeFileSync(join(dataDir, "figures.json"), JSON.stringify(figures, null, 2) + "\n"); console.log("figures.json:", JSON.stringify(figures)); diff --git a/packages/reference/no-own-execution.json b/packages/reference/no-own-execution.json new file mode 100644 index 0000000..74250b3 --- /dev/null +++ b/packages/reference/no-own-execution.json @@ -0,0 +1,65 @@ +{ + "specVersion": "2.1", + "panels": [ + { + "id": "A", + "title": "data-host invokes nothing", + "claim": "F-Profile-DataHost: no constructor and no function is invoked, asserted on both observers rather than observed", + "fixtures": 19, + "invocations": 0, + "witnessed": 0, + "byRule": {}, + "counters": { + "factoryInvocations": 0, + "projectFactoryInvocations": 0, + "factoryInterpretations": 0 + }, + "failures": [] + }, + { + "id": "B", + "title": "a fully folding estate runs only what the rule admits", + "claim": "F-NoOwnExecution: every invocation maps to a named rule, and two independent counts of them agree", + "fixtures": 29, + "invocations": 24, + "witnessed": 24, + "byRule": { + "F-Eval-CallEager": 1, + "F-Val-Fate": 23 + }, + "counters": { + "factoryInvocations": 0, + "projectFactoryInvocations": 0, + "factoryInterpretations": 0 + }, + "failures": [] + }, + { + "id": "C", + "title": "a mixed estate shows the run path and its taint casualties", + "claim": "F-NoOwnExecution is per file: a neighbour that runs licenses no execution inside a file that folds", + "fixtures": 32, + "invocations": 21, + "witnessed": 21, + "byRule": { + "F-Val-Fate": 15, + "F-Call": 6 + }, + "counters": { + "factoryInvocations": 6, + "projectFactoryInvocations": 0, + "factoryInterpretations": 9 + }, + "failures": [] + } + ], + "arms": { + "reached": { + "F-Val-Fate": 38, + "F-Eval-CallEager": 1, + "F-Eval-CallMethod": 1, + "F-Call": 6 + }, + "missing": [] + } +} diff --git a/packages/reference/src/fold.ts b/packages/reference/src/fold.ts index 57550b7..10b1183 100644 --- a/packages/reference/src/fold.ts +++ b/packages/reference/src/fold.ts @@ -16,6 +16,7 @@ import { import { isFoldableHelperName } from "./foldable-helpers.js"; import { isLiteralKey, isLiteralElementKey, isUnclaimedCallee } from "./subset.js"; import { findFnBodyViolation, plainBindingKey, type FnDecl } from "./fnbody.js"; +import { record } from "./trace"; /** A located rejection, per R9.3: the node and the rule, wording unconstrained. */ export class FoldRejection extends Error { @@ -656,7 +657,9 @@ export function foldExpr(node: ts.Expression, scope: Scope, host: EvalHost): unk // F-Eval-CallEager if (host.intrinsics.some((i) => i.name === name && intrinsicCallFoldsEagerly(i))) { if (typeof local !== "function") reject("F-Eval-CallEager", node, `"${name}" did not resolve to a function`); - return (local as (...a: unknown[]) => unknown)(...node.arguments.map((a) => F(a))); + const eagerArgs = node.arguments.map((a) => F(a)); + record("F-Eval-CallEager", "eager intrinsic", name); + return (local as (...a: unknown[]) => unknown)(...eagerArgs); } // S-FactoryBody rule 5: inside a factory body a call through a bare @@ -681,7 +684,9 @@ export function foldExpr(node: ts.Expression, scope: Scope, host: EvalHost): unk } const fn = (receiver as Record)[method]; if (typeof fn !== "function") reject("F-Eval-CallMethod", node, `"${method}" is not a callable method on the folded value`); - return (fn as (...a: unknown[]) => unknown).apply(receiver, node.arguments.map((a) => F(a))); + const methodArgs = node.arguments.map((a) => F(a)); + record("F-Eval-CallMethod", "method on a real receiver", method); + return (fn as (...a: unknown[]) => unknown).apply(receiver, methodArgs); } reject("F-Eval-Reject", node, "function call as a value is not foldable"); diff --git a/packages/reference/src/index.ts b/packages/reference/src/index.ts index f880efc..86b53cc 100644 --- a/packages/reference/src/index.ts +++ b/packages/reference/src/index.ts @@ -8,3 +8,4 @@ export * from "./project.js"; export { referenceAdapter, referenceDataHostAdapter } from "./adapter.js"; export { runRules, RULES, namespaceOf, artifactOf, type Finding } from "./rules.js"; export { generate, NoSourceForm } from "./generate.js"; +export { recording, record, type ExecutionEvent } from "./trace.js"; diff --git a/packages/reference/src/project.ts b/packages/reference/src/project.ts index a402507..7fcb2b5 100644 --- a/packages/reference/src/project.ts +++ b/packages/reference/src/project.ts @@ -29,6 +29,7 @@ function locate(n: ts.Node): [number, number] { import { revive } from "./revive.js"; import type { FnDecl } from "./fnbody.js"; import { plainBindingKey } from "./fnbody.js"; +import { record } from "./trace"; export type Verdict = | { kind: "fold"; exports: Map; captures: Set } @@ -409,6 +410,7 @@ function foldFile(path: string, session: Session): Verdict { // Step 6: invoked with the resolved arguments; a live argument passes through and an attribute reference stays symbolic (L6.9). const args = folded.map((v, i) => live(v, call.arguments[i], c.text)); counters.factoryInvocations += 1; + record("F-Call", "package factory (step 6)", c.text); try { result = (bound as (...a: unknown[]) => unknown)(...args); } catch (err) { @@ -427,6 +429,7 @@ function foldFile(path: string, session: Session): Verdict { if (isCompositeFactory(bound)) return live(interpret(bound, args, sf, 0, evalHost), sf, callee); if (hostBound.has(callee) && typeof bound === "function") { counters.factoryInvocations += 1; + record("F-Call", "package factory (step 6)", callee); let r: unknown; try { r = (bound as (...a: unknown[]) => unknown)(...args); } catch (err) { throw new FoldRejection("F-Call", 1, 1, `invoking "${callee}" threw: ${err instanceof Error ? err.message : String(err)}`); } diff --git a/packages/reference/src/recording.test.ts b/packages/reference/src/recording.test.ts new file mode 100644 index 0000000..c714070 --- /dev/null +++ b/packages/reference/src/recording.test.ts @@ -0,0 +1,157 @@ +/** + * The F-NoOwnExecution recording, as a gate (#178). + * + * Two kinds of test. The first three hold the committed tree to the property. + * The rest are non-vacuity: a gate nothing can fail is a picture, so each one + * builds a host that violates the property and asserts the harness catches it. + */ +import { describe, expect, test } from "vitest"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { ADMITTED, byRule, observe, record, witnessed, EXEMPLAR } from "./recording.js"; +import { recording, type ExecutionEvent } from "./trace.js"; +import type { ConformanceHost, ProjectFixture } from "@intentius/tsad-conformance"; + +const SPEC = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "spec"); + +describe("F-NoOwnExecution, recorded rather than sampled (#178)", () => { + const r = record(SPEC); + + test("panel A: data-host invokes nothing, on both observers", () => { + const a = r.panels[0]; + expect(a.failures).toEqual([]); + expect(a.events).toEqual([]); + expect(a.witnessed).toBe(0); + // Asserted rather than observed: F-Profile-DataHost says no constructor + // and no function is invoked, so an empty ledger is the rule made visible. + expect(a.fixtures.length).toBeGreaterThan(0); + }); + + test("panel B: a fully folding estate runs only what the rule admits", () => { + const b = r.panels[1]; + expect(b.failures).toEqual([]); + expect(b.fixtures.length).toBeGreaterThan(0); + for (const e of b.events) expect(ADMITTED.has(e.rule), `${e.rule} is not admitted by F-NoOwnExecution`).toBe(true); + // The two observers are independent. Agreement is the closure claim. + expect(b.witnessed).toBe(b.events.length); + }); + + test("panel C: a mixed estate keeps its verdicts and its taint edges", () => { + const c = r.panels[2]; + expect(c.failures).toEqual([]); + expect(c.fixtures).toContain(EXEMPLAR); + expect(c.witnessed).toBe(c.events.length); + }); + + test("every arm F-NoOwnExecution names is reached by something", () => { + // A listed rule nothing exercises is either a rule naming something + // unreachable or a hole in the fixtures. F-Eval-CallMethod is reached only + // by an expression fixture, which is why armCoverage sweeps those too. + expect(r.arms.missing).toEqual([]); + for (const rule of ADMITTED.keys()) expect(r.arms.reached[rule], `${rule} is never exercised`).toBeGreaterThan(0); + }); + + test("panels B and C between them cover every whole-build fixture in `full`", () => { + const covered = new Set([...r.panels[1].fixtures, ...r.panels[2].fixtures]); + const all = new Set([...r.panels[1].fixtures, ...r.panels[2].fixtures]); + expect(covered.size).toBe(all.size); + // B is the fully folding estates and C is the complement, so no fixture in + // `full` sits outside both and none sits in both. + const both = r.panels[1].fixtures.filter((f) => r.panels[2].fixtures.includes(f)); + expect(both).toEqual([]); + }); +}); + +/** + * A host in one file, with the classes a fixture's source can import. + * `build` lets each test decide what the constructor does. + */ +function hostWith(ctor: new (...a: unknown[]) => object): ConformanceHost { + return { + name: "probe", + ownedSpecifierPrefixes: ["probe-pkg"], + intrinsics: [], + helpers: [], + values: new Map([["probe-pkg", new Map([["Thing", ctor]])]]), + }; +} + +const fixtureWith = (source: string): ProjectFixture => ({ + kind: "project", + profiles: ["full"], + id: "probe/one-file", + dir: "probe", + rules: [], + files: new Map([["app.ts", source]]), + verdicts: { "app.ts": "fold" }, + host: "probe", +}); + +const SOURCE = `import { Thing } from "probe-pkg";\nexport const t = new Thing({ name: "x" });\n`; + +describe("non-vacuity: the recording fails when the property does not hold", () => { + test("a thin constructor passes, and the ledger names the rule that admits it", () => { + const marker = Symbol.for("tsad.conformance.declarable"); + class Thin { + readonly entityType = "Thing"; + readonly lexicon = "probe"; + constructor(readonly props: Record = {}) { + Object.defineProperty(this, marker, { value: true, enumerable: false }); + } + } + const o = observe(fixtureWith(SOURCE), "full", hostWith(Thin as never)); + expect(o.result).not.toBe("unavailable"); + expect(byRule(o.events)).toEqual({ "F-Val-Fate": 1 }); + expect(o.witnessed).toBe(o.events.length); + }); + + test("an invocation site with no record beside it is caught as an unmapped frame", () => { + // The failure this gate exists for: someone adds a call into host code in + // the reference and forgets the `record` line. The ledger stays silent and + // the witness does not, so the counts diverge. + // + // Simulated here by entering host code directly while a recording is open, + // which is what such a site would do. + const marker = Symbol.for("tsad.conformance.declarable"); + class Thin { + readonly entityType = "Thing"; + constructor(readonly props: Record = {}) { + Object.defineProperty(this, marker, { value: true, enumerable: false }); + } + } + const w = witnessed(hostWith(Thin as never)); + const Wrapped = w.host.values.get("probe-pkg")!.get("Thing") as new (p: Record) => object; + + const events: ExecutionEvent[] = []; + recording((e) => events.push(e), () => { + new Wrapped({ name: "unledgered" }); + }); + + expect(w.count()).toBe(1); + expect(events.length).toBe(0); + expect(w.count(), "a witnessed invocation the ledger never recorded").not.toBe(events.length); + }); + + test("an invocation under data-host fails panel A", () => { + const marker = Symbol.for("tsad.conformance.declarable"); + class Thin { + readonly entityType = "Thing"; + constructor(readonly props: Record = {}) { + Object.defineProperty(this, marker, { value: true, enumerable: false }); + } + } + // data-host drops the classes (F-Profile-DataHost), so nothing is + // constructible and the ledger must stay empty even with a host present. + const o = observe(fixtureWith(SOURCE), "data-host", hostWith(Thin as never)); + expect(o.events).toEqual([]); + expect(o.witnessed).toBe(0); + }); + + test("an unadmitted rule in a ledger is a failure, not a pass", () => { + // The allowlist is the gate's whole content, so it must reject something. + expect(ADMITTED.has("F-Eval-CallLocal")).toBe(false); + expect(ADMITTED.has("F-Val-Fate")).toBe(true); + const bogus = { rule: "F-Eval-CallLocal", what: "a project-local function", name: "f" }; + expect(ADMITTED.has(bogus.rule)).toBe(false); + }); +}); diff --git a/packages/reference/src/recording.ts b/packages/reference/src/recording.ts new file mode 100644 index 0000000..3003e76 --- /dev/null +++ b/packages/reference/src/recording.ts @@ -0,0 +1,312 @@ +/** + * F-NoOwnExecution, recorded rather than sampled (#178). + * + * The property is closure: for a file whose verdict is `fold`, none of its own + * top-level statements runs, and what *does* run is a closed set the rule + * names — "revival of envelopes (F-Val-Fate), F-Eval-CallEager, + * F-Eval-CallMethod on a real receiver, and invocation of a package's factory + * (J2 F-Call step 6)". + * + * chant's `test/leftness` profile is the wrong instrument for that claim twice + * over. Its estate is required to fold completely, so it is a best case that + * cannot show a fallback; and a `node --cpu-prof` figure has a sampling floor, + * so its "0 MB" means "nothing the profiler could see" rather than "nothing + * ran" (#177). Something does run: revival constructs entities through real + * host classes. + * + * So this harness counts instead of sampling, and it counts twice. + * + * - The **ledger** is this package's own `trace` hook: every site in it + * which invokes code it did not write records the invocation with + * the rule that admits it. + * - The **witness** is a counting Proxy around every callable the host + * supplies, which knows nothing about rules and only sees that it was + * called. + * + * Neither can see what the other sees. An invocation the witness counted and + * the ledger missed is an unmapped frame: code ran through a path that claims + * no rule, which is the violation the acceptance criteria ask to fail on. + * Agreement of two independent counts is what makes this a gate rather than a + * picture. The failure it is built to catch is a new invocation site added to + * the reference without a `record` call beside it. + * + * WHAT NEITHER OBSERVER SEES. The witness wraps the callables the host + * publishes, so it counts entries through the host map and nothing else. Host + * code that calls a function it closed over privately is invisible to both: + * the ledger was never told and the witness never wrapped it. That case is + * F-Host-Interface item 1's to forbid rather than this harness's to detect, + * and since spec 2.1 it does — a constructor holds its props and does no more. + * The bound is normative and this instrument does not enforce it. + */ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { recording, type ExecutionEvent } from "./trace.js"; +import { referenceAdapter, referenceDataHostAdapter } from "./adapter.js"; +import { requireHost, type ConformanceHost } from "@intentius/tsad-conformance"; +import { loadFixtures, type Fixture, type ProjectFixture, type ExpressionFixture } from "@intentius/tsad-conformance"; +import type { ExecutionCounters, ProjectResult } from "@intentius/tsad-conformance"; + +/** + * The closed set, as `observables.md` names it. `F-Call` is step 6, the only + * arm of that rule which invokes rather than interprets. + * + * `ι = executing` would add project-owned invocation and is absent here: the + * reference reports that mode `unavailable` (CAVEATS.md), so no panel can + * reach it. + */ +export const ADMITTED: ReadonlyMap = new Map([ + ["F-Val-Fate", "revival of an envelope"], + ["F-Eval-CallEager", "an eager intrinsic"], + ["F-Eval-CallMethod", "a method on a real receiver"], + ["F-Call", "a package's factory, step 6"], +]); + +export interface Panel { + readonly id: string; + readonly title: string; + /** What the panel establishes, in the terms of the rule. */ + readonly claim: string; + readonly fixtures: readonly string[]; + /** The ledger, one entry per invocation, with the rule that admits it. */ + readonly events: readonly ExecutionEvent[]; + /** The witness: invocations the proxies actually saw. */ + readonly witnessed: number; + readonly counters: ExecutionCounters; + /** Every reason this panel fails. Empty is a pass. */ + readonly failures: readonly string[]; +} + +/** Invocations per admitting rule, for reading a panel back. */ +export const byRule = (events: readonly ExecutionEvent[]): Record => { + const out: Record = {}; + for (const e of events) out[e.rule] = (out[e.rule] ?? 0) + 1; + return out; +}; + +/** + * The host with every callable it supplies wrapped in a counting Proxy. + * + * `construct` and `apply` are the two ways host code is entered: an entity + * constructor is `new`ed (F-Host-Interface item 1) and an intrinsic, helper or + * factory is called. A Proxy is transparent to both, so the fold is unchanged + * and the count is exact. + */ +export function witnessed(h: ConformanceHost): { host: ConformanceHost; count: () => number } { + let n = 0; + const wrap = (v: unknown): unknown => + typeof v === "function" + ? new Proxy(v, { + apply: (t, thisArg, a) => { n += 1; return Reflect.apply(t as (...x: unknown[]) => unknown, thisArg, a); }, + construct: (t, a, nt) => { n += 1; return Reflect.construct(t as new (...x: unknown[]) => object, a, nt); }, + }) + : v; + const values = new Map([...h.values].map(([spec, exports]) => [spec, new Map([...exports].map(([name, v]) => [name, wrap(v)]))])); + return { host: { ...h, values }, count: () => n }; +} + +const isProject = (f: Fixture): f is ProjectFixture => f.kind === "project"; + +/** Every whole-build fixture, from the committed tree. */ +export function projectFixtures(specDir: string): ProjectFixture[] { + return loadFixtures(join(specDir, "fixtures")).filter(isProject); +} + +const ZERO: ExecutionCounters = { factoryInvocations: 0, projectFactoryInvocations: 0, factoryInterpretations: 0 }; +const add = (a: ExecutionCounters, b: ExecutionCounters | undefined): ExecutionCounters => ({ + factoryInvocations: a.factoryInvocations + (b?.factoryInvocations ?? 0), + projectFactoryInvocations: a.projectFactoryInvocations + (b?.projectFactoryInvocations ?? 0), + factoryInterpretations: a.factoryInterpretations + (b?.factoryInterpretations ?? 0), +}); + +/** + * One fold, with both observers attached. + * + * `hostOverride` exists for the non-vacuity tests, which need a host the + * committed tree does not contain: the gate is only worth running if a + * violating host actually fails it. + */ +export function observe(f: ProjectFixture, profile: "full" | "data-host", hostOverride?: ConformanceHost) { + const adapter = profile === "full" ? referenceAdapter : referenceDataHostAdapter; + const base = hostOverride ?? (f.host ? requireHost(f.host) : undefined); + const w = base ? witnessed(base) : undefined; + const events: ExecutionEvent[] = []; + const result = recording((e) => events.push(e), () => adapter.foldProject!(f.files, w?.host ?? base, f.mode)); + return { events, witnessed: w?.count() ?? 0, result: result as ProjectResult | "unavailable" }; +} + +/** + * Panel A. `data-host`, where the rule is stated rather than measured: + * `F-Profile-DataHost` says "No constructor and no function is invoked". + * Zero is asserted on both observers, so the panel fails if anything runs. + */ +export function panelA(specDir: string): Panel { + const fixtures = projectFixtures(specDir).filter((f) => f.profiles.includes("data-host")); + const events: ExecutionEvent[] = []; + const failures: string[] = []; + let seen = 0; + let counters = ZERO; + for (const f of fixtures) { + const o = observe(f, "data-host"); + if (o.result === "unavailable") continue; + events.push(...o.events); + seen += o.witnessed; + counters = add(counters, o.result.counters); + for (const e of o.events) failures.push(`${f.id}: ${e.what} "${e.name}" was invoked under data-host (${e.rule}); F-Profile-DataHost invokes no constructor and no function`); + if (o.witnessed > 0) failures.push(`${f.id}: the host's callables were entered ${o.witnessed} time(s) under data-host`); + } + return { + id: "A", + title: "data-host invokes nothing", + claim: "F-Profile-DataHost: no constructor and no function is invoked, asserted on both observers rather than observed", + fixtures: fixtures.map((f) => f.id), + events, + witnessed: seen, + counters, + failures, + }; +} + +/** + * Panel B. `full`, over every whole-build fixture that folds completely. + * + * The gate: each ledger entry names a rule in {@link ADMITTED}, and the two + * observers agree. An entry naming an unlisted rule, or a witnessed + * invocation the ledger never recorded, fails the panel. + */ +export function panelB(specDir: string): Panel { + const fixtures = projectFixtures(specDir).filter( + (f) => f.profiles.includes("full") && Object.values(f.verdicts).length > 0 && Object.values(f.verdicts).every((v) => v === "fold"), + ); + const events: ExecutionEvent[] = []; + const failures: string[] = []; + let seen = 0; + let counters = ZERO; + for (const f of fixtures) { + const o = observe(f, "full"); + if (o.result === "unavailable") continue; + events.push(...o.events); + seen += o.witnessed; + counters = add(counters, o.result.counters); + for (const e of o.events) { + if (!ADMITTED.has(e.rule)) failures.push(`${f.id}: ${e.what} "${e.name}" ran under ${e.rule}, which F-NoOwnExecution does not admit`); + } + if (o.witnessed !== o.events.length) { + failures.push( + `${f.id}: the witness counted ${o.witnessed} invocation(s) of host code and the ledger recorded ${o.events.length}. ` + + `A witnessed invocation with no ledger entry is an unmapped frame: code ran through a path that names no rule.`, + ); + } + for (const [path, v] of Object.entries(o.result.verdicts)) { + if (v.kind !== "fold") failures.push(`${f.id}: ${path} was expected to fold and did not (${v.rule})`); + } + } + return { + id: "B", + title: "a fully folding estate runs only what the rule admits", + claim: "F-NoOwnExecution: every invocation maps to a named rule, and two independent counts of them agree", + fixtures: fixtures.map((f) => f.id), + events, + witnessed: seen, + counters, + failures, + }; +} + +/** + * Panel C. Mixed estates, which no recording in either repository has shown. + * + * `test/leftness` cannot produce one: its run fails unless every file reports + * `[fold:fold]`, so it is necessarily a best case. Every whole-build fixture + * that mixes the two verdicts is one, and `F-Succ/forward-into-imports` is the + * exemplar — `config.ts` folds on its own and runs because `app.ts`, which + * imports it, runs. + * + * The panel holds each fixture's per-file verdicts and taint edges to its own + * expectation, so the demonstration and the conformance suite cannot drift + * apart. What it establishes is that F-NoOwnExecution is per file: a + * neighbour that runs licenses no execution inside a file that folds. + */ +export const EXEMPLAR = "F-Succ/forward-into-imports"; + +export function panelC(specDir: string): Panel { + // The complement of panel B: every whole-build fixture that does not fold + // completely. That includes the exemplar, whose two files both end at `run` + // while `config.ts` folds tentatively and is taken by the forward edge — + // the taint casualty that a fully folding estate can never show. + const fixtures = projectFixtures(specDir).filter( + (f) => f.profiles.includes("full") && Object.values(f.verdicts).some((v) => v === "run"), + ); + const events: ExecutionEvent[] = []; + const failures: string[] = []; + let seen = 0; + let counters = ZERO; + if (!fixtures.some((f) => f.id === EXEMPLAR)) failures.push(`the exemplar ${EXEMPLAR} is not among the mixed estates`); + for (const f of fixtures) { + const o = observe(f, "full"); + if (o.result === "unavailable") continue; + events.push(...o.events); + seen += o.witnessed; + counters = add(counters, o.result.counters); + for (const [path, want] of Object.entries(f.verdicts)) { + const got = o.result.verdicts[path]; + if (!got) failures.push(`${f.id}: no verdict reported for ${path}`); + else if (got.kind !== want) failures.push(`${f.id}: ${path} expected ${want} and got ${got.kind}`); + } + for (const [path, from] of Object.entries(f.taintedBy ?? {})) { + if (o.result.taintedBy?.[path] !== from) failures.push(`${f.id}: ${path} should be tainted by ${from} and is ${o.result.taintedBy?.[path] ?? "untainted"}`); + } + for (const e of o.events) { + if (!ADMITTED.has(e.rule)) failures.push(`${f.id}: ${e.what} "${e.name}" ran under ${e.rule}, which F-NoOwnExecution does not admit`); + } + if (o.witnessed !== o.events.length) { + failures.push(`${f.id}: the witness counted ${o.witnessed} invocation(s) and the ledger recorded ${o.events.length}, so a frame maps to no rule`); + } + } + return { + id: "C", + title: "a mixed estate shows the run path and its taint casualties", + claim: "F-NoOwnExecution is per file: a neighbour that runs licenses no execution inside a file that folds", + fixtures: fixtures.map((f) => f.id), + events, + witnessed: seen, + counters, + failures, + }; +} + +/** + * Which arms of {@link ADMITTED} anything reaches, so the allowlist has no + * dead entry. A rule listed by F-NoOwnExecution that nothing ever exercises is + * either a rule naming something unreachable or a hole in the fixtures, and + * both are worth failing on. + * + * `F-Eval-CallMethod` is reachable only at expression level: no whole-build + * fixture calls a method on a real receiver, so the sweep below folds the + * expression fixtures too rather than leave the arm unaccounted for. + */ +export function armCoverage(specDir: string, panels: readonly Panel[]): { reached: Record; missing: string[] } { + const reached: Record = {}; + for (const r of ADMITTED.keys()) reached[r] = 0; + for (const p of panels) for (const e of p.events) reached[e.rule] = (reached[e.rule] ?? 0) + 1; + + const expressions = loadFixtures(join(specDir, "fixtures")).filter((f): f is ExpressionFixture => f.kind === "expression" && f.profiles.includes("full")); + for (const f of expressions) { + const events: ExecutionEvent[] = []; + try { + recording((e) => events.push(e), () => referenceAdapter.foldExport!(f.input, f.exportName)); + } catch { + continue; + } + for (const e of events) reached[e.rule] = (reached[e.rule] ?? 0) + 1; + } + return { reached, missing: [...ADMITTED.keys()].filter((r) => reached[r] === 0) }; +} + +export function record(specDir: string): { specVersion: string; panels: Panel[]; arms: ReturnType } { + const panels = [panelA(specDir), panelB(specDir), panelC(specDir)]; + return { + specVersion: readFileSync(join(specDir, "VERSION"), "utf8").trim(), + panels, + arms: armCoverage(specDir, panels), + }; +} diff --git a/packages/reference/src/revive.ts b/packages/reference/src/revive.ts index 1bceed2..b19bcb0 100644 --- a/packages/reference/src/revive.ts +++ b/packages/reference/src/revive.ts @@ -14,6 +14,7 @@ * declarator produced. */ import { FoldRejection, isEnvelope, isLiveObject } from "./fold.js"; +import { record } from "./trace"; /** Where a revival happened, for the located rejection F-Reason wants. */ export interface RevivalSite { @@ -95,17 +96,38 @@ function reviveEnvelope(e: Env, bindings: ReadonlyMap, site: Re const name = e.__resource as string; const C = callable(name, bindings, site) as unknown as new (...a: unknown[]) => unknown; // F-Val-Arity: spread `args` when present, otherwise props and optional attributes. - if (Array.isArray(e.args)) return new C(...(e.args as unknown[]).map((x) => revive(x, bindings, site, false))); + if (Array.isArray(e.args)) { + const spread = (e.args as unknown[]).map((x) => revive(x, bindings, site, false)); + record("F-Val-Fate", "entity constructor", name); + return new C(...spread); + } const props = revive(e.props, bindings, site, false); - return "attributes" in e ? new C(props, revive(e.attributes, bindings, site, false)) : new C(props); + // The arity is the envelope's, never the revived value's: `attributes` + // present and reviving to undefined is still the two-argument form + // (F-Val-Arity). + const hasAttributes = "attributes" in e; + const attributes = hasAttributes ? revive(e.attributes, bindings, site, false) : undefined; + record("F-Val-Fate", "entity constructor", name); + return hasAttributes ? new C(props, attributes) : new C(props); } if ("__intrinsic" in e) { const fn = callable(e.__intrinsic as string, bindings, site); // The tag form keeps its cooked strings; the call form is a plain call. - if (Array.isArray(e.strings)) return fn(e.strings as unknown as string[], ...args(e.values)); - return fn(...args(e.args)); + if (Array.isArray(e.strings)) { + const values = args(e.values); + record("F-Val-Fate", "intrinsic", e.__intrinsic as string); + return fn(e.strings as unknown as string[], ...values); + } + const callArgs = args(e.args); + record("F-Val-Fate", "intrinsic", e.__intrinsic as string); + return fn(...callArgs); + } + if ("__helper" in e) { + const helper = callable(e.__helper as string, bindings, site); + const helperArgs = args(e.args); + record("F-Val-Fate", "authoring helper", e.__helper as string); + return helper(...helperArgs); } - if ("__helper" in e) return callable(e.__helper as string, bindings, site)(...args(e.args)); if ("__symbol" in e) { const text = e.__symbol as string; if (!DOTTED.test(text)) fail(site, `a symbolic reference revives only through a simple dotted chain, and "${text}" is not one`); diff --git a/packages/reference/src/trace.ts b/packages/reference/src/trace.ts new file mode 100644 index 0000000..e1e91d7 --- /dev/null +++ b/packages/reference/src/trace.ts @@ -0,0 +1,52 @@ +/** + * An exact ledger of everything this implementation invokes while folding. + * + * F-NoOwnExecution names a closed set: "revival of envelopes (F-Val-Fate), + * F-Eval-CallEager, F-Eval-CallMethod on a real receiver, and invocation of a + * package's factory (J2 F-Call step 6)". The claim is closure rather than + * volume, so the instrument has to enumerate what ran and not sample it. A + * CPU profile cannot: it has a floor, and "0 MB" means "nothing the profiler + * could see" rather than "nothing ran" (#177). + * + * So every site in this package that invokes code it did not write records + * the invocation here first, tagged with the rule that admits it. A reader of + * the ledger can check the tags against F-NoOwnExecution's list and an + * untagged invocation is a violation by construction. + * + * Process-wide and resettable, which is the shape F-Obs-Counters already + * specifies for the three integers in L10.1. This is those counters at the + * grain the property is stated in. + * + * The ledger is evidence, never semantics: with no sink installed `record` is + * a single optional call and the fold is unchanged. Nothing in this package + * reads it back. + */ + +/** One invocation of code this implementation did not write. */ +export interface ExecutionEvent { + /** The rule that admits it, as F-NoOwnExecution names them. */ + readonly rule: string; + /** Which arm of that rule: what kind of thing was invoked. */ + readonly what: string; + /** The binding it was reached through, for reading the ledger back. */ + readonly name: string; +} + +let sink: ((e: ExecutionEvent) => void) | undefined; + +/** Called immediately before an invocation, at every site that performs one. */ +export const record = (rule: string, what: string, name: string): void => sink?.({ rule, what, name }); + +/** + * Collect every invocation `body` performs. Restores the previous sink, so a + * harness that folds more than once keeps the panels apart. + */ +export function recording(into: (e: ExecutionEvent) => void, body: () => T): T { + const previous = sink; + sink = into; + try { + return body(); + } finally { + sink = previous; + } +} diff --git a/scripts/record-no-own-execution.mjs b/scripts/record-no-own-execution.mjs new file mode 100644 index 0000000..5047fa4 --- /dev/null +++ b/scripts/record-no-own-execution.mjs @@ -0,0 +1,40 @@ +#!/usr/bin/env node +// Regenerate the F-NoOwnExecution recording (#178). +// +// Writes packages/conformance/no-own-execution.json from the committed +// fixtures, which docs/scripts/sync-spec.mjs reads into figures.json. JSON and +// not a markdown report on purpose: the corpus report is slurped back with +// regexes and #190 is the bug that habit produced, so this artifact is read +// with JSON.parse and has no table to drift from. +// +// The same numbers are asserted by packages/conformance/src/no-own-execution.test.ts, +// so a stale artifact is a diff and a wrong one is a failing gate. +import { execFileSync } from "node:child_process"; +import { writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const out = join(root, "packages", "reference", "no-own-execution.json"); + +const script = ` +import { record, byRule } from ${JSON.stringify(pathToFileURL(join(root, "packages", "reference", "src", "recording.ts")).href)}; +const r = record(${JSON.stringify(join(root, "spec"))}); +const panels = r.panels.map((p) => ({ + id: p.id, title: p.title, claim: p.claim, + fixtures: p.fixtures.length, invocations: p.events.length, witnessed: p.witnessed, + byRule: byRule(p.events), counters: p.counters, failures: p.failures, +})); +process.stdout.write(JSON.stringify({ specVersion: r.specVersion, panels, arms: r.arms }, null, 2) + "\\n"); +`; + +const json = execFileSync("npx", ["tsx", "-e", script], { cwd: root, encoding: "utf8", maxBuffer: 32 * 1024 * 1024 }); +const parsed = JSON.parse(json); +const failed = parsed.panels.flatMap((p) => p.failures); +if (failed.length > 0) { + console.error("the recording does not hold:"); + for (const f of failed) console.error(" " + f); + process.exit(1); +} +writeFileSync(out, JSON.stringify(parsed, null, 2) + "\n"); +console.log(`no-own-execution.json: ${parsed.panels.map((p) => `${p.id}=${p.invocations}/${p.fixtures}`).join(" ")} arms=${JSON.stringify(parsed.arms.reached)}`); diff --git a/spec/fixtures/UNCOVERED.md b/spec/fixtures/UNCOVERED.md index fbb18a9..2f01278 100644 --- a/spec/fixtures/UNCOVERED.md +++ b/spec/fixtures/UNCOVERED.md @@ -5,6 +5,6 @@ Deliberate, and this list may only shrink (#8). Each entry names the rule and wh 135 of 139 rules have fixtures. Every rule below needs something the reference implementation does not have, or something no adapter can observe; the entry says which. - `F-Host-Generality` — says what a host may vary and what it may not; no verdict exercises it -- `F-NoOwnExecution` — measured by chant's `test/leftness` profile; an adapter reports verdicts and cannot observe execution +- `F-NoOwnExecution` — an adapter reports verdicts and cannot observe execution, so no fixture can carry this. Recorded instead against the reference by `packages/reference/src/recording.ts`, which ledgers every invocation with the rule admitting it and fails on one that maps to none (#178). chant's `test/leftness` profile measures the product comparison - `F-NotProject` — a file inside the host's own module tree; the reference's project is a map with no outside - `F-Obs-Provenance` — an optional capability, reported rather than asserted diff --git a/spec/rationale.md b/spec/rationale.md index 6640e6c..fe8ec60 100644 --- a/spec/rationale.md +++ b/spec/rationale.md @@ -654,9 +654,11 @@ bad props reports mid-fold as a failure to fold with no rule identifier and no position. F-Rule-Finding names the rule and the position and reaches the author at the keystroke. -The published measurement changes status. `paper/measurements.md`'s 0 MB row -was a property of chant's generated lexicons being data holders. It is now a -property the specification requires of any conforming host. +The published measurement is a separate question. `paper/measurements.md`'s +0 MB row records what a CPU profile could see and carries that instrument's +floor. What 2.1 requires is the thinness that row reflects rather than the row +itself. A constructor still runs under revival and counting one exactly is +F-Obs-Counters' job. ---