memlnaut-nisps/codegen/tests/curve_drift_test.ts

186 lines
7.2 KiB
TypeScript
Raw Permalink Normal View History

feat: curve truth, DriverConfig, real telemetry, engine benchmark Four items from one workflow, committed together because their build and CI wiring genuinely interleaves — nisps/CMakeLists.txt, run-all-tests.sh and ci.yml each carry hunks from two of them, and the stage renumbering (1/5 -> 1/6) touches every line. Splitting would produce commits that do not build, which is worse than a commit that does four things and says so. S26 part 2 — the curve declaration now matches reality. params[].curve stays the mode-wide DEFAULT; a voice_spaces entry may now be {name, curve_overrides} declaring only the slots where THAT voice space deviates. The 6 modes with one voice space are byte-identical. The values were derived MECHANICALLY by a new codegen/curve-audit.ts that models the four idioms a p[N]*p[N] regex misses (alias form, memlcelium's implicit-counter sq() lambda, loop-generated indices, smooth_params_), inlines helpers, and RAISES rather than guessing when it cannot reduce an expression. A drift gate cross-checks 1179 (voice space x param) slots against engine source on every run and was proved to fail loudly on three drift classes. Application stays in the engine: nisps/engines, nisps/pipeline and nisps/core are untouched, generated output is pure insertion (755 insertions, 0 deletions), and the rebuilt nisps.wasm was byte-identical. S4 / 7.2 — firmware reads the active mode's driver config at mode start, and mic/line is real. My brief assumed the engine owns this; the code disagreed and the code was right. sound_analysis_midi's EngineT is NoOpEngine — the mic lives on a separately-composed AnalysisEngine member — so engine-level wiring would have compiled, passed every gate, and left the one mic mode on line input. Hence a mode-level seam defaulting to engine().driver_config(). Separately, DriverConfig's defaults (line_level 0, output_volume 1.0) had drifted from memllib's actual 3/0.8 because nothing had ever read them; wiring them as-is would have made every silent mode louder and its line input maximally insensitive — a behaviour change disguised as plumbing. Now pinned by a test. Also: GetSysClockSpeed() panic()s on unsupported sample rates and runs on the first line of setup(), so sample_rate needed a fallback ahead of clock setup. CI's firmware env list gains soundanalysismidi — it is the only mic variant and nothing else compiles that path. Plan 5e — telemetry is real. A loss_history C-API entry across the full 5-layer chain lets the browser read the per-iteration loss the core already records. The audit named one fabrication site; there were two — wasm-iml.ts's synchronous train() published lossHistory: [loss] as well. A third, ctx.loss, was not merely dead but actively synthetic (fallbacks of prev * 0.82 and a literal 0.5, rendered by nothing) and is deleted. The firmware buffer stays untouched, per the L25 call. EngineApi.lossHistory() reads spine state rather than the MLP handle, because trainAsync() fits on the worker's mirror net and the handle would give a subtly-wrong second answer. Plan 5f — engine throughput is measurable. One source compiled twice (CMake natively, emcc for WASM) so the targets compare directly and no WASM export is added. Sequencers are driven into a working state, and every row prints its own working-state evidence so a number produced by an idle engine is visible rather than plausible. Reports, never asserts: a wall-clock threshold on shared hardware is meaningless or flaky, same call as the firmware size job. ALIGNMENT: the telemetry defect is deleted (built, not deferred); the performance defect is rewritten to what is actually left — these are HOST numbers, and nothing measures the RP2350 at 150 MHz, which is the target the mission's constraint is about. Q4 (memllib ownership) and Q5 (legacy feedback modes) are closed. Corrections to my own earlier claims, both found by agents contradicting the brief: manifold/ONBOARDING.md was NOT "now accurate" — its primitives list still named five deleted primitives and cited a seededGradient() that does not exist. And the parity harness misses the sequencer engines because it runs 128 frames while their sequencers evaluate every 400-500 samples, NOT because all-params-0.5 fails to trigger them (it does trigger: 0.5 maps to ratio 2, firing three times per bar). The fix is a longer window, not different params. Gates: run-all-tests.sh ALL GREEN — 4/4 ctest, parity PASS, lint clean, curve drift 1179 slots ok, 39 e2e (was 33). Firmware: 5 envs built including the mic variant.
2026-07-21 22:02:23 +02:00
#!/usr/bin/env bun
/**
* Curve drift check the schemas' declared response curves must equal what
* `nisps/engines/*.hpp` actually does, per voice space.
*
* WHY THIS CHECK IS SOURCE-LEVEL, NOT BEHAVIOURAL
* -----------------------------------------------
* You cannot observe "the curve" from engine output. A voice space maps a
* normalised slot into engine state as `base + f(p) * scale` and the state
* then disappears into DSP; without independently knowing `base`/`scale` (and
* the DSP transfer function) there is no way to recover `f` from audio. The
* engines expose no accessor for the mapped state, and adding one would mean
* editing engine internals to make a declaration checkable the tail wagging
* the dog. So the fact lives in the arithmetic, and that is what we read.
*
* The upside of being source-level: it verifies the WHOLE table (9 modes, 26
* voice spaces, 344 params) rather than the handful of code paths any
* behavioural harness would reach. The parity harness, for contrast, only
* exercises PAFSynth + ChannelStrip at all-params-0.5.
*
* It fails loudly on three separate classes of drift:
* 1. a declared curve that disagrees with the engine,
* 2. a schema voice-space list that disagrees with the engine's
* `kVoiceSpaceNames` (order matters the schema index IS the enum
* ordinal that `ModeBase::set_voice_space` casts to),
* 3. an engine idiom the extractor cannot reduce (codegen/curve-audit.ts
* raises rather than guessing "linear").
*
* It checks the JSON schemas AND the generated TypeScript, so a codegen bug
* that drops the table cannot pass.
*/
import { readFileSync, readdirSync } from "node:fs";
import { join, dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { auditAllEngines, CurveAuditError, type Curve } from "../curve-audit.ts";
import { ALL_MODE_SCHEMAS, effectiveCurve } from "../../manifold/src/modes/generated/index.ts";
const __dirname = dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = resolve(__dirname, "..", "..");
const MODES_DIR = join(REPO_ROOT, "schemas", "modes");
const ENGINES_DIR = join(REPO_ROOT, "nisps", "engines");
type VoiceSpaceDecl = string | { name: string; curve_overrides: Record<string, Curve> };
interface JsonModeSchema {
mode_id: string;
engine_id: string;
params: Array<{ name: string; curve: Curve }>;
voice_spaces: VoiceSpaceDecl[];
}
const vsName = (v: VoiceSpaceDecl): string => (typeof v === "string" ? v : v.name);
/** Resolve the JSON declaration into curves[voiceSpace][param]. */
function declaredCurves(s: JsonModeSchema): Curve[][] {
const defaults = s.params.map((p) => p.curve);
const byName = new Map(s.params.map((p, i) => [p.name, i] as const));
const rows = s.voice_spaces.length === 0 ? [null] : s.voice_spaces;
return rows.map((v) => {
const row = [...defaults];
if (v && typeof v !== "string") {
for (const [name, c] of Object.entries(v.curve_overrides)) {
row[byName.get(name)!] = c;
}
}
return row;
});
}
function run(): number {
const problems: string[] = [];
let engines;
try {
engines = auditAllEngines(ENGINES_DIR);
} catch (e) {
if (e instanceof CurveAuditError) {
console.error(`\nFAILED to read the engines' curve arithmetic:\n ${e.message}\n`);
console.error(
"The extractor refuses to guess. Either the engine grew an idiom\n" +
"codegen/curve-audit.ts does not model, or a voice space lost its\n" +
"dispatch case. Teach the extractor, do not weaken it.\n"
);
return 1;
}
throw e;
}
const tsByModeId = new Map(ALL_MODE_SCHEMAS.map((m) => [m.mode_id, m] as const));
let checkedModes = 0;
let checkedSlots = 0;
for (const f of readdirSync(MODES_DIR).filter((n) => n.endsWith(".json")).sort()) {
const s = JSON.parse(readFileSync(join(MODES_DIR, f), "utf8")) as JsonModeSchema;
const eng = engines.get(s.engine_id);
if (!eng) {
problems.push(`${f}: engine_id ${JSON.stringify(s.engine_id)} matches no engine in nisps/engines/`);
continue;
}
// (2) voice-space identity. Index i in the schema IS VoiceSpace ordinal i.
if (eng.voiceSpaceNames !== null) {
const declared = s.voice_spaces.map(vsName);
if (JSON.stringify(declared) !== JSON.stringify(eng.voiceSpaceNames)) {
problems.push(
`${f}: voice_spaces disagree with ${eng.file}'s kVoiceSpaceNames\n` +
` schema: ${JSON.stringify(declared)}\n` +
` engine: ${JSON.stringify(eng.voiceSpaceNames)}`
);
continue;
}
} else if (s.voice_spaces.length > 1) {
problems.push(
`${f}: declares ${s.voice_spaces.length} voice spaces but ${eng.file} has no VoiceSpace enum`
);
continue;
}
// An engine with no params of its own (NoOpEngine, engine_id "thru") maps
// nothing: the mode's outputs are MIDI CCs it emits itself, unshaped.
const allLinear: Curve[] = s.params.map(() => "linear");
const actual =
eng.nParams === 0
? [allLinear]
: eng.voiceSpaceNames !== null
? eng.curves
: [eng.curves[0]!];
if (eng.nParams !== 0 && eng.nParams !== s.params.length) {
problems.push(`${f}: ${s.params.length} params but ${eng.engineId} has kNParams = ${eng.nParams}`);
continue;
}
// (1) the declared table, from the JSON…
const declared = declaredCurves(s);
// …and independently from the generated TypeScript, so a codegen bug that
// drops or mis-indexes the table is caught too.
const ts = tsByModeId.get(s.mode_id);
if (!ts) {
problems.push(`${f}: no generated TypeScript schema for mode_id ${s.mode_id}`);
continue;
}
const nVs = Math.max(declared.length, 1);
for (let vs = 0; vs < nVs; vs++) {
const expect = actual.length === 1 ? actual[0]! : actual[vs]!;
for (let i = 0; i < s.params.length; i++) {
checkedSlots++;
const label = `${s.mode_id}[${vsName(s.voice_spaces[vs] ?? "-")}].${s.params[i]!.name} (slot ${i})`;
if (declared[vs]![i] !== expect[i]) {
problems.push(
`${label}: schema says ${declared[vs]![i]}, ${eng.file} applies ${expect[i]}`
);
}
const fromTs = effectiveCurve(ts, vs, i);
if (fromTs !== declared[vs]![i]) {
problems.push(
`${label}: generated TS says ${fromTs}, schemas/modes/${f} says ${declared[vs]![i]}`
);
}
}
}
checkedModes++;
}
if (problems.length > 0) {
console.error(`\ncurve drift: ${problems.length} problem(s)\n`);
for (const p of problems) console.error(` ${p}`);
console.error(
"\nThe schemas' `curve` fields are DESCRIPTIVE: they record what the\n" +
"engine already does. If an engine's arithmetic changed on purpose,\n" +
"update schemas/modes/*.json (params[].curve for the default, or the\n" +
"voice space's curve_overrides for a deviation) and re-run codegen.\n" +
"Do NOT change the engine to match the declaration.\n"
);
return 1;
}
console.log(
`curve drift: ok — ${checkedModes} modes, ${checkedSlots} (voice space x param) slots ` +
`cross-checked against nisps/engines/ source.`
);
return 0;
}
process.exit(run());