Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/content/what-it-enables/no-execution.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 19 additions & 1 deletion docs/scripts/sync-spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
65 changes: 65 additions & 0 deletions packages/reference/no-own-execution.json
Original file line number Diff line number Diff line change
@@ -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": []
}
}
9 changes: 7 additions & 2 deletions packages/reference/src/fold.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -681,7 +684,9 @@ export function foldExpr(node: ts.Expression, scope: Scope, host: EvalHost): unk
}
const fn = (receiver as Record<string, unknown>)[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");
Expand Down
1 change: 1 addition & 0 deletions packages/reference/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
3 changes: 3 additions & 0 deletions packages/reference/src/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>; captures: Set<string> }
Expand Down Expand Up @@ -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) {
Expand All @@ -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)}`); }
Expand Down
157 changes: 157 additions & 0 deletions packages/reference/src/recording.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>([["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<string, unknown> = {}) {
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<string, unknown> = {}) {
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<string, unknown>) => 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<string, unknown> = {}) {
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);
});
});
Loading