jenkins d2f4e920ff bstein: serve direct-duration digital RCT reference runs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 14:08:00 -06:00

167 lines
9.7 KiB
JavaScript

// Only the explicit numeric projection below can leave the browser. Never
// pass a receipt, device object, error string, frame, PCM or DOM value to fetch.
export function reportMetrics(receipt) {
const finite=value=>typeof value==='number'&&Number.isFinite(value)&&value>=0 ? value : null;
const v=receipt.video??{},a=receipt.audio??{},s=receipt.settings??{},p=receipt.paired??{};
const c=p.continuity??{},pilot=p.pilot??{},recent=pilot.recent??{};
const estimate=typeof p.estimatedMedianSignedMs==='number'&&Number.isFinite(p.estimatedMedianSignedMs)?p.estimatedMedianSignedMs:null;
return Object.fromEntries(Object.entries({
elapsed_ms:receipt.elapsedMs,
video_width:s.video?.width,video_height:s.video?.height,video_fps:s.video?.frameRate,
audio_rate:s.audio?.sampleRate,audio_channels:s.audio?.channelCount,
video_callbacks:v.callbacks,video_unobserved:v.unobservedPresentedFrames,
video_resets:v.clockOrCounterResets,video_interval_p95_ms:v.callbackIntervalP95Ms,
video_gap_max_ms:v.callbackGapMaxMs,audio_input_frames:a.inputFrames,
audio_processed_frames:a.processedFrames,audio_zero_frames:a.exactZeroFrames,
audio_rms:a.rms,audio_peak:a.peak,audio_context_rate:a.sampleRate,
paired_audio_signals:p.audioSignals,paired_video_signals:p.videoSignals,
paired_matches:p.pairs,paired_ambiguous:p.ambiguous,paired_overflow:p.overflow,
paired_estimate_audio_late_ms:estimate===null?null:Math.max(0,estimate),
paired_estimate_audio_early_ms:estimate===null?null:Math.max(0,-estimate),
marker_frames:c.frames,marker_bad:c.badMarkers,marker_ambiguous:c.ambiguousGaps,
marker_missing_fraction:c.missingFraction,marker_duplicate_fraction:c.duplicateFraction,
pilot_windows:pilot.windows,pilot_gap_max_ms:pilot.gapMaxMs,
pilot_missing_fraction:pilot.missingFraction,pilot_trailing_gap_ms:pilot.trailingGapMs,
pilot_discontinuities:pilot.discontinuities,
pilot_recent_windows:recent.observedWindows,pilot_recent_observed_ms:recent.observedMs,
pilot_recent_age_ms:recent.observationAgeMs,pilot_recent_absent_fraction:recent.absentFraction,
pilot_recent_absence_max_ms:recent.absenceMaxMs,pilot_recent_trailing_ms:recent.trailingAbsenceMs,
pilot_recent_interruptions:recent.interruptions,
pilot_recent_coverage_complete:typeof recent.coverageComplete==='boolean'?Number(recent.coverageComplete):null,
}).map(([key,value])=>[key,finite(value)]));
}
export function stopState(reason) {
if(reason==='120 seconds complete'||reason==='phone test complete'||reason==='reference complete')return 'completed';
if(reason==='page hidden; timing invalid')return 'hidden';
if(reason==='page closed')return 'closed';
if(reason==='device ended'||reason==='device selection changed')return 'device-change';
if(reason==='operator'||reason==='selecting devices'||reason==='signal report window closed')return 'stopped';
return 'failed';
}
// Only fixed, bounded integers supplement an authenticated acoustic receipt.
// First-event offsets use offset+1, reserving zero for no event.
export function acousticReceipt(path, clock) {
if (!path || ![1,5,10,15,20,30,60].includes(path.stageMinutes)) return null;
const offset = value => value === null ? 0 : Math.round(value) + 1;
const timing = [path.stageMinutes,Math.round(path.observedMs),offset(path.firstLevelDropMs),
Math.round(path.longestLevelDropMs),offset(path.firstUnclearMs),Math.round(path.gapMaxMs),
path.discontinuities];
if (!timing.every(v=>Number.isSafeInteger(v) && v>=0 && v<=3600011)) return null;
const end = clock && Number.isFinite(path.observedAtMono) ? Math.round(path.observedAtMono + clock.offset) : 0;
const t=path.timing;
if (!t) return null;
const warp=[Math.round(t.rateCoverageMs),t.edgeCount,t.maxRatePpm,offset(t.firstRateMs),t.maxShiftMs,offset(t.firstShiftMs),t.baselinePpm??0];
if (!warp.every(v=>Number.isSafeInteger(v) && Math.abs(v)<=3600011)) return null;
return [...timing,end,clock?.uncertainty ?? 0,...warp].join(',');
}
export function speechReceipt(speech) {
if (!speech) return null;
const integer = (v,min,max) => Number.isSafeInteger(v) && v>=min && v<=max;
if (!integer(speech.coverageMs,0,3600000) || !integer(speech.phase,-1,9999) ||
!integer(speech.phaseAgeMs,-1,3600000) || !integer(speech.total,0,999999) ||
!integer(speech.maxCadencePpm,-1000000,1000000) || !Array.isArray(speech.events) ||
speech.events.length>16) return null;
const rows=[[speech.kind===2?2:1,speech.coverageMs,speech.phase,speech.phaseAgeMs,speech.total,speech.maxCadencePpm]];
for (const row of speech.events) {
if (!Array.isArray(row) || row.length!==6 || !integer(row[0],1,speech.total) ||
!integer(row[1],1,4) || !integer(row[2],0,3600000) ||
!integer(row[3],0,3600000-row[2]) || !integer(row[4],-1000000,1000000) || !integer(row[5],-1,9999)) return null;
rows.push(row);
}
return rows.map(row=>row.join(',')).join(';');
}
export class RunReporter {
constructor(status,request=globalThis.fetch.bind(globalThis)) {
this.status=status;this.request=request;this.pending=null;this.busy=false;
this.terminal=false;this.sequence=0;this.lastProgress=-Infinity;this.available=true;
status('Reporting: connecting…');
this.ready=this.open();
}
async open() {
try {
const sentAt=performance.now();
const r=await this.request('/av-test/api/start',{method:'POST',credentials:'omit',
headers:{'Content-Type':'application/json'},body:'{}',signal:AbortSignal.timeout(5000)});
if(!r.ok)throw new Error('start rejected');
const receivedAt=performance.now();
const stamp=r.headers?.get?.('X-AV-Clock');
if (/^[0-9]{10}\.[0-9]{3}$/.test(stamp)) {
this.clock={offset:Number(stamp)*1000-(sentAt+receivedAt)/2,
uncertainty:Math.ceil((receivedAt-sentAt)/2)+1};
}
const data=await r.json();
if(!/^[a-f0-9]{32}$/.test(data.run_id)||!/^[A-Za-z0-9_-]{43}$/.test(data.write_token))throw new Error('bad receipt');
this.runId=data.run_id;this.token=data.write_token;
this.status(`Reporting enabled · test ${this.runId.slice(0,8)}`);
} catch {
this.available=false;this.status('Reporting unavailable · Save metrics remains available');
}
}
observe(receipt) {
if(this.terminal)return;
// Paired tests reset elapsed time when the known source first arrives.
// A long signal wait must not suppress the next minute of progress.
if(receipt.elapsedMs<this.lastProgress)this.lastProgress=-Infinity;
if(receipt.elapsedMs-this.lastProgress<10000)return;
this.lastProgress=receipt.elapsedMs;this.queue('running',receipt);
}
finish(receipt) {
if(!this.terminal) {
this.terminal=true;
this.finished=new Promise(resolve=>{this.resolveFinished=resolve;});
this.queue(stopState(receipt.reason),receipt);
}
return this.finished;
}
queue(state,receipt) {
// One latest snapshot, not a growing queue. Terminal state supersedes
// pending progress; a stopped run never becomes running again.
this.pending={state,metrics:reportMetrics(receipt),path:receipt.paired?.pilot,watch:receipt.audio?.watch};
void this.flush();
}
async flush() {
if(this.busy)return;
this.busy=true;
try {
await this.ready;
if(!this.available){this.pending=null;this.resolveFinished?.(false);return;}
while(this.pending) {
const report=this.pending;this.pending=null;
const payload={run_id:this.runId,sequence:++this.sequence,state:report.state,metrics:report.metrics};
const stage=acousticReceipt(report.path,this.clock);
const headers={'Content-Type':'application/json',Authorization:`Bearer ${this.token}`};
if(stage)headers['X-AV-Stage']=stage;
const speech=speechReceipt(report.path?.speech);
if(speech)headers['X-AV-Speech']=speech;
const watch=typeof report.watch==='function'?report.watch():null;
if(watch)headers['X-AV-Watch']=watch;
let delivered=false;
for(let attempt=0;attempt<2&&!delivered;attempt++) {
try {
const response=await this.request('/av-test/api/report',{
method:'POST',credentials:'omit',keepalive:true,
headers,
body:JSON.stringify(payload),signal:AbortSignal.timeout(5000),
});
delivered=response.ok && (!stage || (this.clock && response.headers?.get?.('X-AV-Stage-Ack')==='1')) &&
(!report.path?.speech || (speech && response.headers?.get?.('X-AV-Speech-Ack')==='1')) &&
(!watch || response.headers?.get?.('X-AV-Watch-Ack')==='1');
if(response.status>=400&&response.status<500)break;
} catch { /* No raw exception or endpoint response is displayed. */ }
}
if(report.state!=='running') {
this.resolveFinished?.(!!delivered);
this.status(delivered ? `Result reported · test ${this.runId.slice(0,8)}` :
'Result not reported · use Save metrics');
} else if(!delivered) {
this.status('Reporting interrupted · local test continues');
}
}
} finally {this.busy=false;}
}
}