From eac1fad2e2d54163d845771bae29aa81b6d9f9a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:46:13 +0100 Subject: [PATCH 01/29] Keep each DSP core's peak and three readings a state in device:price (#2104) The price tool parsed the stats line's mean/peak pairs and kept only the means, from one 8-second reading per state. It now keeps each core's peak, takes three readings of the before, at-rest and in-use states by default (--readings), and records how far they spread. --key-bus live|silent records what the key bus carried. All new fields are optional, so older cpu-price.json records load unchanged; module:doctor names the spread. Co-authored-by: Claude Opus 5.5 --- changelog/2026-11-24-device-price-peaks.md | 1 + docs/TEST_PROCEDURE.md | 4 +- scripts/module-cpu-price.mjs | 15 +++- scripts/module-cpu-price.test.mjs | 13 ++- scripts/octatrack-price.mjs | 97 +++++++++++++++------- scripts/octatrack-price.test.mjs | 35 +++++++- 6 files changed, 129 insertions(+), 36 deletions(-) create mode 100644 changelog/2026-11-24-device-price-peaks.md diff --git a/changelog/2026-11-24-device-price-peaks.md b/changelog/2026-11-24-device-price-peaks.md new file mode 100644 index 0000000000..66e6ceb9f8 --- /dev/null +++ b/changelog/2026-11-24-device-price-peaks.md @@ -0,0 +1 @@ +Development: `npm run device:price` now keeps each DSP core's peak beside its mean and takes three readings of every state by default (`--readings`), so `evidence/cpu-price.json` records the worst block each core saw and how far the readings agreed (`spread`); `--key-bus live|silent` records what the key bus carried. Older records load unchanged, and `module:doctor` names the spread of a record that has one. diff --git a/docs/TEST_PROCEDURE.md b/docs/TEST_PROCEDURE.md index f93fc7ec9f..48f5ce4e04 100644 --- a/docs/TEST_PROCEDURE.md +++ b/docs/TEST_PROCEDURE.md @@ -52,7 +52,7 @@ Each step proves only what it ran. Steps 1 to 5 prove the code paths they exerci - **5.** Start `ot_emu` with `--usb-host SOCK` on a development twin of the base, from [the adapted emulator builder](../scripts/octatrack-emulator/build.py) (the plain port refused the trial with loader refusal 5, 20 November 2026). A ColdFire module needs no `--dsp`, which runs about ten times faster; give the base 20 s after the socket appears. Or run steps 6 to 10 there instead, through `npm run device:emulator` ([below](#one-set-of-cases-two-targets)). What passes here can still fail on the unit: read [what `ot_emu` does not show](OCTATRACK_HARDWARE_TRAPS.md#the-emulator-and-the-tools). Build the twin with `build_core.py --dev` and the beta flags; on main it links only with `--resident-stock-hooks --resident-on-demand` among them, and without them stops at "Core has unexpected unresolved imports" (the arena, bss and run symbols and the `ev_` hooks). This set linked on 21 November 2026: `--dsp-loader --dev --usb-midi --packaged-usb-audio --site-events --table-owners sdk/machines/octatrack/module-adapters/table-owners.json --resident-stock-hooks --resident-on-demand --cached-modules --module-sets --sample-editor --module-ui-roots --part-menu`, with `ELEKLOADER_DSP_ASM` naming `dsp_asm` in the `dsp56300` build tree and `dsp56kDisassemble` built beside it. - **6-10.** The unit steps go through the device commands and keep [the driving rules](OCTATRACK_DRIVING.md): a development base, transport stopped, a bank and Part whose working copy equals its saved one. Nothing is kept: every install is a trial that rolls back. The runner takes the unit for steps 6 to 10 as one turn of [the unit queue](OCTATRACK_DRIVING.md#taking-turns-on-the-unit) (`npm run unit -- run`), and the device commands inside it do not queue again; an emulator target takes no turn. - **8.** The fast seeded soak needs the MIDI bridge on the computer the unit is plugged into (`scripts/octatrack-midi-bridge.py`; outside Windows its Python needs `pip install mido python-rtmidi`, or the soak fails with no MIDI bridge on its port) and the project's MIDI receive settings ([A fast soak](OCTATRACK_DRIVING.md)). Its program changes select patterns: by default programs 0-3 (bank A) on channel 1, and the unit stays where the last one put it, so step 9 then prices that scene. Point them at the test scene and the project's channels with `--soak-programs 32-35 --soak-pc-channel 11` (`--soak-auto-channel` for the crossfader and scenes). A failure prints the seed and a log that replays it (`--replay FILE`). In a checkout without `scripts/octatrack-soak.mjs`, a module soaks inside step 7 (`device:test --soak 120`) instead. -- **9.** "At rest" is the module installed and used nowhere: what every player pays for having it. The figure is `device:price`'s at-rest reading: the share of the frame interrupt (`guard`, 8 s) the module adds while the selected pattern plays with sounding sample tracks, installed and used nowhere, against the same scene without it, on a development twin of the base it is released for. It is the one measure the limit is judged on: a machine's render price or a figure from another tool is not compared with it, and the record (`evidence/cpu-price.json`) names its base and scene. Above 0.2 points the module must rest: a machine does by itself, any other module answers `ev_in_use` and marks its frame detours `"rests"`, and `module:doctor` fails a release from 20 November 2026 that does neither (`AT_REST_LIMIT` and `AT_REST_FROM` in `scripts/module-cpu-price.mjs`, both the owner's to change). Judge both figures against [MODULE_PERFORMANCE.md](MODULE_PERFORMANCE.md); a base-bound package is left out, since a development twin does not trust it. An effect or a machine is then placed on one to four empty tracks for its instance curve, and picked alone on the empty pattern (`--pick-pattern`, 2) and the medium one (`--measure-pattern`, 1) after each has played: a refusal, a dropped render, a stall, or a first reading past 100 % of a frame fails the step, and a release from 24 November 2026 needs the same in its `evidence/frame-cost.json` ([what a release measures](MODULE_PERFORMANCE.md#measure-a-module)). The test bank therefore needs an empty pattern and a medium one (a trig every four steps on six tracks, two playing samples) with T1, T3, T6 and T7 free. The medium pattern is for admission, a pattern with room for the curve: a bank's medium pattern can read past 80 % with stock alone (Dev17 C04: 81 %), and a machine whose first instance costs 20 to 30 points then reads the overload (Amiga 0.3.1, SYNTIZ 0.1.0 and FM Synth 0.1.5 there). The tool does not start the curve when the pattern with the module at rest plus its booked first instance reaches 100 %, and says so: read the curve on a lighter pattern with `--measure-pattern` (one sample track, or none) and keep admission on the medium one with `--admission-pattern`. Each reading presses STOP before PLAY, and one the transport did not play through is refused and ends the run. +- **9.** "At rest" is the module installed and used nowhere: what every player pays for having it. The figure is `device:price`'s at-rest reading: the share of the frame interrupt (`guard`, three 8-s readings a state, `--readings`) the module adds while the selected pattern plays with sounding sample tracks, installed and used nowhere, against the same scene without it, on a development twin of the base it is released for. It is the one measure the limit is judged on: a machine's render price or a figure from another tool is not compared with it, and the record (`evidence/cpu-price.json`) names its base and scene. Above 0.2 points the module must rest: a machine does by itself, any other module answers `ev_in_use` and marks its frame detours `"rests"`, and `module:doctor` fails a release from 20 November 2026 that does neither (`AT_REST_LIMIT` and `AT_REST_FROM` in `scripts/module-cpu-price.mjs`, both the owner's to change). Judge both figures against [MODULE_PERFORMANCE.md](MODULE_PERFORMANCE.md); a base-bound package is left out, since a development twin does not trust it. An effect or a machine is then placed on one to four empty tracks for its instance curve, and picked alone on the empty pattern (`--pick-pattern`, 2) and the medium one (`--measure-pattern`, 1) after each has played: a refusal, a dropped render, a stall, or a first reading past 100 % of a frame fails the step, and a release from 24 November 2026 needs the same in its `evidence/frame-cost.json` ([what a release measures](MODULE_PERFORMANCE.md#measure-a-module)). The test bank therefore needs an empty pattern and a medium one (a trig every four steps on six tracks, two playing samples) with T1, T3, T6 and T7 free. The medium pattern is for admission, a pattern with room for the curve: a bank's medium pattern can read past 80 % with stock alone (Dev17 C04: 81 %), and a machine whose first instance costs 20 to 30 points then reads the overload (Amiga 0.3.1, SYNTIZ 0.1.0 and FM Synth 0.1.5 there). The tool does not start the curve when the pattern with the module at rest plus its booked first instance reaches 100 %, and says so: read the curve on a lighter pattern with `--measure-pattern` (one sample track, or none) and keep admission on the medium one with `--admission-pattern`. Each reading presses STOP before PLAY, and one the transport did not play through is refused and ends the run. - **11.** Reach every control and screen by the README's button steps and take a `png:` screenshot of each. Record MAIN and CUE over USB with a sustained sound and look for runs of exact zeros or a block played twice. Then Undo and check the inventory again ([/modwerk-test-on-unit](../.claude/skills/modwerk-test-on-unit/SKILL.md)). - **12.** The developer here is the submitter: the person whose agent ran steps 1 to 11, at their own unit, not a reviewer. Only after 1 to 11 passed on this build. Give the developer the button steps and what they should see or hear for each item the record lists: the sound, timing by ear, MIDI and scenes, two instances, Part and project reload, the Keep and the power cycle. On a contributor's unit the Keep, the power cycle, a flash and listening are theirs, and the agent asks for each run; on the owner's computer agents need no OK for trials, RAM boots of development builds or a Keep a test needs, and never ask him for a card, while flashing and power cycles stay his ([owner operations](OWNER_OPERATIONS.md)). A fault they find is fixed, and the procedure starts again on the new build. @@ -66,7 +66,7 @@ Every release of an Octatrack module proves these on a unit, on the version it s | --- | --- | --- | --- | | Idle | what it adds installed and used nowhere | `device:price --write` | `evidence/cpu-price.json` (`atRest`) | | Mean | its CPU price: the frame interrupt's share in use | `device:price --write`; a machine with `guard` (below) | `resources.cpuPrice` | -| DSP | both cores' load in use, for a module with DSP code | `device:price --write` | `evidence/cpu-price.json` (`inUse.dsp1to4`, `dsp5to8`) | +| DSP | both cores' load in use, for a module with DSP code | `device:price --write` | `evidence/cpu-price.json` (`inUse.dsp1to4`, `dsp5to8`, each core's peak `dsp1to4Peak`, `dsp5to8Peak`, and the readings' `spread`) | | Curve | the longest frame with 1 to 4 instances: `first`, `each`, `rest` | `device:price --write --curve` | `evidence/frame-cost.json` | | Admission | alone on an empty and on a medium pattern: admitted, then played with no dropped render and no stall | the same run | `evidence/frame-cost.json` (`admission`) | | Worst case | worst-case cycles, a stock benchmark and a stress run | `perf:audit` | `evidence/performance.json` | diff --git a/scripts/module-cpu-price.mjs b/scripts/module-cpu-price.mjs index 4cd045d07c..75484fadea 100644 --- a/scripts/module-cpu-price.mjs +++ b/scripts/module-cpu-price.mjs @@ -34,6 +34,17 @@ export function manifestWithoutPrice(text) { /** The price a device:price reading gives: the larger of what the module added at rest and in use, never below 0. */ export const measuredPrice = result => Math.max(0, result.atRestAdds.frame, result.inUseAdds?.frame ?? 0) +/** How far a device:price record's own readings agreed, for module:doctor: '' for a record of one reading a state (every record + * before 24 November 2026), else the count and the widest spread of the frame interrupt's share and of the slot core's DSP peak. */ +export function readingsNote(record) { + if (!(record?.readings > 1)) return '' + const states = ['before', 'atRest', 'inUse'].map(key => record.result?.[key]?.spread).filter(Boolean) + const widest = key => { const values = states.map(spread => spread[key]).filter(value => typeof value === 'number'); return values.length ? Math.max(...values) : null } + const frame = widest('frame'), track = Number(/^T(\d)/.exec(record.result?.inUseOn ?? '')?.[1]) + const peak = track ? widest(track <= 4 ? 'dsp1to4Peak' : 'dsp5to8Peak') : null + return '; ' + record.readings + ' readings a state' + (frame === null ? '' : ', the frame interrupt within ' + frame + ' points') + + (peak === null ? '' : ', the ' + (track <= 4 ? 'T1-4' : 'T5-8') + ' DSP peak within ' + peak) +} /** How to measure the price of a machine (true) or of any other module (false), for the messages. */ export function cpuPriceHowTo(id, machine) { @@ -147,8 +158,10 @@ export function cpuPriceStatus({ root, document, pending, glue = null }) { if (!declared) return { state: 'fail', detail: 'it names no CPU price (resources.cpuPrice)', fix: howTo } if (machine && declared.measure !== 'machine-render') return { state: 'fail', detail: 'it is a machine, so its price is what one playing track adds ("measure": "machine-render"), not ' + declared.measure, fix: howTo } if (!machine && declared.measure !== 'frame-interrupt') return { state: 'fail', detail: 'it is not a machine, so its price is the frame interrupt\'s share ("measure": "frame-interrupt"); only a machine\'s descriptor carries a render price', fix: howTo } + let repeat = '' if (declared.source.endsWith('.json')) { // a price device:price wrote: recomputed from its readings, never taken on trust const record = readJson(resolve(root, 'sdk/octatrack/modules', id, declared.source)) + repeat = readingsNote(record) if (record?.module !== id || !record.result?.atRestAdds) return { state: 'fail', detail: 'its price names ' + declared.source + ' as its source, which holds no device:price reading of ' + id, fix: howTo } // Tape Echo 0.1.9 carried the price read on 0.1.6: a release from RELEASE_COST_FROM measures its own. const date = releaseDate({ root, document }), logged = existsSync(resolve(root, 'src/community/module-changelogs', id + '.json')) @@ -168,7 +181,7 @@ export function cpuPriceStatus({ root, document, pending, glue = null }) { if (meter) return { state: 'fail', ...meter } const what = declared.value + ' % of a frame (' + declared.measure + ', ' + declared.tool + ', ' + declared.date + ')' const adds = document.resources.cpuMeter ? '; adds ' + document.resources.cpuMeter.value + ' meter points (reserved[1], ' + document.resources.cpuMeter.date + ')' : '' - return { state: 'ok', detail: what + (descriptors.length ? '; ' + descriptors.map(item => item.symbol).join(', ') + ' carries the same in reserved[0]' : '') + adds } + return { state: 'ok', detail: what + repeat + (descriptors.length ? '; ' + descriptors.map(item => item.symbol).join(', ') + ' carries the same in reserved[0]' : '') + adds } } /** The meter points a machine adds, recomputed from its paired readings: { added } or { problem }. */ diff --git a/scripts/module-cpu-price.test.mjs b/scripts/module-cpu-price.test.mjs index 45a6832fb3..acb25b4540 100644 --- a/scripts/module-cpu-price.test.mjs +++ b/scripts/module-cpu-price.test.mjs @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { parseModuleCpuMeter, parseModuleCpuPrice, parseModuleDocument } from '../src/catalog/module-contract.ts' -import { AT_REST_FROM, AT_REST_LIMIT, CPU_PRICE_PENDING_REASON, RELEASE_COST_FROM, curveProblem, FRAME_COST_FROM, FRAME_COST_RECORD, FRAME_COSTS_BASE_PATH, atRestStatus, frameCostStatus, generateFrameCosts, cReserved0, cpuPriceProblems, cpuPriceStatus, glueReserved0, machineDescriptors, parseCpuPricePending, portGlue, readCpuPricePending } from './module-cpu-price.mjs' +import { AT_REST_FROM, AT_REST_LIMIT, CPU_PRICE_PENDING_REASON, RELEASE_COST_FROM, curveProblem, FRAME_COST_FROM, FRAME_COST_RECORD, FRAME_COSTS_BASE_PATH, atRestStatus, frameCostStatus, generateFrameCosts, cReserved0, cpuPriceProblems, cpuPriceStatus, glueReserved0, machineDescriptors, parseCpuPricePending, portGlue, readCpuPricePending, readingsNote } from './module-cpu-price.mjs' const repo = fileURLToPath(new URL('../', import.meta.url)) const roots = [] @@ -67,6 +67,17 @@ describe('every Octatrack module names its CPU price', () => { expect(missing).toMatchObject({ state: 'fail', detail: expect.stringContaining('holds no device:price reading of other') }) }) + it('says how far a record of several readings a state agreed, and nothing for a record of one', () => { + const spread = (frame, dsp1to4Peak) => ({ spread: { frame, frameMax: 3, dsp1to4: 0.4, dsp1to4Peak, dsp5to8Peak: 9 } }) + const record = { module: 'echo', readings: 3, result: { atRestAdds: { frame: 0.2 }, inUseAdds: { frame: 1.3 }, inUseOn: 'T2 FX2', before: spread(0.3, 2.1), atRest: spread(0.6, 1.2), inUse: spread(0.4, 4.4) } } + expect(readingsNote(record)).toBe('; 3 readings a state, the frame interrupt within 0.6 points, the T1-4 DSP peak within 4.4') + expect(readingsNote({ ...record, result: { ...record.result, inUseOn: 'T6 FX1' } })).toMatch(/T5-8 DSP peak within 9$/) + expect(readingsNote({ module: 'echo', seconds: 8, result: { atRestAdds: { frame: 0 } } })).toBe('') + const root = fixture({ 'sdk/octatrack/modules/echo/evidence/cpu-price.json': record }) + expect(cpuPriceStatus({ root, document: module('echo', 'FX2', { ...share(1.3), source: 'evidence/cpu-price.json' }), pending: new Map(), glue: {} })) + .toMatchObject({ state: 'ok', detail: expect.stringContaining('3 readings a state, the frame interrupt within 0.6 points') }) + }) + it('takes a machine whose descriptor carries the price it names, literal or #define', () => { expect(cpuPriceStatus({ root: fixture(machineFolder('\n .reserved = {7},')), document: module('wave', 'Track machine', render(7)), pending: new Map(), glue: {} })).toMatchObject({ state: 'ok' }) expect(cpuPriceStatus({ root: fixture(machineFolder('\n .reserved = { WAVE_PRICE },')), document: module('wave', 'Track machine', render(9)), pending: new Map(), glue: {} })).toMatchObject({ state: 'ok' }) diff --git a/scripts/octatrack-price.mjs b/scripts/octatrack-price.mjs index c43cdc6682..90e8b2365e 100644 --- a/scripts/octatrack-price.mjs +++ b/scripts/octatrack-price.mjs @@ -3,7 +3,9 @@ // Copyright (c) 2026 Jannik Aßfalg (repeat98) // What a module costs an Octatrack, measured on a unit: the frame interrupt's share, the CPU meter and both DSPs, // before the module, with it installed but used nowhere (at rest), and for an effect on one slot (in use). -// npm run device:price -- [--memory] [--out FILE.json] [--base ID --scene TEXT] [--seconds 8] [--slot T1] [--fx-name ID=NAME…] ID|FILE.mwrm… (none: every USB package) +// npm run device:price -- [--memory] [--out FILE.json] [--base ID --scene TEXT] [--seconds 8] [--readings 3] [--key-bus live|silent] [--slot T1] [--fx-name ID=NAME…] ID|FILE.mwrm… (none: every USB package) +// Each state (before, at rest, in use) is --readings readings of --seconds: the record keeps their means, the highest longest +// frame and DSP peak, and each figure's spread. --key-bus says whether the scene plays into the key bus a key-bus effect reads. // --curve T1,T3,T6,T7 [--pick-pattern 2] [--measure-pattern 1] [--admission-pattern N] [--limit 125] [--write-costs]: what the longest frame gains with the module on // 1, 2, 3… of those empty tracks (machines) or their slots (effects), each picked on the empty pattern and read on the busy one, // and the next-instance cost from it (curveFit: `first`, then `each`); it stops at the first skipped render or past --limit % (lower it @@ -32,13 +34,32 @@ import { CPU_PRICE_PENDING_PATH, CPU_PRICE_RECORD, CURVE_ROOM, FRAME_COSTS_BASE_ import { takeUnitTurn } from './unit-queue.mjs' const mean = values => values.reduce((sum, value) => sum + value, 0) / values.length, tenth = value => Math.round(value * 10) / 10 -/** One reading from the session's `guard` line and `stats` lines: percent of a frame, percent of the meter, per mille of a DSP. */ +/** One reading from the session's `guard` line and `stats` lines: percent of a frame, percent of the meter, percent of a DSP. + * A `stats` line gives each core's mean and peak (status.c: the busiest frame of its last 1,024-frame window); the reading + * keeps the means' mean and the highest peak, since admission has to hold the worst block, not the average one. */ export function reading(text) { const guard = /frame max ([\d.]+) %, latest start ([\d.]+) %, in the frame interrupt ([\d.]+) % over (\d+) frames, skipped (\d+)/.exec(text) - const stats = [...text.matchAll(/stats cpu (\d+) T1-4 (\d+)\/\d+ T5-8 (\d+)\/\d+/g)] + const stats = [...text.matchAll(/stats cpu (\d+) T1-4 (\d+)\/(\d+) T5-8 (\d+)\/(\d+)/g)] if (!guard || !stats.length) throw new Error('No guard and stats reading in: ' + text.slice(0, 200)) + const meanOf = at => tenth(mean(stats.map(m => m[at] / 10))), peakOf = at => tenth(Math.max(...stats.map(m => m[at] / 10))) return { frame: Number(guard[3]), frameMax: Number(guard[1]), frames: Number(guard[4]), skipped: Number(guard[5]), - cpu: tenth(mean(stats.map(m => m[1] / 10))), dsp1to4: tenth(mean(stats.map(m => m[2] / 10))), dsp5to8: tenth(mean(stats.map(m => m[3] / 10))) } + cpu: meanOf(1), dsp1to4: meanOf(2), dsp5to8: meanOf(4), dsp1to4Peak: peakOf(3), dsp5to8Peak: peakOf(5) } +} +/** The figures a reading averages and the ones it keeps the highest of. */ +const MEANS = ['frame', 'cpu', 'dsp1to4', 'dsp5to8'], PEAKS = ['frameMax', 'dsp1to4Peak', 'dsp5to8Peak'] +/** Several readings of one state as one record: the means averaged, the peaks the highest any reading saw, `frames` summed, + * `skipped` and the allocation the last reading's (the guard counts skips since boot), and, from two readings on, `readings` + * and each figure's `spread` (highest less lowest), so a record shows how far its own readings agreed. One reading is + * returned as it is, as before 24 November 2026. */ +export function combined(readings) { + if (readings.length < 2) return readings[0] + const values = key => readings.map(item => item[key]).filter(value => typeof value === 'number') + const out = { ...readings.at(-1), frames: values('frames').reduce((sum, value) => sum + value, 0) } + for (const key of MEANS) if (values(key).length) out[key] = tenth(mean(values(key))) + for (const key of PEAKS) if (values(key).length) out[key] = Math.max(...values(key)) + out.readings = readings.length + out.spread = Object.fromEntries([...MEANS, ...PEAKS].filter(key => values(key).length).map(key => [key, tenth(Math.max(...values(key)) - Math.min(...values(key)))])) + return out } /** Tracked allocation only. The module pool and each DSP program arena have distinct units and capacities. */ export function allocationReading(text) { @@ -48,7 +69,6 @@ export function allocationReading(text) { if (!pool || !core1 || !core0) return { unavailable: 'The development base did not report the module pool and both DSP program arenas.' } return { modulePoolBytes: Number(pool[1]), dspProgramWordsT1to4: Number(core1[1]), dspProgramWordsT5to8: Number(core0[1]) } } -/** What the second reading added to the first, in points, one decimal. */ /** What went wrong with a pick, from the session's reply (device.mjs pick's errors), or null when the slot runs it. */ export const pickFailure = reply => /error|refused|not admitted|timed out/i.test(reply) ? reply.trim().split('\n').find(line => /error|refused|not admitted|timed out/i.test(line)).slice(0, 200) : null /** The session's `state` reply says the transport is stopped (device.mjs: "stopped" or "playing"). */ @@ -63,7 +83,15 @@ export function curveRoom({ atRest, booked, pattern }) { return atRest + booked < CURVE_ROOM ? null : `no room on pattern ${pattern}: it reads ${atRest} % with the module at rest, and its booked first instance ` + `${booked} would take it to ${tenth(atRest + booked)} %, past ${CURVE_ROOM} %. Pick a pattern with room with --measure-pattern (fewer sample tracks)` } -export const added = (before, after) => Object.fromEntries(['frame', 'cpu', 'dsp1to4', 'dsp5to8'].map(key => [key, tenth(after[key] - before[key])])) +/** What the second reading added to the first, in points, one decimal: the means, and each core's peak where both have one + * (a reading taken before 24 November 2026 kept no peak). */ +export const added = (before, after) => Object.fromEntries([...MEANS, 'dsp1to4Peak', 'dsp5to8Peak'] + .filter(key => typeof before[key] === 'number' && typeof after[key] === 'number').map(key => [key, tenth(after[key] - before[key])])) +/** What the record says played: device:price reads with the sequencer playing; the key bus's input only when the caller named it. */ +export function priceInputs(keyBus) { + if (keyBus !== undefined && !['live', 'silent'].includes(keyBus)) throw new Error('--key-bus takes live (the scene plays into the key bus) or silent') + return keyBus ? { transport: 'playing', keyBus } : { transport: 'playing' } +} /** A file trial uses the package header for its name and slots (loader.c). Its runtime id * also identifies a published module when the filename is a version or was renamed. */ @@ -78,6 +106,9 @@ export function priceFileTarget(file, data, catalogue) { } const OVERLOAD = 125 // percent of a frame: no skips up to ~115 on an MKII, drops from ~120 (22 Nov 2026) +/** Readings a state by default (--readings): one 8-s reading could not tell a module's cost from the scene's own scatter + * (±2.5 points of the longest frame between two readings, REST_NOISE below), and its spread now says how far they agree. */ +export const READINGS = 3 /** What a module adds to the longest frame while installed on no track or slot (its `rest`), in percent: the reading * installed less the one before it. Under REST_NOISE it is the readings' own scatter (±2.5 between two 8-s readings of one * scene on the owner's MKII, 22 November 2026) and counts 0, since the base adds every installed module's rest to the @@ -104,7 +135,7 @@ export const machinePick = (track, row = 5) => `NO w200 ${track} w300 ${track} $ export const machineToStatic = track => `NO w200 ${track} w300 ${track} ${track} w500 LEFT w400 UP*12 w200 YES w800 NO w300` /** --write for one module's result: its price into its manifest, its readings beside it, its line off the pending list. What it did. */ -export function writePrice({ root, result, base, scene, seconds, measuredAt }) { +export function writePrice({ root, result, base, scene, seconds, measuredAt, readings = 1, inputs }) { const id = result.id, folder = resolve(root, 'sdk/octatrack/modules', id), manifest = resolve(folder, 'octamod.module.json') if (!existsSync(manifest)) return 'not written: no sdk/octatrack/modules/' + id if (result.refused || !result.rolledBack || result.restore || result.inUseError || result.notPlayed || !result.atRestAdds) return 'not written: the run was not clean' @@ -112,12 +143,12 @@ export function writePrice({ root, result, base, scene, seconds, measuredAt }) { if (document.compatibility?.location === 'Track machine' || machineDescriptors({ root, id }).length) return 'not written: a machine\'s price is what one playing track adds ("machine-render"), read on a track (docs/MODULE_PERFORMANCE.md)' if (document.compatibility?.effectId != null && !result.inUseAdds) return 'not written: an effect is priced on a slot too, and this run has no reading on one' if (result.version !== 'file' && result.version !== document.version) return 'not written: this measured the published ' + result.version + ' but the manifest is ' + document.version + '; measure the new build\'s .mwrm' - const record = { module: id, version: document.version, base, scene, seconds, measuredAt, result } + const record = { module: id, version: document.version, base, scene, ...(inputs ? { inputs } : {}), seconds, ...(readings > 1 ? { readings } : {}), measuredAt, result } mkdirSync(dirname(resolve(folder, CPU_PRICE_RECORD)), { recursive: true }) writeFileSync(resolve(folder, CPU_PRICE_RECORD), JSON.stringify(record, null, 2) + '\n') const { before, atRest, inUse } = result document.resources.cpuPrice = { value: measuredPrice(result), unit: 'percent-of-frame', measure: 'frame-interrupt', tool: 'npm run device:price -- --write', date: measuredAt.slice(0, 10), - conditions: (scene + '; base ' + base + '; ' + seconds + ' s per reading. Frame interrupt ' + before.frame + ' % before, ' + atRest.frame + ' % installed and used nowhere' + (inUse ? ', ' + inUse.frame + ' % on ' + result.inUseOn : '') + + conditions: (scene + '; base ' + base + '; ' + (readings > 1 ? readings + ' readings of ' + seconds + ' s a state' : seconds + ' s per reading') + '. Frame interrupt ' + before.frame + ' % before, ' + atRest.frame + ' % installed and used nowhere' + (inUse ? ', ' + inUse.frame + ' % on ' + result.inUseOn : '') + '; CPU meter ' + before.cpu + ' % before, ' + atRest.cpu + ' % at rest' + (inUse ? ', ' + inUse.cpu + ' % in use' : '') + '.').slice(0, 1000), source: CPU_PRICE_RECORD } // shortcut: a hand-formatted manifest (an object on one line) comes back as plain two-space JSON; keep it if review asks. @@ -132,10 +163,13 @@ export function writePrice({ root, result, base, scene, seconds, measuredAt }) { if (import.meta.filename === process.argv[1]) { const { values: args, positionals } = parseArgs({ allowPositionals: true, options: { out: { type: 'string' }, seconds: { type: 'string', default: '8' }, slot: { type: 'string', default: 'T1' }, 'fx-name': { type: 'string', multiple: true }, base: { type: 'string' }, scene: { type: 'string' }, write: { type: 'boolean' }, memory: { type: 'boolean' }, - curve: { type: 'string' }, 'pick-pattern': { type: 'string', default: '2' }, 'measure-pattern': { type: 'string', default: '1' }, 'admission-pattern': { type: 'string' }, limit: { type: 'string', default: String(OVERLOAD) }, 'write-costs': { type: 'boolean' }, stock: { type: 'boolean' }, socket: { type: 'string', default: process.env.MODWERK_DEV_SOCKET ?? '/tmp/modwerk-dev.sock' }, share: { type: 'string', default: '/tmp/modwerk-share.sock' } } }) + curve: { type: 'string' }, 'pick-pattern': { type: 'string', default: '2' }, 'measure-pattern': { type: 'string', default: '1' }, 'admission-pattern': { type: 'string' }, limit: { type: 'string', default: String(OVERLOAD) }, 'write-costs': { type: 'boolean' }, stock: { type: 'boolean' }, socket: { type: 'string', default: process.env.MODWERK_DEV_SOCKET ?? '/tmp/modwerk-dev.sock' }, share: { type: 'string', default: '/tmp/modwerk-share.sock' }, + readings: { type: 'string', default: String(READINGS) }, 'key-bus': { type: 'string' } } }) // Admission is judged on the bank's medium pattern, the curve read on one with room (owner, 23 November 2026): by default the same. const admissionPattern = args['admission-pattern'] ?? args['measure-pattern'] const root = resolve(import.meta.dirname, '..'), seconds = Number(args.seconds), measuredAt = new Date().toISOString() + const readings = Number(args.readings), inputs = priceInputs(args['key-bus']) + if (!Number.isInteger(readings) || readings < 1 || readings > 9) throw new Error('--readings takes 1 to 9 readings a state') const fxNames = new Map((args['fx-name'] ?? []).map(pair => { const at = pair.indexOf('='); if (at < 1) throw new Error('--fx-name takes ID=NAME, the name the FX chooser shows'); return [pair.slice(0, at), pair.slice(at + 1)] })) if ((args.write || args['write-costs']) && !(args.base && args.scene)) throw new Error('--write and --write-costs need --base and --scene: the price names the base and what played (model, project, pattern)') if (args['write-costs'] && !args.curve && !args.stock) throw new Error('--write-costs writes a curve (--curve T1,T3,T6,T7) or the stock reserve (--stock)') @@ -153,23 +187,30 @@ if (import.meta.filename === process.argv[1]) { : catalogue.filter(row => !row.requiredBase) // All the readings are one turn on the unit (scripts/unit-queue.mjs); the trials below run inside it. await takeUnitTurn({ note: 'device:price ' + chosen.map(row => row.id).join(' ').slice(0, 100), command: 'npm run device:price -- ' + process.argv.slice(2).join(' ').slice(0, 300), - expectMs: Math.max(10, 3 * chosen.length) * 60000 }) + expectMs: Math.max(10, (2 + readings) * chosen.length) * 60000 }) const wait = ms => new Promise(done => setTimeout(done, ms)) const send = line => new Promise((done, fail) => { // one line to the session, its whole reply let reply = ''; const socket = connect(args.socket, () => socket.write(line + '\n')) socket.setTimeout(30000, () => socket.destroy(new Error('The session did not answer "' + line + '" in 30 s.'))) socket.on('data', chunk => { reply += chunk }).on('end', () => done(reply)).on('error', fail) }) - const measure = async () => { // playing: a new guard window, then its mean beside three meter readings - // STOP first: PLAY on a unit that is already playing pauses it, and that reading would be the stopped frame (frame 24 %, - // longest 32 % where the pattern plays at 75 %: the first module of a run read a false rest of 13 to 18, 23 November 2026). - await send('STOP w500 PLAY w2000 guard') - let text = '', stopped = 0 - for (let i = 0; i < 3; i++) { await wait(seconds * 1000 / 3); text += await send('stats'); if (!notPlaying(await send('state'))) continue; stopped++ } - const text2 = await send('guard') - await send('STOP w500') - if (stopped) throw new NotPlayed(`the transport was stopped at ${stopped} of 3 checks during a reading, so it measured no pattern: nothing was priced`) - const load = reading(text2 + text) + // `count` readings of one state (--readings for the before, at-rest and in-use states; the curve, the admission runs and + // --stock take one a point). Each is STOP, PLAY, a new guard window, a meter reading about every second, the window, STOP. + // STOP first: PLAY on a unit that is already playing pauses it, and that reading would be the stopped frame (frame 24 %, + // longest 32 % where the pattern plays at 75 %: the first module of a run read a false rest of 13 to 18, 23 November 2026). + const measure = async (count = 1) => { + const taken = [] + for (let n = 0; n < count; n++) { + await send('STOP w500 PLAY w2000 guard') + let text = '', stopped = 0 + const samples = Math.max(3, Math.round(seconds)) + for (let i = 0; i < samples; i++) { await wait(seconds * 1000 / samples); text += await send('stats'); if (notPlaying(await send('state'))) stopped++ } + const text2 = await send('guard') + await send('STOP w500') + if (stopped) throw new NotPlayed(`the transport was stopped at ${stopped} of ${samples} checks during a reading, so it measured no pattern: nothing was priced`) + taken.push(reading(text2 + text)) + } + const load = combined(taken) if (!args.memory) return load try { return { ...load, allocation: allocationReading(await send('memory')) } @@ -293,7 +334,7 @@ if (import.meta.filename === process.argv[1]) { const packagePath = row.file ?? resolve(root, 'public', row.path) const packageSha256 = createHash('sha256').update(readFileSync(packagePath)).digest('hex') if (row.sha256 && packageSha256 !== row.sha256) throw new Error('Package SHA-256 differs from the release catalogue for ' + row.id) - const trigs = await patternTrigs(), before = await measure(), result = { id: row.id, version: row.version, packageSha256, before } + const trigs = await patternTrigs(), before = await measure(readings), result = { id: row.id, version: row.version, packageSha256, before } const trial = spawn(process.execPath, [resolve(root, 'scripts/device.mjs'), 'try', packagePath, '--seconds', '600', '--socket', args.share]) let log = ''; trial.stdout.on('data', chunk => { log += chunk }); trial.stderr.on('data', chunk => { log += chunk }) const ended = new Promise(done => trial.on('exit', done)) @@ -310,7 +351,7 @@ if (import.meta.filename === process.argv[1]) { } if (!result.refused) try { await wait(2000) - result.atRest = await measure(); result.atRestAdds = added(before, result.atRest) + result.atRest = await measure(readings); result.atRestAdds = added(before, result.atRest) const fx = { fx1: '1', fx2: '2', both: '2' }[row.slots] if (fx) try { // an effect: on the slot, measured, and the slot's own effect picked back const was = (await slotNames())[Number(fx)] @@ -319,7 +360,7 @@ if (import.meta.filename === process.argv[1]) { // package "SC Ringmod"): --fx-name ID=NAME names it. A pick that fails must not be measured as the effect in use. const name = fxNames.get(row.id) ?? row.name, failed = pickFailure(await send(`pick:${args.slot}:FX${fx}:${name.replaceAll(' ', '_')}`)) if (failed) throw new Error('picking ' + name + ': ' + failed) - result.inUse = await measure(); result.inUseAdds = added(before, result.inUse); result.inUseOn = args.slot + ' FX' + fx + result.inUse = await measure(readings); result.inUseAdds = added(before, result.inUse); result.inUseOn = args.slot + ' FX' + fx const back = await send(`pick:${args.slot}:FX${fx}:${was.replaceAll(' ', '_')}`) if (/error|refus|timed out/i.test(back)) result.restore = 'picking ' + was + ' back: ' + back.trim().slice(0, 120) } catch (error) { result.inUseError = error.message.slice(0, 200) } @@ -340,16 +381,16 @@ if (import.meta.filename === process.argv[1]) { ', which its rollback left: clear them (or reload the project without saving) and measure it on a scratch pattern' results.push(result) // Written after every module: a unit that hangs on the next one must not take the finished readings with it. - if (args.out) writeFileSync(args.out, JSON.stringify({ base: args.base, scene: args.scene, seconds, slot: args.slot, measuredAt, results }, null, 1) + '\n') + if (args.out) writeFileSync(args.out, JSON.stringify({ base: args.base, scene: args.scene, inputs, seconds, readings, slot: args.slot, measuredAt, results }, null, 1) + '\n') const signed = value => (value >= 0 ? '+' : '') + value if (result.notPlayed) console.log(row.id.padEnd(28) + 'NOT MEASURED: ' + result.notPlayed + '. Stopped; check that the pattern plays (npm run device -- state) and run it again') else console.log(row.id.padEnd(28) + (result.refused ? 'not installed: ' + result.refused : `at rest frame ${signed(result.atRestAdds.frame)}, cpu ${signed(result.atRestAdds.cpu)}` + - (result.inUseAdds ? `; in use frame ${signed(result.inUseAdds.frame)}, cpu ${signed(result.inUseAdds.cpu)}, DSP ${signed(result.inUseAdds.dsp1to4)}/${signed(result.inUseAdds.dsp5to8)}` : '') + (result.inUseError ? '; in use: ' + result.inUseError : '') + + (result.inUseAdds ? `; in use frame ${signed(result.inUseAdds.frame)}, cpu ${signed(result.inUseAdds.cpu)}, DSP ${signed(result.inUseAdds.dsp1to4)}/${signed(result.inUseAdds.dsp5to8)}` + (result.inUseAdds.dsp1to4Peak === undefined ? '' : ` (peak ${signed(result.inUseAdds.dsp1to4Peak)}/${signed(result.inUseAdds.dsp5to8Peak)})`) : '') + (result.inUseError ? '; in use: ' + result.inUseError : '') + (result.restore ? '; ' + result.restore : '') + (result.rolledBack ? '' : '; THE TRIAL DID NOT ROLL BACK: stop and look'))) if (!result.rolledBack || result.restore || result.notPlayed) break // never go on over a unit left in a state nobody chose } - if (args.out) writeFileSync(args.out, JSON.stringify({ base: args.base, scene: args.scene, seconds, slot: args.slot, measuredAt, results }, null, 1) + '\n') - if (args.write) for (const result of results) console.log(result.id.padEnd(28) + writePrice({ root, result, base: args.base, scene: args.scene, seconds, measuredAt })) + if (args.out) writeFileSync(args.out, JSON.stringify({ base: args.base, scene: args.scene, inputs, seconds, readings, slot: args.slot, measuredAt, results }, null, 1) + '\n') + if (args.write) for (const result of results) console.log(result.id.padEnd(28) + writePrice({ root, result, base: args.base, scene: args.scene, seconds, measuredAt, readings, inputs })) for (const result of results.filter(result => result.curve && !result.curve.error)) { const { first, each, adds, tracks, notes } = result.curve, wanted = args.curve.split(',').length const rest = restCost(result.before, result.atRest) diff --git a/scripts/octatrack-price.test.mjs b/scripts/octatrack-price.test.mjs index d57153d3d3..69b3d6b65a 100644 --- a/scripts/octatrack-price.test.mjs +++ b/scripts/octatrack-price.test.mjs @@ -2,7 +2,7 @@ // Copyright (c) 2026 Jannik Aßfalg (repeat98) import { expect, it } from 'vitest' import { createHash } from 'node:crypto' -import { added, allocationReading, curveFit, curveRoom, notPlaying, restCost, REST_NOISE, machinePick, stockFit, machineToStatic, pickFailure, priceFileTarget, reading, writePrice } from './octatrack-price.mjs' +import { added, allocationReading, combined, curveFit, curveRoom, notPlaying, priceInputs, restCost, REST_NOISE, machinePick, stockFit, machineToStatic, pickFailure, priceFileTarget, reading, writePrice } from './octatrack-price.mjs' function runtimeEffect(slots) { const data = Buffer.alloc(76) @@ -33,13 +33,36 @@ it('finds a published package by runtime id even when its file is named after th it('reads the guard window and the mean of the meter readings, and what a module added', () => { const guard = share => `frame max 112.2 %, latest start 12.2 %, in the frame interrupt ${share} % over 22000 frames, skipped 2 on T1 T3, share 80.0 %\n` - const before = reading(guard('41.1') + 'stats cpu 640 T1-4 328/338 T5-8 419/420 passes 1.0 2.0\nstats cpu 660 T1-4 330/338 T5-8 419/420 passes 1.0 2.0\n') - expect(before).toEqual({ frame: 41.1, frameMax: 112.2, frames: 22000, skipped: 2, cpu: 65, dsp1to4: 32.9, dsp5to8: 41.9 }) + const before = reading(guard('41.1') + 'stats cpu 640 T1-4 328/338 T5-8 419/420 passes 1.0 2.0\nstats cpu 660 T1-4 330/352 T5-8 419/420 passes 1.0 2.0\n') + expect(before).toEqual({ frame: 41.1, frameMax: 112.2, frames: 22000, skipped: 2, cpu: 65, dsp1to4: 32.9, dsp5to8: 41.9, dsp1to4Peak: 35.2, dsp5to8Peak: 42 }) const after = reading(guard('64.5') + 'stats cpu 750 T1-4 428/438 T5-8 419/420 passes 1.0 2.0\n') - expect(added(before, after)).toEqual({ frame: 23.4, cpu: 10, dsp1to4: 9.9, dsp5to8: 0 }) + expect(added(before, after)).toEqual({ frame: 23.4, cpu: 10, dsp1to4: 9.9, dsp5to8: 0, dsp1to4Peak: 8.6, dsp5to8Peak: 0 }) expect(() => reading('stats cpu 1 T1-4 1/1 T5-8 1/1')).toThrow('No guard') }) +it('keeps no peak in what a module added when the reading before it kept none (a record from before the peaks)', () => { + const old = { frame: 41, frameMax: 74.2, cpu: 60.5, dsp1to4: 38.4, dsp5to8: 45.6 } + expect(added(old, { ...old, dsp1to4: 45.9, dsp1to4Peak: 50, dsp5to8Peak: 47 })).toEqual({ frame: 0, cpu: 0, dsp1to4: 7.5, dsp5to8: 0 }) +}) + +it('takes several readings of one state as one: means averaged, peaks the highest, and how far they spread', () => { + const one = (frame, frameMax, dsp1to4, dsp1to4Peak, skipped) => ({ frame, frameMax, frames: 22000, skipped, cpu: 60, dsp1to4, dsp5to8: 40, dsp1to4Peak, dsp5to8Peak: 44 }) + const a = one(41, 74.2, 45.9, 52.1, 0) + expect(combined([a])).toBe(a) // one reading is the record it always was: no count, no spread + expect(combined([a, one(41.4, 76.9, 46.3, 58.4, 0), one(40.9, 75, 45.6, 51, 1)])).toEqual({ + frame: 41.1, frameMax: 76.9, frames: 66000, skipped: 1, cpu: 60, dsp1to4: 45.9, dsp5to8: 40, dsp1to4Peak: 58.4, dsp5to8Peak: 44, + readings: 3, spread: { frame: 0.5, cpu: 0, dsp1to4: 0.7, dsp5to8: 0, frameMax: 2.7, dsp1to4Peak: 7.4, dsp5to8Peak: 0 }, + }) + const allocation = { modulePoolBytes: 0, dspProgramWordsT1to4: 1, dspProgramWordsT5to8: 2 } + expect(combined([a, { ...a, allocation }]).allocation).toEqual(allocation) // the last reading's, read after them +}) + +it('records what played: the transport always, the key bus only when the caller says', () => { + expect(priceInputs(undefined)).toEqual({ transport: 'playing' }) + expect(priceInputs('live')).toEqual({ transport: 'playing', keyBus: 'live' }) + expect(() => priceInputs('on')).toThrow(/--key-bus takes live/) +}) + it('records the module pool and each DSP program arena in their own units', () => { const report = [ 'pool: 128 of 10912 bytes used; free 10784, largest free run 10784 (100 % of free)', @@ -76,6 +99,10 @@ it('writes a clean reading as the module\'s price, its readings beside it, and t expect(price.conditions).toBe('MKII, bank C pattern C01; base 945cc074; 8 s per reading. Frame interrupt 30.1 % before, 30.3 % installed and used nowhere, 31.4 % on T1 FX2; CPU meter 50 % before, 50.2 % at rest, 51 % in use.') expect(JSON.parse(readFileSync(join(root, 'sdk/octatrack/modules/echo/evidence/cpu-price.json'), 'utf8'))).toMatchObject({ module: 'echo', version: '0.2.0', base: '945cc074', result: { inUseAdds: { frame: 1.3 } } }) expect(JSON.parse(readFileSync(join(root, 'sdk/module-cpu-prices-pending.json'), 'utf8')).pending).toEqual({ other: 'price not yet measured' }) + // Three readings a state and a named key bus: the record says so, and so do the price's conditions. + expect(writePrice({ root, result, base: '945cc074', scene: 'MKII, bank C pattern C01', seconds: 8, measuredAt: '2026-11-24T10:00:00.000Z', readings: 3, inputs: priceInputs('live') })).toMatch(/1.3 % of a frame/) + expect(JSON.parse(readFileSync(manifest, 'utf8')).resources.cpuPrice.conditions).toMatch(/^MKII, bank C pattern C01; base 945cc074; 3 readings of 8 s a state\. Frame interrupt 30.1 % before/) + expect(JSON.parse(readFileSync(join(root, 'sdk/octatrack/modules/echo/evidence/cpu-price.json'), 'utf8'))).toMatchObject({ readings: 3, inputs: { transport: 'playing', keyBus: 'live' }, seconds: 8 }) writeFileSync(manifest, JSON.stringify({ id: 'echo', version: '0.2.0', compatibility: { location: 'Track machine' }, resources: {} })) expect(write({})).toMatch(/machine-render/) } finally { rmSync(root, { recursive: true, force: true }) } From 5eaf5921e75a55ae7eadaefae06a859a861811bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:51:08 +0100 Subject: [PATCH 02/29] Compare only like cases in cycle-scan unit and generate its README table (#2106) cycle-scan unit paired readings taken on base 0.7.8 twins with the key-bus charge timed on a later base, and a scan whose key bus is silent with readings where the key bus carried a kick, then called the gap an outlier. Each side now carries its case (package, setting, transport, key-bus input for a key-bus reader, the base a base charge was timed on); a mismatch prints "not comparable" with the reason and no ratio. Where a reading kept a DSP peak, it is compared with the dearest setting. The README table still charged the key bus 51 after dsp-sites.json moved to 43. It is now written by unit --write between markers, and cycle-scan check fails when the committed table differs. Co-authored-by: Claude Opus 5.5 --- changelog/2026-11-24-cycle-scan-like-cases.md | 1 + scripts/cycle-scan.mjs | 133 ++++++++++++++---- scripts/cycle-scan.test.mjs | 69 ++++++++- sdk/cycle-scan/README.md | 65 +++++---- 4 files changed, 213 insertions(+), 55 deletions(-) create mode 100644 changelog/2026-11-24-cycle-scan-like-cases.md diff --git a/changelog/2026-11-24-cycle-scan-like-cases.md b/changelog/2026-11-24-cycle-scan-like-cases.md new file mode 100644 index 0000000000..68b2d81591 --- /dev/null +++ b/changelog/2026-11-24-cycle-scan-like-cases.md @@ -0,0 +1 @@ +Development: `node scripts/cycle-scan.mjs unit` compares a unit reading with the scan's model only when both are the same case (package, setting, transport, what the key bus carried for a key-bus effect, and the base a base charge was timed on), and prints "not comparable" with the reason otherwise; it compares a reading's DSP peak, where it kept one, with the dearest setting. The table in `sdk/cycle-scan/README.md` is now written by `unit --write`, and `cycle-scan check` fails when it differs (it still charged the key bus 51 after the charge became 43). diff --git a/scripts/cycle-scan.mjs b/scripts/cycle-scan.mjs index 8666900e06..55b3704d81 100644 --- a/scripts/cycle-scan.mjs +++ b/scripts/cycle-scan.mjs @@ -4,7 +4,8 @@ // // node scripts/cycle-scan.mjs record [ ...] # on your computer: scan each Octatrack module, write its record // node scripts/cycle-scan.mjs check # anywhere, CI included: judge every committed record -// node scripts/cycle-scan.mjs unit [--markdown] # anywhere: the records against the unit's in-use readings (report only) +// node scripts/cycle-scan.mjs unit [--markdown|--write] # anywhere: the records against the unit's in-use readings (report only; +// # --write puts the table into sdk/cycle-scan/README.md, which check holds to it) // // `record` runs sdk/cycle-scan/interlock_scan.py --sweep on the module and on the stock effect its performance.json compares // it with, and writes sdk/cycle-scan/records/.json: the dearest setting's instructions, cycles and stalls a sample, @@ -62,52 +63,125 @@ export function atSetting(report, setting) { return { setting, instructions: round(run.instr), cycles: round(run.cycles), stalls: round(run.stall) } } -/** The meter points an in-use reading added on the core of the slot it was taken on (T1-T4 core 1, T5-T8 core 0). */ +/** The meter points an in-use reading added on the core of the slot it was taken on (T1-T4 core 1, T5-T8 core 0): the mean, + * and the peak, the core's busiest block, which device:price keeps from 24 November 2026 (null in an older record). */ export function inUsePoints(result) { const track = Number(/^T(\d)/.exec(result?.inUseOn ?? '')?.[1]) if (!result?.inUseAdds || !track) return null - return { on: result.inUseOn, points: track <= 4 ? result.inUseAdds.dsp1to4 : result.inUseAdds.dsp5to8 } + const core = track <= 4 ? 'dsp1to4' : 'dsp5to8', peak = result.inUseAdds[core + 'Peak'] + return { on: result.inUseOn, points: result.inUseAdds[core], peak: typeof peak === 'number' ? peak : null } } -/** One module's line of the unit report: its cpu-price.json in-use reading against the record's model at the same - * setting (the defaults, where a fresh pick starts), plus what the base charges for features its package requires, - * which run outside the effect's proc and so outside the scan. `price` is evidence/cpu-price.json or null; `extra` - * [{name, cycles}]. */ -export function unitLine({ id, record, price, extra = [] }) { +/** The base identities a text names: each hex run of eight or more digits, cut to eight ("development twin d3d71297 of base + * 0.7.8 (main 02dfa20ca)" names d3d71297 and 02dfa20c). */ +export const identities = text => (String(text ?? '').match(/\b[0-9a-f]{8,}\b/g) ?? []).map(id => id.slice(0, 8)) + +/** The case a cycle-scan record models: the version and the published package it covers (the package row of that version), + * the setting, and what plays. dsp_host runs the proc block after block, as a playing unit does, and feeds no key bus, so a + * key-bus effect is scanned with its key bus silent. `keyBus` says whether the module reads the key bus at all. */ +export function scanCase({ record, row, keyBus = false }) { + return { version: record.version, package: row?.version === record.version ? row.sha256 ?? null : null, setting: record.defaults?.setting ?? null, + transport: 'playing', keyBus: keyBus ? record.inputs?.keyBus ?? 'silent' : null } +} + +/** The case a device:price reading measured (evidence/cpu-price.json): the version and package, the setting (a fresh pick + * starts at the defaults), what played (`inputs`, recorded from 24 November 2026: the transport always, the key bus when the + * caller named it; device:price always reads playing) and the base it ran on. */ +export function unitCase({ price, record, keyBus = false }) { + return { version: price.version, package: price.result?.packageSha256 ?? null, setting: price.result?.setting ?? record.defaults?.setting ?? null, + transport: price.inputs?.transport ?? 'playing', keyBus: keyBus ? price.inputs?.keyBus ?? 'not stated' : null, base: price.base ?? null } +} + +/** Why a reading and a model are not the same case: [] when they are. `extra` is the base charges added to the model, each + * with the base identities it was timed on (`bases`): a reading on another base ran another build of that base code. */ +export function notComparable(scan, unit, extra = []) { + const why = [] + if (scan.package && unit.package && scan.package !== unit.package) + why.push(`the unit measured package ${unit.package.slice(0, 8)}, not the published ${scan.version} (${scan.package.slice(0, 8)})`) + if (scan.setting !== unit.setting) why.push(`the unit read it at ${unit.setting}, the model is at ${scan.setting}`) + if (scan.transport !== unit.transport) why.push(`the unit read with the sequencer ${unit.transport}, the scan runs every block`) + if (scan.keyBus !== unit.keyBus) why.push(unit.keyBus === 'not stated' + ? `the reading does not say what its key bus carried, the scan's was ${scan.keyBus}` + : `its key bus was ${unit.keyBus} on the unit and ${scan.keyBus} in the scan`) + const seen = identities(unit.base) + for (const charge of extra) if (charge.bases?.length && !charge.bases.some(id => seen.includes(id))) + why.push(`the unit read on ${seen[0] ?? (unit.base || 'an unnamed base')}, the ${charge.name} charge (${charge.cycles}) was timed on ${charge.bases[0]}`) + return why +} + +/** One module's line of the unit report: its cpu-price.json in-use reading against the record's model, only where both are + * the same case (notComparable); else the line says why not and gives no ratio. The mean is compared with the model at the + * defaults (where a fresh pick starts), the peak, where the reading kept one, with the dearest setting, which bounds every + * setting. Both add what the base charges for features the package requires, which run outside the effect's proc and so + * outside the scan. `price` is evidence/cpu-price.json or null; `extra` [{name, cycles, bases?}]; `row` the USB package row. */ +export function unitLine({ id, record, price, extra = [], row, keyBus = false }) { const line = { id, version: record.version, modelDefaults: record.defaults?.cycles ?? null, modelDearest: record.dearest.cycles, - setting: record.defaults?.setting ?? null, outside: extra, notes: [] } + setting: record.defaults?.setting ?? null, outside: extra.map(({ name, cycles }) => ({ name, cycles })), notes: [] } const reading = inUsePoints(price?.result) if (!reading) { line.notes.push('no in-use reading on the unit'); return line } if (price.version !== record.version) { line.notes.push(`the unit reading is for ${price.version}, the record for ${record.version}`); return line } Object.assign(line, { on: reading.on, points: reading.points, unit: round(reading.points * POINT), base: price.base, measuredAt: price.measuredAt }) + if (reading.peak != null) Object.assign(line, { peak: reading.peak, unitPeak: round(reading.peak * POINT) }) if (line.modelDefaults == null) { line.notes.push('the record keeps no defaults run: record it again'); return line } - line.model = round(line.modelDefaults + extra.reduce((sum, e) => sum + e.cycles, 0)) + const charges = extra.reduce((sum, e) => sum + e.cycles, 0) + line.model = round(line.modelDefaults + charges) + const why = notComparable(scanCase({ record, row, keyBus }), unitCase({ price, record, keyBus }), extra) + if (why.length) { line.notComparable = why; return line } line.ratio = round(line.unit / line.model) if (Math.abs(line.unit / line.model - 1) > OUTLIER) line.outlier = true + if (line.unitPeak != null) { + line.modelPeak = round(line.modelDearest + charges) + line.peakRatio = round(line.unitPeak / line.modelPeak) + if (line.unitPeak > line.modelPeak * (1 + OUTLIER)) line.peakAbove = true + } return line } /** Every record against the unit's in-use readings, and the scanned modules that lack one. */ export function unitReport(base = root) { const dir = join(base, RECORDS), packages = readJson(join(base, 'src/engine/assets/octatrack-module-packages.json')).packages - const features = readJson(join(base, 'sdk/machines/octatrack/dsp-sites.json')).features + const sites = readJson(join(base, 'sdk/machines/octatrack/dsp-sites.json')), features = sites.features + const keyBusBits = features.filter(f => f.name === 'keybus').map(f => f.bit) + // A base charge's evidence names the base it was timed on (keybus-tap-timing-*.json's `base`). + const timedOn = f => { const path = f.evidence && join(base, 'sdk/machines/octatrack', f.evidence); return path && existsSync(path) ? identities(JSON.stringify(readJson(path).base)) : [] } const lines = readdirSync(dir).filter(name => name.endsWith('.json')).sort().map(name => { const record = readJson(join(dir, name)), id = record.module, pricePath = join(base, MODULES, id, 'evidence/cpu-price.json') - const requires = packages.find(row => row.id === id)?.requires ?? 0 - const extra = features.filter(f => requires & f.bit && typeof f.hardware === 'number').map(f => ({ name: f.name, cycles: f.hardware })) - return unitLine({ id, record, price: existsSync(pricePath) ? readJson(pricePath) : null, extra }) + const row = packages.find(item => item.id === id), requires = row?.requires ?? 0 + const extra = features.filter(f => requires & f.bit && typeof f.hardware === 'number').map(f => ({ name: f.name, cycles: f.hardware, bases: timedOn(f) })) + // A key-bus reader: its package requires the key bus, or the module owns a key-bus site (Sidechain Compressor's tap). + const keyBus = keyBusBits.some(bit => requires & bit) || sites.sites.some(site => site.module === id && keyBusBits.includes(site.feature)) + return unitLine({ id, record, price: existsSync(pricePath) ? readJson(pricePath) : null, extra, row, keyBus }) }) return { lines, missing: lines.filter(line => line.unit == null).map(line => line.id) } } /** The unit report as the Markdown table in sdk/cycle-scan/README.md. */ export function unitMarkdown({ lines }) { - const f = n => n == null ? '–' : String(Math.round(n)) + const f = n => n == null ? '–' : String(Math.round(n)), base = l => l.outside.length ? ' + ' + l.outside.map(e => `${e.cycles} ${e.name}`).join(' + ') : '' + const verdict = l => l.notComparable ? 'not comparable: ' + l.notComparable.join('; ') + : l.ratio == null ? l.notes.join('; ') : (l.outlier ? '**outlier**' : 'within ' + OUTLIER * 100 + ' %') + (l.peakAbove ? '; **peak above the dearest model**' : '') const rows = lines.map(l => `| ${l.id} ${l.version.replace(/-experimental$/, '')} | ${l.points == null ? '–' : `${l.points} = ${f(l.unit)} (${l.on})`} | ` + - `${l.setting ?? '–'} | ${f(l.modelDefaults)}${l.outside.length ? ' + ' + l.outside.map(e => `${e.cycles} ${e.name}`).join(' + ') : ''} | ${f(l.modelDearest)} | ` + - `${l.ratio == null ? '–' : l.ratio.toFixed(2)} | ${l.outlier ? '**outlier**' : l.notes.join('; ') || 'within ' + OUTLIER * 100 + ' %'} |`) - return ['| Module | Unit, in use (points = cycles a sample) | Defaults run | Model at defaults (+ base features) | Model, dearest | Unit ÷ model | Verdict |', - '|---|---|---|---|---|---|---|', ...rows].join('\n') + `${l.peak == null ? '–' : `${l.peak} = ${f(l.unitPeak)}`} | ${l.setting ?? '–'} | ${f(l.modelDefaults)}${base(l)} | ${f(l.modelDearest)}${base(l)} | ` + + `${l.ratio == null ? '–' : l.ratio.toFixed(2)} | ${l.peakRatio == null ? '–' : l.peakRatio.toFixed(2)} | ${verdict(l)} |`) + return ['| Module | Unit, in use (points = cycles a sample) | Unit, peak | Defaults run | Model at defaults (+ base features) | Model, dearest (+ base features) | Unit ÷ model | Peak ÷ dearest | Verdict |', + '|---|---|---|---|---|---|---|---|---|', ...rows].join('\n') +} + +export const README = 'sdk/cycle-scan/README.md' +const TABLE_START = '', TABLE_END = '' +/** The README's text with the table between its markers replaced. */ +export function withTable(text, table) { + const start = text.indexOf(TABLE_START), end = text.indexOf(TABLE_END) + if (start < 0 || end < start) throw new Error(`${README} has lost the generated table's markers`) + return text.slice(0, start + TABLE_START.length) + '\n' + table + '\n' + text.slice(end) +} +/** A failure when the README's committed table is not what the records and readings generate now, else null. */ +export function tableDrift(base = root) { + const path = join(base, README) + if (!existsSync(path)) return null + const text = readFileSync(path, 'utf8') + return withTable(text, unitMarkdown(unitReport(base))) === text ? null + : `${README}: the table under "Checked against the unit" is not what the records and the unit readings give now: run node scripts/cycle-scan.mjs unit --write` } /** One record's verdict: {fail: [...], info: [...]}. `sourceSha256` is the module's source now; `performance` its @@ -175,6 +249,9 @@ export async function check(base = root) { } const unscanned = readdirSync(join(base, MODULES)).filter(id => !ids.includes(id) && performanceOf(join(base, MODULES, id))?.kind === 'dsp') if (unscanned.length) info.push(`no cycle scan yet: ${unscanned.sort().join(', ')}`) + // The README's unit table is generated: it fell behind the key-bus charge once (51 there, 43 in dsp-sites.json). + const drift = ids.length ? tableDrift(base) : null + if (drift) fail.push(drift) return { fail, info, records: ids.length } } @@ -220,15 +297,21 @@ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.ur const { fail, info, records } = await check() for (const line of info) console.log(' · ' + line) for (const line of fail) console.error(' ✗ ' + line) - console.log(fail.length ? `Cycle scan: ${fail.length} of ${records} records fail.` : `Cycle scan: ${records} records current, none under-reported.`) + console.log(fail.length ? `Cycle scan: ${fail.length} failure${fail.length === 1 ? '' : 's'} over ${records} records.` : `Cycle scan: ${records} records current, none under-reported.`) if (fail.length) process.exitCode = 1 } else if (command === 'unit') { const report = unitReport() if (ids.includes('--markdown')) console.log(unitMarkdown(report)) - else for (const l of report.lines) console.log(` ${l.outlier ? '!' : '·'} ${l.id}: ` + (l.unit == null ? l.notes.join('; ') : - `unit ${l.unit} cycles a sample (${l.points} points on ${l.on}), model ${l.model} at ${l.setting}` + - (l.outside.length ? ` with ${l.outside.map(e => e.name + ' ' + e.cycles).join(', ')}` : '') + `, ${l.ratio}x` + (l.outlier ? ': an outlier' : ''))) - if (report.missing.length && !ids.includes('--markdown')) console.log(`No in-use reading to compare: ${report.missing.join(', ')}. A report only; nothing fails.`) - } else { console.error('Usage: node scripts/cycle-scan.mjs record [ ...] | check | unit [--markdown]'); process.exitCode = 2 } + else if (ids.includes('--write')) { + const path = join(root, README), text = readFileSync(path, 'utf8'), next = withTable(text, unitMarkdown(report)) + if (next !== text) writeFileSync(path, next) + console.log(next === text ? `${README}: the table is current.` : `${README}: wrote the table.`) + } else for (const l of report.lines) console.log(` ${l.notComparable ? '×' : l.outlier || l.peakAbove ? '!' : '·'} ${l.id}: ` + (l.unit == null ? l.notes.join('; ') : + `unit ${l.unit} cycles a sample (${l.points} points on ${l.on}${l.peak == null ? '' : `, peak ${l.peak}`}), model ${l.model} at ${l.setting}` + + (l.outside.length ? ` with ${l.outside.map(e => e.name + ' ' + e.cycles).join(', ')}` : '') + + (l.notComparable ? `: not comparable: ${l.notComparable.join('; ')}` : `, ${l.ratio}x` + (l.outlier ? ': an outlier' : '') + + (l.peakRatio == null ? '' : `; peak ${l.unitPeak} against ${l.modelPeak} at the dearest, ${l.peakRatio}x` + (l.peakAbove ? ': above the model' : ''))))) + if (report.missing.length && !ids.includes('--markdown') && !ids.includes('--write')) console.log(`No in-use reading to compare: ${report.missing.join(', ')}. A report only; nothing fails.`) + } else { console.error('Usage: node scripts/cycle-scan.mjs record [ ...] | check | unit [--markdown | --write]'); process.exitCode = 2 } } catch (error) { console.error(error.message); process.exitCode = 1 } } diff --git a/scripts/cycle-scan.test.mjs b/scripts/cycle-scan.test.mjs index ab1400332a..f7770489b9 100644 --- a/scripts/cycle-scan.test.mjs +++ b/scripts/cycle-scan.test.mjs @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' -import { CHARGE_COVERS_MODEL_FROM, POINT, UNDER_REPORT, atSetting, charged, check, dearest, inUsePoints, judge, judgeCharge, unitLine, unitMarkdown, unitReport } from './cycle-scan.mjs' +import { CHARGE_COVERS_MODEL_FROM, POINT, UNDER_REPORT, atSetting, charged, check, dearest, identities, inUsePoints, judge, judgeCharge, notComparable, scanCase, + tableDrift, unitCase, unitLine, unitMarkdown, unitReport, withTable } from './cycle-scan.mjs' const record = (more = {}) => ({ schema: 1, module: 'fx', version: '0.1.0', sourceSha256: 'a'.repeat(64), dearest: { setting: 'MODE=B/max', settings: 4, instructions: 400, cycles: 650, stalls: 90, stallsByKind: { arith: 60 } }, @@ -67,10 +68,19 @@ describe('the unit report', () => { const withDefaults = record({ defaults: { setting: 'MODE=A/def', instructions: 380, cycles: 600, stalls: 80 } }) it('reads the meter of the core the slot is on, at 45.32 cycles a point', () => { expect(POINT).toBe(45.32) - expect(inUsePoints({ inUseOn: 'T1 FX2', inUseAdds: { dsp1to4: 7.5, dsp5to8: 0.9 } })).toEqual({ on: 'T1 FX2', points: 7.5 }) - expect(inUsePoints({ inUseOn: 'T5 FX1', inUseAdds: { dsp1to4: 6.3, dsp5to8: 5.5 } })).toEqual({ on: 'T5 FX1', points: 5.5 }) + expect(inUsePoints({ inUseOn: 'T1 FX2', inUseAdds: { dsp1to4: 7.5, dsp5to8: 0.9 } })).toEqual({ on: 'T1 FX2', points: 7.5, peak: null }) + expect(inUsePoints({ inUseOn: 'T5 FX1', inUseAdds: { dsp1to4: 6.3, dsp5to8: 5.5, dsp1to4Peak: 9, dsp5to8Peak: 8.1 } })).toEqual({ on: 'T5 FX1', points: 5.5, peak: 8.1 }) expect(inUsePoints({ atRestAdds: {} })).toBeNull() }) + it('compares the peak with the dearest run, which bounds every setting, and flags one above it', () => { + const peaked = peak => price({ result: { inUseOn: 'T1 FX2', inUseAdds: { dsp1to4: 14.3, dsp5to8: 0.6, dsp1to4Peak: peak, dsp5to8Peak: 1 } } }) + expect(unitLine({ id: 'fx', record: withDefaults, price: peaked(15) })).toMatchObject({ peak: 15, unitPeak: 679.8, modelPeak: 650, peakRatio: 1.05 }) + const above = unitLine({ id: 'fx', record: withDefaults, price: peaked(16), extra: [{ name: 'keybus', cycles: 43 }] }) + expect(above).toMatchObject({ unitPeak: 725.12, modelPeak: 693, peakRatio: 1.05 }) + expect(above.peakAbove).toBeUndefined() + expect(unitLine({ id: 'fx', record: withDefaults, price: peaked(16) }).peakAbove).toBe(true) + expect(unitMarkdown({ lines: [unitLine({ id: 'fx', record: withDefaults, price: peaked(16) })] })).toContain('| 16 = 725 | MODE=A/def | 600 | 650 | 1.08 | 1.12 | within 10 %; **peak above the dearest model** |') + }) it('compares the reading with the model at the defaults and lists an outlier', () => { const near = unitLine({ id: 'fx', record: withDefaults, price: price() }) expect(near).toMatchObject({ unit: 648.08, model: 600, ratio: 1.08, setting: 'MODE=A/def' }) @@ -94,6 +104,59 @@ describe('the unit report', () => { }) }) +describe('only like cases are compared', () => { + const price = (more = {}) => ({ version: '0.1.0', base: 'development twin d3d71297 of base 0.7.8 (main 02dfa20ca)', measuredAt: '2026-11-18', + result: { inUseOn: 'T1 FX2', inUseAdds: { dsp1to4: 7.5, dsp5to8: 0.9 } }, ...more }) + const ring = record({ defaults: { setting: 'DUCK/def', instructions: 2.5, cycles: 5, stalls: 0 } }) + const tap = [{ name: 'keybus', cycles: 43, bases: ['856cbbcf', '9ac83b23', '1c937ed6'] }] + it('reads the base identities a base names, eight hex digits each', () => { + expect(identities('development twin d3d71297 of base 0.7.8 (main 02dfa20ca)')).toEqual(['d3d71297', '02dfa20c']) + expect(identities('8850f5399c453b9c (development twin, ef6099b0a)')).toEqual(['8850f539', 'ef6099b0']) + expect(identities(undefined)).toEqual([]) + }) + it('keeps a key-bus effect read with an unstated or live key bus, on another base than its charge, out of the ratio', () => { + const line = unitLine({ id: 'ring-sc', record: ring, price: price(), extra: tap, keyBus: true }) + expect(line.ratio).toBeUndefined() + expect(line.outlier).toBeUndefined() + expect(line.notComparable).toEqual([ + 'the reading does not say what its key bus carried, the scan\'s was silent', + 'the unit read on d3d71297, the keybus charge (43) was timed on 856cbbcf', + ]) + expect(unitMarkdown({ lines: [line] })).toMatch(/\| – \| – \| not comparable: the reading does not say what its key bus carried/) + const live = unitLine({ id: 'ring-sc', record: ring, price: price({ base: 'twin 856cbbcf', inputs: { transport: 'playing', keyBus: 'live' } }), extra: tap, keyBus: true }) + expect(live.notComparable).toEqual(['its key bus was live on the unit and silent in the scan']) + }) + it('pairs a key-bus effect read with a silent key bus on the base its charge was timed on', () => { + const silent = price({ base: 'development twin 1c937ed6', inputs: { transport: 'playing', keyBus: 'silent' } }) + expect(unitLine({ id: 'ring-sc', record: ring, price: silent, extra: tap, keyBus: true })).toMatchObject({ model: 48, ratio: 7.08, outlier: true }) + }) + it('refuses a reading of another package, another setting or a stopped sequencer', () => { + const row = { id: 'fx', version: '0.1.0', sha256: 'c'.repeat(64) }, scan = scanCase({ record: ring, row }) + expect(scan).toEqual({ version: '0.1.0', package: 'c'.repeat(64), setting: 'DUCK/def', transport: 'playing', keyBus: null }) + const unit = more => unitCase({ price: price(more), record: ring }) + expect(notComparable(scan, unit())).toEqual([]) // an older reading names no package: its version stands for it + expect(notComparable(scan, unit({ result: { packageSha256: 'c'.repeat(64) } }))).toEqual([]) + expect(notComparable(scan, unit({ result: { packageSha256: '9f22861f'.padEnd(64, '0') } }))).toEqual(['the unit measured package 9f22861f, not the published 0.1.0 (cccccccc)']) + expect(notComparable(scan, unit({ result: { setting: 'DUCK/max' } }))).toEqual(['the unit read it at DUCK/max, the model is at DUCK/def']) + expect(notComparable(scan, unit({ inputs: { transport: 'stopped' } }))).toEqual(['the unit read with the sequencer stopped, the scan runs every block']) + expect(scanCase({ record: ring, row: { ...row, version: '0.1.1' } }).package).toBeNull() // the row is another version's package + }) +}) + +describe('the README\'s unit table', () => { + // Generated from sdk/cycle-scan/records/, each module's evidence/cpu-price.json, sdk/machines/octatrack/dsp-sites.json and + // src/engine/assets/octatrack-module-packages.json; a change to any of them that moves a row must regenerate it. + it('is what node scripts/cycle-scan.mjs unit --markdown generates now', () => { + expect(tableDrift()).toBeNull() + }) + it('replaces only what lies between its markers, and fails without them', () => { + const start = '' + const text = `# x\n${start}\n| old |\n\nafter\n` + expect(withTable(text, '| new |')).toBe(`# x\n${start}\n| new |\n\nafter\n`) + expect(() => withTable('# no table', '| new |')).toThrow(/sdk\/cycle-scan\/README.md has lost the generated table's markers/) + }) +}) + describe('the committed records', () => { it('finds every committed record current and none under-reported', async () => { const result = await check() diff --git a/sdk/cycle-scan/README.md b/sdk/cycle-scan/README.md index 0fa2f79b14..6b3d06c5fc 100644 --- a/sdk/cycle-scan/README.md +++ b/sdk/cycle-scan/README.md @@ -84,45 +84,56 @@ It is a model, not a measurement: the unit stays the judge ([MODULE_PERFORMANCE. ```bash node scripts/cycle-scan.mjs unit # anywhere: each record against its module's in-use reading; a report, it fails nothing node scripts/cycle-scan.mjs unit --markdown # the table below +node scripts/cycle-scan.mjs unit --write # writes it here; `check` fails when the committed table differs ``` Each module's `evidence/cpu-price.json` holds a reading `npm run device:price` took on an MKII: the DSP load meter of the slot's core with the effect picked on that slot in place of NONE, against the same scene without it (`inUseAdds`; T1-T4 -are core 1's meter, T5-T8 core 0's). A fresh pick starts from the effect's defaults, so the report compares it with the -scan's run at the defaults. **Scale:** one point of the meter is 45.32 cycles a sample. `status.c`'s `busy()` gives per -mille of `FRAME_CYCLES`, 72,520 (4,532 cycles a sample, the board's clock, as `CYCLE_SCAN.md`'s "% of a frame" uses, times -16 samples a frame), from idle passes whose cycles were calibrated on the unit with `--dsp-burn` (11 October 2026, -`idle_cycles` there). A module whose package requires a base DSP feature with a hardware charge in -`sdk/machines/octatrack/dsp-sites.json` (the key bus: 51) has it added to the model, since that work runs outside the -effect's proc and so outside the scan. +are core 1's meter, T5-T8 core 0's). A fresh pick starts from the effect's defaults, so the report compares the reading's +mean with the scan's run at the defaults, and its peak (the core's busiest block, which `device:price` keeps from +24 November 2026) with the dearest run, which bounds every setting. **Scale:** one point of the meter is 45.32 cycles a +sample. `status.c`'s `busy()` gives per mille of `FRAME_CYCLES`, 72,520 (4,532 cycles a sample, the board's clock, as +`CYCLE_SCAN.md`'s "% of a frame" uses, times 16 samples a frame), from idle passes whose cycles were calibrated on the +unit with `--dsp-burn` (11 October 2026, `idle_cycles` there). A module whose package requires a base DSP feature with a +`hardware` charge in `sdk/machines/octatrack/dsp-sites.json` (the key bus) has it added to the model, since that work runs +outside the effect's proc and so outside the scan. + +**Only like cases are compared.** A reading and a model are paired when they cover the same package of the record's +version, the same setting, the transport playing, the same key-bus input for a module that reads the key bus (the scan's +`dsp_host` feeds it silence; a reading names its own in `inputs.keyBus`, `live` or `silent`), and, where a base charge is added, +a reading taken on a base that charge was timed on (the identities its evidence names). Any other pair prints "not +comparable" with the reason and no ratio: re-measure on that case rather than read the gap as a model error. The readings, 18 November 2026, on development twins of base 0.7.8 (Sidechain Compressor's on another twin, `8850f539`), one 8-second reading each; modules with no DSP code moved the same meters by -0.6 to +0.6 points (±27 cycles) in the same runs, once 2.9. Records scanned 23 November 2026: -| Module | Unit, in use (points = cycles a sample) | Defaults run | Model at defaults (+ base features) | Model, dearest | Unit ÷ model | Verdict | -|---|---|---|---|---|---|---| -| airwindows-chorus 0.1.3 | – | defaults/def | 602 | 649 | – | no in-use reading on the unit | -| bbd 0.1.2 | 10.8 = 489 (T1 FX2) | STGS=1024/def | 469 | 528 | 1.04 | within 10 % | -| euclid 0.1.5 | 5.5 = 249 (T1 FX2) | RATE=1/16/def | 232 | 232 | 1.07 | within 10 % | -| everb 0.1.2 | 13.3 = 603 (T1 FX2) | REV=OFF/def | 603 | 665 | 1.00 | within 10 % | -| lofi2 0.1.1 | 10.3 = 467 (T1 FX2) | RING/def | 425 | 654 | 1.10 | within 10 % | -| miniverb 0.2.3 | 14.1 = 639 (T1 FX2) | RATE=1.01/def | 641 | 699 | 1.00 | within 10 % | -| ring-sc 0.2.1 | 7.5 = 340 (T1 FX2) | DUCK/def | 5 + 51 keybus | 122 | 6.04 | **outlier** | -| sidechain-compressor 0.2.2 | 5.5 = 249 (T5 FX1) | MON=OFF/def | 107 | 107 | 2.34 | **outlier** | -| tapehead 0.1.2 | 9.3 = 421 (T1 FX2) | COLOR=NORM/def | 425 | 426 | 0.99 | within 10 % | -| vibrato 0.1.0 | – | SHP=SINE/def | 204 | 207 | – | no in-use reading on the unit | + +| Module | Unit, in use (points = cycles a sample) | Unit, peak | Defaults run | Model at defaults (+ base features) | Model, dearest (+ base features) | Unit ÷ model | Peak ÷ dearest | Verdict | +|---|---|---|---|---|---|---|---|---| +| airwindows-chorus 0.1.3 | – | – | defaults/def | 602 | 649 | – | – | no in-use reading on the unit | +| bbd 0.1.2 | 10.8 = 489 (T1 FX2) | – | STGS=1024/def | 469 | 528 | 1.04 | – | within 10 % | +| euclid 0.1.5 | 5.5 = 249 (T1 FX2) | – | RATE=1/16/def | 232 | 232 | 1.07 | – | within 10 % | +| everb 0.1.2 | 13.3 = 603 (T1 FX2) | – | REV=OFF/def | 603 | 665 | 1.00 | – | within 10 % | +| lofi2 0.1.1 | 10.3 = 467 (T1 FX2) | – | RING/def | 425 | 654 | 1.10 | – | within 10 % | +| miniverb 0.2.3 | 14.1 = 639 (T1 FX2) | – | RATE=1.01/def | 641 | 699 | 1.00 | – | within 10 % | +| ring-sc 0.2.1 | 7.5 = 340 (T1 FX2) | – | DUCK/def | 5 + 43 keybus | 122 + 43 keybus | – | – | not comparable: the reading does not say what its key bus carried, the scan's was silent; the unit read on d3d71297, the keybus charge (43) was timed on 856cbbcf | +| sidechain-compressor 0.2.2 | 5.5 = 249 (T5 FX1) | – | MON=OFF/def | 107 | 107 | – | – | not comparable: the unit measured package 9f22861f, not the published 0.2.2-experimental (cbd0fa73); the reading does not say what its key bus carried, the scan's was silent | +| tapehead 0.1.2 | 9.3 = 421 (T1 FX2) | – | COLOR=NORM/def | 425 | 426 | 0.99 | – | within 10 % | +| vibrato 0.1.0 | – | – | SHP=SINE/def | 204 | 207 | – | – | no in-use reading on the unit | + - **Effects whose work is all in their proc:** the model at the defaults is 1 % above to 10 % below the unit (mean 3 % below), for six modules. LOFI2 (9.95 %) is the widest, and EUCLID's 7 % is within the meter's noise at its size. Upstream found its model 3.0 % *above* its own meter (`CYCLE_SCAN.md` section 1): the two meters differ, and Modwerk's - reads 7 to 19 % above octabam's slot costs for the same DSP code (LOFI2, BBD, EUCLID). -- **Key-bus effects cost far more on the unit than the scan sees.** RINGMOD SC at its defaults runs 2.5 instructions a - sample in the scan (`dsp_host` feeds no key bus, so its key path may stay idle), yet the unit read 340 cycles on core 1, - where its key-bus tap is charged 51; core 0 read +0.9 points (41). Even its dearest run plus the tap (173) leaves half - of it unexplained. Sidechain Compressor read 249 on its own core against 107 modelled, and +6.3 points (285) on the - other core, where it has no instance: its detector and the key-bus tap are base-resident code on both cores - (`dsp-sites.json`'s `sidechain` and `keybus`), outside the proc. Whether the key path, the tap (timed on 23 October on - the older 41-instruction tap) or something else costs the rest needs a unit run. + reads 7 to 19 % above octabam's slot costs for the same DSP code (LOFI2, BBD, EUCLID). None of these readings kept a + peak, so nothing is compared with the dearest run yet. +- **The key-bus effects are not comparable yet.** RINGMOD SC at its defaults runs 2.5 instructions a sample in the scan, + whose key bus is silent, while the unit's kick on T1 fed it: the unit read 340 cycles on core 1 and +0.9 points (41) on + core 0. Its reading was also taken on 0.7.8's 41-instruction tap, before the one-pass tap the charge (43) was timed on. + Sidechain Compressor read 249 on its own core and +6.3 points (285) on the other, where it has no instance: its detector + and the key-bus tap are base-resident code on both cores (`dsp-sites.json`'s `sidechain` and `keybus`), outside the + proc, and the build it was read on is not the published package. To compare them: read both on the current base with + what the key bus carried recorded, and scan their key path with the key bus fed. - **No reading to compare:** VIBRATO and Air Chorus (`airwindows-chorus`) have no `cpu-price.json` in-use reading yet; Output Matrix has no scan record (its mix is base-resident code too). From b6763dfe78a77bfab44ca72c4d4dd7ed88cabfc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jannik=20A=C3=9Ffalg?= <67785539+repeat98@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:56:39 +0100 Subject: [PATCH 03/29] Improvement: Copy details, Save report and a prefilled Report a problem after a USB error (#2105) * Improvement: Copy details, Save report and a prefilled Report a problem after a USB error A member who leaves diagnostics sharing off had no trail of a failed sync, install or base update: the link dropped every diagnostic event when nobody listened (octatrack-link.ts diagnostic()), and Report a problem asked for what the Octatrack runs by hand. The link now keeps its last 100 diagnostic events in the page's memory (link-trail.ts), the same records shared diagnostics carry, whether or not the member shares. Nothing is sent by itself; shared diagnostics go to the same listeners as before, and the EP0 counter read stays for sharing only. - Copy details and Save report beside the link, sync, self-test and base update errors (SupportActions): what failed, the base with its layout, the model text and the events, readable and as JSON lines (support-report.ts, parseSupportFile reads a saved file back). - Report a problem fills in "It is running" and the last error, and offers the recent events as an attachment the member sees and can remove. The Worker checks each event against the shared diagnostics' rules and puts them in the GitHub issue beside the log. - A failed base update names the layout when two bases share a version (describeBase, moved to base-variants.ts). - Privacy page and the Diagnostics section say what the page keeps locally. - ?preview=usb-link&refusal=7 shows a refused sync with the new actions. Co-Authored-By: Claude Opus 5.5 * List support-report.ts as shared site and Worker code The Worker renders and checks attached USB events with it, so it is shared code under the same licence as the diagnostics contract; notices regenerated. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .agents/skills/modwerk-diagnostics/SKILL.md | 2 +- .claude/skills/modwerk-diagnostics/SKILL.md | 2 +- LICENSES/platform.json | 1 + changelog/2026-11-24-usb-support-details.md | 1 + public/licenses/THIRD_PARTY_NOTICES.html | 1 + public/licenses/THIRD_PARTY_NOTICES.txt | 1 + server/configuration-reports.ts | 15 ++- server/github.ts | 13 ++- server/support-attachment.ts | 38 +++++++ src/community/ConfigurationReport.tsx | 25 ++++- src/community/PrivacyPage.tsx | 3 +- .../configuration-report-flow.test.ts | 18 ++++ src/community/support-report.test.ts | 86 ++++++++++++++++ src/community/support-report.ts | 99 +++++++++++++++++++ src/components/BaseInstallDialog.tsx | 3 + src/components/LoadDialog.tsx | 3 +- src/components/OctatrackDiagnostics.tsx | 8 +- src/components/OctatrackHub.tsx | 2 + src/components/OctatrackOverview.tsx | 3 +- src/components/SupportActions.test.ts | 93 +++++++++++++++++ src/components/SupportActions.tsx | 30 ++++++ src/components/UnitPanel.tsx | 7 +- src/dev/octatrack-link-fake.ts | 7 +- src/engine/elekloader/base-variants.ts | 6 ++ src/engine/elekloader/link-trail.test.ts | 90 +++++++++++++++++ src/engine/elekloader/link-trail.ts | 47 +++++++++ src/engine/elekloader/octatrack-link.ts | 22 +++-- src/styles.css | 2 + 28 files changed, 595 insertions(+), 33 deletions(-) create mode 100644 changelog/2026-11-24-usb-support-details.md create mode 100644 server/support-attachment.ts create mode 100644 src/community/support-report.test.ts create mode 100644 src/community/support-report.ts create mode 100644 src/components/SupportActions.test.ts create mode 100644 src/components/SupportActions.tsx create mode 100644 src/engine/elekloader/link-trail.test.ts create mode 100644 src/engine/elekloader/link-trail.ts diff --git a/.agents/skills/modwerk-diagnostics/SKILL.md b/.agents/skills/modwerk-diagnostics/SKILL.md index 832667edde..496ab94b61 100644 --- a/.agents/skills/modwerk-diagnostics/SKILL.md +++ b/.agents/skills/modwerk-diagnostics/SKILL.md @@ -9,7 +9,7 @@ If the developer is not the owner, say that shared diagnostics are private to th The records are private. Tester names and anything quoted from a record stay in chat and in `~/.cache/modwerk-local/`: never in a commit, pull request, issue, changelog or document. There, write "a tester" and only the technical fact. -1. **Pull.** `git fetch`, then `npm run diagnostics:pull` on Node 24. The summary is long, so write it to `~/.cache/modwerk-local/diagnostics/pull-.txt` and read its Problems section first; every record is in `~/.cache/modwerk-local/diagnostics/latest.json` (UTC). What the summary means, its known noise and an HTTP 403 are in `docs/MAINTENANCE.md#beta-worker`; the record schema is `src/community/octatrack-diagnostics-contract.ts`. With an argument, read only that member's, module's or symptom's records. +1. **Pull.** `git fetch`, then `npm run diagnostics:pull` on Node 24. The summary is long, so write it to `~/.cache/modwerk-local/diagnostics/pull-.txt` and read its Problems section first; every record is in `~/.cache/modwerk-local/diagnostics/latest.json` (UTC). What the summary means, its known noise and an HTTP 403 are in `docs/MAINTENANCE.md#beta-worker`; the record schema is `src/community/octatrack-diagnostics-contract.ts`. With an argument, read only that member's, module's or symptom's records. A member who does not share can hand over the same records themselves: Copy details or a saved `modwerk-support-*.txt` after a USB error, or the USB events block of a report they posted; read their JSON lines with `parseSupportFile` (`src/community/support-report.ts`). 2. **Sort the failures into causes**, not records: sync and link failures, build failures, browser errors, unresponsive units, stalls and crashes in device logs, restores that were not `RESTORED`, CPU or DSP near the limit. One cause is one line: what happens, on which base, set, browser and OS, how many units, first and last seen. 3. **Drop what is not open.** For each cause check, in this order: the unit's base and module versions against what is live (an old build's bug that `changelog/` or the module's changelog already fixed is done), the open issues and pull requests (`gh issue list`, `gh pr list`), the findings in `docs/OCTATRACK_BETA_TEST_PLAN.md`, and the stock OS's own behaviour. Say which it was. 4. **Prove the rest before fixing it.** Find the code the record points at and reproduce the failure in a test, over HTTP, or with the developer MCP. On the owner's computer, take a turn through the [unit queue](../../../docs/OCTATRACK_DRIVING.md#taking-turns-on-the-unit) for hardware reproduction (`/modwerk-test-on-unit`). Confirm the shared emulator is free before starting it. A cause you cannot reproduce is a hypothesis: say what would confirm it, and add the missing diagnostic field or log line as the fix if that is what stands in the way. Never ask a tester to run tests. diff --git a/.claude/skills/modwerk-diagnostics/SKILL.md b/.claude/skills/modwerk-diagnostics/SKILL.md index 832667edde..496ab94b61 100644 --- a/.claude/skills/modwerk-diagnostics/SKILL.md +++ b/.claude/skills/modwerk-diagnostics/SKILL.md @@ -9,7 +9,7 @@ If the developer is not the owner, say that shared diagnostics are private to th The records are private. Tester names and anything quoted from a record stay in chat and in `~/.cache/modwerk-local/`: never in a commit, pull request, issue, changelog or document. There, write "a tester" and only the technical fact. -1. **Pull.** `git fetch`, then `npm run diagnostics:pull` on Node 24. The summary is long, so write it to `~/.cache/modwerk-local/diagnostics/pull-.txt` and read its Problems section first; every record is in `~/.cache/modwerk-local/diagnostics/latest.json` (UTC). What the summary means, its known noise and an HTTP 403 are in `docs/MAINTENANCE.md#beta-worker`; the record schema is `src/community/octatrack-diagnostics-contract.ts`. With an argument, read only that member's, module's or symptom's records. +1. **Pull.** `git fetch`, then `npm run diagnostics:pull` on Node 24. The summary is long, so write it to `~/.cache/modwerk-local/diagnostics/pull-.txt` and read its Problems section first; every record is in `~/.cache/modwerk-local/diagnostics/latest.json` (UTC). What the summary means, its known noise and an HTTP 403 are in `docs/MAINTENANCE.md#beta-worker`; the record schema is `src/community/octatrack-diagnostics-contract.ts`. With an argument, read only that member's, module's or symptom's records. A member who does not share can hand over the same records themselves: Copy details or a saved `modwerk-support-*.txt` after a USB error, or the USB events block of a report they posted; read their JSON lines with `parseSupportFile` (`src/community/support-report.ts`). 2. **Sort the failures into causes**, not records: sync and link failures, build failures, browser errors, unresponsive units, stalls and crashes in device logs, restores that were not `RESTORED`, CPU or DSP near the limit. One cause is one line: what happens, on which base, set, browser and OS, how many units, first and last seen. 3. **Drop what is not open.** For each cause check, in this order: the unit's base and module versions against what is live (an old build's bug that `changelog/` or the module's changelog already fixed is done), the open issues and pull requests (`gh issue list`, `gh pr list`), the findings in `docs/OCTATRACK_BETA_TEST_PLAN.md`, and the stock OS's own behaviour. Say which it was. 4. **Prove the rest before fixing it.** Find the code the record points at and reproduce the failure in a test, over HTTP, or with the developer MCP. On the owner's computer, take a turn through the [unit queue](../../../docs/OCTATRACK_DRIVING.md#taking-turns-on-the-unit) for hardware reproduction (`/modwerk-test-on-unit`). Confirm the shared emulator is free before starting it. A cause you cannot reproduce is a hypothesis: say what would confirm it, and add the missing diagnostic field or log line as the fix if that is what stands in the way. Never ask a tester to run tests. diff --git a/LICENSES/platform.json b/LICENSES/platform.json index 50842fca41..4393ed618b 100644 --- a/LICENSES/platform.json +++ b/LICENSES/platform.json @@ -42,6 +42,7 @@ "src/community/profile-links.ts", "src/community/remote-session-contract.ts", "src/community/report-closure.ts", + "src/community/support-report.ts", "src/community/usage-contract.ts", "src/community/usage-pages.ts", "src/config/beta-invitation.ts", diff --git a/changelog/2026-11-24-usb-support-details.md b/changelog/2026-11-24-usb-support-details.md new file mode 100644 index 0000000000..15d5153cea --- /dev/null +++ b/changelog/2026-11-24-usb-support-details.md @@ -0,0 +1 @@ +Your Octatrack: after a failed sync, connection, self-test or base update, **Copy details** and **Save report** next to the error give you what went wrong, the base with its USB Audio layout and the last USB events, to paste in a message or keep as a file. The page keeps its last 100 USB events in memory whether or not you share diagnostics, and sends none of them by itself. **Report a problem** now fills in what the Octatrack runs and the last error, and offers to attach those events; you see what is attached and can remove it before posting. A failed base update that changes only the USB Audio layout now names the layout ("came back on base 0.8.1 (USB Audio off)") instead of reading like the same base. diff --git a/public/licenses/THIRD_PARTY_NOTICES.html b/public/licenses/THIRD_PARTY_NOTICES.html index 77e00d348a..ee25d82537 100644 --- a/public/licenses/THIRD_PARTY_NOTICES.html +++ b/public/licenses/THIRD_PARTY_NOTICES.html @@ -89,6 +89,7 @@ src/community/profile-links.ts src/community/remote-session-contract.ts src/community/report-closure.ts +src/community/support-report.ts src/community/usage-contract.ts src/community/usage-pages.ts src/config/beta-invitation.ts diff --git a/public/licenses/THIRD_PARTY_NOTICES.txt b/public/licenses/THIRD_PARTY_NOTICES.txt index 10ac7f8491..3852d1c198 100644 --- a/public/licenses/THIRD_PARTY_NOTICES.txt +++ b/public/licenses/THIRD_PARTY_NOTICES.txt @@ -88,6 +88,7 @@ src/community/ot-log.ts src/community/profile-links.ts src/community/remote-session-contract.ts src/community/report-closure.ts +src/community/support-report.ts src/community/usage-contract.ts src/community/usage-pages.ts src/config/beta-invitation.ts diff --git a/server/configuration-reports.ts b/server/configuration-reports.ts index 3f84403913..b35db22fd8 100644 --- a/server/configuration-reports.ts +++ b/server/configuration-reports.ts @@ -5,11 +5,13 @@ import { followReportedModules } from './module-updates' import type { Database, Env, User } from './platform' import { HttpError, jsonBody, optional, required, response } from './security' import { configurationSummary, validateConfigurationReportContext } from '../src/community/configuration-report' -import { IssueInputError } from '../src/community/issue-context' +import { IssueInputError, isDigiIssue } from '../src/community/issue-context' import { OT_LOG_MAX_BYTES, OtLogError, parseOtLog } from '../src/community/ot-log' import { communityModule } from '../src/community/modules' +import { SUPPORT_ATTACHMENT_BYTES } from '../src/community/support-report' +import { validateSupportAttachment } from './support-attachment' -const FIELDS = ['title', 'steps', 'expected', 'actual', 'context', 'log', 'maintainerSharing', 'visibility', 'notifyUpdates'] +const FIELDS = ['title', 'steps', 'expected', 'actual', 'context', 'log', 'usbEvents', 'maintainerSharing', 'visibility', 'notifyUpdates'] function input(read: () => T): T { try { return read() } catch (error) { if (error instanceof IssueInputError || error instanceof OtLogError) throw new HttpError(400, error.message); throw error } } /** @@ -19,7 +21,7 @@ function input(read: () => T): T { try { return read() } catch (error) { if ( */ export async function createConfigurationReport(request: Request, env: Env, db: Database, user: User | null) { const owner = needMember(user) - const body = await jsonBody(request, OT_LOG_MAX_BYTES + 32 * 1024) + const body = await jsonBody(request, OT_LOG_MAX_BYTES + SUPPORT_ATTACHMENT_BYTES + 32 * 1024) if (Object.keys(body).some(key => !FIELDS.includes(key))) throw new HttpError(400, 'Unexpected report field. Files and firmware are not accepted.') if (body.notifyUpdates !== undefined && typeof body.notifyUpdates !== 'boolean') throw new HttpError(400, 'Choose whether to follow module updates.') if (body.visibility !== undefined && body.visibility !== 'forum' && body.visibility !== 'private') throw new HttpError(400, 'Choose a public forum report or a private report.') @@ -31,6 +33,11 @@ export async function createConfigurationReport(request: Request, env: Env, db: const log = attached ? input(() => parseOtLog(body.log as string)) : null // An attached log records the configuration the device ran; otherwise the reporter names it. const { context, modules } = input(() => validateConfigurationReportContext(body.context, log?.summary ?? null)) + // USB events the reporter chose to attach (support-report.ts): kept with the configuration, which reaches GitHub on the + // same terms as the log. + const usb = body.usbEvents === undefined || body.usbEvents === null ? undefined : validateSupportAttachment(body.usbEvents) + if (usb && isDigiIssue(context)) throw new HttpError(400, 'USB events come from an Octatrack. Remove them and post the report again.') + if (usb && JSON.stringify(usb).length > SUPPORT_ATTACHMENT_BYTES) throw new HttpError(400, 'The attached USB events are too long. Remove them and post the report again.') // Member first, so one member's refused reports never fill the address's or the site's counter. await throttle(db, 'issue-member:' + owner.id, 10) await throttle(db, 'issue-ip:' + (request.headers.get('CF-Connecting-IP') ?? 'local'), 10) @@ -47,7 +54,7 @@ export async function createConfigurationReport(request: Request, env: Env, db: db.prepare('INSERT INTO forum_posts(id,thread_id,user_id,body) VALUES(?,?,?,?)').bind(postId, threadId, owner.id, 'Configuration (' + configurationSummary(modules.length) + '): ' + modules.map(module => module.name + ' ' + module.version).join(', ') + '\n\n' + details), db.prepare('INSERT INTO forum_follows(thread_id,user_id) VALUES(?,?)').bind(threadId, owner.id), ] : [] - statements.push(db.prepare("INSERT INTO issues(id,module_id,author_login,reporter_id,title,body,context_json,github_state,maintainer_sharing,forum_thread_id,public_json,scope) VALUES(?,?,?,?,?,?,?,?,?,?,?,'configuration')").bind(id, anchor.id, anchor.author, owner.id, title, details, JSON.stringify(context), github ? 'pending' : 'none', Number(publicReport || body.maintainerSharing === true), threadId, publicDetails && JSON.stringify(publicDetails))) + statements.push(db.prepare("INSERT INTO issues(id,module_id,author_login,reporter_id,title,body,context_json,github_state,maintainer_sharing,forum_thread_id,public_json,scope) VALUES(?,?,?,?,?,?,?,?,?,?,?,'configuration')").bind(id, anchor.id, anchor.author, owner.id, title, details, JSON.stringify(usb ? { ...context, usb } : context), github ? 'pending' : 'none', Number(publicReport || body.maintainerSharing === true), threadId, publicDetails && JSON.stringify(publicDetails))) for (const module of modules) statements.push(db.prepare('INSERT INTO issue_modules(issue_id,module_id,version) VALUES(?,?,?) ON CONFLICT DO NOTHING').bind(id, module.id, module.version)) if (log) statements.push(db.prepare('INSERT INTO issue_logs(issue_id,text,bytes,summary_json) VALUES(?,?,?,?)').bind(id, log.text, log.text.length, JSON.stringify(log.summary))) if (body.notifyUpdates !== false) statements.push(...followReportedModules(db, modules.map(module => module.id), owner.id)) diff --git a/server/github.ts b/server/github.ts index 0d098b2640..438a3f9883 100644 --- a/server/github.ts +++ b/server/github.ts @@ -8,6 +8,7 @@ import { profilePath } from '../src/community/forum-links' import { FLASH_STATES, type IssueContext } from '../src/community/issue-context' import { REPORT_CLOSURE_REASONS, REPORT_COMMANDS, type ReportClosureReason } from '../src/community/report-closure' import { digest } from './security' +import { supportBlock, type SupportAttachment } from '../src/community/support-report' const API = 'https://api.github.com' const BODY_LIMIT = 60000 @@ -69,7 +70,7 @@ const quote = (text: string) => inert(text).split(/\r?\n/).map(line => '> ' + li */ export type PublicBugDetails = { device: string; version: string; steps: string; expected: string; actual: string; modules?: { id: string; name: string; version: string }[]; full?: boolean } /** A whole-configuration report lists every module in `moduleIds`; `module_id` is then only the first of them. */ -export type MirroredIssue = { id: string; module_id: string; scope?: 'module' | 'configuration'; moduleIds?: string[]; title: string; reporter: string | null; owners: string[]; details: PublicBugDetails; context?: IssueContext; log?: string } +export type MirroredIssue = { id: string; module_id: string; scope?: 'module' | 'configuration'; moduleIds?: string[]; title: string; reporter: string | null; owners: string[]; details: PublicBugDetails; context?: IssueContext; log?: string; usb?: SupportAttachment } export function issueTitle(issue: Pick) { return ('[' + (issue.scope === 'configuration' ? 'configuration' : issue.module_id) + '] ' + issue.title).slice(0, 256) } const GITHUB_LOGIN = /^[A-Za-z0-9-]{1,39}$/ @@ -115,8 +116,10 @@ export function issueMarkdown(issue: MirroredIssue, app?: string) { 'Only the registered release author can use `resolve`, after verifying that exact published download fixes the report on their unit. Ordinary closures claim no new firmware fix.', '', 'A merged PR alone does not resolve a report. [Author release steps](https://github.com/repeat98/modwerk/blob/main/docs/MODULE_AUTHOR_UPDATES.md).', ] - const log = issue.log ? ['### Device log', '', ...logBlock(issue.log, BODY_LIMIT - [...report, ...rest].join('\n').length)] : [] - return [...report, ...log, ...rest].join('\n').slice(0, BODY_LIMIT) + // The reporter attached them themselves (support-report.ts); checked to numbers, codes and hashes when they posted. + const usb = issue.usb ? ['### USB events', '', ...supportBlock(issue.usb)] : [] + const log = issue.log ? ['### Device log', '', ...logBlock(issue.log, BODY_LIMIT - [...report, ...usb, ...rest].join('\n').length)] : [] + return [...report, ...usb, ...log, ...rest].join('\n').slice(0, BODY_LIMIT) } export async function createGithubIssue(config: GithubConfig, issue: MirroredIssue, app?: string) { @@ -178,8 +181,8 @@ export async function mirrorIssue(db: Database, env: Env, id: string, stale = fa const details = JSON.parse(row.public_json) as PublicBugDetails // Only reporters who agreed to publish them get their configuration and log on GitHub. const log = details.full ? (await db.prepare('SELECT text FROM issue_logs WHERE issue_id=?').bind(id).first<{ text: string }>())?.text : undefined - const context = details.full && row.context_json ? JSON.parse(row.context_json) as IssueContext : undefined - const created = await createGithubIssue(config, { id: row.id, module_id: row.module_id, scope: row.scope, moduleIds, title: row.title, reporter: row.reporter, owners, details, context, log }, env.APP_URL) + const context = details.full && row.context_json ? JSON.parse(row.context_json) as IssueContext & { usb?: SupportAttachment } : undefined + const created = await createGithubIssue(config, { id: row.id, module_id: row.module_id, scope: row.scope, moduleIds, title: row.title, reporter: row.reporter, owners, details, context, log, ...(context?.usb ? { usb: context.usb } : {}) }, env.APP_URL) await db.prepare("UPDATE issues SET github_state='synced',github_number=?,github_url=?,github_error='' WHERE id=?").bind(created.number, created.url, id).run() return { state: 'synced' as const, url: created.url } } catch (error) { diff --git a/server/support-attachment.ts b/server/support-attachment.ts new file mode 100644 index 0000000000..d137dc9ca5 --- /dev/null +++ b/server/support-attachment.ts @@ -0,0 +1,38 @@ +import { HttpError } from './security' +import { validateDiagnostic } from './octatrack-diagnostics' +import { DIAGNOSTIC_USB_EVENTS } from '../src/community/octatrack-diagnostics-contract' +import { SUPPORT_ATTACHED_EVENTS, SUPPORT_LAYOUTS, type SupportAttachment, type SupportEvent } from '../src/community/support-report' + +const object = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v) +const hash = (v: unknown) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v) +/** validateDiagnostic wants a record id; an attached event has none of its own. */ +const NO_ID = '00000000-0000-4000-8000-000000000000' +/** The link's own events: no device log (the collector reads that, not the link) and no browser or build events. */ +const LINK_EVENTS: readonly string[] = [...DIAGNOSTIC_USB_EVENTS.filter(event => event !== 'device_log'), 'link_failed'] +const refuse = (): never => { throw new HttpError(400, 'The attached USB events are unreadable. Remove them and post the report again.') } +const checked = (record: Record) => { try { return validateDiagnostic({ id: NO_ID, ...record }) } catch { return refuse() } } + +/** + * USB events a member attached to a problem report (support-report.ts): the trail's records, each held to the shared + * diagnostics' field rules (validateDiagnostic), with when the page saw it, plus the unit's base, version, layout, model + * text and running set, and the browser family. Anything else is refused, so no free text reaches the issue. + */ +export function validateSupportAttachment(value: unknown): SupportAttachment { + if (!object(value) || value.schema !== 1 || !Object.keys(value).every(key => ['schema', 'unit', 'client', 'events'].includes(key))) return refuse() + const { unit, client, events } = value + if (unit !== undefined && !(object(unit) && Object.keys(unit).every(key => ['base', 'version', 'layout', 'model', 'active'].includes(key)) && hash(unit.base) + && (unit.version === undefined || typeof unit.version === 'string' && /^[0-9]{1,3}(?:\.[0-9]{1,3}){1,3}$/.test(unit.version)) + && (unit.layout === undefined || SUPPORT_LAYOUTS.includes(unit.layout as string)) + && (unit.model === undefined || typeof unit.model === 'string' && /^[A-Za-z0-9 ._+-]{1,16}$/.test(unit.model)) + && (unit.active === undefined || hash(unit.active)))) return refuse() + if (client !== undefined) checked({ event: 'connected', phase: 'ready', client }) + if (!Array.isArray(events) || !events.length || events.length > SUPPORT_ATTACHED_EVENTS) return refuse() + const list = events.map(entry => { + if (!object(entry) || typeof entry.at !== 'string' || entry.at.length > 30 || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/.test(entry.at) || !Number.isFinite(Date.parse(entry.at))) return refuse() + const { at, ...record } = entry + if (!LINK_EVENTS.includes(record.event as string) || 'modules' in record || 'client' in record) return refuse() + checked(record) + return { at, ...record } as SupportEvent + }) + return { schema: 1, ...(unit ? { unit: unit as unknown as SupportAttachment['unit'] } : {}), ...(client ? { client: client as SupportAttachment['client'] } : {}), events: list } +} diff --git a/src/community/ConfigurationReport.tsx b/src/community/ConfigurationReport.tsx index 4c3cbbe739..92ebbd2327 100644 --- a/src/community/ConfigurationReport.tsx +++ b/src/community/ConfigurationReport.tsx @@ -1,4 +1,6 @@ -import { useEffect, useId, useRef, useState, type FormEvent } from 'react' +import { useContext, useEffect, useId, useRef, useState, type FormEvent } from 'react' +import { OctatrackLinkContext } from '../hooks/useOctatrackLink' +import { SUPPORT_ATTACHED_EVENTS, supportBase, supportLines } from './support-report' import { createPortal } from 'react-dom' import { Icon } from '../components/Icon' import { DEVICES_BY_ID } from '../devices/registry' @@ -23,7 +25,13 @@ export function ConfigurationReportDialog({ machine, configurationId, onClose }: const dialog = useRef(null), heading = useId(), success = useRef(null), logHelp = useId() const { session } = useCommunity(), workspace = useWorkspaceReportContext(machine), device = DEVICES_BY_ID[machine] const { file, input: logInput, read: readLog, remove: removeLog } = useOtLogFile(), digi = machine !== 'octatrack' - const [model, setModel] = useState(''), [flash, setFlash] = useState('') + // The USB link fills in what it knows, all of it editable: what the Octatrack runs, the last error the page showed, + // and its recent USB events, which the reporter sees and can remove before posting (support-report.ts). IDENTIFY names + // the stock OS, not MKI or MKII, so the model stays the reporter's choice. + const link = useContext(OctatrackLinkContext), usbLink = digi ? null : link + const [attachment] = useState(() => usbLink?.supportAttachment?.(SUPPORT_ATTACHED_EVENTS)) + const [attach, setAttach] = useState(() => !!attachment?.events.length), lastError = usbLink?.trail?.lastError?.text ?? '' + const [model, setModel] = useState(''), [flash, setFlash] = useState(() => usbLink?.getState().identity ? 'usb' : '') const [sent, setSent] = useState(null), [busy, setBusy] = useState(false), [error, setError] = useState('') useEffect(() => { const element = dialog.current, previousFocus = document.activeElement @@ -50,7 +58,7 @@ export function ConfigurationReportDialog({ machine, configurationId, onClose }: const context: IssueContext = digi ? { machine: machine as 'digitakt' | 'digitone', model: fields.model, flash: fields.flash as FlashState, os: fields.os, moduleVersion: resolved.modules[0]?.version ?? '', modules: resolved.modules, keepStockFx2: null, build: '' } : { model: model as OtModel, flash: flash as FlashState, os: file.log?.summary.os ?? REPORT_OS, modules: resolved.modules, keepStockFx2: resolved.keepStockFx2, build: resolved.build } - const result = await post('/configuration-reports', { title: fields.title, steps: fields.steps, expected: fields.expected, actual: fields.actual, context, visibility: 'forum', notifyUpdates: fields.notifyUpdates === 'on', ...(file.log ? { log: file.log.text } : {}) }) + const result = await post('/configuration-reports', { title: fields.title, steps: fields.steps, expected: fields.expected, actual: fields.actual, context, visibility: 'forum', notifyUpdates: fields.notifyUpdates === 'on', ...(file.log ? { log: file.log.text } : {}), ...(!digi && attach && attachment?.events.length ? { usbEvents: attachment } : {}) }) setSent(result) for (const module of catalogued) refreshModuleIssues(module.id) window.dispatchEvent(new Event('modwerk-module-updates')) @@ -90,8 +98,15 @@ export function ConfigurationReportDialog({ machine, configurationId, onClose }: {modules > catalogued.length && catalogued.length > 0 &&

{modules - catalogued.length} {modules - catalogued.length === 1 ? 'module is' : 'modules are'} no longer in the catalog and cannot be notified.

} -