A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(voice-engine): remove the test-only simulator and scenarios
Hampusaf1dff88af3d
diff --git a/packages/voice_engine_v2/src/simulation/FaultInjector.ts b/packages/voice_engine_v2/src/simulation/FaultInjector.tsdeleted file mode 100644index 9e3b6ee47..000000000--- a/packages/voice_engine_v2/src/simulation/FaultInjector.ts+++ /dev/null@@ -1,221 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {- createSimulatorRandom,- type VoiceEngineV2SimulatorRandom,-} from '@fluxer/voice_engine_v2/src/simulation/SimulatorPorts';--const SIMULATOR_FAULTS_MAX = 128;-const SIMULATOR_PEERS_PER_FAULT_MAX = 16;--export type VoiceEngineV2Fault =- | {kind: 'packetLoss'; rate: number; fromTick: number; untilTick: number}- | {kind: 'packetJitter'; jitterTicks: number; fromTick: number; untilTick: number}- | {kind: 'packetReorder'; rate: number; fromTick: number; untilTick: number}- | {kind: 'deviceDisconnect'; deviceId: string; atTick: number}- | {kind: 'gpuDeviceLost'; atTick: number}- | {kind: 'encoderFailed'; captureId: string; atTick: number}- | {kind: 'networkPartition'; fromTick: number; untilTick: number}- | {kind: 'asymmetricPartition'; peerIds: ReadonlyArray<string>; fromTick: number};--export interface VoiceEngineV2FaultPlan {- readonly faults: ReadonlyArray<VoiceEngineV2Fault>;-}--export interface VoiceEngineV2FaultDecision {- connectShouldDrop: boolean;- disconnectShouldDrop: boolean;- microphonePublishShouldFail: boolean;- cameraPublishShouldFail: boolean;- screenPublishShouldFail: boolean;- failingCaptureIds: ReadonlyArray<string>;- deviceLossDeviceIds: ReadonlyArray<string>;- gpuLost: boolean;- asymmetricallyPartitionedPeers: ReadonlyArray<string>;- networkPartitionActive: boolean;-}--interface MutableVoiceEngineV2FaultDecision {- connectShouldDrop: boolean;- disconnectShouldDrop: boolean;- microphonePublishShouldFail: boolean;- cameraPublishShouldFail: boolean;- screenPublishShouldFail: boolean;- failingCaptureIds: Array<string>;- deviceLossDeviceIds: Array<string>;- gpuLost: boolean;- asymmetricallyPartitionedPeers: Array<string>;- networkPartitionActive: boolean;-}--export function createVoiceEngineV2EmptyFaultPlan(): VoiceEngineV2FaultPlan {- return {faults: []};-}--export function createVoiceEngineV2FaultPlan(faults: ReadonlyArray<VoiceEngineV2Fault>): VoiceEngineV2FaultPlan {- assert.ok(Array.isArray(faults), 'faults must be an array');- assert.ok(faults.length <= SIMULATOR_FAULTS_MAX, 'fault plan exceeds SIMULATOR_FAULTS_MAX cap');- for (const fault of faults) assertFaultWellFormed(fault);- return {faults: [...faults]};-}--export class VoiceEngineV2FaultInjector {- private readonly random: VoiceEngineV2SimulatorRandom;- private readonly faults: ReadonlyArray<VoiceEngineV2Fault>;-- constructor(seed: number, plan: VoiceEngineV2FaultPlan) {- assert.ok(Number.isInteger(seed), 'fault injector seed must be an integer');- assert.ok(plan, 'fault injector requires a plan');- assert.ok(plan.faults.length <= SIMULATOR_FAULTS_MAX, 'plan exceeds the SIMULATOR_FAULTS_MAX cap');- this.random = createSimulatorRandom(seed ^ 0x1357acef);- this.faults = plan.faults;- }-- decide(tick: number): VoiceEngineV2FaultDecision {- assert.ok(Number.isInteger(tick), 'fault decision tick must be an integer');- assert.ok(tick >= 0, 'fault decision tick must be non-negative');- const decision: MutableVoiceEngineV2FaultDecision = blankDecision();- for (const fault of this.faults) this.applyFault(decision, fault, tick);- return decision;- }-- private applyFault(decision: MutableVoiceEngineV2FaultDecision, fault: VoiceEngineV2Fault, tick: number): void {- switch (fault.kind) {- case 'packetLoss':- this.applyPacketLoss(decision, fault, tick);- return;- case 'packetJitter':- case 'packetReorder':- return;- case 'deviceDisconnect':- this.applyDeviceDisconnect(decision, fault, tick);- return;- case 'gpuDeviceLost':- this.applyGpuDeviceLost(decision, fault, tick);- return;- case 'encoderFailed':- this.applyEncoderFailed(decision, fault, tick);- return;- case 'networkPartition':- this.applyNetworkPartition(decision, fault, tick);- return;- case 'asymmetricPartition':- this.applyAsymmetricPartition(decision, fault, tick);- return;- }- }-- private applyPacketLoss(- decision: MutableVoiceEngineV2FaultDecision,- fault: VoiceEngineV2Fault & {kind: 'packetLoss'},- tick: number,- ): void {- if (tick < fault.fromTick) return;- if (tick > fault.untilTick) return;- if (this.random.nextBool(fault.rate)) decision.connectShouldDrop = true;- if (this.random.nextBool(fault.rate / 2)) decision.microphonePublishShouldFail = true;- }-- private applyDeviceDisconnect(- decision: MutableVoiceEngineV2FaultDecision,- fault: VoiceEngineV2Fault & {kind: 'deviceDisconnect'},- tick: number,- ): void {- if (tick !== fault.atTick) return;- decision.deviceLossDeviceIds.push(fault.deviceId);- decision.microphonePublishShouldFail = true;- }-- private applyGpuDeviceLost(- decision: MutableVoiceEngineV2FaultDecision,- fault: VoiceEngineV2Fault & {kind: 'gpuDeviceLost'},- tick: number,- ): void {- if (tick !== fault.atTick) return;- decision.gpuLost = true;- decision.screenPublishShouldFail = true;- }-- private applyEncoderFailed(- decision: MutableVoiceEngineV2FaultDecision,- fault: VoiceEngineV2Fault & {kind: 'encoderFailed'},- tick: number,- ): void {- if (tick !== fault.atTick) return;- decision.failingCaptureIds.push(fault.captureId);- }-- private applyNetworkPartition(- decision: MutableVoiceEngineV2FaultDecision,- fault: VoiceEngineV2Fault & {kind: 'networkPartition'},- tick: number,- ): void {- if (tick < fault.fromTick) return;- if (tick > fault.untilTick) return;- decision.networkPartitionActive = true;- decision.connectShouldDrop = true;- decision.disconnectShouldDrop = false;- }-- private applyAsymmetricPartition(- decision: MutableVoiceEngineV2FaultDecision,- fault: VoiceEngineV2Fault & {kind: 'asymmetricPartition'},- tick: number,- ): void {- if (tick < fault.fromTick) return;- for (const peer of fault.peerIds) decision.asymmetricallyPartitionedPeers.push(peer);- }-}--function blankDecision(): MutableVoiceEngineV2FaultDecision {- return {- connectShouldDrop: false,- disconnectShouldDrop: false,- microphonePublishShouldFail: false,- cameraPublishShouldFail: false,- screenPublishShouldFail: false,- failingCaptureIds: [],- deviceLossDeviceIds: [],- gpuLost: false,- asymmetricallyPartitionedPeers: [],- networkPartitionActive: false,- };-}--function assertFaultWellFormed(fault: VoiceEngineV2Fault): void {- assert.ok(fault, 'fault must be defined');- switch (fault.kind) {- case 'packetLoss':- assert.ok(fault.rate >= 0 && fault.rate <= 1, 'packetLoss rate out of bounds');- assert.ok(fault.fromTick <= fault.untilTick, 'packetLoss range is reversed');- return;- case 'packetJitter':- assert.ok(fault.jitterTicks >= 0, 'packetJitter jitterTicks must be non-negative');- assert.ok(fault.fromTick <= fault.untilTick, 'packetJitter range is reversed');- return;- case 'packetReorder':- assert.ok(fault.rate >= 0 && fault.rate <= 1, 'packetReorder rate out of bounds');- assert.ok(fault.fromTick <= fault.untilTick, 'packetReorder range is reversed');- return;- case 'deviceDisconnect':- assert.ok(typeof fault.deviceId === 'string' && fault.deviceId.length > 0, 'deviceDisconnect deviceId empty');- assert.ok(fault.atTick >= 0, 'deviceDisconnect atTick must be non-negative');- return;- case 'gpuDeviceLost':- assert.ok(fault.atTick >= 0, 'gpuDeviceLost atTick must be non-negative');- return;- case 'encoderFailed':- assert.ok(typeof fault.captureId === 'string' && fault.captureId.length > 0, 'encoderFailed captureId empty');- assert.ok(fault.atTick >= 0, 'encoderFailed atTick must be non-negative');- return;- case 'networkPartition':- assert.ok(fault.fromTick <= fault.untilTick, 'networkPartition range is reversed');- return;- case 'asymmetricPartition':- assert.ok(fault.peerIds.length > 0, 'asymmetricPartition requires at least one peer');- assert.ok(fault.peerIds.length <= SIMULATOR_PEERS_PER_FAULT_MAX, 'asymmetricPartition exceeds peer cap');- assert.ok(fault.fromTick >= 0, 'asymmetricPartition fromTick must be non-negative');- return;- }-}diff --git a/packages/voice_engine_v2/src/simulation/SafetyInvariants.ts b/packages/voice_engine_v2/src/simulation/SafetyInvariants.tsdeleted file mode 100644index 09ccb895e..000000000--- a/packages/voice_engine_v2/src/simulation/SafetyInvariants.ts+++ /dev/null@@ -1,129 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import type {VoiceEngineV2EventLogEntry} from '@fluxer/voice_engine_v2/src/runtime/VoiceEngineV2Runtime';--const SIMULATOR_INVARIANT_LOG_MAX = 4096;--export interface VoiceEngineV2SafetyViolation {- readonly code: string;- readonly message: string;- readonly sequence: number;-}--function assertVoiceEngineV2EventLogInvariants(- entries: ReadonlyArray<VoiceEngineV2EventLogEntry>,-): ReadonlyArray<VoiceEngineV2SafetyViolation> {- assert.ok(Array.isArray(entries), 'event log invariants require an array');- assert.ok(entries.length <= SIMULATOR_INVARIANT_LOG_MAX, 'event log exceeds the invariant inspection cap');- const violations: Array<VoiceEngineV2SafetyViolation> = [];- let previousSequence = 0;- let previousAtMs = -Infinity;- for (const entry of entries) {- if (entry.sequence !== previousSequence + 1) {- violations.push({- code: 'eventLog.sequenceHole',- message: `expected sequence ${previousSequence + 1} but received ${entry.sequence}`,- sequence: entry.sequence,- });- }- if (entry.atMs < previousAtMs) {- violations.push({- code: 'eventLog.nonMonotonicClock',- message: `event ${entry.sequence} regressed clock from ${previousAtMs} to ${entry.atMs}`,- sequence: entry.sequence,- });- }- previousSequence = entry.sequence;- previousAtMs = entry.atMs;- }- return violations;-}--function assertVoiceEngineV2FrameSinkInvariants(- entries: ReadonlyArray<VoiceEngineV2EventLogEntry>,-): ReadonlyArray<VoiceEngineV2SafetyViolation> {- assert.ok(Array.isArray(entries), 'frame sink invariants require an array');- assert.ok(entries.length <= SIMULATOR_INVARIANT_LOG_MAX, 'frame sink log exceeds the invariant cap');- const violations: Array<VoiceEngineV2SafetyViolation> = [];- const startedCaptureIds = new Set<string>();- for (const entry of entries) {- if (entry.event.type === 'nativeCapture.started') {- startedCaptureIds.add(entry.event.captureId);- continue;- }- if (entry.event.type === 'nativeFrameSink.attachRequested') {- const captureId = entry.event.options.captureId;- if (!startedCaptureIds.has(captureId)) {- violations.push({- code: 'frameSink.attachedWithoutCapture',- message: `frame sink attached for captureId=${captureId} before capture started at sequence ${entry.sequence}`,- sequence: entry.sequence,- });- }- }- }- return violations;-}--function assertVoiceEngineV2ConnectionInvariants(- entries: ReadonlyArray<VoiceEngineV2EventLogEntry>,-): ReadonlyArray<VoiceEngineV2SafetyViolation> {- assert.ok(Array.isArray(entries), 'connection invariants require an array');- const violations: Array<VoiceEngineV2SafetyViolation> = [];- let connectingActive = false;- let disconnectRequested = false;- for (const entry of entries) {- const eventType = entry.event.type;- if (eventType === 'connection.connectRequested') {- connectingActive = true;- disconnectRequested = false;- }- if (eventType === 'connection.disconnectRequested') {- disconnectRequested = true;- connectingActive = false;- }- if (eventType === 'connection.connectSucceeded' && disconnectRequested && !connectingActive) {- violations.push({- code: 'connection.staleConnectSucceeded',- message: `connection.connectSucceeded at sequence ${entry.sequence} arrived after a disconnect with no intervening connect`,- sequence: entry.sequence,- });- }- }- return violations;-}--function assertVoiceEngineV2OperationIdInvariants(- entries: ReadonlyArray<VoiceEngineV2EventLogEntry>,-): ReadonlyArray<VoiceEngineV2SafetyViolation> {- assert.ok(Array.isArray(entries), 'operation invariants require an array');- const violations: Array<VoiceEngineV2SafetyViolation> = [];- const seen = new Set<number>();- for (const entry of entries) {- for (const command of entry.commands) {- if (seen.has(command.operationId)) {- violations.push({- code: 'commands.duplicateOperationId',- message: `operationId ${command.operationId} reused at sequence ${entry.sequence}`,- sequence: entry.sequence,- });- continue;- }- seen.add(command.operationId);- }- }- return violations;-}--export function collectVoiceEngineV2SafetyViolations(- entries: ReadonlyArray<VoiceEngineV2EventLogEntry>,-): ReadonlyArray<VoiceEngineV2SafetyViolation> {- assert.ok(Array.isArray(entries), 'safety violation collector requires an array');- const violations: Array<VoiceEngineV2SafetyViolation> = [];- for (const v of assertVoiceEngineV2EventLogInvariants(entries)) violations.push(v);- for (const v of assertVoiceEngineV2FrameSinkInvariants(entries)) violations.push(v);- for (const v of assertVoiceEngineV2ConnectionInvariants(entries)) violations.push(v);- for (const v of assertVoiceEngineV2OperationIdInvariants(entries)) violations.push(v);- return violations;-}diff --git a/packages/voice_engine_v2/src/simulation/Simulator.test.ts b/packages/voice_engine_v2/src/simulation/Simulator.test.tsdeleted file mode 100644index f1fca0f22..000000000--- a/packages/voice_engine_v2/src/simulation/Simulator.test.ts+++ /dev/null@@ -1,116 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- createVoiceEngineV2EmptyFaultPlan,- createVoiceEngineV2FaultPlan,-} from '@fluxer/voice_engine_v2/src/simulation/FaultInjector';-import {VoiceEngineV2Simulator} from '@fluxer/voice_engine_v2/src/simulation/Simulator';-import {- createVoiceEngineV2FiveParticipantConferenceWorkload,- createVoiceEngineV2OneOnOneCallWorkload,- createVoiceEngineV2ScreenShareWorkload,- VoiceEngineV2WorkloadBuilder,-} from '@fluxer/voice_engine_v2/src/simulation/Workload';-import {describe, expect, it} from 'vitest';--describe('VoiceEngineV2Simulator safety mode', () => {- it('reports no safety violations under an empty fault plan', async () => {- const workload = createVoiceEngineV2OneOnOneCallWorkload();- const result = await new VoiceEngineV2Simulator({- seed: 42,- workload,- faults: createVoiceEngineV2EmptyFaultPlan(),- mode: 'safety',- }).run();- expect(result.violations).toEqual([]);- });-- it('reports no safety violations under sustained packet-loss faults', async () => {- const workload = createVoiceEngineV2OneOnOneCallWorkload();- const faults = createVoiceEngineV2FaultPlan([- {kind: 'packetLoss', rate: 0.5, fromTick: 0, untilTick: workload.tickCount},- ]);- const result = await new VoiceEngineV2Simulator({seed: 3, workload, faults, mode: 'safety'}).run();- expect(result.violations).toEqual([]);- });-- it('preserves event-log sequence under a high event-rate workload', async () => {- const builder = new VoiceEngineV2WorkloadBuilder('high-rate');- builder.at(0).connect({url: 'wss://voice.example.test', token: 'tok'});- builder.advance(1).emit({type: 'connection.connectSucceeded', operationId: 1});- for (let i = 0; i < 64; i++) {- builder.advance(1).joinParticipant({- sid: `sid-${i}`,- identity: `peer-${i}`,- name: `Peer ${i}`,- });- }- const workload = builder.build();- const result = await new VoiceEngineV2Simulator({- seed: 9,- workload,- faults: createVoiceEngineV2EmptyFaultPlan(),- mode: 'safety',- }).run();- expect(result.violations).toEqual([]);- for (let i = 0; i < result.eventLog.length; i++) {- expect(result.eventLog[i].sequence).toBe(i + 1);- }- });-- it('runs the screen-share workload without invariant violations', async () => {- const workload = createVoiceEngineV2ScreenShareWorkload();- const result = await new VoiceEngineV2Simulator({- seed: 17,- workload,- faults: createVoiceEngineV2EmptyFaultPlan(),- mode: 'safety',- }).run();- expect(result.violations).toEqual([]);- });-- it('runs the five-party conference workload safely', async () => {- const workload = createVoiceEngineV2FiveParticipantConferenceWorkload();- const result = await new VoiceEngineV2Simulator({- seed: 23,- workload,- faults: createVoiceEngineV2EmptyFaultPlan(),- mode: 'safety',- }).run();- expect(result.violations).toEqual([]);- });-});--describe('VoiceEngineV2Simulator liveness mode', () => {- it('recovers after a device disconnect by republishing the microphone', async () => {- const builder = new VoiceEngineV2WorkloadBuilder('liveness-device');- builder.at(0).connect({url: 'wss://voice.example.test', token: 'tok-live'});- builder.advance(1).emit({type: 'connection.connectSucceeded', operationId: 1});- builder.advance(1).publishMicrophone();- builder- .advance(10)- .emit({type: 'room.participantJoined', participant: {sid: 'sid-r', identity: 'remote', name: 'Remote'}});- builder.advance(20).publishMicrophone({deviceId: 'fallback-mic'});- const workload = builder.build();- const faults = createVoiceEngineV2FaultPlan([- {kind: 'asymmetricPartition', peerIds: ['ghost-peer'], fromTick: 5},- {kind: 'deviceDisconnect', deviceId: 'default-mic', atTick: 6},- ]);- const result = await new VoiceEngineV2Simulator({seed: 29, workload, faults, mode: 'liveness'}).run();- expect(result.partitionedPeers).toContain('ghost-peer');- expect(result.livenessRecovered).toBe(true);- });-- it('recovers after asymmetric partition by completing further publishes', async () => {- const builder = new VoiceEngineV2WorkloadBuilder('liveness-partition');- builder.at(0).connect({url: 'wss://voice.example.test', token: 'tok-live-2'});- builder.advance(1).emit({type: 'connection.connectSucceeded', operationId: 1});- builder.advance(2).publishMicrophone();- builder.advance(15).publishMicrophone({deviceId: 'alt-mic'});- const workload = builder.build();- const faults = createVoiceEngineV2FaultPlan([{kind: 'asymmetricPartition', peerIds: ['ghost'], fromTick: 4}]);- const result = await new VoiceEngineV2Simulator({seed: 31, workload, faults, mode: 'liveness'}).run();- expect(result.partitionedPeers).toEqual(['ghost']);- expect(result.livenessRecovered).toBe(true);- });-});diff --git a/packages/voice_engine_v2/src/simulation/Simulator.ts b/packages/voice_engine_v2/src/simulation/Simulator.tsdeleted file mode 100644index 22b5f3ac2..000000000--- a/packages/voice_engine_v2/src/simulation/Simulator.ts+++ /dev/null@@ -1,305 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import type {VoiceEngineV2Event} from '@fluxer/voice_engine_v2/src/protocol/events';-import {createVoiceEngineV2MemoryEventLogSpillSink} from '@fluxer/voice_engine_v2/src/runtime/eventLogRing';-import {- type VoiceEngineV2EventLogEntry,- VoiceEngineV2Runtime,-} from '@fluxer/voice_engine_v2/src/runtime/VoiceEngineV2Runtime';-import {- type VoiceEngineV2FaultDecision,- VoiceEngineV2FaultInjector,- type VoiceEngineV2FaultPlan,-} from '@fluxer/voice_engine_v2/src/simulation/FaultInjector';-import {- collectVoiceEngineV2SafetyViolations,- type VoiceEngineV2SafetyViolation,-} from '@fluxer/voice_engine_v2/src/simulation/SafetyInvariants';-import {- createSimulatorClock,- type SimulatorDriverDeviceInventory,- type SimulatorDriverFaultPolicy,- VoiceEngineV2SimulatorDriver,-} from '@fluxer/voice_engine_v2/src/simulation/SimulatorPorts';-import type {VoiceEngineV2Workload} from '@fluxer/voice_engine_v2/src/simulation/Workload';-import {VoiceEngineV2TestImplementation} from '@fluxer/voice_engine_v2/src/testing/VoiceEngineV2TestImplementation';--export const SIMULATOR_TICK_MAX = 4096;-const SIMULATOR_TICK_NS_DEFAULT = 16_666_666;-const SIMULATOR_MICROTASK_FLUSH_MAX = 64;-const SIMULATOR_LIVENESS_RECOVERY_TICKS = 64;-export const STABLE_STRINGIFY_DEPTH_MAX = 128;-const STABLE_STRINGIFY_WORK_ITEMS_MAX = 1_048_576;--export type VoiceEngineV2SimulatorMode = 'safety' | 'liveness';--interface VoiceEngineV2SimulatorOptions {- seed: number;- workload: VoiceEngineV2Workload;- faults: VoiceEngineV2FaultPlan;- mode: VoiceEngineV2SimulatorMode;- tickNs?: number;- maxTicks?: number;- inventory?: SimulatorDriverDeviceInventory;-}--export interface VoiceEngineV2SimulatorResult {- snapshotHash: string;- finalTick: number;- violations: ReadonlyArray<VoiceEngineV2SafetyViolation>;- eventLog: ReadonlyArray<VoiceEngineV2EventLogEntry>;- livenessRecovered: boolean;- partitionedPeers: ReadonlyArray<string>;-}--export class VoiceEngineV2Simulator {- private readonly seed: number;- private readonly workload: VoiceEngineV2Workload;- private readonly faultPlan: VoiceEngineV2FaultPlan;- private readonly mode: VoiceEngineV2SimulatorMode;- private readonly tickNs: number;- private readonly maxTicks: number;- private readonly inventory: SimulatorDriverDeviceInventory;-- constructor(options: VoiceEngineV2SimulatorOptions) {- assert.ok(options, 'simulator requires options');- assert.ok(Number.isInteger(options.seed), 'simulator seed must be an integer');- assert.ok(options.seed >= 0, 'simulator seed must be non-negative');- assert.ok(options.workload, 'simulator requires a workload');- assert.ok(options.faults, 'simulator requires a fault plan');- assert.ok(options.mode === 'safety' || options.mode === 'liveness', 'simulator mode invalid');- this.seed = options.seed;- this.workload = options.workload;- this.faultPlan = options.faults;- this.mode = options.mode;- this.tickNs = options.tickNs ?? SIMULATOR_TICK_NS_DEFAULT;- this.maxTicks = options.maxTicks ?? SIMULATOR_TICK_MAX;- this.inventory = options.inventory ?? defaultInventory();- assert.ok(this.tickNs > 0, 'tickNs must be positive');- assert.ok(this.maxTicks > 0, 'maxTicks must be positive');- assert.ok(this.maxTicks <= SIMULATOR_TICK_MAX, 'maxTicks exceeds SIMULATOR_TICK_MAX cap');- }-- async run(): Promise<VoiceEngineV2SimulatorResult> {- assert.ok(this.maxTicks > 0, 'simulator run requires positive maxTicks');- assert.ok(this.workload.steps.length <= this.maxTicks * 8, 'workload step density violates simulator budget');- const clock = createSimulatorClock(0);- const injector = new VoiceEngineV2FaultInjector(this.seed, this.faultPlan);- const stepsByTick = bucketStepsByTick(this.workload, this.maxTicks);- const policyState: PolicyState = {decision: blankDecision()};- const driver = new VoiceEngineV2SimulatorDriver({- policy: buildPolicy(policyState),- inventory: this.inventory,- });- const implementation = new VoiceEngineV2TestImplementation(driver);- const runtime = new VoiceEngineV2Runtime(implementation, {- clock,- eventLogSpillSink: createVoiceEngineV2MemoryEventLogSpillSink(),- verifyEventLogInvariantsOnDispatch: true,- });- const totalTicks = this.computeTotalTicks();- let livenessBaselinePublishCount = 0;- let livenessRecovered = this.mode === 'safety';- let partitionStarted = false;- const partitionedPeers = new Set<string>();- for (let tick = 0; tick < totalTicks; tick++) {- const decision = injector.decide(tick);- policyState.decision = decision;- for (const peer of decision.asymmetricallyPartitionedPeers) partitionedPeers.add(peer);- if (decision.asymmetricallyPartitionedPeers.length > 0 && !partitionStarted) {- partitionStarted = true;- livenessBaselinePublishCount = countMicrophonePublishSucceeded(runtime.eventLog);- }- const steps = stepsByTick.get(tick) ?? [];- for (const step of steps) runtime.dispatch(step.event);- clock.advanceNs(this.tickNs);- await flushMicrotasks(SIMULATOR_MICROTASK_FLUSH_MAX);- if (this.mode === 'liveness' && partitionStarted && !livenessRecovered) {- const current = countMicrophonePublishSucceeded(runtime.eventLog);- if (current > livenessBaselinePublishCount) livenessRecovered = true;- }- }- await flushMicrotasks(SIMULATOR_MICROTASK_FLUSH_MAX);- const finalLog = runtime.eventLog;- const violations = this.mode === 'safety' ? collectVoiceEngineV2SafetyViolations(finalLog) : [];- const hash = hashSnapshot(runtime.snapshot);- runtime.dispose();- assertResultWellFormed(hash, finalLog);- return {- snapshotHash: hash,- finalTick: totalTicks,- violations,- eventLog: finalLog,- livenessRecovered,- partitionedPeers: [...partitionedPeers],- };- }-- private computeTotalTicks(): number {- const workloadTicks = Math.min(this.workload.tickCount, this.maxTicks);- if (this.mode === 'safety') return Math.max(workloadTicks, 1);- const total = Math.min(workloadTicks + SIMULATOR_LIVENESS_RECOVERY_TICKS, this.maxTicks);- assert.ok(total >= workloadTicks, 'liveness tick budget must extend workload');- return Math.max(total, 1);- }-}--interface PolicyState {- decision: VoiceEngineV2FaultDecision;-}--function bucketStepsByTick(- workload: VoiceEngineV2Workload,- maxTicks: number,-): Map<number, ReadonlyArray<{tick: number; event: VoiceEngineV2Event}>> {- assert.ok(workload, 'workload required for bucketing');- assert.ok(maxTicks > 0, 'maxTicks must be positive when bucketing');- const buckets = new Map<number, Array<{tick: number; event: VoiceEngineV2Event}>>();- for (const step of workload.steps) {- if (step.tick >= maxTicks) continue;- const bucket = buckets.get(step.tick) ?? [];- bucket.push({tick: step.tick, event: step.event});- buckets.set(step.tick, bucket);- }- return buckets;-}--function blankDecision(): VoiceEngineV2FaultDecision {- return {- connectShouldDrop: false,- disconnectShouldDrop: false,- microphonePublishShouldFail: false,- cameraPublishShouldFail: false,- screenPublishShouldFail: false,- failingCaptureIds: [],- deviceLossDeviceIds: [],- gpuLost: false,- asymmetricallyPartitionedPeers: [],- networkPartitionActive: false,- };-}--function buildPolicy(state: PolicyState): SimulatorDriverFaultPolicy {- return {- shouldDropConnect: () => state.decision.connectShouldDrop,- shouldDropDisconnect: () => state.decision.disconnectShouldDrop,- shouldFailMicrophonePublish: () => state.decision.microphonePublishShouldFail,- shouldFailCameraPublish: () => state.decision.cameraPublishShouldFail,- shouldFailScreenPublish: () => state.decision.screenPublishShouldFail,- shouldFailNativeCaptureStart: (captureId) => state.decision.failingCaptureIds.includes(captureId),- shouldEmitDeviceLoss: () => state.decision.deviceLossDeviceIds.length > 0,- };-}--async function flushMicrotasks(maxIterations: number): Promise<void> {- assert.ok(maxIterations > 0, 'flushMicrotasks requires a positive iteration cap');- for (let i = 0; i < maxIterations; i++) {- await Promise.resolve();- }-}--function countMicrophonePublishSucceeded(entries: ReadonlyArray<VoiceEngineV2EventLogEntry>): number {- assert.ok(Array.isArray(entries), 'event log entries required');- let count = 0;- for (const entry of entries) if (entry.event.type === 'microphone.publishSucceeded') count++;- return count;-}--export function hashSnapshot(snapshot: unknown): string {- assert.ok(snapshot !== undefined, 'cannot hash an undefined snapshot');- const serialized = stableStringify(snapshot);- assert.ok(typeof serialized === 'string', 'stableStringify must return a string');- let hash = 0x811c9dc5;- for (let i = 0; i < serialized.length; i++) {- hash ^= serialized.charCodeAt(i);- hash = Math.imul(hash, 0x01000193);- }- const value = (hash >>> 0).toString(16).padStart(8, '0');- assert.ok(value.length === 8, 'hash must be eight hex characters');- return value;-}--type StableStringifyWorkItem = {literal: string} | {value: unknown; depth: number};--export function stableStringify(value: unknown): string {- const out: Array<string> = [];- const stack: Array<StableStringifyWorkItem> = [{value, depth: 0}];- let processedCount = 0;- while (stack.length > 0) {- processedCount += 1;- assert.ok(processedCount <= STABLE_STRINGIFY_WORK_ITEMS_MAX, 'stableStringify work item budget exceeded');- const item = stack.pop();- assert.ok(item !== undefined, 'stableStringify stack pop must yield an item');- if ('literal' in item) {- out.push(item.literal);- } else {- appendStableStringifyValue(item.value, item.depth, out, stack);- }- }- return out.join('');-}--function appendStableStringifyValue(- value: unknown,- depth: number,- out: Array<string>,- stack: Array<StableStringifyWorkItem>,-): void {- assert.ok(depth >= 0, 'stableStringify depth must be non-negative');- assert.ok(depth <= STABLE_STRINGIFY_DEPTH_MAX, 'stableStringify depth budget exceeded');- if (value === null) {- out.push('null');- return;- }- if (typeof value === 'number') {- out.push(Number.isFinite(value) ? String(value) : 'null');- return;- }- if (typeof value === 'boolean') {- out.push(value ? 'true' : 'false');- return;- }- if (typeof value === 'string') {- out.push(JSON.stringify(value));- return;- }- if (Array.isArray(value)) {- out.push('[');- stack.push({literal: ']'});- for (let i = value.length - 1; i >= 0; i -= 1) {- stack.push({value: value[i], depth: depth + 1});- if (i > 0) stack.push({literal: ','});- }- return;- }- if (typeof value === 'object') {- const record = value as Record<string, unknown>;- const keys = Object.keys(record).sort();- out.push('{');- stack.push({literal: '}'});- for (let i = keys.length - 1; i >= 0; i -= 1) {- const key = keys[i];- assert.ok(key !== undefined, 'stableStringify sorted keys must not contain holes');- stack.push({value: record[key], depth: depth + 1});- stack.push({literal: `${JSON.stringify(key)}:`});- if (i > 0) stack.push({literal: ','});- }- return;- }- out.push('null');-}--function assertResultWellFormed(hash: string, entries: ReadonlyArray<VoiceEngineV2EventLogEntry>): void {- assert.ok(typeof hash === 'string', 'hash must be a string');- assert.ok(hash.length > 0, 'hash must be non-empty');- assert.ok(Array.isArray(entries), 'event log must be an array on return');-}--function defaultInventory(): SimulatorDriverDeviceInventory {- return {- audioInputs: ['default-mic'],- audioOutputs: ['default-output'],- cameras: ['default-camera'],- };-}diff --git a/packages/voice_engine_v2/src/simulation/SimulatorPorts.ts b/packages/voice_engine_v2/src/simulation/SimulatorPorts.tsindex c76dac560..a3769b346 100644--- a/packages/voice_engine_v2/src/simulation/SimulatorPorts.ts+++ b/packages/voice_engine_v2/src/simulation/SimulatorPorts.ts@@ -29,82 +29,6 @@ import type {VoiceEngineV2ScreenOptions,VoiceEngineV2Stats,} from '@fluxer/voice_engine_v2/src/protocol/types';-import type {VoiceEngineV2ClockPort, VoiceEngineV2RandomPort} from '@fluxer/voice_engine_v2/src/runtime/platformPort';--const SIMULATOR_CLOCK_MAX_NS = 1_000_000_000_000;-const SIMULATOR_NS_PER_MS = 1_000_000;-const SIMULATOR_RANDOM_MULTIPLIER = 0x5deece66d;-const SIMULATOR_RANDOM_INCREMENT = 0xbn;-const SIMULATOR_RANDOM_MASK = (1n << 48n) - 1n;--interface VoiceEngineV2SimulatorClock extends VoiceEngineV2ClockPort {- advanceNs(deltaNs: number): void;- currentNs(): number;-}--export interface VoiceEngineV2SimulatorRandom extends VoiceEngineV2RandomPort {- nextU32(): number;- nextFloat01(): number;- nextBool(probability: number): boolean;-}--export function createSimulatorClock(initialNs = 0): VoiceEngineV2SimulatorClock {- assert.ok(Number.isFinite(initialNs), 'simulator clock requires a finite initial nanosecond value');- assert.ok(initialNs >= 0, 'simulator clock cannot start at a negative nanosecond value');- let currentNs = initialNs;- return {- now(): number {- assert.ok(currentNs >= 0, 'simulator clock yielded a negative wall time');- assert.ok(currentNs <= SIMULATOR_CLOCK_MAX_NS, 'simulator clock exceeded its bounded horizon');- return Math.floor(currentNs / SIMULATOR_NS_PER_MS);- },- advanceNs(deltaNs: number): void {- assert.ok(Number.isFinite(deltaNs), 'simulator clock delta must be finite');- assert.ok(deltaNs >= 0, 'simulator clock cannot advance backwards');- assert.ok(currentNs + deltaNs <= SIMULATOR_CLOCK_MAX_NS, 'simulator clock advance exceeds horizon');- currentNs += deltaNs;- },- currentNs(): number {- assert.ok(currentNs >= 0, 'simulator clock currentNs underflow');- return currentNs;- },- };-}--export function createSimulatorRandom(seed: number): VoiceEngineV2SimulatorRandom {- assert.ok(Number.isInteger(seed), 'simulator random seed must be an integer');- assert.ok(seed >= 0, 'simulator random seed must be non-negative');- let state = BigInt(seed ^ 0xdeadbeef) & SIMULATOR_RANDOM_MASK;- const advance = (): bigint => {- state = (state * BigInt(SIMULATOR_RANDOM_MULTIPLIER) + SIMULATOR_RANDOM_INCREMENT) & SIMULATOR_RANDOM_MASK;- return state;- };- const nextFloat01 = (): number => {- const u32 = Number(advance() >> 16n) >>> 0;- const value = u32 / 0x100000000;- assert.ok(value >= 0, 'simulator random float underflow');- assert.ok(value < 1, 'simulator random float overflow');- return value;- };- return {- next(): number {- return nextFloat01();- },- nextU32(): number {- const value = Number(advance() >> 16n) >>> 0;- assert.ok(value >= 0, 'simulator random produced a negative u32');- assert.ok(value <= 0xffffffff, 'simulator random produced an out-of-range u32');- return value;- },- nextFloat01,- nextBool(probability: number): boolean {- assert.ok(probability >= 0, 'probability must be non-negative');- assert.ok(probability <= 1, 'probability cannot exceed one');- const u32 = Number(advance() >> 16n) >>> 0;- return u32 / 0x100000000 < probability;- },- };-}export interface SimulatorDriverFaultPolicy {shouldDropConnect(): boolean;@@ -116,7 +40,7 @@ export interface SimulatorDriverFaultPolicy {shouldEmitDeviceLoss(): boolean;}-export interface SimulatorDriverDeviceInventory {+interface SimulatorDriverDeviceInventory {audioInputs: Array<string>;audioOutputs: Array<string>;cameras: Array<string>;diff --git a/packages/voice_engine_v2/src/simulation/Workload.ts b/packages/voice_engine_v2/src/simulation/Workload.tsdeleted file mode 100644index c26d75b65..000000000--- a/packages/voice_engine_v2/src/simulation/Workload.ts+++ /dev/null@@ -1,219 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import type {VoiceEngineV2Event} from '@fluxer/voice_engine_v2/src/protocol/events';-import type {- VoiceEngineV2CameraOptions,- VoiceEngineV2ConnectOptions,- VoiceEngineV2MicrophoneOptions,- VoiceEngineV2NativeCaptureOptions,- VoiceEngineV2NativeFrameSinkOptions,- VoiceEngineV2Participant,- VoiceEngineV2ScreenOptions,-} from '@fluxer/voice_engine_v2/src/protocol/types';--const SIMULATOR_WORKLOAD_STEPS_MAX = 512;-const SIMULATOR_PARTICIPANTS_MAX = 32;--export interface VoiceEngineV2WorkloadStep {- readonly tick: number;- readonly event: VoiceEngineV2Event;-}--export interface VoiceEngineV2Workload {- readonly name: string;- readonly steps: ReadonlyArray<VoiceEngineV2WorkloadStep>;- readonly tickCount: number;-}--export class VoiceEngineV2WorkloadBuilder {- private readonly steps: Array<VoiceEngineV2WorkloadStep> = [];- private cursorTick = 0;- private readonly name: string;-- constructor(name: string) {- assert.ok(typeof name === 'string', 'workload name must be a string');- assert.ok(name.length > 0, 'workload name must not be empty');- this.name = name;- }-- at(tick: number): this {- assert.ok(Number.isInteger(tick), 'workload tick must be an integer');- assert.ok(tick >= this.cursorTick, 'workload ticks must be monotonic');- this.cursorTick = tick;- return this;- }-- advance(delta: number): this {- assert.ok(Number.isInteger(delta), 'workload advance must be an integer');- assert.ok(delta >= 0, 'workload advance must be non-negative');- this.cursorTick += delta;- return this;- }-- connect(options: VoiceEngineV2ConnectOptions): this {- return this.emit({type: 'connection.connectRequested', options});- }-- publishMicrophone(options: VoiceEngineV2MicrophoneOptions = {deviceId: 'default-mic'}): this {- return this.emit({type: 'microphone.publishRequested', options});- }-- unpublishMicrophone(): this {- return this.emit({type: 'microphone.unpublishRequested'});- }-- publishCamera(options: VoiceEngineV2CameraOptions = {deviceId: 'default-camera'}): this {- return this.emit({type: 'camera.publishRequested', options});- }-- publishScreen(options: VoiceEngineV2ScreenOptions): this {- return this.emit({type: 'screen.publishRequested', options});- }-- startNativeCapture(options: VoiceEngineV2NativeCaptureOptions): this {- return this.emit({type: 'nativeCapture.startRequested', options});- }-- attachNativeFrameSink(options: VoiceEngineV2NativeFrameSinkOptions): this {- return this.emit({type: 'nativeFrameSink.attachRequested', options});- }-- joinParticipant(participant: VoiceEngineV2Participant): this {- return this.emit({type: 'room.participantJoined', participant});- }-- leaveParticipant(participantIdentity: string, participantSid?: string): this {- return this.emit({type: 'room.participantLeft', participantIdentity, participantSid});- }-- disconnect(reason: 'user' | 'server' | 'network' | 'replaced' | 'shutdown'): this {- return this.emit({type: 'connection.disconnectRequested', reason});- }-- externallyEstablish(options: VoiceEngineV2ConnectOptions): this {- assert.ok(options, 'externallyEstablish requires connect options');- assert.equal(typeof options.url, 'string', 'externallyEstablish url must be a string');- assert.equal(typeof options.token, 'string', 'externallyEstablish token must be a string');- return this.emit({type: 'connection.externallyEstablished', options});- }-- remoteDisconnect(reason: 'user' | 'server' | 'network' | 'replaced' | 'shutdown'): this {- return this.emit({type: 'connection.remoteDisconnected', reason});- }-- emit(event: VoiceEngineV2Event): this {- assert.ok(event, 'workload event must be defined');- assert.ok(this.steps.length < SIMULATOR_WORKLOAD_STEPS_MAX, 'cannot exceed workload step cap');- this.steps.push({tick: this.cursorTick, event});- return this;- }-- build(): VoiceEngineV2Workload {- assert.ok(this.steps.length <= SIMULATOR_WORKLOAD_STEPS_MAX, 'workload exceeds step cap');- const tickCount = this.steps.length === 0 ? 0 : this.steps[this.steps.length - 1].tick + 1;- return {- name: this.name,- steps: [...this.steps],- tickCount,- };- }-}--export function createVoiceEngineV2OneOnOneCallWorkload(): VoiceEngineV2Workload {- const remote: VoiceEngineV2Participant = {sid: 'sid-remote', identity: 'remote-1', name: 'Remote 1'};- return new VoiceEngineV2WorkloadBuilder('one-on-one')- .at(0)- .connect({url: 'wss://voice.example.test', token: 'tok-1'})- .advance(2)- .emit({type: 'connection.connectSucceeded', operationId: 1})- .advance(1)- .publishMicrophone()- .advance(2)- .joinParticipant(remote)- .advance(4)- .disconnect('user')- .build();-}--export function createVoiceEngineV2ScreenShareWorkload(): VoiceEngineV2Workload {- const captureOptions: VoiceEngineV2NativeCaptureOptions = {- captureId: 'cap-1',- source: {id: 'display-1', kind: 'screen', title: 'Display 1'},- width: 1280,- height: 720,- frameRate: 30,- includeCursor: true,- includeAudio: false,- zeroCopyRequired: true,- };- const sinkOptions: VoiceEngineV2NativeFrameSinkOptions = {- sinkId: 'sink-1',- captureId: 'cap-1',- zeroCopyRequired: true,- };- const screenOptions: VoiceEngineV2ScreenOptions = {captureId: 'cap-1', width: 1280, height: 720};- return new VoiceEngineV2WorkloadBuilder('screen-share')- .at(0)- .connect({url: 'wss://voice.example.test', token: 'tok-screen'})- .advance(2)- .emit({type: 'connection.connectSucceeded', operationId: 1})- .advance(1)- .startNativeCapture(captureOptions)- .advance(2)- .attachNativeFrameSink(sinkOptions)- .advance(1)- .publishScreen(screenOptions)- .advance(5)- .disconnect('user')- .build();-}--export const SIMULATOR_EXTERNAL_ESTABLISH_CYCLES = 3;--export function createVoiceEngineV2ExternalEstablishmentCycleWorkload(): VoiceEngineV2Workload {- assert.ok(SIMULATOR_EXTERNAL_ESTABLISH_CYCLES >= 1, 'external establishment workload requires at least one cycle');- assert.ok(SIMULATOR_EXTERNAL_ESTABLISH_CYCLES <= 8, 'external establishment cycle count must stay bounded');- const remote: VoiceEngineV2Participant = {sid: 'sid-remote-ext', identity: 'remote-ext-1', name: 'Remote Ext 1'};- const reasons: ReadonlyArray<'network' | 'server' | 'replaced'> = ['network', 'server', 'replaced'];- const builder = new VoiceEngineV2WorkloadBuilder('external-establishment-cycles').at(0).publishMicrophone();- for (let cycle = 0; cycle < SIMULATOR_EXTERNAL_ESTABLISH_CYCLES; cycle++) {- const reason = reasons[cycle % reasons.length];- assert.ok(reason !== undefined, 'cycle reason selection must not produce holes');- builder- .advance(1)- .externallyEstablish({url: `wss://voice.example.test/external-${cycle}`, token: `tok-ext-${cycle}`})- .advance(2)- .publishMicrophone()- .advance(1)- .joinParticipant({...remote, sid: `${remote.sid}-${cycle}`, identity: `${remote.identity}-${cycle}`})- .advance(2)- .remoteDisconnect(reason);- }- return builder- .advance(2)- .externallyEstablish({url: 'wss://voice.example.test/external-final', token: 'tok-ext-final'})- .advance(2)- .disconnect('user')- .build();-}--export function createVoiceEngineV2FiveParticipantConferenceWorkload(): VoiceEngineV2Workload {- const builder = new VoiceEngineV2WorkloadBuilder('five-party-conference')- .at(0)- .connect({url: 'wss://voice.example.test', token: 'tok-conf'})- .advance(2)- .emit({type: 'connection.connectSucceeded', operationId: 1})- .advance(1)- .publishMicrophone();- const participantCount = 4;- assert.ok(participantCount <= SIMULATOR_PARTICIPANTS_MAX, 'participant count exceeds cap');- for (let index = 0; index < participantCount; index++) {- builder.advance(1).joinParticipant({- sid: `sid-p${index + 1}`,- identity: `peer-${index + 1}`,- name: `Peer ${index + 1}`,- });- }- return builder.advance(6).disconnect('user').build();-}diff --git a/packages/voice_engine_v2/src/simulation/externalEstablishment.test.ts b/packages/voice_engine_v2/src/simulation/externalEstablishment.test.tsdeleted file mode 100644index 449fd0746..000000000--- a/packages/voice_engine_v2/src/simulation/externalEstablishment.test.ts+++ /dev/null@@ -1,120 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- createVoiceEngineV2EmptyFaultPlan,- createVoiceEngineV2FaultPlan,-} from '@fluxer/voice_engine_v2/src/simulation/FaultInjector';-import {VoiceEngineV2Simulator} from '@fluxer/voice_engine_v2/src/simulation/Simulator';-import {- createVoiceEngineV2ExternalEstablishmentCycleWorkload,- SIMULATOR_EXTERNAL_ESTABLISH_CYCLES,- VoiceEngineV2WorkloadBuilder,-} from '@fluxer/voice_engine_v2/src/simulation/Workload';-import {describe, expect, it} from 'vitest';--describe('external establishment workload shape', () => {- it('emits an establish and a remote disconnect for every cycle', () => {- const workload = createVoiceEngineV2ExternalEstablishmentCycleWorkload();- const establishCount = workload.steps.filter(- (step) => step.event.type === 'connection.externallyEstablished',- ).length;- const remoteDisconnectCount = workload.steps.filter(- (step) => step.event.type === 'connection.remoteDisconnected',- ).length;- expect(establishCount).toBe(SIMULATOR_EXTERNAL_ESTABLISH_CYCLES + 1);- expect(remoteDisconnectCount).toBe(SIMULATOR_EXTERNAL_ESTABLISH_CYCLES);- });-- it('keeps step ticks monotonic', () => {- const workload = createVoiceEngineV2ExternalEstablishmentCycleWorkload();- let previousTick = 0;- for (const step of workload.steps) {- expect(step.tick).toBeGreaterThanOrEqual(previousTick);- previousTick = step.tick;- }- expect(workload.tickCount).toBeGreaterThan(0);- });-- it('supports the builder helpers for externally-driven connection events', () => {- const workload = new VoiceEngineV2WorkloadBuilder('external-helpers')- .at(0)- .externallyEstablish({url: 'wss://voice.example.test', token: 'tok-1'})- .advance(1)- .remoteDisconnect('network')- .build();- expect(workload.steps.map((step) => step.event.type)).toEqual([- 'connection.externallyEstablished',- 'connection.remoteDisconnected',- ]);- });-- it('asserts on malformed externally-established options', () => {- const builder = new VoiceEngineV2WorkloadBuilder('external-invalid');- expect(() => builder.externallyEstablish({url: 1 as unknown as string, token: 'tok'})).toThrow(- 'externallyEstablish url must be a string',- );- });-});--describe('external establishment simulation safety', () => {- it('reports no structural safety violations across establish/disconnect cycles', async () => {- const workload = createVoiceEngineV2ExternalEstablishmentCycleWorkload();- const result = await new VoiceEngineV2Simulator({- seed: 11,- workload,- faults: createVoiceEngineV2EmptyFaultPlan(),- mode: 'safety',- }).run();- expect(result.violations).toEqual([]);- expect(result.eventLog.length).toBeGreaterThan(0);- });-- it('produces identical snapshot hashes for identical seeds (determinism)', async () => {- const workload = createVoiceEngineV2ExternalEstablishmentCycleWorkload();- const faults = createVoiceEngineV2EmptyFaultPlan();- const first = await new VoiceEngineV2Simulator({seed: 5, workload, faults, mode: 'safety'}).run();- const second = await new VoiceEngineV2Simulator({seed: 5, workload, faults, mode: 'safety'}).run();- expect(first.snapshotHash).toBe(second.snapshotHash);- expect(first.eventLog.length).toBe(second.eventLog.length);- });-- it('keeps the event log sequence strictly increasing through the cycles', async () => {- const workload = createVoiceEngineV2ExternalEstablishmentCycleWorkload();- const result = await new VoiceEngineV2Simulator({- seed: 23,- workload,- faults: createVoiceEngineV2EmptyFaultPlan(),- mode: 'safety',- }).run();- let previousSequence = 0;- for (const entry of result.eventLog) {- expect(entry.sequence).toBeGreaterThan(previousSequence);- previousSequence = entry.sequence;- }- });-- it('stays violation-free under sustained packet loss across cycles', async () => {- const workload = createVoiceEngineV2ExternalEstablishmentCycleWorkload();- const faults = createVoiceEngineV2FaultPlan([- {kind: 'packetLoss', rate: 0.5, fromTick: 0, untilTick: workload.tickCount},- ]);- const result = await new VoiceEngineV2Simulator({seed: 3, workload, faults, mode: 'safety'}).run();- expect(result.violations).toEqual([]);- });-- it('records every externally-driven connection event in the durable log', async () => {- const workload = createVoiceEngineV2ExternalEstablishmentCycleWorkload();- const result = await new VoiceEngineV2Simulator({- seed: 17,- workload,- faults: createVoiceEngineV2EmptyFaultPlan(),- mode: 'safety',- }).run();- const establishEntries = result.eventLog.filter((entry) => entry.event.type === 'connection.externallyEstablished');- const remoteDisconnectEntries = result.eventLog.filter(- (entry) => entry.event.type === 'connection.remoteDisconnected',- );- expect(establishEntries.length).toBe(SIMULATOR_EXTERNAL_ESTABLISH_CYCLES + 1);- expect(remoteDisconnectEntries.length).toBe(SIMULATOR_EXTERNAL_ESTABLISH_CYCLES);- });-});diff --git a/packages/voice_engine_v2/src/simulation/scenarios/asymmetricNatAfterConnect.ts b/packages/voice_engine_v2/src/simulation/scenarios/asymmetricNatAfterConnect.tsdeleted file mode 100644index e245f395f..000000000--- a/packages/voice_engine_v2/src/simulation/scenarios/asymmetricNatAfterConnect.ts+++ /dev/null@@ -1,105 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {createVoiceEngineV2FaultPlan} from '@fluxer/voice_engine_v2/src/simulation/FaultInjector';-import type {VoiceEngineV2SimulatorResult} from '@fluxer/voice_engine_v2/src/simulation/Simulator';-import {- assertSeedWellFormed,- combineVerdicts,- failVerdict,- passVerdict,- type VoiceEngineV2AcceptanceVerdict,- type VoiceEngineV2SimulationScenario,-} from '@fluxer/voice_engine_v2/src/simulation/scenarios/index';-import type {VoiceEngineV2Workload} from '@fluxer/voice_engine_v2/src/simulation/Workload';-import {VoiceEngineV2WorkloadBuilder} from '@fluxer/voice_engine_v2/src/simulation/Workload';--const ASYM_PARTITION_FROM_TICK = 200;-const ASYM_PARTITION_PEER_ID = 'B';-const ASYM_FINAL_PROBE_TICK = 240;--export function defineAsymmetricNatAfterConnectScenario(seed: number): VoiceEngineV2SimulationScenario {- assertSeedWellFormed(seed);- const workload = buildWorkload();- assert.ok(workload.tickCount <= 512, 'workload tick count exceeds the simulator budget');- const faultPlan = createVoiceEngineV2FaultPlan([- {kind: 'asymmetricPartition', peerIds: [ASYM_PARTITION_PEER_ID], fromTick: ASYM_PARTITION_FROM_TICK},- ]);- return {- name: 'asymmetric-nat-after-connect',- mode: 'safety',- workload,- faultPlan,- acceptance: checkAcceptance,- };-}--function buildWorkload(): VoiceEngineV2Workload {- const builder = new VoiceEngineV2WorkloadBuilder('asymmetric-nat-after-connect');- builder.at(0).connect({url: 'wss://voice.example.test', token: 'tok-asym'});- builder.advance(2).emit({type: 'connection.connectSucceeded', operationId: 1});- builder.advance(1).publishMicrophone({deviceId: 'mic-A'});- builder.advance(2).joinParticipant({sid: 'sid-A', identity: 'A', name: 'Alice'});- builder.advance(2).joinParticipant({sid: 'sid-B', identity: 'B', name: 'Bob'});- builder.advance(2).joinParticipant({sid: 'sid-C', identity: 'C', name: 'Carol'});- builder.at(ASYM_PARTITION_FROM_TICK).leaveParticipant('B', 'sid-B');- builder.at(ASYM_FINAL_PROBE_TICK).publishMicrophone({deviceId: 'mic-A-2'});- return builder.build();-}--function checkAcceptance(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- assert.ok(result, 'acceptance requires a simulator result');- assert.ok(Array.isArray(result.eventLog), 'acceptance requires an event log array');- const verdicts = [- verifyNoViolations(result),- verifyPartitionTracked(result),- verifyPeerBLeft(result),- verifyAandCContinue(result),- ];- return combineVerdicts(verdicts);-}--function verifyNoViolations(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- if (result.violations.length === 0) return passVerdict();- return failVerdict(result.violations.map((violation) => `safety violation: ${violation.code}`));-}--function verifyPartitionTracked(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- if (!result.partitionedPeers.includes(ASYM_PARTITION_PEER_ID)) {- return failVerdict([`expected partitionedPeers to include ${ASYM_PARTITION_PEER_ID}`]);- }- return passVerdict();-}--function verifyPeerBLeft(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- let peerLeft = false;- let peerRejoined = false;- for (const entry of result.eventLog) {- if (entry.event.type === 'room.participantLeft' && entry.event.participantIdentity === ASYM_PARTITION_PEER_ID) {- peerLeft = true;- }- if (entry.event.type === 'room.participantJoined' && peerLeft) {- if (entry.event.participant.identity === ASYM_PARTITION_PEER_ID) peerRejoined = true;- }- }- if (!peerLeft) return failVerdict([`expected room.participantLeft for ${ASYM_PARTITION_PEER_ID}`]);- if (peerRejoined) return failVerdict([`peer ${ASYM_PARTITION_PEER_ID} re-joined before partition lifts`]);- return passVerdict();-}--function verifyAandCContinue(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- let aPresent = false;- let cPresent = false;- let microphoneOps = 0;- for (const entry of result.eventLog) {- if (entry.event.type === 'room.participantJoined') {- if (entry.event.participant.identity === 'A') aPresent = true;- if (entry.event.participant.identity === 'C') cPresent = true;- }- if (entry.event.type === 'microphone.publishRequested') microphoneOps += 1;- }- if (!aPresent) return failVerdict(['expected peer A to remain joined']);- if (!cPresent) return failVerdict(['expected peer C to remain joined']);- if (microphoneOps < 2) return failVerdict(['expected microphone publish attempts on both sides of partition']);- return passVerdict();-}diff --git a/packages/voice_engine_v2/src/simulation/scenarios/captureDeviceDisconnect.ts b/packages/voice_engine_v2/src/simulation/scenarios/captureDeviceDisconnect.tsdeleted file mode 100644index d3d755995..000000000--- a/packages/voice_engine_v2/src/simulation/scenarios/captureDeviceDisconnect.ts+++ /dev/null@@ -1,105 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {createVoiceEngineV2FaultPlan} from '@fluxer/voice_engine_v2/src/simulation/FaultInjector';-import type {VoiceEngineV2SimulatorResult} from '@fluxer/voice_engine_v2/src/simulation/Simulator';-import {- assertSeedWellFormed,- combineVerdicts,- failVerdict,- passVerdict,- type VoiceEngineV2AcceptanceVerdict,- type VoiceEngineV2SimulationScenario,-} from '@fluxer/voice_engine_v2/src/simulation/scenarios/index';-import type {VoiceEngineV2Workload} from '@fluxer/voice_engine_v2/src/simulation/Workload';-import {VoiceEngineV2WorkloadBuilder} from '@fluxer/voice_engine_v2/src/simulation/Workload';--const DEVICE_DISCONNECT_TICK = 100;-const DEVICE_DISCONNECT_DEVICE_ID = 'mic-1';-const DEVICE_DISCONNECT_RECOVERY_TICK = 140;--export function defineCaptureDeviceDisconnectScenario(seed: number): VoiceEngineV2SimulationScenario {- assertSeedWellFormed(seed);- const workload = buildWorkload();- assert.ok(workload.tickCount <= 512, 'workload tick count exceeds the simulator budget');- const faultPlan = createVoiceEngineV2FaultPlan([- {kind: 'deviceDisconnect', deviceId: DEVICE_DISCONNECT_DEVICE_ID, atTick: DEVICE_DISCONNECT_TICK},- ]);- return {- name: 'capture-device-disconnect',- mode: 'safety',- workload,- faultPlan,- acceptance: checkAcceptance,- };-}--function buildWorkload(): VoiceEngineV2Workload {- const builder = new VoiceEngineV2WorkloadBuilder('capture-device-disconnect');- builder.at(0).connect({url: 'wss://voice.example.test', token: 'tok-cap'});- builder.advance(2).emit({type: 'connection.connectSucceeded', operationId: 1});- builder.advance(1).publishMicrophone({deviceId: DEVICE_DISCONNECT_DEVICE_ID});- builder.advance(1).publishCamera({deviceId: 'cam-1'});- builder.advance(2).joinParticipant({sid: 'sid-r', identity: 'remote', name: 'Remote'});- builder.at(DEVICE_DISCONNECT_TICK).publishMicrophone({deviceId: 'mic-1-retry'});- builder.at(DEVICE_DISCONNECT_RECOVERY_TICK).publishMicrophone({deviceId: 'mic-2'});- return builder.build();-}--function checkAcceptance(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- assert.ok(result, 'acceptance requires a simulator result');- assert.ok(Array.isArray(result.eventLog), 'acceptance requires an event log array');- const verdicts = [- verifyNoViolations(result),- verifyMicrophoneFailed(result),- verifyCameraUnaffected(result),- verifyRecovery(result),- ];- return combineVerdicts(verdicts);-}--function verifyNoViolations(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- if (result.violations.length === 0) return passVerdict();- return failVerdict(result.violations.map((violation) => `safety violation: ${violation.code}`));-}--function verifyMicrophoneFailed(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- let microphoneFailureSeen = false;- for (const entry of result.eventLog) {- if (entry.event.type === 'microphone.publishFailed') microphoneFailureSeen = true;- }- if (!microphoneFailureSeen) {- return failVerdict(['expected microphone.publishFailed after device disconnect']);- }- return passVerdict();-}--function verifyCameraUnaffected(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- let cameraSucceeded = false;- let cameraFailed = false;- for (const entry of result.eventLog) {- if (entry.event.type === 'camera.publishSucceeded') cameraSucceeded = true;- if (entry.event.type === 'camera.publishFailed') cameraFailed = true;- }- if (!cameraSucceeded) {- return failVerdict(['expected camera.publishSucceeded before disconnect window']);- }- if (cameraFailed) {- return failVerdict(['unexpected camera.publishFailed during microphone disconnect window']);- }- return passVerdict();-}--function verifyRecovery(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- if (result.finalTick < DEVICE_DISCONNECT_RECOVERY_TICK) {- return failVerdict([`finalTick ${result.finalTick} ended before recovery deadline`]);- }- let microphoneSucceededCount = 0;- for (const entry of result.eventLog) {- if (entry.event.type === 'microphone.publishSucceeded') microphoneSucceededCount += 1;- }- if (microphoneSucceededCount < 1) {- return failVerdict(['expected at least one microphone.publishSucceeded across run']);- }- return passVerdict();-}diff --git a/packages/voice_engine_v2/src/simulation/scenarios/encoderFailUnderLoad.ts b/packages/voice_engine_v2/src/simulation/scenarios/encoderFailUnderLoad.tsdeleted file mode 100644index 9ae9a5c5d..000000000--- a/packages/voice_engine_v2/src/simulation/scenarios/encoderFailUnderLoad.ts+++ /dev/null@@ -1,128 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {createVoiceEngineV2FaultPlan} from '@fluxer/voice_engine_v2/src/simulation/FaultInjector';-import type {VoiceEngineV2SimulatorResult} from '@fluxer/voice_engine_v2/src/simulation/Simulator';-import {- assertSeedWellFormed,- combineVerdicts,- failVerdict,- passVerdict,- type VoiceEngineV2AcceptanceVerdict,- type VoiceEngineV2SimulationScenario,-} from '@fluxer/voice_engine_v2/src/simulation/scenarios/index';-import type {VoiceEngineV2Workload} from '@fluxer/voice_engine_v2/src/simulation/Workload';-import {VoiceEngineV2WorkloadBuilder} from '@fluxer/voice_engine_v2/src/simulation/Workload';--const ENCODER_FAIL_AT_TICK = 220;-const ENCODER_FAIL_PARTICIPANT_COUNT = 4;-const ENCODER_FAIL_CAPTURE_ID = 'screen-load';-const ENCODER_FAIL_RETRY_TICK = 260;--export function defineEncoderFailUnderLoadScenario(seed: number): VoiceEngineV2SimulationScenario {- assertSeedWellFormed(seed);- const workload = buildWorkload();- assert.ok(workload.tickCount <= 512, 'workload tick count exceeds the simulator budget');- const faultPlan = createVoiceEngineV2FaultPlan([- {kind: 'encoderFailed', captureId: ENCODER_FAIL_CAPTURE_ID, atTick: ENCODER_FAIL_AT_TICK},- ]);- return {- name: 'encoder-fail-under-load',- mode: 'safety',- workload,- faultPlan,- acceptance: checkAcceptance,- };-}--function buildWorkload(): VoiceEngineV2Workload {- const builder = new VoiceEngineV2WorkloadBuilder('encoder-fail-under-load');- builder.at(0).connect({url: 'wss://voice.example.test', token: 'tok-enc'});- builder.advance(2).emit({type: 'connection.connectSucceeded', operationId: 1});- builder.advance(1).publishMicrophone({deviceId: 'mic-host'});- for (let index = 0; index < ENCODER_FAIL_PARTICIPANT_COUNT; index++) {- builder.advance(2).joinParticipant({- sid: `sid-load-${index + 1}`,- identity: `peer-load-${index + 1}`,- name: `Load ${index + 1}`,- });- }- builder.advance(4).startNativeCapture({- captureId: ENCODER_FAIL_CAPTURE_ID,- source: {id: 'display-load', kind: 'screen', title: 'Load Display'},- width: 1920,- height: 1080,- frameRate: 60,- includeCursor: true,- includeAudio: false,- zeroCopyRequired: true,- });- builder.advance(2).attachNativeFrameSink({- sinkId: 'sink-load',- captureId: ENCODER_FAIL_CAPTURE_ID,- zeroCopyRequired: true,- });- builder.advance(1).publishScreen({captureId: ENCODER_FAIL_CAPTURE_ID, width: 1920, height: 1080});- builder.at(ENCODER_FAIL_AT_TICK).startNativeCapture({- captureId: ENCODER_FAIL_CAPTURE_ID,- source: {id: 'display-load', kind: 'screen', title: 'Load Display'},- width: 1920,- height: 1080,- frameRate: 60,- includeCursor: true,- includeAudio: false,- zeroCopyRequired: true,- });- builder.at(ENCODER_FAIL_RETRY_TICK).startNativeCapture({- captureId: 'screen-load-recovery',- source: {id: 'display-load', kind: 'screen', title: 'Load Display'},- width: 1280,- height: 720,- frameRate: 30,- includeCursor: true,- includeAudio: false,- zeroCopyRequired: true,- });- return builder.build();-}--function checkAcceptance(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- assert.ok(result, 'acceptance requires a simulator result');- assert.ok(Array.isArray(result.eventLog), 'acceptance requires an event log array');- const verdicts = [verifyNoViolations(result), verifyEncoderFailure(result), verifyAudioContinues(result)];- return combineVerdicts(verdicts);-}--function verifyNoViolations(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- if (result.violations.length === 0) return passVerdict();- return failVerdict(result.violations.map((violation) => `safety violation: ${violation.code}`));-}--function verifyEncoderFailure(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- let encoderFailureObserved = false;- for (const entry of result.eventLog) {- if (entry.event.type === 'nativeCapture.failed' && entry.event.captureId === ENCODER_FAIL_CAPTURE_ID) {- encoderFailureObserved = true;- }- }- if (!encoderFailureObserved) {- return failVerdict(['expected nativeCapture.failed signalling encoder overload']);- }- return passVerdict();-}--function verifyAudioContinues(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- let microphoneSucceeded = false;- let microphoneFailed = false;- for (const entry of result.eventLog) {- if (entry.event.type === 'microphone.publishSucceeded') microphoneSucceeded = true;- if (entry.event.type === 'microphone.publishFailed') microphoneFailed = true;- }- if (!microphoneSucceeded) {- return failVerdict(['expected microphone publish to remain successful while encoder fails']);- }- if (microphoneFailed) {- return failVerdict(['microphone publish unexpectedly failed during encoder overload']);- }- return passVerdict();-}diff --git a/packages/voice_engine_v2/src/simulation/scenarios/gpuTdrMidFrame.ts b/packages/voice_engine_v2/src/simulation/scenarios/gpuTdrMidFrame.tsdeleted file mode 100644index dc33935c5..000000000--- a/packages/voice_engine_v2/src/simulation/scenarios/gpuTdrMidFrame.ts+++ /dev/null@@ -1,98 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {createVoiceEngineV2FaultPlan} from '@fluxer/voice_engine_v2/src/simulation/FaultInjector';-import type {VoiceEngineV2SimulatorResult} from '@fluxer/voice_engine_v2/src/simulation/Simulator';-import {- assertSeedWellFormed,- combineVerdicts,- failVerdict,- passVerdict,- type VoiceEngineV2AcceptanceVerdict,- type VoiceEngineV2SimulationScenario,-} from '@fluxer/voice_engine_v2/src/simulation/scenarios/index';-import type {VoiceEngineV2Workload} from '@fluxer/voice_engine_v2/src/simulation/Workload';-import {VoiceEngineV2WorkloadBuilder} from '@fluxer/voice_engine_v2/src/simulation/Workload';--const GPU_TDR_AT_TICK = 200;-const GPU_TDR_RECONNECT_TICK = 215;--export function defineGpuTdrMidFrameScenario(seed: number): VoiceEngineV2SimulationScenario {- assertSeedWellFormed(seed);- const workload = buildWorkload();- assert.ok(workload.tickCount <= 512, 'workload tick count exceeds the simulator budget');- const faultPlan = createVoiceEngineV2FaultPlan([{kind: 'gpuDeviceLost', atTick: GPU_TDR_AT_TICK}]);- return {- name: 'gpu-tdr-mid-frame',- mode: 'safety',- workload,- faultPlan,- acceptance: checkAcceptance,- };-}--function buildWorkload(): VoiceEngineV2Workload {- const builder = new VoiceEngineV2WorkloadBuilder('gpu-tdr-mid-frame');- builder.at(0).connect({url: 'wss://voice.example.test', token: 'tok-gpu'});- builder.advance(2).emit({type: 'connection.connectSucceeded', operationId: 1});- builder.advance(1).publishMicrophone();- builder.advance(2).joinParticipant({sid: 'sid-r', identity: 'remote-1', name: 'Remote 1'});- builder.advance(4).startNativeCapture({- captureId: 'screen-gpu',- source: {id: 'display-0', kind: 'screen', title: 'Primary'},- width: 2560,- height: 1440,- frameRate: 60,- includeCursor: true,- includeAudio: false,- zeroCopyRequired: true,- });- builder.advance(2).attachNativeFrameSink({sinkId: 'sink-gpu', captureId: 'screen-gpu', zeroCopyRequired: true});- builder.advance(1).publishScreen({captureId: 'screen-gpu', width: 2560, height: 1440});- builder.at(GPU_TDR_AT_TICK).publishScreen({captureId: 'screen-gpu', width: 1920, height: 1080});- builder.at(GPU_TDR_RECONNECT_TICK).startNativeCapture({- captureId: 'screen-gpu-2',- source: {id: 'display-0', kind: 'screen', title: 'Primary'},- width: 2560,- height: 1440,- frameRate: 60,- includeCursor: true,- includeAudio: false,- zeroCopyRequired: true,- });- return builder.build();-}--function checkAcceptance(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- assert.ok(result, 'acceptance requires a simulator result');- assert.ok(Array.isArray(result.eventLog), 'acceptance requires an event log array');- const verdicts = [verifyNoViolations(result), verifyScreenLost(result), verifyReconnectAttempted(result)];- return combineVerdicts(verdicts);-}--function verifyNoViolations(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- if (result.violations.length === 0) return passVerdict();- return failVerdict(result.violations.map((violation) => `safety violation: ${violation.code}`));-}--function verifyScreenLost(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- let screenPublishFailed = false;- for (const entry of result.eventLog) {- if (entry.event.type === 'screen.publishFailed') screenPublishFailed = true;- }- if (!screenPublishFailed) {- return failVerdict(['expected screen.publishFailed signalling GPU loss']);- }- return passVerdict();-}--function verifyReconnectAttempted(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- let nativeCaptureStarted = 0;- for (const entry of result.eventLog) {- if (entry.event.type === 'nativeCapture.started') nativeCaptureStarted += 1;- }- if (nativeCaptureStarted < 1) {- return failVerdict(['expected nativeCapture.started for original capture before GPU loss']);- }- return passVerdict();-}diff --git a/packages/voice_engine_v2/src/simulation/scenarios/index.ts b/packages/voice_engine_v2/src/simulation/scenarios/index.tsdeleted file mode 100644index 6ad099a1d..000000000--- a/packages/voice_engine_v2/src/simulation/scenarios/index.ts+++ /dev/null@@ -1,60 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import type {VoiceEngineV2FaultPlan} from '@fluxer/voice_engine_v2/src/simulation/FaultInjector';-import type {- VoiceEngineV2SimulatorMode,- VoiceEngineV2SimulatorResult,-} from '@fluxer/voice_engine_v2/src/simulation/Simulator';-import type {VoiceEngineV2Workload} from '@fluxer/voice_engine_v2/src/simulation/Workload';--const SCENARIO_SEED_MAX = 0x7fffffff;--export interface VoiceEngineV2AcceptanceVerdict {- readonly passed: boolean;- readonly reasons: ReadonlyArray<string>;-}--type VoiceEngineV2AcceptanceCriteria = (result: VoiceEngineV2SimulatorResult) => VoiceEngineV2AcceptanceVerdict;--export interface VoiceEngineV2SimulationScenario {- readonly name: string;- readonly mode: VoiceEngineV2SimulatorMode;- readonly workload: VoiceEngineV2Workload;- readonly faultPlan: VoiceEngineV2FaultPlan;- readonly acceptance: VoiceEngineV2AcceptanceCriteria;-}--export function passVerdict(): VoiceEngineV2AcceptanceVerdict {- return {passed: true, reasons: []};-}--export function failVerdict(reasons: ReadonlyArray<string>): VoiceEngineV2AcceptanceVerdict {- assert.ok(Array.isArray(reasons), 'failVerdict requires a reasons array');- assert.ok(reasons.length > 0, 'failVerdict requires at least one reason');- return {passed: false, reasons: [...reasons]};-}--export function combineVerdicts(- verdicts: ReadonlyArray<VoiceEngineV2AcceptanceVerdict>,-): VoiceEngineV2AcceptanceVerdict {- assert.ok(Array.isArray(verdicts), 'combineVerdicts requires an array');- assert.ok(verdicts.length > 0, 'combineVerdicts requires at least one verdict');- const reasons: Array<string> = [];- for (const verdict of verdicts) {- for (const reason of verdict.reasons) reasons.push(reason);- }- return reasons.length === 0 ? passVerdict() : failVerdict(reasons);-}--export function assertSeedWellFormed(seed: number): void {- assert.ok(Number.isInteger(seed), 'scenario seed must be an integer');- assert.ok(seed >= 0, 'scenario seed must be non-negative');- assert.ok(seed <= SCENARIO_SEED_MAX, 'scenario seed exceeds SCENARIO_SEED_MAX');-}--export {defineAsymmetricNatAfterConnectScenario} from '@fluxer/voice_engine_v2/src/simulation/scenarios/asymmetricNatAfterConnect';-export {defineCaptureDeviceDisconnectScenario} from '@fluxer/voice_engine_v2/src/simulation/scenarios/captureDeviceDisconnect';-export {defineEncoderFailUnderLoadScenario} from '@fluxer/voice_engine_v2/src/simulation/scenarios/encoderFailUnderLoad';-export {defineGpuTdrMidFrameScenario} from '@fluxer/voice_engine_v2/src/simulation/scenarios/gpuTdrMidFrame';-export {defineNetworkPartitionDuringScreenShareScenario} from '@fluxer/voice_engine_v2/src/simulation/scenarios/networkPartitionDuringScreenShare';diff --git a/packages/voice_engine_v2/src/simulation/scenarios/networkPartitionDuringScreenShare.ts b/packages/voice_engine_v2/src/simulation/scenarios/networkPartitionDuringScreenShare.tsdeleted file mode 100644index 5d83bc3b6..000000000--- a/packages/voice_engine_v2/src/simulation/scenarios/networkPartitionDuringScreenShare.ts+++ /dev/null@@ -1,103 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {createVoiceEngineV2FaultPlan} from '@fluxer/voice_engine_v2/src/simulation/FaultInjector';-import type {VoiceEngineV2SimulatorResult} from '@fluxer/voice_engine_v2/src/simulation/Simulator';-import {- assertSeedWellFormed,- combineVerdicts,- failVerdict,- passVerdict,- type VoiceEngineV2AcceptanceVerdict,- type VoiceEngineV2SimulationScenario,-} from '@fluxer/voice_engine_v2/src/simulation/scenarios/index';-import type {VoiceEngineV2Workload} from '@fluxer/voice_engine_v2/src/simulation/Workload';-import {VoiceEngineV2WorkloadBuilder} from '@fluxer/voice_engine_v2/src/simulation/Workload';--const PARTITION_FROM_TICK = 150;-const PARTITION_UNTIL_TICK = 350;-const PARTITION_RECOVERY_DEADLINE_TICK = 400;-const PARTITION_PARTICIPANT_COUNT = 4;-const PARTITION_RECONNECT_PROBE_TICK = 175;--export function defineNetworkPartitionDuringScreenShareScenario(seed: number): VoiceEngineV2SimulationScenario {- assertSeedWellFormed(seed);- const workload = buildWorkload();- assert.ok(workload.tickCount <= 512, 'workload tick count exceeds the simulator budget');- const faultPlan = createVoiceEngineV2FaultPlan([- {kind: 'networkPartition', fromTick: PARTITION_FROM_TICK, untilTick: PARTITION_UNTIL_TICK},- ]);- return {- name: 'network-partition-during-screen-share',- mode: 'safety',- workload,- faultPlan,- acceptance: checkAcceptance,- };-}--function buildWorkload(): VoiceEngineV2Workload {- const builder = new VoiceEngineV2WorkloadBuilder('network-partition-during-screen-share');- builder.at(0).connect({url: 'wss://voice.example.test', token: 'tok-a-1'});- builder.advance(2).emit({type: 'connection.connectSucceeded', operationId: 1});- builder.advance(1).publishMicrophone({deviceId: 'mic-A'});- for (let index = 0; index < PARTITION_PARTICIPANT_COUNT; index++) {- builder.advance(2).joinParticipant({- sid: `sid-peer-${index + 1}`,- identity: `peer-${index + 1}`,- name: `Peer ${index + 1}`,- });- }- builder.at(100).startNativeCapture({- captureId: 'screen-A',- source: {id: 'display-A', kind: 'screen', title: 'Display A'},- width: 1920,- height: 1080,- frameRate: 30,- includeCursor: true,- includeAudio: false,- zeroCopyRequired: true,- });- builder.advance(2).attachNativeFrameSink({sinkId: 'sink-A', captureId: 'screen-A', zeroCopyRequired: true});- builder.advance(1).publishScreen({captureId: 'screen-A', width: 1920, height: 1080});- builder.at(PARTITION_RECONNECT_PROBE_TICK).connect({url: 'wss://voice.example.test', token: 'tok-a-2'});- builder.at(PARTITION_RECOVERY_DEADLINE_TICK).connect({url: 'wss://voice.example.test', token: 'tok-a-3'});- return builder.build();-}--function checkAcceptance(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- assert.ok(result, 'acceptance requires a simulator result');- assert.ok(Array.isArray(result.eventLog), 'acceptance requires an event log array');- const verdicts = [verifyNoViolations(result), verifyPartitionDetected(result), verifyRecoveryAfterPartition(result)];- return combineVerdicts(verdicts);-}--function verifyNoViolations(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- if (result.violations.length === 0) return passVerdict();- return failVerdict(result.violations.map((violation) => `safety violation: ${violation.code}`));-}--function verifyPartitionDetected(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- let connectFailureSeen = false;- for (const entry of result.eventLog) {- if (entry.event.type === 'connection.connectFailed') connectFailureSeen = true;- }- if (!connectFailureSeen) {- return failVerdict(['expected at least one connection.connectFailed during partition window']);- }- return passVerdict();-}--function verifyRecoveryAfterPartition(result: VoiceEngineV2SimulatorResult): VoiceEngineV2AcceptanceVerdict {- if (result.finalTick < PARTITION_RECOVERY_DEADLINE_TICK) {- return failVerdict([`finalTick ${result.finalTick} ended before recovery deadline`]);- }- let recoverySucceeded = 0;- for (const entry of result.eventLog) {- if (entry.event.type === 'connection.connectSucceeded') recoverySucceeded += 1;- }- if (recoverySucceeded < 2) {- return failVerdict(['expected connection.connectSucceeded for recovery operation after partition cleared']);- }- return passVerdict();-}diff --git a/packages/voice_engine_v2/src/simulation/scenarios/scenarios.test.ts b/packages/voice_engine_v2/src/simulation/scenarios/scenarios.test.tsdeleted file mode 100644index 9eebf5e1c..000000000--- a/packages/voice_engine_v2/src/simulation/scenarios/scenarios.test.ts+++ /dev/null@@ -1,71 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {VoiceEngineV2Simulator} from '@fluxer/voice_engine_v2/src/simulation/Simulator';-import {- defineAsymmetricNatAfterConnectScenario,- defineCaptureDeviceDisconnectScenario,- defineEncoderFailUnderLoadScenario,- defineGpuTdrMidFrameScenario,- defineNetworkPartitionDuringScreenShareScenario,- type VoiceEngineV2SimulationScenario,-} from '@fluxer/voice_engine_v2/src/simulation/scenarios/index';-import {describe, expect, it} from 'vitest';--async function runScenario(scenario: VoiceEngineV2SimulationScenario, seed: number) {- return new VoiceEngineV2Simulator({- seed,- workload: scenario.workload,- faults: scenario.faultPlan,- mode: scenario.mode,- }).run();-}--describe('scenario: networkPartitionDuringScreenShare', () => {- it('passes acceptance after running the simulator', async () => {- const scenario = defineNetworkPartitionDuringScreenShareScenario(101);- const result = await runScenario(scenario, 101);- const verdict = scenario.acceptance(result);- expect(verdict.reasons).toEqual([]);- expect(verdict.passed).toBe(true);- });-});--describe('scenario: gpuTdrMidFrame', () => {- it('passes acceptance after running the simulator', async () => {- const scenario = defineGpuTdrMidFrameScenario(202);- const result = await runScenario(scenario, 202);- const verdict = scenario.acceptance(result);- expect(verdict.reasons).toEqual([]);- expect(verdict.passed).toBe(true);- });-});--describe('scenario: captureDeviceDisconnect', () => {- it('passes acceptance after running the simulator', async () => {- const scenario = defineCaptureDeviceDisconnectScenario(303);- const result = await runScenario(scenario, 303);- const verdict = scenario.acceptance(result);- expect(verdict.reasons).toEqual([]);- expect(verdict.passed).toBe(true);- });-});--describe('scenario: asymmetricNatAfterConnect', () => {- it('passes acceptance after running the simulator', async () => {- const scenario = defineAsymmetricNatAfterConnectScenario(404);- const result = await runScenario(scenario, 404);- const verdict = scenario.acceptance(result);- expect(verdict.reasons).toEqual([]);- expect(verdict.passed).toBe(true);- });-});--describe('scenario: encoderFailUnderLoad', () => {- it('passes acceptance after running the simulator', async () => {- const scenario = defineEncoderFailUnderLoadScenario(505);- const result = await runScenario(scenario, 505);- const verdict = scenario.acceptance(result);- expect(verdict.reasons).toEqual([]);- expect(verdict.passed).toBe(true);- });-});