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 000000000..66e6ceb9f --- /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 480eea09c..83f418627 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`) and the project's MIDI receive settings ([A fast soak](OCTATRACK_DRIVING.md)). 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. +- **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. - **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 34a476a97..c038dda05 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 1dafcefcd..9dc0d7003 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 dcfcb8bcb..9a49b5dc9 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] [--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 @@ -30,13 +32,32 @@ import { CPU_PRICE_PENDING_PATH, CPU_PRICE_RECORD, FRAME_COSTS_BASE_PATH, FRAME_ 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) { @@ -46,10 +67,17 @@ 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 -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. */ @@ -64,6 +92,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 @@ -90,7 +121,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.atRestAdds) return 'not written: the run was not clean' @@ -98,12 +129,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. @@ -118,8 +149,11 @@ 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' }, limit: { type: 'string', default: String(OVERLOAD) }, 'write-costs': { type: 'boolean' }, stock: { type: 'boolean' }, socket: { type: 'string', default: '/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' }, limit: { type: 'string', default: String(OVERLOAD) }, 'write-costs': { type: 'boolean' }, stock: { type: 'boolean' }, socket: { type: 'string', default: '/tmp/modwerk-dev.sock' }, share: { type: 'string', default: '/tmp/modwerk-share.sock' }, + readings: { type: 'string', default: String(READINGS) }, 'key-bus': { type: 'string' } } }) 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)') @@ -134,20 +168,27 @@ 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 - await send('PLAY w2000 guard') - let text = '' - for (let i = 0; i < 3; i++) { await wait(seconds * 1000 / 3); text += await send('stats') } - const text2 = await send('guard') - await send('STOP w500') - 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 PLAY, a new guard window, a meter reading about every second, the window, STOP. + const measure = async (count = 1) => { + const taken = [] + for (let n = 0; n < count; n++) { + await send('PLAY w2000 guard') + let text = '' + const samples = Math.max(3, Math.round(seconds)) + for (let i = 0; i < samples; i++) { await wait(seconds * 1000 / samples); text += await send('stats') } + const text2 = await send('guard') + await send('STOP w500') + taken.push(reading(text2 + text)) + } + const load = combined(taken) if (!args.memory) return load try { return { ...load, allocation: allocationReading(await send('memory')) } @@ -264,7 +305,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)) @@ -281,7 +322,7 @@ if (import.meta.filename === process.argv[1]) { } if (!result.refused) { 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)] @@ -290,7 +331,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) } @@ -307,15 +348,15 @@ 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 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) 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 27fa6c60f..462849a7c 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, restCost, REST_NOISE, machinePick, stockFit, machineToStatic, pickFailure, priceFileTarget, reading, writePrice } from './octatrack-price.mjs' +import { added, allocationReading, combined, curveFit, 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)', @@ -75,6 +98,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 }) }