import assert from 'node:assert/strict'; import {readFileSync, writeFileSync, mkdtempSync, copyFileSync} from 'node:fs'; import {createHash} from 'node:crypto'; import {fileURLToPath} from 'node:url'; import {dirname, join} from 'node:path'; import {inspectDurationWindow, inspectDurationClock} from './k2100-duration-window-proof.mjs'; import {inspectDurationProvenance} from './k2100-duration-provenance-proof.mjs'; import {createDurationServiceReplay} from './k2100-duration-service-replay.mjs'; const artifact = path => ({path, sha256: createHash('sha256').update(readFileSync(path)).digest('hex')}); const checked = a => { assert.equal(artifact(a.path).sha256, a.sha256, a.path); return readFileSync(a.path); }; const read = path => JSON.parse(readFileSync(path)); const reviewPath = process.argv[2]; assert.ok(reviewPath, 'pass a completed short/long duration review'); const directory = mkdtempSync('reports/os-implementation/K2100-duration-window-proof-'); copyFileSync(fileURLToPath(import.meta.url), directory + '/harness.mjs.txt'); copyFileSync('scripts/os-acceptance/k2100-duration-window-proof.mjs', directory + '/proof.mjs.txt'); copyFileSync('scripts/os-acceptance/k2100-duration-provenance-proof.mjs', directory + '/provenance.mjs.txt'); copyFileSync('scripts/os-acceptance/k2100-duration-service-replay.mjs', directory + '/replay-builder.mjs.txt'); try { const review = read(reviewPath), long = review.status === 'LONG_WORKLOAD_GUEST_RETURNED'; assert.ok(long || review.status === 'DURATION_COMPONENT_GUEST_RETURNED'); const candidate = JSON.parse(checked(review.candidate)), image = checked(candidate.artifacts.image); const nm = checked(candidate.artifacts.nm).toString(), symbols = {}; for (const line of nm.split('\n')) { const match = line.trim().match(/^([0-9a-f]+)\s+([0-9a-f]+)\s+\S\s+(\S+)$/i); if (match) symbols[match[3]] = {address: parseInt(match[1], 16), size: parseInt(match[2], 16)}; } const compiled = {}; for (const [key, name] of [['authorityLayout', 'OS_K1000_AUTHORITY_LAYOUT_EXPECTED'], ['lifecycleLayout', 'OS_K2100_PROFILE_LIFECYCLE_LAYOUT'], ['sharedLayout', 'OS_K2045_SHARED_LAYOUT']]) { const s = symbols[name]; assert.ok(s); const offset = s.address - symbols._image_start.address; assert.ok(offset >= 0 && offset + s.size <= image.length); compiled[key] = image.subarray(offset, offset + s.size); } const physical = JSON.parse(checked(review.physical)); const diagnosticPath = join(dirname(review.physical.path), 'diagnostic.json'), diagnostic = read(diagnosticPath); assert.equal(diagnostic.status, 'GUEST_RETURNED'); assert.deepEqual(diagnostic.smpWorkers, review.physical); const provenanceInput = {physical, symbols, cpuCount: review.cpuCount, memoryMiB: review.memoryMiB ?? 256, qmp: JSON.parse(checked(diagnostic.qmp)), timeline: JSON.parse(checked(diagnostic.timeline)), wholeRsp: JSON.parse(checked(diagnostic.wholeRsp)), readArtifact: checked, long}; const provenance = inspectDurationProvenance(provenanceInput); const replayModule = await createDurationServiceReplay({captureSource: review.captureHarness, outputDirectory: directory, readArtifact: checked}); const guestDtb = physical.profileCheckpoints[2].dumps.dtb; checked(guestDtb); const replayContext = {symbols, cpuCount: review.cpuCount, memoryMiB: review.memoryMiB ?? 256, bootId: diagnostic.row.bootId, fixturePath: guestDtb.path, readArtifact: checked}; let replayedCaptures = 0; for (const [index, capture] of physical.checkpoints.entries()) { await replayModule.replay({...replayContext, capture, index, expectedWindows: physical.windowCheckpoints.length}); replayedCaptures++; } for (const [index, capture] of physical.windowCheckpoints.entries()) { await replayModule.replay({...replayContext, capture, index: 1, live: true, expectedWindows: index + 1}); replayedCaptures++; } const lifecycle = JSON.parse(checked(review.lifecycle)); assert.equal(lifecycle.status, 'RUNNER_PASSED'); assert.equal(lifecycle.allOwnedGuestsStopped, true); const load = capture => Object.fromEntries(Object.entries(capture.dumps).map(([name, a]) => [name, checked(a)])); const baseline = load(physical.checkpoints[0]); const cpus = review.cpuCount; const memoryMiB = review.memoryMiB ?? 256; let previousCounter = baseline.OS_K2100_WORKLOAD_SUMMARY.readBigUInt64LE(16), previousLate = [0n, 0n]; let previousStaleRefusals = 0n; const results = [], inputs = []; let priorClock = 0; for (const [index, capture] of physical.windowCheckpoints.entries()) { const input = {data: load(capture), baseline, compiled, symbols, cpuCount: cpus, memoryMiB, window: index + 1, previousCounter, previousLate, previousStaleRefusals, long}; const result = inspectDurationWindow(input); inputs.push(input); const running = inspectDurationClock(capture.hostClock); assert.ok(running > priorClock); priorClock = running; results.push({window: result.windows, staleRefusals: result.staleRefusals, guestElapsedSeconds: result.guestElapsedSeconds, hostRunningMilliseconds: running}); previousCounter = result.counter; previousLate = result.late; previousStaleRefusals = BigInt(result.staleRefusals); } assert.ok(results.length >= 3); const final = inspectDurationWindow({data: load(physical.checkpoints[1]), baseline, compiled, symbols, cpuCount: cpus, memoryMiB, window: results.length, previousCounter, previousLate, previousStaleRefusals, final: true, long}); const hostRunningMilliseconds = inspectDurationClock(physical.workloadMeasurement, {requireDuration: long}); assert.ok(hostRunningMilliseconds >= priorClock); const controls = []; function reject(name, change) { const input = {...inputs[0], data: Object.fromEntries(Object.entries(inputs[0].data).map(([k, b]) => [k, Buffer.from(b)]))}; change(input); assert.throws(() => inspectDurationWindow(input), undefined, name); controls.push(name); } const put = (p, name, index, value) => p.data[name].writeBigUInt64LE(BigInt(value), index * 8); for (const [name, index, value] of [['root', 0, 0], ['frequency', 1, 1], ['CPU count', 2, cpus === 1 ? 2 : 1], ['start', 3, 1], ['observation', 4, 1], ['CPU generation', 7, 2], ['CPU identity', 8, 3], ['service completion', 9, 999], ['page total', 45, 1], ['owner count', 46, 1], ['guard count', 47, 1], ['canary failure', 48, 1], ['window count', 49, 2], ['stale count', 50, 99], ['closed early', 52, 1]]) reject('monitor ' + name, p => put(p, 'OS_K2100_WORKLOAD_MONITOR', index, value)); reject('summary two-hour deadline', p => put(p, 'OS_K2100_WORKLOAD_SUMMARY', 4, 1)); reject('summary wrong Monitor address', p => put(p, 'OS_K2100_WORKLOAD_SUMMARY', 5, 1)); reject('missing complete CPU progress', p => put(p, 'OS_K2100_WORKLOAD_PROGRESS', 4, 0)); reject('future window acknowledgement', p => put(p, 'OS_K2100_WORKLOAD_WINDOW_ACK', 0, 2)); reject('host supplies completion', p => put(p, 'OS_K2100_HOST_DURATION_CONTROL', 0, 3)); for (const [name, index, value] of [['table', 2, 0], ['old generation', 4, 0], ['current generation', 5, 0], ['counter', 6, 1], ['authorized pages', 7, 0], ['live pages', 8, 0], ['unchanged receipt', 13, 0], ['thread', 14, 0]]) reject('stale receipt ' + name, p => put(p, 'OS_K2100_WORKLOAD_STALE', index, value)); reject('shared owner changed', p => p.data.shared.writeBigUInt64LE(1n, Number(compiled.sharedLayout.readBigUInt64LE(8)))); reject('online generation changed', p => p.data.lifecycle.writeBigUInt64LE(2n, 112)); reject('central allocator plan changed', p => p.data.authority[0] ^= 1); reject('central live record removed', p => { const l = Array.from({length: 24}, (_, i) => Number(compiled.authorityLayout.readBigUInt64LE(i * 8))); for (let i = 0; i < l[10]; i++) if (p.data.authority[l[5] + i * l[6] + l[9]]) { p.data.authority[l[5] + i * l[6] + l[9]] = 0; return; } assert.fail('fixture has no live record'); }); reject('high-bit monitor identity', p => put(p, 'OS_K2100_WORKLOAD_MONITOR', 5, 0x8000000000000001n)); const clock = physical.workloadMeasurement; for (const [name, change] of [ ['paused time counted', c => {c.runningMilliseconds = c.wallMilliseconds;}], ['missing real segments', c => {c.segments = [];}], ['forged duration claim', c => {c.durationMet = !c.durationMet;}], ['shorter threshold', c => {c.minimumRunningMilliseconds = 3600000;}], ['overlapping segments', c => {c.segments[1].start = c.segments[0].start;}], ]) { const changed = structuredClone(clock); change(changed); assert.throws(() => inspectDurationClock(changed), undefined, name); controls.push(name); } if (!long) {assert.throws(() => inspectDurationClock(clock, {requireDuration: true})); controls.push('short actual run cannot be admitted as two hours');} // Explicitly modeled inputs exercise the late-window branches before a real // two-hour run reaches them. These never become guest evidence or reviews. const modeledLateCases = []; if (!long) for (let ordinal = 1; ordinal <= cpus; ordinal++) { const shift = 200_000_000_000n; const shifted = original => { const p = {...original, long: true, data: Object.fromEntries(Object.entries(original.data).map(([k, b]) => [k, Buffer.from(b)]))}; const add = (name, index) => p.data[name].writeBigUInt64LE(p.data[name].readBigUInt64LE(index * 8) + shift, index * 8); add('OS_K2100_WORKLOAD_MONITOR', 4); add('OS_K2100_WORKLOAD_SUMMARY', 11); add('OS_K2100_WORKLOAD_STALE', 6); for (let cpu = 0; cpu < cpus; cpu++) { add('OS_K2100_CPU_PROCESS_SUMMARY', cpu * 16 + 2); add('OS_K2100_CPU_PROCESS_SUMMARY', cpu * 16 + 3); add('OS_K2100_CPU_PROCESS', cpu * 32 + 19); } put(p, 'OS_K2100_WORKLOAD_SUMMARY', 8, 1); put(p, 'OS_K2100_WORKLOAD_SUMMARY', 10, ordinal); put(p, 'OS_K2100_WORKLOAD_MONITOR', 50, ordinal); put(p, 'OS_K2100_HOST_DURATION_CONTROL', 0, 0); return p; }; const first = shifted(inputs[0]), cpu = ordinal === cpus ? 0 : ordinal; const late = cpu === 0 ? first.data.OS_K2100_WORKLOAD_STALE.readBigUInt64LE(48) : first.data.OS_K2100_CPU_PROCESS_SUMMARY.readBigUInt64LE((cpu * 16 + 2) * 8) + 1n; put(first, 'OS_K2100_WORKLOAD_SUMMARY', 9, late); put(first, 'OS_K2100_WORKLOAD_MONITOR', 51, late); const result = inspectDurationWindow(first); const next = shifted(inputs[1]); next.previousCounter = result.counter; next.previousLate = result.late; next.previousStaleRefusals = BigInt(ordinal); put(next, 'OS_K2100_WORKLOAD_SUMMARY', 9, late); put(next, 'OS_K2100_WORKLOAD_MONITOR', 51, late); inspectDurationWindow(next); const changed = {...next, data: {...next.data, OS_K2100_WORKLOAD_MONITOR: Buffer.from(next.data.OS_K2100_WORKLOAD_MONITOR), OS_K2100_WORKLOAD_SUMMARY: Buffer.from(next.data.OS_K2100_WORKLOAD_SUMMARY)}}; put(changed, 'OS_K2100_WORKLOAD_MONITOR', 50, ordinal + 1); put(changed, 'OS_K2100_WORKLOAD_SUMMARY', 10, ordinal + 1); assert.throws(() => inspectDurationWindow(changed)); modeledLateCases.push({cpu, ordinal, firstLateWindow: 1, subsequentWindow: 2, changedPinnedCountRejected: true}); } for (const [name, change] of [ ['wrong physical address', p => {p.physical.windowCheckpoints[0].captures[0].val += 8;}], ['wrong physical length', p => {p.physical.windowCheckpoints[0].captures[0].size += 8;}], ['wrong QMP receipt', p => {p.physical.windowCheckpoints[0].captures[0].requestId = 1;}], ['wrong gate address', p => {p.physical.windowCheckpoints[0].gateAddress += 8;}], ['capture omitted', p => {p.physical.windowCheckpoints[0].captures.pop();}], ['capture acknowledgement substituted', p => {p.physical.windowCheckpoints[0].rsp[2].payload = 'M40000000,8:0000000000000000';}], ['QMP reading while running', p => { const id = p.timeline.find(x => x.stage === 21101 && x.execute === 'query-status').id; p.qmp = p.qmp.map(r => r.direction === 'rx' && r.message.id === id ? {...r, message: {...r.message, return: {status: 'running'}}} : r); }], ['QMP physical source substituted', p => { const id = p.physical.windowCheckpoints[0].captures[0].requestId; p.qmp = p.qmp.map(r => r.direction === 'tx' && r.message.id === id ? {...r, message: {...r.message, arguments: {...r.message.arguments, val: 0x40000000}}} : r); }], ['debugger result write', p => { const id = p.physical.windowCheckpoints[0].rsp[2].id; p.wholeRsp = p.wholeRsp.map(r => r.direction === 'tx' && r.id === id ? {...r, payload: 'M40000000,8:0000000000000000'} : r); }], ]) { const changed = {...provenanceInput, physical: structuredClone(physical)}; change(changed); assert.throws(() => inspectDurationProvenance(changed), undefined, name); controls.push(name); } const firstCapture = physical.windowCheckpoints[0]; const replayChanges = [ ['UDP request bytes', 'OS_K2100_CPU_NETWORK_RX', b => {b[20] ^= 1;}], ['UDP reply bytes', 'OS_K2100_CPU_NETWORK_TX', b => {b[25] ^= 1;}], ['EL0 SVC exception class', 'OS_K2100_CPU_CALLS', b => b.writeBigUInt64LE(0n, 6 * 8)], ['EL0 root identity', 'OS_K2100_CPU_CALLS', b => b.writeBigUInt64LE(0n, 14 * 8)], ['EL0 return PC', 'OS_K2100_CPU_EL0_FRAME', b => b.writeBigUInt64LE(0n, 264)], ['IPC service completion', 'OS_K2100_CPU_SERVICE', b => b.writeBigUInt64LE(0n, 8 * 8)], ['process CPU identity', 'OS_K2100_CPU_PROCESS', b => b.writeBigUInt64LE(3n, 16 * 8)], ]; if (cpus > 1) replayChanges.push( ['private stack canary', 'stackPages1', b => {b[4096] ^= 1;}], ['secondary timer INTID', 'OS_K2100_SECONDARY_TIMERS', b => b.writeBigUInt64LE(29n, (128 + 8 + 6) * 8)], ['secondary IRQ saved PC', 'OS_K2100_SECONDARY_TIMERS', b => b.writeBigUInt64LE(0n, (128 + 20 + 32) * 8)], ); for (const [name, key, change] of replayChanges) { const a = firstCapture.dumps[key], buffer = Buffer.from(checked(a)); change(buffer); const reader = candidate => candidate.path === a.path ? buffer : checked(candidate); await assert.rejects(() => replayModule.replay({...replayContext, capture: firstCapture, index: 1, live: true, expectedWindows: 1, readArtifact: reader}), undefined, name); controls.push('service replay ' + name); } const report = {status: 'DURATION_WINDOW_PHYSICAL_COMPONENT_PASSED', guestAccepted: false, productAccepted: false, scope: 'Additional raw-memory checks bind the Monitor to CPU generations, central live leases and reservations, private worker stack owners, per-window progress, actual stale receipt identities and host running segments. QMP/RSP provenance binds paused physical reads and permits only checkpoint/duration gate writes throughout the workload. Exhaustive compiled control flow and all long profiles remain separate obligations. Short input cannot satisfy duration admission.', review: artifact(reviewPath), physical: review.physical, image: candidate.artifacts.image, source: artifact(directory + '/proof.mjs.txt'), harness: artifact(directory + '/harness.mjs.txt'), provenanceSource: artifact(directory + '/provenance.mjs.txt'), diagnostic: artifact(diagnosticPath), provenance, serviceReplay: {source: review.captureHarness, generated: artifact(replayModule.path), builder: artifact(directory + '/replay-builder.mjs.txt'), guestDtb, replayedCaptures, guestEvidenceCreated: false}, cpuCount: cpus, memoryMiB, longInput: long, windows: results, hostRunningMilliseconds, guestElapsedSeconds: final.guestElapsedSeconds, rejectedControls: controls, rejectedControlCount: controls.length, modeledLateCases, modeledLateCasesAreGuestEvidence: false}; writeFileSync(directory + '/report.json', JSON.stringify(report, null, 2) + '\n'); console.log(JSON.stringify({status: report.status, report: directory + '/report.json', windows: results.length, rejectedControls: controls.length})); } catch (error) { writeFileSync(directory + '/report.json', JSON.stringify({status: 'DURATION_WINDOW_PHYSICAL_COMPONENT_FAILED', guestAccepted: false, productAccepted: false, review: reviewPath, error: error.stack}, null, 2) + '\n'); console.error(directory + '/report.json'); console.error(error.stack); process.exitCode = 1; }