diff --git a/audit/audit.ts b/audit/audit.ts index 1f2cdb66..dd9d7e43 100644 --- a/audit/audit.ts +++ b/audit/audit.ts @@ -19,10 +19,7 @@ import { checkParse } from "./src/checks/parse"; import { buildTrustedVocabulary, checkConstructVocabulary } from "./src/checks/construct-vocabulary"; import { checkWarnings } from "./src/checks/warnings"; import { missingConfiguredPaths, REPO_ROOT } from "./src/config"; -import { extractConformanceCases, extractPhysicalFixtures } from "./src/extract/fixtures"; -import { extractInlineTestLiterals } from "./src/extract/inline-tests"; -import { extractNonTrustedDocsFences, extractTrustedCorpusFences } from "./src/extract/markdown-fences"; -import { extractTmpfileWrites } from "./src/extract/tmpfile-writes"; +import { collectCorpusParts } from "./src/corpus"; import { printReport } from "./src/report"; import { runSelfTest } from "./src/self-test"; import type { Finding, Snippet } from "./src/types"; @@ -49,20 +46,10 @@ if (missing.length > 0) { } // 1. Extraction -const trustedFences = extractTrustedCorpusFences(); -const nonTrustedDocsFences = extractNonTrustedDocsFences(); -const physicalFixtures = extractPhysicalFixtures(); -const conformanceCases = extractConformanceCases(); -const { snippets: inlineLiterals, skipped } = extractInlineTestLiterals(); -const tmpfileWrites = extractTmpfileWrites(); - -const auditTargets: Snippet[] = [ - ...nonTrustedDocsFences, - ...physicalFixtures, - ...conformanceCases, - ...inlineLiterals, - ...tmpfileWrites, -].filter(matchesFilter); +const corpus = collectCorpusParts(); +const trustedFences = corpus.trusted; +const skipped = corpus.skipped; +const auditTargets: Snippet[] = corpus.targets.filter(matchesFilter); // 2. Calibration — must run before any format-diff finding below is trusted. const calibration = calibrateFormatter(trustedFences); @@ -98,7 +85,7 @@ for (const snippet of auditTargets) { } // 5. Self-test — validates the tool's own coverage against known mistakes. -const selfTest = runSelfTest(trustedVocabulary); +const selfTest = runSelfTest(trustedVocabulary, corpus.selfTest); const report = { calibration, diff --git a/audit/package.json b/audit/package.json index 1269c3bf..6fb53541 100644 --- a/audit/package.json +++ b/audit/package.json @@ -3,6 +3,9 @@ "version": "1.5.0", "private": true, "type": "module", + "exports": { + "./corpus": "./src/corpus.ts" + }, "scripts": { "audit": "bun run audit.ts", "audit:json": "bun run audit.ts --json" diff --git a/audit/src/corpus.ts b/audit/src/corpus.ts new file mode 100644 index 00000000..bb33b6cc --- /dev/null +++ b/audit/src/corpus.ts @@ -0,0 +1,44 @@ +import { extractConformanceCases, extractPhysicalFixtures } from "./extract/fixtures"; +import { extractInlineTestLiterals } from "./extract/inline-tests"; +import { extractNonTrustedDocsFences, extractTrustedCorpusFences } from "./extract/markdown-fences"; +import { extractSelfTestSnippets } from "./extract/self-test-cases"; +import { extractTmpfileWrites } from "./extract/tmpfile-writes"; +import type { SkippedExtraction, Snippet } from "./types"; + +/** Every piece of Gram source in the repo, grouped by the role the audit gives it. */ +export interface CorpusParts { + /** reference/syntax pages (EN+FR) ✅ fences: the known-good vocabulary. */ + trusted: Snippet[]; + /** What the audit triages: docs fences, fixtures, conformance cases, test literals. */ + targets: Snippet[]; + /** ai-generation-notes ❌/✅ pairs, checked against the audit's own coverage. */ + selfTest: { bad: Snippet[]; good: Snippet[]; staleness: string | null }; + /** Inline test literals the extractor could not read statically. */ + skipped: SkippedExtraction[]; +} + +/** + * The single collector of Gram sources in the repo, shared by the content + * audit (`audit.ts`) and the fuzzer (`fuzz/`): no list of paths lives twice. + */ +export function collectCorpusParts(): CorpusParts { + const { snippets: inlineLiterals, skipped } = extractInlineTestLiterals(); + return { + trusted: extractTrustedCorpusFences(), + targets: [ + ...extractNonTrustedDocsFences(), + ...extractPhysicalFixtures(), + ...extractConformanceCases(), + ...inlineLiterals, + ...extractTmpfileWrites(), + ], + selfTest: extractSelfTestSnippets(), + skipped, + }; +} + +/** Every snippet, whatever its role, invalid ones included. */ +export function collectCorpus(): Snippet[] { + const { trusted, targets, selfTest } = collectCorpusParts(); + return [...trusted, ...targets, ...selfTest.bad, ...selfTest.good]; +} diff --git a/audit/src/self-test.ts b/audit/src/self-test.ts index c842f209..455b3845 100644 --- a/audit/src/self-test.ts +++ b/audit/src/self-test.ts @@ -1,19 +1,22 @@ import { getAST } from "@gram-lang/parser"; -import { extractSelfTestSnippets } from "./extract/self-test-cases"; import { checkConstructVocabulary, type TrustedVocabulary } from "./checks/construct-vocabulary"; import { checkFormatDiff } from "./checks/format-diff"; import { checkWarnings } from "./checks/warnings"; +import type { CorpusParts } from "./corpus"; +import { extractSelfTestSnippets } from "./extract/self-test-cases"; import type { Finding } from "./types"; // Runs checks 1-4 against every ai-generation-notes ❌/✅ pair. This // validates the AUDIT TOOL's own coverage, not new content: a ❌ example that // trips zero checks is a gap in the tool (it can't catch a known mistake); a // ✅ example that trips any check is a false positive on doc-sanctioned Gram. -export function runSelfTest(trusted: TrustedVocabulary): { +export function runSelfTest( + trusted: TrustedVocabulary, + { bad, good, staleness }: CorpusParts["selfTest"] = extractSelfTestSnippets(), +): { findings: Finding[]; staleness: string | null; } { - const { bad, good, staleness } = extractSelfTestSnippets(); const findings: Finding[] = []; for (const snippet of bad) { diff --git a/biome.json b/biome.json index bde1d4e9..2feb139c 100644 --- a/biome.json +++ b/biome.json @@ -11,6 +11,7 @@ "packages/*/src/**", "packages/*/tests/**", "conformance/*.ts", + "fuzz/**/*.ts", "!**/*.gram", "!**/grammar-content.ts", "!**/*.svg", diff --git a/bun.lock b/bun.lock index 5bcf4427..12a352ee 100644 --- a/bun.lock +++ b/bun.lock @@ -47,6 +47,21 @@ "@types/node": "^26.1.1", }, }, + "fuzz": { + "name": "@gram-lang/fuzz", + "version": "0.0.0", + "dependencies": { + "@gram-lang/analyzer": "workspace:*", + "@gram-lang/audit": "workspace:*", + "@gram-lang/format": "workspace:*", + "@gram-lang/kitchen": "workspace:*", + "@gram-lang/parser": "workspace:*", + }, + "devDependencies": { + "@types/bun": "1.4.4", + "typescript": "^6.0.3", + }, + }, "packages/analyzer": { "name": "@gram-lang/analyzer", "version": "1.5.0", @@ -621,6 +636,8 @@ "@gram-lang/format": ["@gram-lang/format@workspace:packages/format"], + "@gram-lang/fuzz": ["@gram-lang/fuzz@workspace:fuzz"], + "@gram-lang/i18n": ["@gram-lang/i18n@workspace:packages/i18n"], "@gram-lang/kitchen": ["@gram-lang/kitchen@workspace:packages/kitchen"], diff --git a/fuzz/cli.ts b/fuzz/cli.ts new file mode 100644 index 00000000..d0f831bc --- /dev/null +++ b/fuzz/cli.ts @@ -0,0 +1,102 @@ +#!/usr/bin/env bun +/** + * Deterministic fuzzing of the parser, the compiler, the analyzer and the formatter. + * + * bun run fuzz # 2 000 inputs, random seed (printed) + * bun run fuzz --seed 1735549293 --iterations 200000 --minimize + * bun run fuzz --seed 1735549293 --index 4211 # replay one input + * bun run fuzz --corpus # the unmutated corpus only + * bun run fuzz --invariant format-idempotent --invariant format-no-throw + */ +import { parseArgs } from "node:util"; +import { fuzzCorpus } from "./src/corpus"; +import { INVARIANTS, invariantsById } from "./src/invariants"; +import { knownFailures } from "./src/known-failures"; +import { + checkInput, + type Finding, + generateInput, + runFuzz, + scanCorpus, +} from "./src/run"; +import { shrink } from "./src/shrink"; + +const { values } = parseArgs({ + options: { + seed: { type: "string" }, + iterations: { type: "string", default: "2000" }, + index: { type: "string" }, + invariant: { type: "string", multiple: true }, + minimize: { type: "boolean", default: false }, + corpus: { type: "boolean", default: false }, + }, +}); + +const seed = + values.seed !== undefined + ? Number(values.seed) >>> 0 + : Math.floor(Math.random() * 0x100000000); +const iterations = Number(values.iterations); +const invariants = values.invariant?.length + ? invariantsById(values.invariant) + : INVARIANTS; +const corpus = fuzzCorpus(); + +if (values.index !== undefined) { + const generated = generateInput(seed, Number(values.index), corpus); + console.log( + `seed ${seed}, index ${generated.index}, from ${generated.corpusId}`, + ); + console.log(`mutations: ${generated.mutations.join(", ")}`); + console.log(`input: ${JSON.stringify(generated.input)}`); + const violations = checkInput(generated.input, invariants); + for (const v of violations) + console.log(`\n✗ ${v.signature}\n${v.stack ?? v.message}`); + if (violations.length === 0) console.log("\n✓ no violation"); + process.exit(violations.length > 0 ? 1 : 0); +} + +const label = values.corpus + ? `${corpus.length} corpus snippets, unmutated` + : `seed ${seed}, ${iterations} inputs`; +console.log(`fuzz: ${label}, ${invariants.length} invariants`); +const start = performance.now(); +const findings: Finding[] = values.corpus + ? scanCorpus(corpus, invariants) + : runFuzz({ + seed, + iterations, + corpus, + invariants, + onInput: (i) => { + if (process.stdout.isTTY && i % 1000 === 999) + process.stdout.write(`\r ${i + 1}/${iterations}`); + }, + }); +if (process.stdout.isTTY) process.stdout.write("\r"); +console.log(`done in ${((performance.now() - start) / 1000).toFixed(1)} s\n`); + +const known = new Map(knownFailures().map((k) => [k.signature, k])); +let fresh = 0; +for (const f of findings) { + const k = known.get(f.signature); + if (!k) fresh++; + console.log( + `${k ? "known" : "NEW "} ×${f.count} ${f.signature}${k ? ` (${k.issue})` : ""}`, + ); + if (!values.corpus) + console.log( + ` replay: bun run fuzz --seed ${seed} --index ${f.index}`, + ); + else console.log(` from: ${f.corpusId}`); + const input = values.minimize + ? shrink(f.input, (c) => + checkInput(c, invariants).some((v) => v.signature === f.signature), + ) + : f.input; + console.log( + ` input${values.minimize ? " (minimized)" : ""}: ${JSON.stringify(input).slice(0, 400)}`, + ); +} +console.log(`\n${findings.length} signature(s), ${fresh} new`); +process.exit(fresh > 0 ? 1 : 0); diff --git a/fuzz/known-failures.json b/fuzz/known-failures.json new file mode 100644 index 00000000..e05f3a03 --- /dev/null +++ b/fuzz/known-failures.json @@ -0,0 +1,146 @@ +[ + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.metrics.activeBreakdown", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "## {\n}" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.registry.ingredients", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "@m\n{g}" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.sections[].ingredients[]", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "@n\n{1}" + }, + { + "signature": "format-preserves-meaning | formatted source no longer parses | parser:header_trailing", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "## {\n~{0}." + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.miseEnPlace[].duration", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "->&dough\n\n## l\n@t\n{0%&dough}" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.metrics.prepBreakdown[]", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "@s\n{}(n)" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.schedule.blocks[]", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "~{5m}{\n\n~{2m}" + }, + { + "signature": "format-preserves-meaning | formatted source no longer parses | parser:throwBracesError", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "@r\n{" + }, + { + "signature": "format-idempotent | second pass reported changes on an unchanged output", + "invariant": "format-idempotent", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "{1\n##}" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.miseEnPlace[].section", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/197", + "example": "## {\n## \n## n\n@r}" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.sections[].title", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/201", + "example": "## {1,0}" + }, + { + "signature": "format-idempotent | second pass changed the output (compositeSeparatorSpacing)", + "invariant": "format-idempotent", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/204", + "example": "<\t@" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.tasks.tasks[]", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/208", + "example": "&@S" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.warnings[].item", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/208", + "example": "~@F{}" + }, + { + "signature": "compile-no-throw | compile threw Error: MULTIPLE_BAKERS_PERCENTAGE: Only one ingredient can be marked with the baker's percentage (*) modifier in a recipe. | kitchen:", + "invariant": "compile-no-throw", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/198", + "example": "@*n @*b" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.cookware[]", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/205", + "example": "## " + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.cookware[].id", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/205", + "example": "## \n#p" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.cookware[]._usageId", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/205", + "example": "## \n#p|#s" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.sections[].steps[]", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/200", + "example": "e\r" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.metrics.activeBreakdown[]", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/200", + "example": ".\n \n[" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.metrics.prepBreakdown", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/200", + "example": "@\r" + }, + { + "signature": "format-preserves-meaning | formatted source no longer parses | parser:getAST", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/199", + "example": "" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.meta", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/206", + "example": "---\ntitle:\n---" + }, + { + "signature": "format-preserves-meaning | compilation differs after formatting at $.sections[]", + "invariant": "format-preserves-meaning", + "issue": "https://git.gram-lang.org/gram-lang/gram/issues/207", + "example": "@use \"a\" as &a\n//" + } +] diff --git a/fuzz/package.json b/fuzz/package.json new file mode 100644 index 00000000..9fcf0fc0 --- /dev/null +++ b/fuzz/package.json @@ -0,0 +1,21 @@ +{ + "name": "@gram-lang/fuzz", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "fuzz": "bun run cli.ts", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@gram-lang/analyzer": "workspace:*", + "@gram-lang/audit": "workspace:*", + "@gram-lang/format": "workspace:*", + "@gram-lang/kitchen": "workspace:*", + "@gram-lang/parser": "workspace:*" + }, + "devDependencies": { + "@types/bun": "1.4.4", + "typescript": "^6.0.3" + } +} diff --git a/fuzz/regressions/.gitkeep b/fuzz/regressions/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/fuzz/src/corpus.ts b/fuzz/src/corpus.ts new file mode 100644 index 00000000..cec89a8c --- /dev/null +++ b/fuzz/src/corpus.ts @@ -0,0 +1,20 @@ +import { collectCorpus } from "@gram-lang/audit/corpus"; +import type { CorpusEntry } from "./run"; + +let cached: CorpusEntry[] | null = null; + +/** + * The fuzz seeds: every Gram snippet the audit collects, invalid ones + * included (they are the most useful starting points), one per content. + */ +export function fuzzCorpus(): CorpusEntry[] { + if (cached) return cached; + const seen = new Set(); + cached = []; + for (const s of collectCorpus()) { + if (seen.has(s.content)) continue; + seen.add(s.content); + cached.push({ id: s.id, content: s.content }); + } + return cached; +} diff --git a/fuzz/src/database.ts b/fuzz/src/database.ts new file mode 100644 index 00000000..b5716748 --- /dev/null +++ b/fuzz/src/database.ts @@ -0,0 +1,22 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { IngredientData } from "@gram-lang/analyzer"; + +/** + * The playground's example database: the one the docs run `analyze()` with on + * every keystroke, so the one a real document meets. + */ +const PATH = join( + import.meta.dir, + "../../packages/docs/src/components/playground/ingredients.yaml", +); + +let cached: Record | null = null; + +export function exampleDatabase(): Record { + cached ??= Bun.YAML.parse(readFileSync(PATH, "utf-8")) as Record< + string, + IngredientData + >; + return cached; +} diff --git a/fuzz/src/invariants.ts b/fuzz/src/invariants.ts new file mode 100644 index 00000000..263511bd --- /dev/null +++ b/fuzz/src/invariants.ts @@ -0,0 +1,199 @@ +import { hasChanges } from "@gram-lang/format"; +import { GramParseError } from "@gram-lang/parser"; +import { + firstDifference, + MEANING_REPAIRS, + normalize, + pathShape, +} from "./normalize"; +import { type Outcome, Prepared } from "./prepared"; +import { signatureOf } from "./signature"; + +export interface Violation { + invariant: string; + message: string; + signature: string; + stack?: string; +} + +export interface Invariant { + id: string; + check(input: Prepared): Violation | null; +} + +function violation( + invariant: string, + message: string, + error?: unknown, +): Violation { + return { + invariant, + message, + signature: signatureOf(invariant, message, error), + ...(error instanceof Error && error.stack ? { stack: error.stack } : {}), + }; +} + +function describe(error: unknown): string { + return error instanceof Error + ? `${error.name}: ${error.message}` + : String(error); +} + +/** A stage that threw where it must not. */ +function noThrow( + id: string, + outcome: Outcome | null, + stage: string, +): Violation | null { + if (!outcome || outcome.ok) return null; + return violation( + id, + `${stage} threw ${describe(outcome.error)}`, + outcome.error, + ); +} + +/** + * The time an input may take through parse + compile + format, in ms. Wide on + * purpose: it catches a super-linear blow-up, not a slow CI runner. + */ +export function timeBudget(length: number): number { + return 200 + 0.05 * length; +} + +export const INVARIANTS: readonly Invariant[] = [ + { + id: "parse-contract", + check: ({ parse, source }) => { + if (parse.ok) return null; + const e = parse.error; + if (!(e instanceof GramParseError)) { + return violation( + "parse-contract", + `getAST threw ${describe(e)} instead of GramParseError`, + e, + ); + } + if ( + !Number.isInteger(e.offset) || + e.offset < 0 || + e.offset > source.length + ) { + return violation( + "parse-contract", + "GramParseError.offset outside [0, source.length]", + ); + } + if (typeof e.expected !== "string" || e.expected.trim() === "") { + return violation("parse-contract", "GramParseError.expected is empty"); + } + return null; + }, + }, + { + id: "compile-no-throw", + check: (p) => noThrow("compile-no-throw", p.compile, "compile"), + }, + { + id: "analyze-no-throw", + check: (p) => noThrow("analyze-no-throw", p.analyze, "analyze"), + }, + { + id: "format-no-throw", + check: (p) => noThrow("format-no-throw", p.format, "formatGram"), + }, + { + id: "format-idempotent", + check: (p) => { + const once = p.format; + const twice = p.reformat; + if (!once.ok || !twice) return null; + if (!twice.ok) + return violation( + "format-idempotent", + `second formatGram threw ${describe(twice.error)}`, + twice.error, + ); + if (twice.value.content !== once.value.content) { + const rules = Object.entries(twice.value.changes) + .filter(([, n]) => n !== 0 && n !== false) + .map(([rule]) => rule); + return violation( + "format-idempotent", + `second pass changed the output (${rules.join(", ") || "no rule reported"})`, + ); + } + if (hasChanges(twice.value.changes)) { + return violation( + "format-idempotent", + "second pass reported changes on an unchanged output", + ); + } + return null; + }, + }, + { + id: "format-preserves-meaning", + check: (p) => { + // An input that does not parse may be "repaired" by the formatter: + // not a violation. One whose compilation throws is I2's business. + if (!p.parse.ok || !p.compile?.ok) return null; + const after = p.formattedCompile; + if (!after || !p.format.ok) return null; + const changes = p.format.value.changes; + if (MEANING_REPAIRS.some((rule) => changes[rule])) return null; + if (!after.parse.ok) { + return violation( + "format-preserves-meaning", + "formatted source no longer parses", + after.parse.error, + ); + } + if (!after.compile?.ok) { + return violation( + "format-preserves-meaning", + "formatted source no longer compiles", + after.compile?.error, + ); + } + const diff = firstDifference( + normalize(p.compile.value), + normalize(after.compile.value), + ); + if (!diff) return null; + return violation( + "format-preserves-meaning", + `compilation differs after formatting at ${pathShape(diff)}`, + ); + }, + }, + { + id: "time-budget", + check: (p) => { + const elapsed = (q: Prepared) => + q.parse.ms + (q.compile?.ms ?? 0) + q.format.ms; + const budget = timeBudget(p.source.length); + let ms = elapsed(p); + // A GC pause or a cold JIT is not a blow-up: measure twice more, keep the best. + for (let i = 0; i < 2 && ms > budget; i++) + ms = Math.min(ms, elapsed(new Prepared(p.source, p.database))); + if (ms <= budget) return null; + return violation( + "time-budget", + `parse + compile + format took ${Math.round(ms)} ms, budget ${Math.round(budget)} ms`, + ); + }, + }, +]; + +export function invariantsById(ids: readonly string[]): Invariant[] { + return ids.map((id) => { + const inv = INVARIANTS.find((i) => i.id === id); + if (!inv) + throw new Error( + `unknown invariant "${id}" (known: ${INVARIANTS.map((i) => i.id).join(", ")})`, + ); + return inv; + }); +} diff --git a/fuzz/src/known-failures.ts b/fuzz/src/known-failures.ts new file mode 100644 index 00000000..7dabd08f --- /dev/null +++ b/fuzz/src/known-failures.ts @@ -0,0 +1,27 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +/** + * The ratchet: violations already found and not fixed yet, each tied to an + * issue. The fuzz test fails on a violation missing from this list, and on + * an entry whose `example` no longer fails: the file can only shrink. + */ +export interface KnownFailure { + signature: string; + invariant: string; + /** Forgejo issue tracking the fix. */ + issue: string; + /** A minimized input that triggers it. */ + example: string; +} + +export const KNOWN_FAILURES_PATH = join( + import.meta.dir, + "../known-failures.json", +); + +export function knownFailures(): KnownFailure[] { + return JSON.parse( + readFileSync(KNOWN_FAILURES_PATH, "utf-8"), + ) as KnownFailure[]; +} diff --git a/fuzz/src/mutators.ts b/fuzz/src/mutators.ts new file mode 100644 index 00000000..8fad8954 --- /dev/null +++ b/fuzz/src/mutators.ts @@ -0,0 +1,151 @@ +import type { Rng } from "./prng"; + +export interface MutationContext { + /** Other sources to graft fragments from (crossover). */ + donors: readonly string[]; +} + +export interface Mutator { + id: string; + /** Relative frequency among the mutators. */ + weight: number; + apply(source: string, rng: Rng, ctx: MutationContext): string; +} + +const SYNTAX_CHARS = [ + "{", + "}", + "/", + "|", + "&", + "@", + "#", + "~", + "^", + "=", + "(", + ")", + "[", + "]", + "<", + ">", + "%", + "?", + "-", + "+", + "*", + ":", + "'", + '"', +] as const; + +const BREAKS = ["\n", "\n\n", "\r\n", "\r"] as const; + +const TRICKY_UNICODE = [ + " ", // no-break space + "​", // zero-width space + "", // BOM + "‏", // right-to-left mark + "́", // combining acute accent + "👩‍🍳", // multi-code-point emoji (ZWJ sequence) + "\0", + "\ud83d", // lone high surrogate + "\udc00", // lone low surrogate +] as const; + +const at = (source: string, rng: Rng) => rng.int(0, source.length); +const insert = (source: string, index: number, text: string) => + source.slice(0, index) + text + source.slice(index); + +export const MUTATORS: readonly Mutator[] = [ + { + id: "insert-syntax-char", + weight: 5, + apply: (s, rng) => insert(s, at(s, rng), rng.pick(SYNTAX_CHARS)), + }, + { + id: "insert-break", + weight: 2, + apply: (s, rng) => insert(s, at(s, rng), rng.pick(BREAKS)), + }, + { + id: "insert-unicode", + weight: 2, + apply: (s, rng) => insert(s, at(s, rng), rng.pick(TRICKY_UNICODE)), + }, + { + id: "delete-range", + weight: 3, + apply: (s, rng) => { + const start = at(s, rng); + return s.slice(0, start) + s.slice(start + rng.int(1, 8)); + }, + }, + { + id: "duplicate-line", + weight: 1, + apply: (s, rng) => { + const lines = s.split("\n"); + const i = rng.int(0, lines.length - 1); + lines.splice(i, 0, lines[i] ?? ""); + return lines.join("\n"); + }, + }, + { + id: "swap-lines", + weight: 1, + apply: (s, rng) => { + const lines = s.split("\n"); + const i = rng.int(0, lines.length - 1); + const j = rng.int(0, lines.length - 1); + [lines[i], lines[j]] = [lines[j] ?? "", lines[i] ?? ""]; + return lines.join("\n"); + }, + }, + { + id: "truncate", + weight: 1, + apply: (s, rng) => s.slice(0, at(s, rng)), + }, + { + id: "crossover", + weight: 2, + apply: (s, rng, ctx) => { + if (ctx.donors.length === 0) return s; + const donor = rng.pick(ctx.donors).split("\n"); + const from = rng.int(0, donor.length - 1); + const fragment = donor.slice(from, from + rng.int(1, 4)); + const lines = s.split("\n"); + lines.splice(rng.int(0, lines.length), 0, ...fragment); + return lines.join("\n"); + }, + }, +]; + +function pickWeighted(rng: Rng, mutators: readonly Mutator[]): Mutator { + const total = mutators.reduce((sum, m) => sum + m.weight, 0); + let roll = rng.next() * total; + for (const m of mutators) { + roll -= m.weight; + if (roll < 0) return m; + } + return mutators[mutators.length - 1] as Mutator; +} + +/** Stacks 1 to 4 mutations on `source`. */ +export function mutate( + source: string, + rng: Rng, + ctx: MutationContext, + mutators: readonly Mutator[] = MUTATORS, +): { output: string; applied: string[] } { + let output = source; + const applied: string[] = []; + const count = rng.int(1, 4); + for (let i = 0; i < count; i++) { + const m = pickWeighted(rng, mutators); + output = m.apply(output, rng, ctx); + applied.push(m.id); + } + return { output, applied }; +} diff --git a/fuzz/src/normalize.ts b/fuzz/src/normalize.ts new file mode 100644 index 00000000..b1d61fde --- /dev/null +++ b/fuzz/src/normalize.ts @@ -0,0 +1,125 @@ +import type { FormatterChanges } from "@gram-lang/format"; + +/** + * Comparing two compilations "up to positions": the formatter moves text + * around and canonicalizes spellings, while the meaning must not change. + * + * Every rule here is a deliberate, commented decision, each one checked + * against the unmutated corpus. Never widen it to make a violation go away + * without understanding it first: a difference is a formatter bug until a + * rule below says it is a canonicalization. + */ + +/** Keys dropped wherever they appear. */ +export const POSITION_KEYS: ReadonlySet = new Set([ + // Source location of AST nodes, copied onto usages and warnings. + "loc", + // Compiler name and version: not part of the recipe (same as + // `withoutGenerator` in conformance/run.ts). + "generator", + // Source spelling of a quantity or timer (`180 °C`, `{1 cup+2 tbsp}`): + // the formatter respaces it on purpose (rules 2-5); its parsed form + // (`qty`, `unit`, `value`, durations) is still compared. + "raw", +]); + +/** + * Formatter rules that *repair* a common mistake into the syntax the author + * meant, so they change the compilation by design: `@a{} < @b{}` becomes a + * composite (rule 6), `->&dough {}` a declaration (rule 7), `##Prep` a + * section header instead of `#` + cookware `#Prep` (rule 8). I6 does not + * compare an input on which one of them fired. + */ +export const MEANING_REPAIRS: readonly (keyof FormatterChanges)[] = [ + "compositeSeparatorSpacing", + "arrowDeclarationSpacing", + "headerSpacing", +]; + +function normalizeText(text: string, isLast: boolean): string { + // Rule 9 (tabs → 4 spaces) and rule 10 (trailing whitespace) rewrite prose. + const out = text.replace(/\t/g, " ").replace(/[ \t]+(?=\r?\n)/g, ""); + return isLast ? out.replace(/[ \t]+$/, "") : out; +} + +export function normalize(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map((v, i) => + typeof v === "string" + ? normalizeText(v, i === value.length - 1) + : normalize(v), + ); + } + if (value && typeof value === "object") { + const record = value as Record; + const out: Record = {}; + for (const [key, v] of Object.entries(record)) { + if (POSITION_KEYS.has(key)) continue; + // A number's source spelling (`160.0`): rule 4 drops trailing + // zeros; `value` holds the number itself. + if (key === "text" && "value" in record) continue; + // A warning's message quotes the source spelling (`"180 °C"`); + // its `code` and the rest of its fields are still compared. + if (key === "message" && "code" in record) continue; + // Rule 1 lowercases ingredient ids (`@Farine` → `@farine`), and + // the displayed name follows the source's case. + if (key === "name" && typeof v === "string") { + out[key] = v.toLowerCase(); + continue; + } + out[key] = normalize(v); + } + return out; + } + return value; +} + +/** + * The path of the first difference between two normalized values, or null + * when they are equal. Paths look like `$.sections[0].steps[2].text`. + */ +export function firstDifference( + a: unknown, + b: unknown, + path = "$", +): string | null { + if (Object.is(a, b)) return null; + if (Array.isArray(a) && Array.isArray(b)) { + const length = Math.max(a.length, b.length); + for (let i = 0; i < length; i++) { + const d = firstDifference(a[i], b[i], `${path}[${i}]`); + if (d) return d; + } + return null; + } + if ( + a && + b && + typeof a === "object" && + typeof b === "object" && + !Array.isArray(a) && + !Array.isArray(b) + ) { + const ra = a as Record; + const rb = b as Record; + const keys = new Set([...Object.keys(ra), ...Object.keys(rb)]); + for (const key of [...keys].sort()) { + const d = firstDifference(ra[key], rb[key], `${path}.${key}`); + if (d) return d; + } + return null; + } + return path; +} + +/** + * The coarse shape of a path, for signatures: indices blanked and only the + * first segments kept (`$.sections[3].steps[0].text` → `$.sections[].steps[]`), + * so one bug does not split into a signature per ingredient name or field. + */ +export function pathShape(path: string): string { + const segments = path.replace(/\[\d+\]/g, "[]").split("."); + // Frontmatter keys are the author's own words: stop at `$.meta`. + const depth = segments[1] === "meta" ? 2 : 3; + return segments.slice(0, depth).join("."); +} diff --git a/fuzz/src/prepared.ts b/fuzz/src/prepared.ts new file mode 100644 index 00000000..8f875402 --- /dev/null +++ b/fuzz/src/prepared.ts @@ -0,0 +1,89 @@ +import { analyze, type IngredientData } from "@gram-lang/analyzer"; +import { formatGram } from "@gram-lang/format"; +import { type CompilationResult, compile } from "@gram-lang/kitchen"; +import { getAST, type RecipeAST } from "@gram-lang/parser"; + +export type Outcome = + | { ok: true; value: T; ms: number } + | { ok: false; error: unknown; ms: number }; + +function attempt(fn: () => T): Outcome { + const start = performance.now(); + try { + const value = fn(); + return { ok: true, value, ms: performance.now() - start }; + } catch (error) { + return { ok: false, error, ms: performance.now() - start }; + } +} + +type Formatted = ReturnType; + +/** + * Everything the invariants look at, computed once per input and only when + * an invariant asks for it: the same string is never parsed twice. + * A stage whose input stage failed is `null`. + */ +export class Prepared { + readonly #cache = new Map(); + + constructor( + readonly source: string, + readonly database: Record, + ) {} + + #memo(key: string, fn: () => T): T { + if (!this.#cache.has(key)) this.#cache.set(key, fn()); + return this.#cache.get(key) as T; + } + + get parse(): Outcome { + return this.#memo("parse", () => attempt(() => getAST(this.source))); + } + + get compile(): Outcome | null { + return this.#memo("compile", () => { + const parsed = this.parse; + return parsed.ok ? attempt(() => compile(parsed.value)) : null; + }); + } + + get analyze(): Outcome | null { + return this.#memo("analyze", () => { + const compiled = this.compile; + return compiled?.ok + ? attempt(() => analyze(compiled.value, this.database)) + : null; + }); + } + + get format(): Outcome { + return this.#memo("format", () => attempt(() => formatGram(this.source))); + } + + /** `formatGram` run again on its own output. */ + get reformat(): Outcome | null { + return this.#memo("reformat", () => { + const formatted = this.format; + return formatted.ok + ? attempt(() => formatGram(formatted.value.content)) + : null; + }); + } + + /** The formatted source, parsed then compiled. */ + get formattedCompile(): { + parse: Outcome; + compile: Outcome | null; + } | null { + return this.#memo("formattedCompile", () => { + const formatted = this.format; + if (!formatted.ok) return null; + const parse = attempt(() => getAST(formatted.value.content)); + return { + parse, + compile: parse.ok ? attempt(() => compile(parse.value)) : null, + }; + }); + } +} diff --git a/fuzz/src/prng.ts b/fuzz/src/prng.ts new file mode 100644 index 00000000..66c6f5d3 --- /dev/null +++ b/fuzz/src/prng.ts @@ -0,0 +1,56 @@ +/** + * A small seeded PRNG (sfc32, seeded through splitmix32), so a fuzz run is a + * pure function of its seed: same seed, same inputs, on every machine. + */ +export interface Rng { + /** Uniform float in [0, 1). */ + next(): number; + /** Uniform integer in [min, max], both inclusive. */ + int(min: number, max: number): number; + pick(items: readonly T[]): T; + chance(probability: number): boolean; +} + +function splitmix32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x9e3779b9) >>> 0; + let z = state; + z = Math.imul(z ^ (z >>> 16), 0x85ebca6b) >>> 0; + z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35) >>> 0; + return (z ^ (z >>> 16)) >>> 0; + }; +} + +export function createRng(seed: number): Rng { + const init = splitmix32(seed); + let a = init(); + let b = init(); + let c = init(); + let d = init(); + const u32 = (): number => { + const t = (((a + b) >>> 0) + d) >>> 0; + d = (d + 1) >>> 0; + a = b ^ (b >>> 9); + b = (c + (c << 3)) >>> 0; + c = ((c << 21) | (c >>> 11)) >>> 0; + c = (c + t) >>> 0; + return t; + }; + for (let i = 0; i < 12; i++) u32(); + const next = () => u32() / 0x100000000; + return { + next, + int: (min, max) => min + Math.floor(next() * (max - min + 1)), + pick: (items) => { + if (items.length === 0) throw new Error("pick() from an empty list"); + return items[Math.floor(next() * items.length)] as (typeof items)[number]; + }, + chance: (probability) => next() < probability, + }; +} + +/** The seed of iteration `index` of a run: each iteration replays on its own. */ +export function iterationSeed(seed: number, index: number): number { + return splitmix32((seed ^ Math.imul(index + 1, 0x27d4eb2d)) >>> 0)(); +} diff --git a/fuzz/src/regressions.ts b/fuzz/src/regressions.ts new file mode 100644 index 00000000..c901fe34 --- /dev/null +++ b/fuzz/src/regressions.ts @@ -0,0 +1,15 @@ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +/** Minimized inputs of fixed bugs, replayed on every invariant at each run. */ +export const REGRESSIONS_DIR = join(import.meta.dir, "../regressions"); + +export function regressions(): { name: string; content: string }[] { + return readdirSync(REGRESSIONS_DIR) + .filter((f) => f.endsWith(".gram")) + .sort() + .map((name) => ({ + name, + content: readFileSync(join(REGRESSIONS_DIR, name), "utf-8"), + })); +} diff --git a/fuzz/src/run.ts b/fuzz/src/run.ts new file mode 100644 index 00000000..ccefde66 --- /dev/null +++ b/fuzz/src/run.ts @@ -0,0 +1,114 @@ +import type { IngredientData } from "@gram-lang/analyzer"; +import { exampleDatabase } from "./database"; +import { INVARIANTS, type Invariant, type Violation } from "./invariants"; +import { MUTATORS, type Mutator, mutate } from "./mutators"; +import { Prepared } from "./prepared"; +import { createRng, iterationSeed } from "./prng"; + +export interface CorpusEntry { + id: string; + content: string; +} + +export interface GeneratedInput { + index: number; + corpusId: string; + mutations: string[]; + input: string; +} + +export interface Finding extends Violation, GeneratedInput { + /** How many inputs of the run hit this signature. */ + count: number; +} + +export interface RunOptions { + seed: number; + iterations: number; + corpus: readonly CorpusEntry[]; + invariants?: readonly Invariant[]; + mutators?: readonly Mutator[]; + database?: Record; + /** Called after each input, e.g. for a progress line. */ + onInput?: (index: number) => void; +} + +/** Input `index` of a run: a pure function of (seed, index, corpus). */ +export function generateInput( + seed: number, + index: number, + corpus: readonly CorpusEntry[], + mutators: readonly Mutator[] = MUTATORS, +): GeneratedInput { + const rng = createRng(iterationSeed(seed, index)); + const base = rng.pick(corpus); + const donors = corpus.map((c) => c.content); + const { output, applied } = mutate(base.content, rng, { donors }, mutators); + return { index, corpusId: base.id, mutations: applied, input: output }; +} + +export function checkInput( + input: string, + invariants: readonly Invariant[] = INVARIANTS, + database: Record = exampleDatabase(), +): Violation[] { + const prepared = new Prepared(input, database); + const out: Violation[] = []; + for (const inv of invariants) { + const v = inv.check(prepared); + if (v) out.push(v); + } + return out; +} + +function collect( + findings: Map, + violations: Violation[], + generated: GeneratedInput, +): void { + for (const v of violations) { + const existing = findings.get(v.signature); + if (existing) existing.count++; + else findings.set(v.signature, { ...v, ...generated, count: 1 }); + } +} + +/** Mutated inputs: one finding per signature, the first input that hit it. */ +export function runFuzz(opts: RunOptions): Finding[] { + const invariants = opts.invariants ?? INVARIANTS; + const database = opts.database ?? exampleDatabase(); + const findings = new Map(); + for (let i = 0; i < opts.iterations; i++) { + const generated = generateInput(opts.seed, i, opts.corpus, opts.mutators); + collect( + findings, + checkInput(generated.input, invariants, database), + generated, + ); + opts.onInput?.(i); + } + return [...findings.values()]; +} + +/** The corpus itself, unmutated (index -1, no mutation). */ +export function scanCorpus( + corpus: readonly CorpusEntry[], + invariants: readonly Invariant[] = INVARIANTS, + database: Record = exampleDatabase(), +): Finding[] { + const findings = new Map(); + for (const entry of corpus) { + const generated = { + index: -1, + corpusId: entry.id, + mutations: [], + input: entry.content, + }; + collect( + findings, + checkInput(entry.content, invariants, database), + generated, + ); + } + return [...findings.values()]; +} diff --git a/fuzz/src/shrink.ts b/fuzz/src/shrink.ts new file mode 100644 index 00000000..69f6fd68 --- /dev/null +++ b/fuzz/src/shrink.ts @@ -0,0 +1,50 @@ +/** + * Delta-debugging minimization: the smallest input that still fails the + * same way, first by whole lines, then by characters. `stillFails` decides + * what "the same way" means (in practice: same signature). + */ +export function shrink( + input: string, + stillFails: (candidate: string) => boolean, + maxChecks = 5000, +): string { + let checks = 0; + const test = (candidate: string) => { + checks++; + return stillFails(candidate); + }; + + const ddmin = (units: string[], join: string): string[] => { + let current = units; + let granularity = 2; + while (current.length >= 2 && checks < maxChecks) { + const chunk = Math.ceil(current.length / granularity); + let reduced = false; + for ( + let start = 0; + start < current.length && checks < maxChecks; + start += chunk + ) { + const complement = [ + ...current.slice(0, start), + ...current.slice(start + chunk), + ]; + if (complement.length > 0 && test(complement.join(join))) { + current = complement; + granularity = Math.max(granularity - 1, 2); + reduced = true; + break; + } + } + if (!reduced) { + if (granularity >= current.length) break; + granularity = Math.min(granularity * 2, current.length); + } + } + return current; + }; + + const byLines = ddmin(input.split("\n"), "\n").join("\n"); + // Array.from keeps surrogate pairs whole; a lone surrogate stays one unit. + return ddmin(Array.from(byLines), "").join(""); +} diff --git a/fuzz/src/signature.ts b/fuzz/src/signature.ts new file mode 100644 index 00000000..6b179bf5 --- /dev/null +++ b/fuzz/src/signature.ts @@ -0,0 +1,38 @@ +/** + * Two violations with the same signature are the same bug: same invariant, + * same message once the input-specific parts are blanked, thrown from the + * same function of the same package. + */ +export function signatureOf( + invariant: string, + message: string, + error?: unknown, +): string { + const parts = [invariant, normalizeMessage(message)]; + const frame = error instanceof Error ? firstPackageFrame(error.stack) : null; + if (frame) parts.push(frame); + return parts.join(" | "); +} + +export function normalizeMessage(message: string): string { + const firstLine = message.split("\n")[0] ?? ""; + return firstLine + .replace(/"[^"]*"/g, '"…"') + .replace(/'[^']*'/g, "'…'") + .replace(/`[^`]*`/g, "`…`") + .replace(/\d+(\.\d+)?/g, "N") + .trim(); +} + +/** + * `at buildTasks (/…/packages/kitchen/dist/index.js:812:9)` → `kitchen:buildTasks`. + * Line and column are left out: they change with every rebuild of `dist/`. + */ +export function firstPackageFrame(stack: string | undefined): string | null { + if (!stack) return null; + for (const line of stack.split("\n")) { + const m = line.match(/at (?:(\S+) )?\(?.*\/packages\/([^/]+)\//); + if (m) return `${m[2]}:${m[1] ?? ""}`; + } + return null; +} diff --git a/fuzz/tests/__snapshots__/prng.test.ts.snap b/fuzz/tests/__snapshots__/prng.test.ts.snap new file mode 100644 index 00000000..ef3434c9 --- /dev/null +++ b/fuzz/tests/__snapshots__/prng.test.ts.snap @@ -0,0 +1,11 @@ +// Bun Snapshot v1, https://bun.sh/docs/test/snapshots + +exports[`createRng produces a frozen sequence for a given seed 1`] = ` +[ + 780544, + 78839, + 356760, + 892041, + 457148, +] +`; diff --git a/fuzz/tests/fuzz.test.ts b/fuzz/tests/fuzz.test.ts new file mode 100644 index 00000000..31668dc3 --- /dev/null +++ b/fuzz/tests/fuzz.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "bun:test"; +import { fuzzCorpus } from "../src/corpus"; +import { checkInput, type Finding, runFuzz, scanCorpus } from "../src/run"; +import { knownFailures } from "../src/known-failures"; +import { shrink } from "../src/shrink"; + +// Fixed on purpose: adjust ITERATIONS to the CI budget, never the seed at random. +const SEED = 0x6772616d; +const ITERATIONS = 2000; + +const known = knownFailures(); +const knownSignatures = new Set(known.map((k) => k.signature)); + +function report(f: Finding): string { + const minimized = shrink( + f.input, + (c) => checkInput(c).some((v) => v.signature === f.signature), + 2000, + ); + const replay = + f.index < 0 + ? `from ${f.corpusId}` + : `bun run fuzz --seed ${SEED} --index ${f.index} (from ${f.corpusId}, ${f.mutations.join(", ")})`; + return `${f.signature}\n ${replay}\n minimized: ${JSON.stringify(minimized)}\n → fix it, or add it to fuzz/known-failures.json with an issue`; +} + +describe("fuzz", () => { + it("the unmutated corpus breaks no invariant beyond known failures", () => { + const fresh = scanCorpus(fuzzCorpus()).filter( + (f) => !knownSignatures.has(f.signature), + ); + expect(fresh.map(report)).toEqual([]); + }, 60_000); + + it(`${ITERATIONS} mutated inputs break no invariant beyond known failures`, () => { + const findings = runFuzz({ + seed: SEED, + iterations: ITERATIONS, + corpus: fuzzCorpus(), + }); + const fresh = findings.filter((f) => !knownSignatures.has(f.signature)); + expect(fresh.map(report)).toEqual([]); + }, 60_000); + + it("every known failure still fails (else: drop it and add its example to fuzz/regressions/)", () => { + const fixed = known + .filter( + (k) => !checkInput(k.example).some((v) => v.signature === k.signature), + ) + .map((k) => `${k.signature} (${k.issue}): ${JSON.stringify(k.example)}`); + expect(fixed).toEqual([]); + }); +}); diff --git a/fuzz/tests/mutators.test.ts b/fuzz/tests/mutators.test.ts new file mode 100644 index 00000000..e4fe29f3 --- /dev/null +++ b/fuzz/tests/mutators.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from "bun:test"; +import { MUTATORS, mutate } from "../src/mutators"; +import { createRng } from "../src/prng"; +import { generateInput } from "../src/run"; + +const SOURCE = + "## Dough\n\nMix @flour{500 g} with @water{300 ml}.\n\nRest ~{20 min}.\n"; +const corpus = [ + { id: "a", content: SOURCE }, + { id: "b", content: "Bake in #oven at ^{180°C}.\n" }, +]; + +describe("mutators", () => { + it("are deterministic for a given seed", () => { + for (const m of MUTATORS) { + const ctx = { donors: corpus.map((c) => c.content) }; + expect(m.apply(SOURCE, createRng(7), ctx)).toBe( + m.apply(SOURCE, createRng(7), ctx), + ); + } + }); + + it("stack one to four mutations", () => { + for (let seed = 0; seed < 200; seed++) { + const { applied } = mutate(SOURCE, createRng(seed), { donors: [] }); + expect(applied.length).toBeGreaterThanOrEqual(1); + expect(applied.length).toBeLessThanOrEqual(4); + } + }); + + it("survive an empty source", () => { + for (const m of MUTATORS) + expect(typeof m.apply("", createRng(1), { donors: [] })).toBe("string"); + }); + + it("make an input a pure function of (seed, index, corpus)", () => { + expect(generateInput(5, 17, corpus)).toEqual(generateInput(5, 17, corpus)); + expect(generateInput(5, 17, corpus)).not.toEqual( + generateInput(5, 18, corpus), + ); + }); +}); diff --git a/fuzz/tests/normalize.test.ts b/fuzz/tests/normalize.test.ts new file mode 100644 index 00000000..e410d561 --- /dev/null +++ b/fuzz/tests/normalize.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "bun:test"; +import { firstDifference, normalize, pathShape } from "../src/normalize"; + +describe("normalize", () => { + it("drops positions and source spellings, keeps meaning", () => { + const a = { + loc: { start: 1 }, + qty: { value: 160, text: "160.0" }, + raw: "160.0 g", + qty2: 3, + }; + const b = { + loc: { start: 9 }, + qty: { value: 160, text: "160" }, + raw: "160 g", + qty2: 3, + }; + expect(firstDifference(normalize(a), normalize(b))).toBeNull(); + expect(firstDifference(normalize(a), normalize({ ...b, qty2: 4 }))).toBe( + "$.qty2", + ); + }); + + it("does not trim prose in the middle of a step", () => { + expect(normalize(["Bake ", { id: "x" }, "now. "])).toEqual([ + "Bake ", + { id: "x" }, + "now.", + ]); + }); + + it("blanks indices and keeps the first segments for signatures", () => { + expect(pathShape("$.sections[3].steps[0].content[2].raw")).toBe( + "$.sections[].steps[]", + ); + }); +}); diff --git a/fuzz/tests/pathological.test.ts b/fuzz/tests/pathological.test.ts new file mode 100644 index 00000000..16f21291 --- /dev/null +++ b/fuzz/tests/pathological.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from "bun:test"; +import { formatGram } from "@gram-lang/format"; +import { compile } from "@gram-lang/kitchen"; +import { getAST, type RecipeAST } from "@gram-lang/parser"; + +/** Best of three, in ms: a GC pause or a cold JIT only ever adds time. */ +function best(fn: () => unknown): number { + let min = Number.POSITIVE_INFINITY; + for (let i = 0; i < 3; i++) { + const start = performance.now(); + try { + fn(); + } catch { + // Only the time matters here; the other tests own the outcomes. + } + min = Math.min(min, performance.now() - start); + } + return min; +} + +type Stage = "parse" | "compile" | "format"; + +/** Each stage timed on its own, so a slow stage is not diluted by the others. */ +function measure(source: string): Record { + let ast: RecipeAST | null = null; + const parse = best(() => { + ast = getAST(source); + }); + const parsed = ast as RecipeAST | null; + const compileMs = parsed ? best(() => compile(parsed)) : 0; + return { parse, compile: compileMs, format: best(() => formatGram(source)) }; +} + +// Worst cases for a backtracking grammar or a regex-heavy formatter. +const GENERATORS: Record string> = { + "a long line with no break": (n) => `Mix ${"a".repeat(n)}`, + "nested opening braces": (n) => `Mix @flour${"{".repeat(n)}`, + "a run of @": (n) => "@".repeat(n), + "ranges and sums in series": (n) => + `Add @flour{${"1-2 g + ".repeat(n / 8)}1 g}.`, + "an unclosed frontmatter": (n) => + `---\ntitle: x\n${"key: value\n".repeat(n / 11)}`, + "many steps": (n) => "Mix @flour{1 g}.\n\n".repeat(n / 18), +}; + +/** + * Growth is judged by its exponent between a small and a large input + * (t ∝ n^k, k = log(t_large / t_small) / log(16)): linear code measures + * 0.90-1.06, a quadratic step hidden behind linear work already shows + * 1.24 (the compound-quantity AST before its fix), a fully quadratic one 2. + */ +const SMALL = 3_125; +const LARGE = 50_000; +const MAX_EXPONENT = 1.15; +/** Below this, the large input is too fast for its time to mean anything. */ +const NOISE_FLOOR_MS = 20; + +/** + * The ratchet of this file: known super-linear cases, each tied to an issue. + * They run as `it.failing`, so fixing one turns its test red until it is + * removed from here. `scale` shrinks both sizes of a case too slow to run + * at full size (its exponent does not depend on it). + */ +const KNOWN_SLOW: Record = { + // formatGram rule 3 rescans to the end of the input from every unclosed `{`. + "nested opening braces": { + issue: "https://git.gram-lang.org/gram-lang/gram/issues/202", + scale: 1 / 4, + }, + // The compound-quantity action reads `ops.children[i]` in a loop, and ohm + // rebuilds `children` on every access. + "ranges and sums in series": { + issue: "https://git.gram-lang.org/gram-lang/gram/issues/203", + }, +}; + +function exponents(generate: (n: number) => string, scale: number): string[] { + const small = Math.round(SMALL * scale); + const large = Math.round(LARGE * scale); + measure(generate(small)); // warm-up + const a = measure(generate(small)); + const b = measure(generate(large)); + const slow: string[] = []; + for (const stage of ["parse", "compile", "format"] as const) { + if (b[stage] < NOISE_FLOOR_MS) continue; + const k = Math.log(b[stage] / a[stage]) / Math.log(large / small); + if (k > MAX_EXPONENT) { + slow.push( + `${stage}: n^${k.toFixed(2)} (${a[stage].toFixed(1)} ms at ${small}, ${b[stage].toFixed(1)} ms at ${large})`, + ); + } + } + return slow; +} + +describe("growth stays near linear", () => { + for (const [name, generate] of Object.entries(GENERATORS)) { + const known = KNOWN_SLOW[name]; + const test = known ? it.failing : it; + test(known ? `${name} (known: ${known.issue})` : name, () => { + expect(exponents(generate, known?.scale ?? 1)).toEqual([]); + }, 60_000); + } +}); diff --git a/fuzz/tests/prng.test.ts b/fuzz/tests/prng.test.ts new file mode 100644 index 00000000..11c77a33 --- /dev/null +++ b/fuzz/tests/prng.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "bun:test"; +import { createRng, iterationSeed } from "../src/prng"; + +describe("createRng", () => { + it("produces a frozen sequence for a given seed", () => { + const rng = createRng(0x6772616d); + const sequence = Array.from({ length: 5 }, () => rng.int(0, 1_000_000)); + // Changing this sequence changes every fuzz input: do it on purpose only. + expect(sequence).toMatchSnapshot(); + }); + + it("stays within bounds", () => { + const rng = createRng(42); + for (let i = 0; i < 10_000; i++) { + const n = rng.int(3, 7); + expect(n >= 3 && n <= 7).toBe(true); + const f = rng.next(); + expect(f >= 0 && f < 1).toBe(true); + } + }); + + it("gives each iteration its own seed", () => { + const seeds = new Set( + Array.from({ length: 1000 }, (_, i) => iterationSeed(1, i)), + ); + expect(seeds.size).toBe(1000); + }); +}); diff --git a/fuzz/tests/regressions.test.ts b/fuzz/tests/regressions.test.ts new file mode 100644 index 00000000..af296008 --- /dev/null +++ b/fuzz/tests/regressions.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "bun:test"; +import { regressions } from "../src/regressions"; +import { checkInput } from "../src/run"; + +describe("fuzz regressions", () => { + const cases = regressions(); + it.skipIf(cases.length > 0)("none yet", () => {}); + for (const { name, content } of cases) { + it(name, () => { + expect(checkInput(content).map((v) => v.signature)).toEqual([]); + }); + } +}); diff --git a/fuzz/tests/shrink.test.ts b/fuzz/tests/shrink.test.ts new file mode 100644 index 00000000..d1846f94 --- /dev/null +++ b/fuzz/tests/shrink.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "bun:test"; +import { shrink } from "../src/shrink"; + +describe("shrink", () => { + it("keeps only what makes the predicate fail", () => { + const input = + "## A\n\nMix @flour{500 g}.\n\nAdd @*salt and @*sugar.\n\nBake.\n"; + const min = shrink(input, (c) => (c.match(/@\*/g) ?? []).length >= 2); + expect(min).toBe("@*@*"); + }); + + it("returns the input when nothing can be removed", () => { + expect(shrink("x", (c) => c === "x")).toBe("x"); + }); +}); diff --git a/fuzz/tsconfig.json b/fuzz/tsconfig.json new file mode 100644 index 00000000..45db1f78 --- /dev/null +++ b/fuzz/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "declaration": false, + "types": ["bun"] + }, + "include": ["src/**/*", "tests/**/*", "cli.ts"] +} diff --git a/package.json b/package.json index e431868d..b290249d 100644 --- a/package.json +++ b/package.json @@ -51,6 +51,7 @@ "deprecations": "bun run scripts/check-deprecations.ts", "deprecations:check": "bun run scripts/check-deprecations.ts --check", "audit": "bun run --cwd audit audit", + "fuzz": "bun run --cwd fuzz fuzz", "audit:fix": "bun audit fix", "audit:check": "bun audit", "dedupe:check": "bun dedupe --check", @@ -60,6 +61,7 @@ "workspaces": [ "packages/*", "conformance", - "audit" + "audit", + "fuzz" ] }