diff --git a/docs/INT1B_AUDIO_RELIABILITY_PROFILING_20261120.md b/docs/INT1B_AUDIO_RELIABILITY_PROFILING_20261120.md new file mode 100644 index 000000000..be04b9009 --- /dev/null +++ b/docs/INT1B_AUDIO_RELIABILITY_PROFILING_20261120.md @@ -0,0 +1,44 @@ +# INT-1B — real audio-reliability evidence, no speculative DSP refactor + +**Repository:** [ArSonMix](https://github.com/masarray/arsonmix) · parent [INT-1 #837](https://github.com/masarray/arsonmix/issues/837) +**Scope:** existing single-primary-ASIO native PCM/VST3 graph and approved `/preview/`. No multi-device ASIO, graphical overhaul, changed buffer or auto-tuned audio driver. + +## What actually changed + +1. The existing `LiveAudioEngine::status()` publishes the 13 already-accumulated `RealtimeHealthHistogram` bucket counts, with exact provenance. The audio callback keeps precisely its existing relaxed-atomic histogram update; **no allocations, locks, new timers, IO, COM, driver opens or new render graph**. +2. The existing 1 Hz `AUDIO_HEALTH` log now writes a compact, versioned **parseable JSON subset** of the status already fetched by the message thread. The earlier full status can include long FX/device arrays and exceed the 4096-byte async queue entry. The small health record avoids silent JSON truncation without reducing the original interactive SIGNAL CHECK / COPY FULL REPORT data. The log itself stays on the existing asynchronous worker, is local/private and rotates at 2 MB. +3. `scripts/audio_reliability_profile.mjs` compares **changes between consecutive 1 Hz histogram snapshots**. It outputs per-window p95/p99 **callback deadline bucket ceilings**, over-budget per 1,000 callbacks, late scheduling indicators and device-generation changes. It splits samples whenever a device/route/driver/rate/buffer/mode changes, counters reset, the callback disconnects or the recording has a gap over 5 s. It refuses a DRY/FX comparison when hardware parameters differ. Raw buckets permit real *interval* percentiles rather than a stale lifetime average. +4. Portable regression contracts cover malformed/truncated/legacy records, true 13-bucket delta percentiles, >100% deadline, **actual accepted insert/rack/global bypass classification**, matching dry vs FX, device epoch changes, counter resets and unknown hardware XRUN status. Expensive CI is only required once for the final native candidate, not for each test change. + +## Operator procedure — collect once on an exact Windows build + +Use the new INT-1B installer/portable **only when an exact-SHA Windows FAT artifact exists**. Save your existing `.smix` first. ASIO interface and physical output remain chosen explicitly by you. Start at low headphone volume, never auto-arm speakers. + +1. In the approved native application, open **SIGNAL CHECK**, verify driver, exact input/output pins, rate and buffer. Keep the same ASIO device (for example, 48 kHz / 256 frames) and an accepted CH→MAIN routing. +2. Use the **native GLOBAL FX POWER/BYPASS control** (wait for exact accepted ACK/readback) to bypass all FX for at least **2 minutes**, without a route/device change. The old `dryTest` flag is only UI intent and is **not reliable evidence** that the accepted ChannelId DSP is bypassed. Keep the audio signal continuous. `AUDIO_HEALTH` snapshots are collected automatically at the existing 1 Hz rate without any extra GUI telemetry activity. +3. Enable GLOBAL FX POWER and verify at least one installed native FX insert is **actually processing** (accepted rack/slot/global bypass readback). Keep **identical** driver/device/rate/buffer and monitor level, and record at least **2 minutes**. Mark any audible crackle using **MARK CRACKLE**. Do not conflate manual silence with a dropout. +4. In SIGNAL CHECK choose **OPEN DIAGNOSTIC LOG**. The local `audio-diagnostics.log` contains records. It is **not uploaded** by ArSonMix. On a development machine with Node 20+ and the ArSonMix source, run: + +```powershell +node scripts/audio_reliability_profile.mjs "C:\path\to\audio-diagnostics.log" --json int1b-profile.json --markdown int1b-profile.md +``` + +5. Review private device names or FX details before sharing the Markdown/JSON evidence. If the log rotated, analyze each part separately and compare equivalent driver/rate/buffer conditions. Only a single window with >=30 seconds and accepted physical routing is considered minimally comparable; **120 s per mode recommended** for reliability evidence. Never claim long-run stability from 30 seconds. + +## How to interpret accurately + +- **p95/p99** are *upper limits of coarse callback-processing deadline buckets* based on cumulative-count **deltas**, not exact processing-time percentiles or OS CPU percentage. The >100% bucket remains explicitly unknown/unbounded. +- **Over-budget** means measured callback processing time exceeded its actual block-period budget. **Late callback / gap** refers to START-to-START cadence relative to the *previous* variable JUCE quantum. Both are **indicators**, not proof of an actual render-underrun. +- `backendXrunMeaning=WASAPI_CAPTURE_DISCONTINUITIES_ONLY` is specifically **capture flags**, not DAC starvation. `DRIVER_DEFINED` has driver-dependent semantics. True render-hardware XRUN remains **UNAVAILABLE** through the currently pinned JUCE AudioIODevice API. +- `worstPluginUs` is a **cumulative maximum**, not necessarily measured inside the reported window. No automated causal plugin verdict based solely on that value. +- **Verified DRY vs FX:** DRY means effective accepted processing-insert count `0` across both ChannelId FX **and the original externally leased CH1 vendor/Orbit rack**, either by global/rack/slot bypass or no inserts. FX means effective processing-insert count >0, after native ACK/readback; the legacy `dryTest` flag cannot establish either. A non-auditable external lease is rejected rather than falsely labeled DRY. The DRY interval must immediately precede FX in the SAME app session with no more than 60 seconds of transition; never compare a prior launch or stale archive. Device generation, exact hexadecimal ASIO input/output pin masks, native graph revision, input/output names and channel counts must all match. A mere identical driver name is NOT sufficient. Compare p99 bucket ceiling, over-budget/1000, cadence and audible observations together. Only after an actual regression is observed should the responsible DSP/FX/device/GUI subsystem be optimized with a targeted patch and before/after proof. +- Profiling cannot measure acoustic round-trip latency, DPC/ISR or hard OS page faults; those require independent synchronized hardware/Windows tools. Existing [CrackleEvidenceWindow](../engine/diagnostics/CrackleEvidenceWindow.h) and [Windows GUI sampling](../scripts/collect_gui_perf_windows.ps1) remain separate instruments. + +## Exit gates + +- Windows MSVC Release + native CTest + quick source contracts at exact SHA, controlled release artifact installation/upgrade/uninstall **when a user-test binary is required**. +- Read `audio-diagnostics.log` from that exact user-installed binary; assert parseable profile counts, no log truncation and retained device/session/provenance. +- **Physical hardware FAT** (ASIO driver model, hardware, listening, glitch markers, loaded VST3 chain) must be reported PASS/FAIL/NOT RUN. Never infer physical FAT from CI. +- I/O #825/#830 and Graphic EQ #835 remain distinct experiments; no dual-ASIO UI claim. + +**Measured source-workload win:** one existing native status read and 1 Hz asynchronous log write are reused, instead of adding a callback probe, UI polling timer or another audio thread. Without real hardware evidence this does not justify a numerical reduction in CPU, latency or XRUN. diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index e28eb2243..03174bab4 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -178,6 +178,11 @@ class DynamicChannelFxLeaseBank final { std::uint64_t revision() const noexcept{return revision_;} std::size_t lanes() const noexcept{return rows_.size();} ChannelId externalChannel() const noexcept{return external_.id;} + // Read-only CONTROL-plane visibility of the EXACT accepted external + // render lease. No refcount, mutation or render-side ownership change. + const ExternalLease* externalLeaseForControl() const noexcept { + return external_.valid() ? &external_ : nullptr; + } std::size_t insertCount(ChannelId id) const noexcept { const auto* p=find(id);return p?p->count:0; } diff --git a/scripts/audio_reliability_profile.mjs b/scripts/audio_reliability_profile.mjs new file mode 100644 index 000000000..bdd74c8ac --- /dev/null +++ b/scripts/audio_reliability_profile.mjs @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// INT-1B: offline-only analyzer for the 1 Hz AUDIO_HEALTH native diagnostic log. +// NEVER runs in the JUCE audio callback, opens devices, or uploads evidence. +import {readFileSync, writeFileSync} from "node:fs"; +import {resolve} from "node:path"; +import {pathToFileURL} from "node:url"; + +export const SCHEMA="arsonmix.audio-health.int1b.v1"; +export const BUCKET_UPPER=[1,2,4,8,12,20,30,40,55,70,85,100,null]; +const COUNTERS=["callbackCount","overBudgetCount","slowCallbackCount", + "lateCallbackIntervals","callbackGapCount","callbackCadenceClockRegressions", + "deviceStartCount","deviceStopCount"]; +const isCount=x=>Number.isSafeInteger(x)&&x>=0; +const finitePositive=x=>typeof x==="number"&&Number.isFinite(x)&&x>0; +const percent=(a,b)=>b>0?Math.round(10000*a/b)/100:null; + +export function parseHealthLog(log) { + const samples=[], warnings=[], rejectedLines=[]; + let sessionId=0; + for(const [idx,line] of String(log).split(/\r?\n/).entries()){ + if(/ \| SESSION \| started\s*$/.test(line)){sessionId++;continue;} + if(!line.includes(" | AUDIO_HEALTH | "))continue; + const m=/^(\S+) \| AUDIO_HEALTH \| (\{.*\})$/.exec(line); + if(!m){warnings.push("line "+(idx+1)+": malformed/truncated AUDIO_HEALTH");rejectedLines.push(idx+1);continue;} + let sample; + try {sample=JSON.parse(m[2]);} + catch {warnings.push("line "+(idx+1)+": invalid AUDIO_HEALTH JSON");rejectedLines.push(idx+1);continue;} + if(!sample || typeof sample!=="object" || Array.isArray(sample) || + sample.schema!==SCHEMA){ + warnings.push("line "+(idx+1)+": legacy/unknown schema (excluded)"); + rejectedLines.push(idx+1); + continue; + } + const time=Date.parse(m[1]); + if(!Number.isFinite(time)||!finitePositive(sample.rate)|| + !isCount(sample.buffer)||sample.buffer===0|| + !isCount(sample.deviceGeneration)||!isCount(sample.callbackCount)|| + typeof sample.liveBackendClass!=="string" || + typeof sample.dryTest!=="boolean" || typeof sample.connected!=="boolean" || + typeof sample.nativeGlobalFxBypassed!=="boolean" || + !isCount(sample.nativeFxInstalledCount) || + !isCount(sample.nativeFxProcessingCount) || + sample.nativeFxProcessingCount>sample.nativeFxInstalledCount || + sample.nativeFxActivityComplete!==true || + typeof sample.nativeExternalCh1Leased!=="boolean" || + !isCount(sample.nativeExternalCh1InstalledCount) || + !isCount(sample.nativeExternalCh1ProcessingCount) || + sample.nativeExternalCh1ProcessingCount>sample.nativeExternalCh1InstalledCount || + sample.nativeExternalCh1InstalledCount>sample.nativeFxInstalledCount || + sample.nativeExternalCh1ProcessingCount>sample.nativeFxProcessingCount || + (!sample.nativeExternalCh1Leased && sample.nativeExternalCh1InstalledCount!==0) || + (sample.nativeGlobalFxBypassed && sample.nativeFxProcessingCount!==0) || + typeof sample.nativeFxGraphRevision!=="string" || + !/^\d+$/.test(sample.nativeFxGraphRevision) || + typeof sample.activeInputMaskHex!=="string" || + typeof sample.activeOutputMaskHex!=="string" || + !/^[0-9a-f]*$/i.test(sample.activeInputMaskHex) || + !/^[0-9a-f]*$/i.test(sample.activeOutputMaskHex)){ + warnings.push("line "+(idx+1)+": invalid source metadata/counters"); + rejectedLines.push(idx+1); + continue; + } + const buckets=sample.callbackBudgetBuckets; + if(!Array.isArray(buckets)||buckets.length!==13||!buckets.every(isCount)){ + warnings.push("line "+(idx+1)+": missing/invalid 13 histogram buckets"); + rejectedLines.push(idx+1); + continue; + } + if(!COUNTERS.every(key=>isCount(sample[key]))){ + warnings.push("line "+(idx+1)+": missing/invalid cumulative counter"); + rejectedLines.push(idx+1); + continue; + } + samples.push({...sample,atMs:time,line:idx+1,sessionId}); + } + return {samples,warnings,rejectedLines}; +} + +export function p95p99FromDelta(counts) { + if(!Array.isArray(counts)||counts.length!==13||!counts.every(isCount)) + return {p95:null,p99:null,samples:0}; + const total=counts.reduce((n,x)=>n+x,0); + if(!Number.isSafeInteger(total)||total===0) + return {p95:null,p99:null,samples:0}; + const bound=percentile=>{ + const target=Math.ceil(total*percentile); + let seen=0; + for(let i=0;i<13;i++){ + seen+=counts[i]; + if(seen>=target)return BUCKET_UPPER[i]; + } + return null; + }; + return {p95:bound(0.95),p99:bound(0.99),samples:total}; +} + +// Immutable hardware/graph provenance must survive the DRY -> FX switch. +// Mode keys are separate so only the actual accepted global power transition +// can bridge adjacent windows; all other boundary reasons invalidate pairing. +const STABLE_SCOPE_KEYS=[ + "sessionId","deviceGeneration","device","liveBackendClass","driver","rate","buffer", + "inputDevice","outputDevice","deviceInputChannels","deviceOutputChannels", + "activeInputMaskHex","activeOutputMaskHex","nativeFxGraphRevision", + "nativeFxInstalledCount","nativeExternalCh1Leased","nativeExternalCh1InstalledCount", + "connected","diagnosticRoute","productionRoutingState","directRouteAuthorized", + "backendXrunMeaning" +]; +const MODE_KEYS=[ + "nativeFxProcessingCount","nativeGlobalFxBypassed", + "nativeExternalCh1ProcessingCount","dryTest" +]; +const sameValues=(a,b,keys)=>keys.every(k=>a[k]===b[k]); +const nondecreasing=(a,b,key)=>isCount(a[key])&&isCount(b[key])&&b[key]>=a[key]; +const continuousEvidence=(a,b)=>b.atMs>a.atMs && b.atMs-a.atMs<=5000 && + COUNTERS.every(k=>nondecreasing(a,b,k))&& + a.callbackBudgetBuckets.every((x,i)=>b.callbackBudgetBuckets[i]>=x); +const validInterval=(a,b)=>continuousEvidence(a,b) && + sameValues(a,b,STABLE_SCOPE_KEYS)&&sameValues(a,b,MODE_KEYS); +const acceptedGlobalPowerTransition=(a,b)=>continuousEvidence(a,b) && + sameValues(a,b,STABLE_SCOPE_KEYS) && a.connected===true && b.connected===true && + a.nativeGlobalFxBypassed===true && b.nativeGlobalFxBypassed===false && + a.nativeFxProcessingCount===0 && b.nativeFxProcessingCount>0; + +function describeSegment(segment){ + const s=segment.start, first=segment.start, last=segment.last; + const p=p95p99FromDelta(segment.histogram); + const callbacks=segment.delta.callbackCount, period=1000000*s.buffer/s.rate; + const durationSeconds=Math.round(segment.durationMs/100)/10; + const missing=segment.intervals===0||p.samples===0; + const over=segment.delta.overBudgetCount,late=segment.delta.lateCallbackIntervals; + const gap=segment.delta.callbackGapCount; + let diagnosis="INSUFFICIENT_EVIDENCE"; + if(!missing){ + if(segment.delta.deviceStopCount>0||segment.delta.deviceStartCount>0) + diagnosis="DEVICE_LIFECYCLE_CHANGE"; + else if(over>0&&late>0)diagnosis="BOTH_DSP_BUDGET_AND_SCHEDULING_INDICATORS"; + else if(over>0)diagnosis="DSP_BUDGET_PRESSURE_INDICATOR"; + else if(late>0||gap>0)diagnosis="CALLBACK_SCHEDULING_INDICATOR"; + else diagnosis="NO_HOST_TIMING_ANOMALY_OBSERVED"; + } + return { + // The legacy dryTest control is only a UI intent; actual DRY/FX is + // derived from accepted native INSERT+rack+GLOBAL bypass readback. + lineStart:first.line,lineEnd:last.line, + invalidBefore:segment.invalidBefore, + sessionId:s.sessionId,startedAt:new Date(first.atMs).toISOString(), + endedAt:new Date(last.atMs).toISOString(), + startTimeMs:first.atMs,endTimeMs:last.atMs, + mode:s.nativeFxProcessingCount===0?"DRY":"FX", + nativeFxInstalledCount:s.nativeFxInstalledCount, + nativeFxProcessingCount:s.nativeFxProcessingCount, + nativeGlobalFxBypassed:s.nativeGlobalFxBypassed, + nativeExternalCh1Leased:s.nativeExternalCh1Leased, + nativeExternalCh1InstalledCount:s.nativeExternalCh1InstalledCount, + nativeExternalCh1ProcessingCount:s.nativeExternalCh1ProcessingCount, + device:String(s.device??"UNKNOWN"),backend:s.liveBackendClass, + inputDevice:s.inputDevice??"UNKNOWN",outputDevice:s.outputDevice??"UNKNOWN", + inputMask:s.activeInputMaskHex,outputMask:s.activeOutputMaskHex, + nativeFxGraphRevision:s.nativeFxGraphRevision, + inputChannels:s.deviceInputChannels??null, + outputChannels:s.deviceOutputChannels??null, + sampleRate:s.rate,bufferFrames:s.buffer,periodUs:Math.round(period*10)/10, + deviceGeneration:s.deviceGeneration, + diagnosticRoute:s.diagnosticRoute??"UNKNOWN", + productionRoutingState:s.productionRoutingState??"UNKNOWN", + directRouteAuthorized:s.directRouteAuthorized===true, + durationSeconds,intervals:segment.intervals,callbackCount:callbacks, + windowHistogramSamples:p.samples, + p95BudgetUpperPct:p.p95,p99BudgetUpperPct:p.p99, + overBudgetCallbacks:over,overBudgetPer1000:callbacks?Math.round(100000*over/callbacks)/100:null, + slowCallbacks:segment.delta.slowCallbackCount, + lateCallbackIntervals:late,callbackGaps:gap, + clockRegressions:segment.delta.callbackCadenceClockRegressions, + deviceStarts:segment.delta.deviceStartCount,deviceStops:segment.delta.deviceStopCount, + pluginWorstUsCumulative:last.worstPluginUs??null, + backendXrunMeaning:s.backendXrunMeaning??"UNAVAILABLE", + backendXrunDelta:nondecreasing(first,last,"backendXrunCount")? + last.backendXrunCount-first.backendXrunCount:null, + renderHardwareXrun:"UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE", + diagnosis,comparable:!missing&&durationSeconds>=30&&callbacks>0&& + s.connected===true&& + s.productionRoutingState==="NATIVE_ROUTE_ACCEPTED"&& + s.directRouteAuthorized===true, + notes:["Actual DRY/FX includes admitted external CH1 vendor leases and the accepted ChannelId insert-bypass readback.", + "Actual DRY/FX is accepted native insert-bypass readback, NOT the dryTest UI flag.", + "Host callback p95/p99 are bucket CEILINGS, not exact CPU utilization.", + "Callback cadence/over-budget are indicators, not driver render XRUN.", + "Device/driver capture discontinuities are backend-specific.", + "Reported plugin worst time can predate this window; it is not an interval peak."] + }; +} + +export function analyzeHealthLog(log) { + const {samples,warnings,rejectedLines}=parseHealthLog(log); + const groups=[]; + let segment=null; + const start=(s,invalidBefore=false)=>({start:s,last:s,intervals:0,durationMs:0, + delta:Object.fromEntries(COUNTERS.map(k=>[k,0])), + histogram:Array(13).fill(0),invalidBefore}); + for(const current of samples){ + if(!segment){segment=start(current);continue;} + // Rejected telemetry is an absolute comparison barrier, including a + // failed opaque vendor lease. Only an uninterrupted *accepted* global + // bypass ON -> OFF transition may connect a DRY/FX pair. + const missingBetween=rejectedLines.some(line=>line>segment.last.line&&lines.comparable&& + s.diagnosticRoute==="NORMAL"&&s.renderHardwareXrun==="UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE"); + // Pair only an immediately preceding accepted DRY window with the next + // accepted FX window. Never compare an earlier app session, an unrelated + // third run, or a hours-old source recording with today's loaded inserts. + const fxIndex=analysis.segments.findLastIndex(s=>ready.includes(s) && + s.mode==="FX" && s.nativeFxInstalledCount>0 && s.nativeFxProcessingCount>0); + const fx=fxIndex>=0?analysis.segments[fxIndex]:null; + const dry=fxIndex>0?analysis.segments[fxIndex-1]:null; + if(!fx||!dry||!dry.comparable||fx.invalidBefore||dry.mode!=="DRY"|| + dry.diagnosticRoute!=="NORMAL") + return {comparable:false,reason:"Need contiguous real NORMAL/DRY then NORMAL/FX windows, each >=30s."}; + if(dry.sessionId!==fx.sessionId || + fx.startTimeMs60000) + return {comparable:false,reason:"DRY/FX windows belong to different app sessions or are more than 60s apart."}; + for(const key of ["backend","device","inputDevice","outputDevice", + "sessionId","deviceGeneration","nativeFxGraphRevision", + "inputMask","outputMask","inputChannels","outputChannels", + "sampleRate","bufferFrames"]){ + if(dry[key]!==fx[key])return {comparable:false,reason:"Mismatched "+key+": do not compare unlike hardware profiles."}; + } + return {comparable:true,baseline:"DRY",candidate:"FX", + device:dry.device,sampleRate:dry.sampleRate,bufferFrames:dry.bufferFrames, + dry:{p95:dry.p95BudgetUpperPct,p99:dry.p99BudgetUpperPct, + overBudgetPer1000:dry.overBudgetPer1000,late:dry.lateCallbackIntervals}, + fx:{p95:fx.p95BudgetUpperPct,p99:fx.p99BudgetUpperPct, + overBudgetPer1000:fx.overBudgetPer1000,late:fx.lateCallbackIntervals}, + deltaOverBudgetPer1000:Math.round(100*(fx.overBudgetPer1000-dry.overBudgetPer1000))/100, + qualification:"HOST_TIMING_ONLY_NOT_PHYSICAL_XRUN_OR_ROUND_TRIP_FAT"}; +} + +export function markdownReport(analysis){ + const cmp=compareDryFx(analysis); + const lines=["# ArSonMix INT-1B — Audio Reliability Profile","", + "This is native host timing, not physical render-XRUN, GPU, ASIO round-trip or CPU profiling.", + "Real hardware FAT and operator listening remain separately required.","", + "| Mode | Driver | Rate/Frames | Seconds | p95/p99 budget ceiling | Over-budget/1000 | Late callback | Observation |", + "|---|---|---|---:|---:|---:|---:|---|"]; + for(const s of analysis.segments){ + const pct=x=>x===null?">100% / N/A":x+"%"; + lines.push("| "+s.mode+" | "+s.backend+" | "+s.sampleRate+"/"+s.bufferFrames+ + " | "+s.durationSeconds+" | "+pct(s.p95BudgetUpperPct)+"/"+pct(s.p99BudgetUpperPct)+ + " | "+(s.overBudgetPer1000??"N/A")+" | "+s.lateCallbackIntervals+ + " | "+s.diagnosis+" |"); + } + lines.push("",cmp.comparable? + "**Matched actual native dry→FX comparison:** Δ over-budget per 1000 callbacks = "+cmp.deltaOverBudgetPer1000+ + "; **NOT** a hardware XRUN or causal DSP proof.": + "**No valid matched dry/FX comparison:** "+cmp.reason); + if(analysis.warnings.length)lines.push("","Data warnings: "+analysis.warnings.slice(0,12).join("; ")); + lines.push("","Only optimize the measured problematic path; keep primary ASIO direct and one PCM/FX graph."); + return lines.join("\n")+"\n"; +} + +function main(args){ + if(!args.length||args.includes("--help")){ + process.stdout.write("Usage: node scripts/audio_reliability_profile.mjs audio-diagnostics.log [--json report.json] [--markdown report.md]\n"); + return args.includes("--help")?0:2; + } + const input=args[0]; + const opt=name=>{const i=args.indexOf(name);return i>=0?args[i+1]:null;}; + if(args.some((x,i)=>x.startsWith("--")&& + (!["--json","--markdown"].includes(x)||!args[i+1]))) + throw Error("Invalid output option; use --json FILE or --markdown FILE"); + const result=analyzeHealthLog(readFileSync(input,"utf8")); + if(result.totalSamples===0)throw Error("No valid INT-1B AUDIO_HEALTH snapshots; check schema/log rotation"); + const json=opt("--json"), md=opt("--markdown"); + if(json)writeFileSync(json,JSON.stringify({...result,dryFxComparison:compareDryFx(result)},null,2)+"\n"); + if(md)writeFileSync(md,markdownReport(result)); + if(!json&&!md)process.stdout.write(markdownReport(result)); + return 0; +} +if(process.argv[1]&&import.meta.url===pathToFileURL(resolve(process.argv[1])).href){ + try {process.exitCode=main(process.argv.slice(2));} + catch(err){console.error("INT1B_PROFILE_ERROR: "+err.message);process.exitCode=1;} +} diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 42951518e..867d91003 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -2518,7 +2518,96 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback auto* d = dual ? independent_.renderDevice() : deviceManager_.getCurrentAudioDevice(); auto* capture = dual ? independent_.captureDevice() : d; - o->setProperty ("dryRoutingLab",dryRoutingLab_.status(capture)); + const auto nativeRoutingStatus = dryRoutingLab_.status(capture); + o->setProperty ("dryRoutingLab", nativeRoutingStatus); + // INT-1B: native DRY is an accepted DSP fact, NOT the legacy + // dryTest_ UI flag (which only tracks operator intent). + // Count installed/effectively processing inserts from the already + // generated CONTROL readback. No extra render/FX scan on RT. + const bool globalFxBypassed = dryRoutingLab_.globalFxBypassed(); + int installedNativeFx = 0, processingNativeFx = 0; + const auto accountInserts = [&] (const juce::var& inserts, + bool rackBypassed) + { + if (const auto* list = inserts.getArray()) + for (const auto& insert : *list) + if (insert.isObject()) + { + ++installedNativeFx; + if (!globalFxBypassed && !rackBypassed && + !bool (insert.getProperty ("bypassed", false))) + ++processingNativeFx; + } + }; + const auto bus = nativeRoutingStatus.getProperty ("nativeBus", {}); + if (bus.isObject()) + { + const auto channelRows = bus.getProperty ("channels", {}); + if (const auto* channels = channelRows.getArray()) + for (const auto& channel : *channels) + accountInserts ( + channel.getProperty ("inserts", {}), + bool (channel.getProperty ("fxRackBypassed", false))); + } + else + { + const auto rackFlags = + nativeRoutingStatus.getProperty ("fxRackBypassed", {}); + const auto* flags = rackFlags.getArray(); + const auto rackInstances = + nativeRoutingStatus.getProperty ("fxInstances", {}); + if (const auto* racks = rackInstances.getArray()) + for (int lane = 0; lane < racks->size(); ++lane) + accountInserts ((*racks)[lane], + flags != nullptr && lane < flags->size() + && bool ((*flags)[lane])); + } + // Original Channel 1 vendor/Orbit inserts are one SHARED Graph + // leased by the admitted ChannelId renderer, not ordinary entries + // of nativeBus.channels[].inserts. Those entries are intentionally + // zero for the external channel. Never report the live vendor rack + // as DRY simply because its FX live in a distinct native lease. + int externalCh1Installed = 0, externalCh1Processing = 0; + const auto* acceptedExternal = + dryRoutingLab_.acceptedOriginalCh1ExternalLeaseForControl(); + // Admit only OUR historical JUCE Graph callback. Future external + // lease types must not be cast into Graph or falsely labeled DRY. + const bool externalCh1Leased = acceptedExternal != nullptr && + acceptedExternal->render == &processOwnedChannelOne; + const bool externalFxActivityComplete = + !bool (nativeRoutingStatus.getProperty ( + "originalCh1GraphLeased", false)) || externalCh1Leased; + if (externalCh1Leased) + { + const auto* acceptedGraph = + static_cast (acceptedExternal->context); + const bool externalRackBypassed = + acceptedGraph->rackBypassed.load (std::memory_order_acquire); + for (int i = 0; i < acceptedGraph->count; ++i) + { + const int physical = acceptedGraph->physicalAt (i); + if (!acceptedGraph->slots[physical].processor) + continue; + ++externalCh1Installed; + if (!globalFxBypassed && !externalRackBypassed && + !acceptedGraph->bypassFlags[physical].load ( + std::memory_order_acquire)) + ++externalCh1Processing; + } + installedNativeFx += externalCh1Installed; + processingNativeFx += externalCh1Processing; + } + o->setProperty ("nativeFxActivityComplete", externalFxActivityComplete); + o->setProperty ("nativeExternalCh1Leased", externalCh1Leased); + o->setProperty ("nativeExternalCh1InstalledCount", externalCh1Installed); + o->setProperty ("nativeExternalCh1ProcessingCount", externalCh1Processing); + o->setProperty ("nativeGlobalFxBypassed", globalFxBypassed); + o->setProperty ("nativeFxInstalledCount", installedNativeFx); + o->setProperty ("nativeFxProcessingCount", processingNativeFx); + o->setProperty ("nativeFxCountProvenance", + "ACCEPTED_CHANNELID_PLUS_LEASED_EXTERNAL_CH1_SLOT_RACK_GLOBAL_BYPASS_NOT_dryTest"); + o->setProperty ("nativeFxGraphRevision", + nativeRoutingStatus.getProperty ("revision", {}).toString()); o->setProperty("waitingAsioInputs",dryRoutingLab_.waitingAsioInputCount()); // NORMAL mode is never silently served by the legacy CH1 fallback. // This state is for operator feedback; it does not authorize output. @@ -2627,6 +2716,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("outputDevice", dual && d ? d->getName() : setup.outputDeviceName); o->setProperty ("deviceInputChannels", capture ? capture->getActiveInputChannels().countNumberOfSetBits() : 0); o->setProperty ("deviceOutputChannels", d ? d->getActiveOutputChannels().countNumberOfSetBits() : 0); + // Control-only pin-mask evidence: matching channel COUNTS do not + // imply the same physical ASIO pin assignment after a remap. + o->setProperty ("activeInputMaskHex", capture ? + capture->getActiveInputChannels().toString (16) : juce::String()); + o->setProperty ("activeOutputMaskHex", d ? + d->getActiveOutputChannels().toString (16) : juce::String()); o->setProperty ("callbackInputChannels", callbackInputs_.load()); o->setProperty ("callbackOutputChannels", callbackOutputs_.load()); o->setProperty ("callbackCount", static_cast (callbackCount_.load())); @@ -2663,6 +2758,16 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("callbackP95BeyondDeadline", histogram.p95Ceiling < 0); o->setProperty ("callbackP99BeyondDeadline", histogram.p99Ceiling < 0); o->setProperty ("callbackBudgetSamples", static_cast (histogram.total)); + // INT-1B: cumulative buckets enable true 1 Hz interval percentiles + // without resetting/replacing RT atomics at ASIO device transitions. + // The message thread alone allocates this 13-value readback array. + // Never label these host callback timing buckets as hardware XRUNs. + juce::Array budgetBuckets; + for (const auto count : histogram.counts) + budgetBuckets.add (static_cast (count)); + o->setProperty ("callbackBudgetBuckets", juce::var (budgetBuckets)); + o->setProperty ("callbackBudgetBucketProvenance", + "HOST_CALLBACK_BUDGET_CUMULATIVE_13_BUCKETS_NOT_DRIVER_RENDER_XRUN"); o->setProperty ("inputPeak", inputPeak_.load()); o->setProperty ("inputPeakProvenance", "RAW_PCM_BEFORE_HARDWARE_MUTE"); // First Sound: JUCE supplies callback-COMPACT input channels. diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 418465e7b..f0a9dd71d 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1499,6 +1499,20 @@ class LiveDryRoutingLab final { nativeAccepted_.fxOwners->externalChannel()==target && target==nativeAccepted_.graph.ids.inputs[0]; } + // Off-RT diagnostic only: do not infer the active external vendor Graph + // from the latest graphOwned_ pointer, which can differ during a staged + // FX handoff. Read the strong, accepted PCM lease under CONTROL instead. + const armix::mixer::DynamicChannelFxLeaseBank::ExternalLease* + acceptedOriginalCh1ExternalLeaseForControl() const noexcept + { + if (!channelIdPhysicalPcmActive() || !nativeAccepted_.fxOwners) + return nullptr; + const auto* lease = + nativeAccepted_.fxOwners->externalLeaseForControl(); + return lease != nullptr && + lease->id == nativeAccepted_.graph.ids.inputs[0] + ? lease : nullptr; + } // Single global A/B override for M4 and the authoritative ChannelId PCM // graph. Never rewrite saved rack/slot bypass flags or rebuild processors. // A physical ACK requires an accepted CURRENT epoch/revision. diff --git a/src/Main.cpp b/src/Main.cpp index 90e6965a2..dc4f51ad0 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -852,6 +852,47 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return out; } + // INT-1B: preserve a parseable, bounded 1 Hz native health timeline. + // The entire UI status contains large device/FX arrays and can exceed the + // diagnostic worker's 4096-byte record; silently truncated JSON makes + // offline p95/p99 profiling impossible. Reuse the EXISTING status read, + // only on the message thread, with no new timer or audio callback work. + static juce::var makeAudioHealthRecord (const juce::var& state) + { + auto compact = std::make_unique(); + compact->setProperty ("schema", "arsonmix.audio-health.int1b.v1"); + for (const char* key : { + "connected", "liveBackendClass", "device", "driver", + "inputDevice", "outputDevice", "deviceInputChannels", + "deviceOutputChannels", "activeInputMaskHex", + "activeOutputMaskHex", "rate", "buffer", "periodUs", + "deviceGeneration", + "deviceStartCount", "deviceStopCount", "diagnosticRoute", + "productionRoutingState", "directRouteAuthorized", + "dryTest", "nativeGlobalFxBypassed", + "nativeFxInstalledCount", "nativeFxProcessingCount", + "nativeFxCountProvenance", "nativeFxGraphRevision", + "nativeExternalCh1Leased", "nativeExternalCh1InstalledCount", + "nativeExternalCh1ProcessingCount", + "nativeFxActivityComplete", + "callbackCount", "callbackBudgetBuckets", + "callbackBudgetBucketProvenance", "callbackBudgetSamples", + "callbackP95BudgetUpperPct", "callbackP99BudgetUpperPct", + "slowCallbackCount", "overBudgetCount", "callbackGapCount", + "lateCallbackIntervals", "callbackCadenceClockRegressions", + "callbackCadenceComparedIntervals", "worstCallbackUs", + "worstPluginUs", "slowPluginCount", + "backendXrunCount", "backendXrunMeaning", + "renderUnderrunSource", "secondaryOutputUnderflow", + "secondaryOutputOverflow", "secondaryOutputFrames"}) + { + const auto value = state.getProperty (key, {}); + if (!value.isVoid()) + compact->setProperty (juce::Identifier (key), value); + } + return juce::var (compact.release()); + } + static juce::String compactMemoryWindowReport ( const armix::diagnostics::CrackleEvidenceWindow::Window& window) { @@ -7820,7 +7861,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { const auto health = engine_.status(); crackleEvidence_.push (makeEvidenceSample (health)); - diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (health, false)); + diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (makeAudioHealthRecord (health), false)); } if (deviceSettingsDirty_) @@ -8016,7 +8057,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if (timerTicks_ % 12 == 0) { crackleEvidence_.push (makeEvidenceSample (state)); - diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (state, false)); + diagnostics_.record ("AUDIO_HEALTH", juce::JSON::toString (makeAudioHealthRecord (state), false)); } // Guard borrowed VST parameter pointers when a native graph edit, // device epoch change or Show recall retires the instance. diff --git a/tests/direct_restore_recovery_contract_test.mjs b/tests/direct_restore_recovery_contract_test.mjs index 5f7d97c9f..a59b8202d 100644 --- a/tests/direct_restore_recovery_contract_test.mjs +++ b/tests/direct_restore_recovery_contract_test.mjs @@ -110,8 +110,13 @@ test('ASIO/WASAPI DIRECT authorizes the exact active input/output channel map',( const fence=read('engine/device/DirectRouteFence.h'); // Bind BOTH untruncated JUCE BigInteger masks at startup, manual selection, // and verified DIRECT restore, rather than only the friendly device name. - assert.equal(engine.split('getActiveInputChannels().toString (16)').length-1,3); - assert.equal(engine.split('getActiveOutputChannels().toString (16)').length-1,3); + // INT-1B reads the same two untruncated masks once more on CONTROL + // for evidence-only status. Retain ALL three exact direct-fence checks + // below: telemetry is not authorization to arm a different device. + assert.equal(engine.split('getActiveInputChannels().toString (16)').length-1,4); + assert.equal(engine.split('getActiveOutputChannels().toString (16)').length-1,4); + assert.match(engine, /setProperty \("activeInputMaskHex"/); + assert.match(engine, /setProperty \("activeOutputMaskHex"/); for (const operation of ['approve','resumeExpected','observeStart']) { // Match the verified native device/mask inputs independently of cosmetic // line wrapping introduced by the ASIO control-plane identity guard. diff --git a/tests/smart_audio_diagnostic_contract_test.mjs b/tests/smart_audio_diagnostic_contract_test.mjs index 7865acd51..f3b004b0b 100644 --- a/tests/smart_audio_diagnostic_contract_test.mjs +++ b/tests/smart_audio_diagnostic_contract_test.mjs @@ -2,6 +2,7 @@ // Permanent source contracts. CPU/FIFO functional correctness is independently // tested by Release-active native CTest, not source regexes alone. import test from 'node:test'; +import {analyzeHealthLog,compareDryFx,p95p99FromDelta,parseHealthLog,markdownReport,SCHEMA} from '../scripts/audio_reliability_profile.mjs'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; const read = p=>readFileSync(p,'utf8'); @@ -145,3 +146,257 @@ test('P0 capture block-head evidence is a single-pass RT heuristic, not invented assert.match(fixture,/100000/); assert.match(cmake,/add_test\(NAME P0CaptureZeroHeadBoundaryCandidates COMMAND ARMixCaptureBoundaryTests\)/); }); + + +// INT-1B: a real 1Hz log reader with deterministic native-source fixtures. +function int1bSample(second,{dryTest=true,deviceGeneration=2,device="ASIO Driver", + rate=48000,buffer=256,over=0,late=0,connected=true, + nativeGlobalFxBypassed=dryTest, + nativeFxProcessingCount=nativeGlobalFxBypassed?0:1, + nativeExternalCh1Leased=false, + nativeExternalCh1InstalledCount=0, + nativeExternalCh1ProcessingCount=0}={}) { + const cumulative=(second+1)*100; + const buckets=Array(13).fill(0); + buckets[3]=cumulative-over; + buckets[12]=over; + return {schema:SCHEMA,connected,liveBackendClass:"ASIO_DIRECT_ZERO_EXTRA_FIFO", + driver:"ASIO",device,inputDevice:"Interface Input",outputDevice:"Interface Output", + deviceInputChannels:2,deviceOutputChannels:2, + activeInputMaskHex:"3",activeOutputMaskHex:"3", + nativeFxGraphRevision:"100", + rate,buffer,periodUs:1000000*buffer/rate, + deviceGeneration,deviceStartCount:deviceGeneration,deviceStopCount:0, + diagnosticRoute:"NORMAL",productionRoutingState:"NATIVE_ROUTE_ACCEPTED", + directRouteAuthorized:true,dryTest, + nativeGlobalFxBypassed,nativeFxInstalledCount:1,nativeFxProcessingCount, + nativeFxActivityComplete:true, + nativeExternalCh1Leased,nativeExternalCh1InstalledCount, + nativeExternalCh1ProcessingCount, + callbackCount:cumulative, + callbackBudgetBuckets:buckets,overBudgetCount:over,slowCallbackCount:over, + lateCallbackIntervals:late,callbackGapCount:0, + callbackCadenceClockRegressions:0,backendXrunMeaning:"UNAVAILABLE", + renderUnderrunSource:"UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE"}; +} +function int1bLine(second,properties){ + return new Date(Date.UTC(2026,10,20,8,0,second)).toISOString()+ + ' | AUDIO_HEALTH | '+JSON.stringify(int1bSample(second,properties)); +} +test('INT-1B native log is bounded and uses one existing off-RT 1Hz snapshot',()=>{ + assert.match(engine,/callbackBudgetBuckets/); + assert.match(engine,/HOST_CALLBACK_BUDGET_CUMULATIVE_13_BUCKETS_NOT_DRIVER_RENDER_XRUN/); + assert.match(host,/arsonmix\.audio-health\.int1b\.v1/); + assert.match(engine,/nativeFxProcessingCount/); + assert.match(engine,/dryRoutingLab_\.globalFxBypassed\(\)/); + assert.match(host,/nativeFxInstalledCount/); + assert.match(engine,/originalCh1GraphLeased/); + assert.match(engine,/acceptedGraph->rackBypassed\.load/); + assert.match(engine,/acceptedGraph->bypassFlags\[physical\]\.load/); + assert.match(host,/nativeExternalCh1InstalledCount/); + assert.match(engine,/acceptedOriginalCh1ExternalLeaseForControl\(\)/); + assert.match(engine,/acceptedExternal->render == &processOwnedChannelOne/); + assert.match(engine,/nativeFxActivityComplete/); + assert.match(host,/nativeFxActivityComplete/); + assert.match(engine,/nativeFxGraphRevision/); + assert.match(engine,/activeInputMaskHex/); + assert.match(host,/makeAudioHealthRecord \(const juce::var& state\)/); + assert.match(host,/juce::JSON::toString \(makeAudioHealthRecord \(health\), false\)/); + assert.match(host,/juce::JSON::toString \(makeAudioHealthRecord \(state\), false\)/); + assert.doesNotMatch(engine,/realtimeHistogram_\.reset\(/); + assert.ok(int1bLine(0,{dryTest:false}).length<4096, + 'single schema record fits existing rotating log queue'); +}); +test('INT-1B interval histogram is a 13-bin delta, not cumulative p99',()=>{ + const pct=p95p99FromDelta([0,0,0,950,0,0,0,0,0,0,0,0,50]); + assert.equal(pct.p95,8); + assert.equal(pct.p99,null); // over deadline, never fabricate 100% p99 + assert.equal(pct.samples,1000); + assert.equal(p95p99FromDelta(Array(13).fill(0)).p95,null); + assert.equal(p95p99FromDelta([1]).samples,0); +}); +test('INT-1B dry vs FX matched 60s evidence and no fabricated physical XRUN',()=>{ + const lines=[]; + for(let s=0;s<=60;s++)lines.push(int1bLine(s,{dryTest:true})); + // Separate 1Hz capture, same physical driver/port/rate/buffer but FX chain. + for(let s=61;s<=122;s++)lines.push(int1bLine(s,{ + dryTest:false,over:(s-61)*4,late:s-61 + })); + const report=analyzeHealthLog(lines.join('\n')); + assert.equal(report.totalSamples,123); + assert.equal(report.segments.length,2); + assert.equal(report.segments[0].durationSeconds,60); + assert.equal(report.segments[0].p99BudgetUpperPct,8); + assert.equal(report.segments[0].overBudgetCallbacks,0); + assert.equal(report.segments[1].p99BudgetUpperPct,null); + assert.equal(report.segments[1].overBudgetPer1000,40); + assert.equal(report.segments[0].nativeGlobalFxBypassed,true); + assert.equal(report.segments[0].nativeFxProcessingCount,0); + assert.equal(report.segments[1].nativeFxProcessingCount,1); + assert.equal(report.segments[1].diagnosis, + 'BOTH_DSP_BUDGET_AND_SCHEDULING_INDICATORS'); + assert.equal(report.segments[1].renderHardwareXrun, + 'UNAVAILABLE_THROUGH_CURRENT_JUCE_AUDIODEVICE'); + const compared=compareDryFx(report); + assert.equal(compared.comparable,true); + assert.equal(compared.deltaOverBudgetPer1000,40); + assert.match(markdownReport(report),/not physical render-XRUN/i); +}); +test('INT-1B refuses device mismatches, resets, gaps, malformed and legacy logs',()=>{ + const legacy='2026-11-20T08:00:00.000Z | AUDIO_HEALTH | {"callbackCount":99}'; + const malformed='2026-11-20T08:00:00.000Z | AUDIO_HEALTH | {"bad":'; + const badLog=[legacy,malformed,int1bLine(0,{}),int1bLine(1,{}), + int1bLine(7,{deviceGeneration:3}),int1bLine(8,{deviceGeneration:3}), + int1bLine(9,{deviceGeneration:2})].join('\n'); + const parsed=parseHealthLog(badLog); + assert.equal(parsed.samples.length,5); + assert.equal(parsed.warnings.length,2); + const analysis=analyzeHealthLog(badLog); + assert.equal(analysis.segments.length,3); + assert.equal(compareDryFx(analysis).comparable,false); + assert.ok(analysis.warnings.some(w=>w.includes('device/graph/epoch'))); + // An interval with a counter going backwards is NOT negative optimization. + const previous=int1bSample(20,{}); + const invalid={...int1bSample(21,{}),callbackCount:1}; + const time=s=>new Date(Date.UTC(2026,10,20,8,0,s)).toISOString(); + const report=analyzeHealthLog( + time(20)+' | AUDIO_HEALTH | '+JSON.stringify(previous)+'\n'+ + time(21)+' | AUDIO_HEALTH | '+JSON.stringify(invalid)); + assert.equal(report.segments.length,2); + const swapped={...int1bSample(21,{}),inputDevice:"Other Driver Input"}; + const mismatch=analyzeHealthLog( + time(20)+' | AUDIO_HEALTH | '+JSON.stringify(previous)+'\n'+ + time(21)+' | AUDIO_HEALTH | '+JSON.stringify(swapped)); + assert.equal(mismatch.segments.length,2, + 'Physical input endpoint change disqualifies the previous timing window'); + const changedPins=analyzeHealthLog( + time(20)+' | AUDIO_HEALTH | '+JSON.stringify(previous)+'\n'+ + time(21)+' | AUDIO_HEALTH | '+ + JSON.stringify({...int1bSample(21,{}),activeInputMaskHex:"c"})); + assert.equal(changedPins.segments.length,2, + 'The same ASIO channel count can hide changed hardware pin ordinals'); + const missing=analyzeHealthLog( + time(20)+' | AUDIO_HEALTH | '+JSON.stringify(previous)+'\n'+ + time(20)+' | AUDIO_HEALTH | null'+'\n'+ + time(21)+' | AUDIO_HEALTH | '+JSON.stringify(int1bSample(21,{}))); + assert.equal(missing.segments.length,2, + 'A malformed/unknown middle snapshot is a hard gap, not a green interval'); + const changedGeneration=[]; + for(let s=0;s<=40;s++)changedGeneration.push(int1bLine(s,{dryTest:true})); + for(let s=41;s<=82;s++)changedGeneration.push(int1bLine(s,{ + dryTest:false,deviceGeneration:3 + })); + assert.equal(compareDryFx(analyzeHealthLog(changedGeneration.join('\n'))).comparable,false, + 'Same-named driver reopened in a new generation is not a matched DRY/FX pair'); +}); +test('INT-1B ignores legacy dryTest visual intent when native FX still processes',()=>{ + const lines=[]; + for(let s=0;s<=40;s++)lines.push(int1bLine(s,{ + dryTest:true,nativeGlobalFxBypassed:false,nativeFxProcessingCount:1 + })); + const result=analyzeHealthLog(lines.join('\n')); + assert.equal(result.segments.length,1); + assert.equal(result.segments[0].mode,'FX', + 'The only DRY proof is actual native DSP bypass/insert readback'); + assert.equal(compareDryFx(result).comparable,false); +}); + +test('INT-1B never pairs another app session or a stale DRY baseline',()=>{ + const makeWindow=(start,end,dryTest)=>Array.from( + {length:end-start+1},(_,i)=>int1bLine(start+i,{dryTest})); + const sessionHeader=new Date(Date.UTC(2026,10,20,8,0,40)).toISOString()+ + ' | SESSION | started'; + const differentApp=analyzeHealthLog([ + ...makeWindow(0,40,true),sessionHeader,...makeWindow(41,81,false) + ].join('\n')); + assert.equal(differentApp.segments.length,2); + assert.equal(compareDryFx(differentApp).comparable,false, + 'the same generation on a new process is not comparable'); + const stale=analyzeHealthLog([ + ...makeWindow(0,40,true),...makeWindow(200,240,false) + ].join('\n')); + assert.equal(compareDryFx(stale).comparable,false, + 'a session gap must not silently pair different performances'); + const intervening=analyzeHealthLog([ + ...makeWindow(0,40,true),...makeWindow(41,81,false), + ...makeWindow(82,122,true) + ].join('\n')); + assert.equal(compareDryFx(intervening).comparable,true, + 'a complete adjacent dry then fx pair remains valid even with a later DRY run'); +}); + +test('INT-1B external-only CH1 vendor rack is FX when powered and DRY when bypassed',()=>{ + const lines=[]; + for(let s=0;s<=40;s++)lines.push(int1bLine(s,{ + dryTest:false,nativeGlobalFxBypassed:true,nativeFxProcessingCount:0, + nativeExternalCh1Leased:true,nativeExternalCh1InstalledCount:1, + nativeExternalCh1ProcessingCount:0 + })); + for(let s=41;s<=81;s++)lines.push(int1bLine(s,{ + dryTest:false,nativeGlobalFxBypassed:false,nativeFxProcessingCount:1, + nativeExternalCh1Leased:true,nativeExternalCh1InstalledCount:1, + nativeExternalCh1ProcessingCount:1 + })); + const report=analyzeHealthLog(lines.join('\n')); + assert.deepEqual(report.segments.map(s=>s.mode),['DRY','FX']); + assert.equal(report.segments[0].nativeExternalCh1InstalledCount,1); + assert.equal(report.segments[1].nativeExternalCh1ProcessingCount,1); + assert.equal(compareDryFx(report).comparable,true, + 'External-only original CH1 Graph is not silently omitted from native FX'); + const malformed=lines.slice(); + malformed[50]=malformed[50].replace('"nativeExternalCh1ProcessingCount":1', + '"nativeExternalCh1ProcessingCount":2'); + assert.ok(analyzeHealthLog(malformed.join('\n')).warnings.some(s=>s.includes('invalid source metadata')), + 'External count cannot exceed the accepted authoritative total'); +}); + +test('INT-1B P2: no DRY/FX match through malformed or opaque-lease telemetry',()=>{ + const dry=[],fx=[]; + for(let s=0;s<=40;s++)dry.push(int1bLine(s,{dryTest:true})); + for(let s=41;s<=82;s++)fx.push(int1bLine(s,{dryTest:false})); + const baseline=analyzeHealthLog([...dry,...fx].join('\n')); + assert.equal(compareDryFx(baseline).comparable,true, + 'An accepted global bypass ON -> OFF transition is allowed'); + assert.equal(baseline.segments[1].invalidBefore,false); + + const midpoint='2026-11-20T08:00:40.500Z | AUDIO_HEALTH | {"invalid":'; + const malformed=analyzeHealthLog([...dry,midpoint,...fx].join('\n')); + assert.equal(malformed.segments.length,2); + assert.equal(malformed.segments[1].invalidBefore,true); + assert.equal(compareDryFx(malformed).comparable,false, + 'Malformed source between two valid 40s windows must invalidate pairing'); + + const opaque={...int1bSample(41,{dryTest:false}),nativeFxActivityComplete:false}; + const rejected='2026-11-20T08:00:41.000Z | AUDIO_HEALTH | '+JSON.stringify(opaque); + const incomplete=analyzeHealthLog([...dry,rejected,...fx.slice(1)].join('\n')); + assert.equal(incomplete.segments.length,2); + assert.equal(incomplete.segments[1].invalidBefore,true); + assert.equal(compareDryFx(incomplete).comparable,false, + 'Rejected opaque external CH1 FX lease is a hard comparability barrier'); + + const regressed={...int1bSample(41,{dryTest:false}),callbackCount:1}; + const counterReset=analyzeHealthLog([...dry, + '2026-11-20T08:00:41.000Z | AUDIO_HEALTH | '+JSON.stringify(regressed), + ...fx.slice(1)].join('\n')); + assert.equal(compareDryFx(counterReset).comparable,false, + 'Counter regression during mode transition must not be a valid pair'); + + const unprovenDry=[],unprovenFx=[]; + for(let s=0;s<=40;s++)unprovenDry.push(int1bLine(s,{ + dryTest:true,nativeGlobalFxBypassed:false,nativeFxProcessingCount:0 + })); + for(let s=41;s<=82;s++)unprovenFx.push(int1bLine(s,{dryTest:false})); + assert.equal(compareDryFx(analyzeHealthLog( + [...unprovenDry,...unprovenFx].join('\n'))).comparable,false, + 'Global power OFF -> OFF is not a verified global FX bypass transition'); +}); + +test('INT-1B rejects missed/unknown data rather than counting missing as zero',()=>{ + const s=int1bSample(1,{}); + delete s.callbackBudgetBuckets; + const p=parseHealthLog( + new Date(Date.UTC(2026,10,20,8,0,1)).toISOString()+ + ' | AUDIO_HEALTH | '+JSON.stringify(s)); + assert.equal(p.samples.length,0); + assert.match(p.warnings[0],/missing\/invalid 13/); +});