A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(voice-engine): delete restated runtime and reducer suites
Hampusf2cdb30cd3fa
diff --git a/packages/voice_engine_v2/src/core/reducer.test.ts b/packages/voice_engine_v2/src/core/reducer.test.tsindex ebfeb1ad6..d030194e5 100644--- a/packages/voice_engine_v2/src/core/reducer.test.ts+++ b/packages/voice_engine_v2/src/core/reducer.test.ts@@ -26,17 +26,6 @@ function applyEvents(snapshot: VoiceEngineV2Snapshot, events: Array<VoiceEngineV}describe('transitionVoiceEngineV2', () => {- it('keeps business state explicit and starts from idle', () => {- const snapshot = initialSnapshot();-- expect(snapshot.connection.status).toBe('idle');- expect(snapshot.microphone.status).toBe('idle');- expect(snapshot.camera.status).toBe('idle');- expect(snapshot.screen.status).toBe('idle');- expect(snapshot.screenAudio.status).toBe('idle');- expect(snapshot.nextOperationId).toBe(1);- });-it('emits a single connect command for a connect request', () => {const transition = transitionVoiceEngineV2(initialSnapshot(), {type: 'connection.connectRequested',@@ -817,11 +806,6 @@ describe('transitionVoiceEngineV2', () => {expect(state?.kind).toBe('failed');});- it('selectors return null for unknown sources', () => {- const snapshot = initialSnapshot();- expect(snapshot.sourceLifecycles['unknown'] ?? null).toBeNull();- });-it('sourceLifecycle.removed drops the lifecycle slot for that source only', () => {const snapshot = applyEvents(initialSnapshot(), [{@@ -851,54 +835,6 @@ describe('transitionVoiceEngineV2', () => {expect((transition.snapshot.sourceLifecycles['source-kept'] ?? null)?.kind).toBe('active');expect(Object.values(transition.snapshot.sourceLifecycles).filter((state) => state.kind === 'failed')).toEqual([]);});-- it('sourceLifecycle.removed for an unknown source leaves the snapshot untouched', () => {- const snapshot = initialSnapshot();-- const transition = transitionVoiceEngineV2(snapshot, {type: 'sourceLifecycle.removed', sourceId: 'source-absent'});-- expect(transition.commands).toEqual([]);- expect(transition.snapshot).toBe(snapshot);- });-- it('replaying the same source lifecycle event sequence yields the same snapshot hash', () => {- const events: Array<VoiceEngineV2Event> = [- {- type: 'sourceLifecycle.transitioned',- sourceId: 'source-d',- kind: 'active',- since: 4n,- attempts: 0,- fault: null,- atMs: 1,- },- {- type: 'sourceLifecycle.transitioned',- sourceId: 'source-d',- kind: 'reconnecting',- since: 7n,- attempts: 1,- fault: 'networkError',- atMs: 5,- },- {- type: 'sourceLifecycle.transitioned',- sourceId: 'source-d',- kind: 'failed',- since: 12n,- attempts: 8,- fault: 'encoderError',- atMs: 9,- },- ];-- const first = applyEvents(initialSnapshot(), events);- const second = applyEvents(initialSnapshot(), events);- const replacer = (_key: string, value: unknown): unknown =>- typeof value === 'bigint' ? `bigint:${value.toString()}` : value;-- expect(JSON.stringify(second, replacer)).toBe(JSON.stringify(first, replacer));- });});describe('terminal operation pruning', () => {@@ -969,11 +905,4 @@ describe('terminal operation pruning', () => {).length;expect(terminalCount).toBe(VOICE_ENGINE_V2_TERMINAL_OPERATIONS_KEPT_MAX);});-- it('prunes deterministically across replays', () => {- const total = VOICE_ENGINE_V2_TERMINAL_OPERATIONS_KEPT_MAX * 2;- const first = completeDiagnosticCycles(initialSnapshot(), total);- const second = completeDiagnosticCycles(initialSnapshot(), total);- expect(second).toEqual(first);- });});diff --git a/packages/voice_engine_v2/src/runtime/VoiceEngineV2Controller.test.ts b/packages/voice_engine_v2/src/runtime/VoiceEngineV2Controller.test.tsdeleted file mode 100644index 7cc99dc87..000000000--- a/packages/voice_engine_v2/src/runtime/VoiceEngineV2Controller.test.ts+++ /dev/null@@ -1,125 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {- VoiceEngineV2CommandResult,- VoiceEngineV2Implementation,-} from '@fluxer/voice_engine_v2/src/implementations/VoiceEngineV2ImplementationBase';-import type {VoiceEngineV2Command} from '@fluxer/voice_engine_v2/src/protocol/commands';-import {createVoiceEngineV2MemoryEventLogSpillSink} from '@fluxer/voice_engine_v2/src/runtime/eventLogRing';-import {VoiceEngineV2Controller} from '@fluxer/voice_engine_v2/src/runtime/VoiceEngineV2Controller';-import {VoiceEngineV2Runtime} from '@fluxer/voice_engine_v2/src/runtime/VoiceEngineV2Runtime';-import {waitForRuntime} from '@fluxer/voice_engine_v2/src/testing/conformance';-import {FakeVoiceEngineV2Driver} from '@fluxer/voice_engine_v2/src/testing/FakeVoiceEngineV2Driver';-import {VoiceEngineV2TestImplementation} from '@fluxer/voice_engine_v2/src/testing/VoiceEngineV2TestImplementation';-import {describe, expect, it} from 'vitest';--interface DeferredCommand {- command: VoiceEngineV2Command;- resolve(result?: VoiceEngineV2CommandResult): void;-}--class DeferredVoiceEngineV2Implementation implements VoiceEngineV2Implementation {- readonly kind = 'js' as const;- readonly started: Array<VoiceEngineV2Command> = [];- readonly deferred: Array<DeferredCommand> = [];-- execute(command: VoiceEngineV2Command): Promise<VoiceEngineV2CommandResult> {- this.started.push(command);- if (command.type !== 'microphone.publish') return Promise.resolve({ok: true});- return new Promise<VoiceEngineV2CommandResult>((resolve) => {- this.deferred.push({- command,- resolve: (result = {ok: true}) => {- resolve(result);- },- });- });- }-}--interface ControllerRuntimeTestOptions {- clock?: {now(): number};-}--function createControllerTestRuntime(- implementation: VoiceEngineV2Implementation,- options: ControllerRuntimeTestOptions = {},-): VoiceEngineV2Runtime {- return new VoiceEngineV2Runtime(implementation, {- eventLogSpillSink: createVoiceEngineV2MemoryEventLogSpillSink(),- verifyEventLogInvariantsOnDispatch: true,- ...options,- });-}--describe('VoiceEngineV2Controller', () => {- it('exposes explicit methods over the v2 event protocol', async () => {- const driver = new FakeVoiceEngineV2Driver();- const controller = new VoiceEngineV2Controller(- createControllerTestRuntime(new VoiceEngineV2TestImplementation(driver)),- );-- controller.connect({url: 'wss://voice', token: 'token'});- await waitForRuntime();- controller.publishMicrophone({deviceId: 'default'});- controller.setMicrophoneEnabled(false);- await waitForRuntime();-- expect(controller.model.connection.connected).toBe(true);- expect(controller.model.media.microphone).toBe('published');- expect(driver.calls).toEqual([- {type: 'connect', options: {url: 'wss://voice', token: 'token'}},- {type: 'publishMicrophone', options: {deviceId: 'default'}},- {type: 'setMicrophoneEnabled', enabled: false},- ]);- });-- it('records an append-only event log with the host clock', () => {- let now = 1000;- const driver = new FakeVoiceEngineV2Driver();- const runtime = createControllerTestRuntime(new VoiceEngineV2TestImplementation(driver), {- clock: {- now: () => {- now += 10;- return now;- },- },- });-- runtime.dispatch({type: 'implementation.prewarmRequested'});-- expect(runtime.eventLog).toHaveLength(1);- expect(runtime.eventLog[0]).toMatchObject({- sequence: 1,- atMs: 1010,- event: {type: 'implementation.prewarmRequested'},- commands: [{type: 'implementation.prewarm', operationId: 1}],- });- });-- it('serializes commands by resource and rejects stale completions', async () => {- const implementation = new DeferredVoiceEngineV2Implementation();- const runtime = createControllerTestRuntime(implementation);-- runtime.dispatch({type: 'connection.connectRequested', options: {url: 'wss://voice', token: 'token'}});- await waitForRuntime();- runtime.dispatch({type: 'microphone.publishRequested', options: {deviceId: 'first'}});- await waitForRuntime();- runtime.dispatch({type: 'microphone.unpublishRequested'});- await waitForRuntime();-- expect(implementation.started.map((command) => command.type)).toEqual(['connection.connect', 'microphone.publish']);- expect(runtime.commandQueue.map((command) => command.type)).toEqual(['microphone.unpublish']);-- implementation.deferred[0]?.resolve();- await waitForRuntime();-- expect(implementation.started.map((command) => command.type)).toEqual([- 'connection.connect',- 'microphone.publish',- 'microphone.unpublish',- ]);- expect(runtime.eventLog.some((entry) => entry.event.type === 'command.staleCompletionRejected')).toBe(true);- expect(runtime.snapshot.microphone.status).toBe('idle');- });-});diff --git a/packages/voice_engine_v2/src/runtime/VoiceEngineV2Runtime.test.ts b/packages/voice_engine_v2/src/runtime/VoiceEngineV2Runtime.test.tsindex 7c7b172fb..8b5e74c14 100644--- a/packages/voice_engine_v2/src/runtime/VoiceEngineV2Runtime.test.ts+++ b/packages/voice_engine_v2/src/runtime/VoiceEngineV2Runtime.test.ts@@ -1,6 +1,5 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import assert from 'node:assert/strict';import type {VoiceEngineV2CommandResult,VoiceEngineV2Implementation,@@ -9,12 +8,6 @@ import type {VoiceEngineV2Command} from '@fluxer/voice_engine_v2/src/protocol/coimport {createVoiceEngineV2MemoryEventLogSpillSink} from '@fluxer/voice_engine_v2/src/runtime/eventLogRing';import {assertEventLogInvariants,- isVoiceEngineV2ProgrammerError,- VOICE_ENGINE_V2_CANCELLED_OPERATIONS_CAP,- VOICE_ENGINE_V2_DIAGNOSTIC_LISTENERS_CAP,- VOICE_ENGINE_V2_LISTENERS_CAP,- VOICE_ENGINE_V2_QUEUED_COMMANDS_CAP,- VOICE_ENGINE_V2_RESOURCE_QUEUES_CAP,VoiceEngineV2Runtime,type VoiceEngineV2RuntimeDiagnostic,} from '@fluxer/voice_engine_v2/src/runtime/VoiceEngineV2Runtime';@@ -55,8 +48,6 @@ class ListenerThrowsImplementation implements VoiceEngineV2Implementation {interface RuntimeTestOptions {queuedCommandsCap?: number;- resourceQueuesCap?: number;- cancelledOperationsCap?: number;}function createTestRuntime(@@ -71,12 +62,6 @@ function createTestRuntime(}describe('VoiceEngineV2Runtime queue caps', () => {- it('exports the documented cap constants', () => {- expect(VOICE_ENGINE_V2_QUEUED_COMMANDS_CAP).toBe(4096);- expect(VOICE_ENGINE_V2_RESOURCE_QUEUES_CAP).toBe(256);- expect(VOICE_ENGINE_V2_CANCELLED_OPERATIONS_CAP).toBe(4096);- });-it('rejects commands beyond queuedCommandsCap and surfaces a queueFull diagnostic', () => {const implementation = new DeferredAllResolveImplementation();const runtime = createTestRuntime(implementation, {queuedCommandsCap: 2});@@ -101,37 +86,6 @@ describe('VoiceEngineV2Runtime queue caps', () => {expect(diagnostic.cap).toBe(2);expect(diagnostic.droppedCommandType).toBe('implementation.prewarm');});-- it('rejects commands beyond resourceQueuesCap when the resource key is new', () => {- const implementation = new DeferredAllResolveImplementation();- const runtime = createTestRuntime(implementation, {resourceQueuesCap: 1});- const diagnostics: Array<VoiceEngineV2RuntimeDiagnostic> = [];- runtime.subscribeDiagnostics((diagnostic) => {- diagnostics.push(diagnostic);- });-- runtime.dispatch({type: 'connection.connectRequested', options: {url: 'wss://voice', token: 't'}});- runtime.dispatch({type: 'gateway.voiceStateClearRequested', guildId: null});-- expect(runtime.activeResourceQueueCount).toBe(1);- expect(runtime.queueFullDropTotal).toBe(1);- expect(diagnostics).toHaveLength(1);- const diagnostic = diagnostics[0];- if (diagnostic === undefined) throw new Error('expected diagnostic');- expect(diagnostic.queue).toBe('resourceQueues');- expect(diagnostic.cap).toBe(1);- });-- it('does not double-drop when the same resource key reappears under cap', () => {- const implementation = new DeferredAllResolveImplementation();- const runtime = createTestRuntime(implementation, {resourceQueuesCap: 1});-- runtime.dispatch({type: 'connection.connectRequested', options: {url: 'wss://voice', token: 't'}});- runtime.dispatch({type: 'connection.disconnectRequested', reason: 'shutdown'});-- expect(runtime.queueFullDropTotal).toBe(0);- expect(runtime.activeResourceQueueCount).toBe(1);- });});describe('VoiceEngineV2Runtime queue-cap rejection events', () => {@@ -189,62 +143,6 @@ describe('VoiceEngineV2Runtime queue-cap rejection events', () => {expect(unpublishFailed).toEqual([unpublishOperationId]);assertEventLogInvariants(runtime);});-- it('dispatches the failure event for drops at the resource-queue cap', async () => {- const implementation = new DeferredAllResolveImplementation();- const runtime = createTestRuntime(implementation, {resourceQueuesCap: 1});- const events: Array<string> = [];- runtime.subscribe(({event}) => {- events.push(event.type);- });-- runtime.dispatch({type: 'connection.connectRequested', options: {url: 'wss://voice', token: 't'}});- runtime.dispatch({type: 'gateway.voiceStateClearRequested', guildId: null});- await waitForRuntime();-- expect(runtime.queueFullDropTotal).toBe(1);- expect(events).toContain('gateway.voiceStateClearFailed');- assertEventLogInvariants(runtime);- });-});--describe('VoiceEngineV2Runtime executing-command visibility', () => {- it('exposes the executing command per resource while it runs and clears it after completion', async () => {- const implementation = new DeferredAllResolveImplementation();- const runtime = createTestRuntime(implementation);-- runtime.dispatch({type: 'connection.connectRequested', options: {url: 'wss://voice', token: 't'}});- await waitForRuntime();-- const executing = runtime.getExecutingCommand('connection');- if (executing === null) throw new Error('expected an executing connection command');- expect(executing.type).toBe('connection.connect');- expect(runtime.isOperationPending(executing.operationId)).toBe(true);- expect(runtime.getExecutingCommand('gateway')).toBeNull();-- implementation.pending[0]?.();- await waitForRuntime();-- expect(runtime.getExecutingCommand('connection')).toBeNull();- expect(runtime.isOperationPending(executing.operationId)).toBe(false);- });-- it('reports queued commands as pending before the resource queue starts them', async () => {- const implementation = new DeferredAllResolveImplementation();- const runtime = createTestRuntime(implementation);-- runtime.dispatch({type: 'implementation.prewarmRequested'});- runtime.dispatch({type: 'implementation.prewarmRequested'});- const queued = runtime.commandQueue;- expect(queued).toHaveLength(2);- const second = queued[1];- if (second === undefined) throw new Error('expected a second queued command');-- await waitForRuntime();-- expect(runtime.isOperationPending(second.operationId)).toBe(true);- expect(runtime.getExecutingCommand('implementation')?.operationId).not.toBe(second.operationId);- });});describe('VoiceEngineV2Runtime terminal failure dispatch', () => {@@ -328,199 +226,6 @@ describe('VoiceEngineV2Runtime cancellation tombstone', () => {expect(startedIds).not.toContain(second.operationId);expect(runtime.cancelledOperationCount).toBe(0);});-- it('tombstone cancellation is O(1) and does not scan the queue', () => {- const runtime = createTestRuntime(new DeferredAllResolveImplementation());- const start = process.hrtime.bigint();- for (let i = 0; i < 100_000; i += 1) {- runtime.cancelOperation(i);- }- const elapsedNs = Number(process.hrtime.bigint() - start);- expect(runtime.cancelledOperationCount).toBe(VOICE_ENGINE_V2_CANCELLED_OPERATIONS_CAP);- expect(elapsedNs).toBeLessThan(2_000_000_000);- });-- it('never grows the tombstone set beyond the named cap', () => {- const runtime = createTestRuntime(new DeferredAllResolveImplementation(), {cancelledOperationsCap: 3});- expect(runtime.cancelledOperationsCapacity).toBe(3);- for (let i = 0; i < 10; i += 1) {- runtime.cancelOperation(i);- expect(runtime.cancelledOperationCount).toBeLessThanOrEqual(3);- }- expect(runtime.cancelledOperationCount).toBe(3);- });-- it('evicts the oldest tombstone when the cap is reached, so the evicted operation executes', async () => {- const implementation = new DeferredAllResolveImplementation();- const runtime = createTestRuntime(implementation, {cancelledOperationsCap: 2});-- runtime.dispatch({type: 'implementation.prewarmRequested'});- runtime.dispatch({type: 'implementation.prewarmRequested'});- const queued = runtime.commandQueue;- expect(queued).toHaveLength(2);- const first = queued[0];- const second = queued[1];- if (first === undefined || second === undefined) throw new Error('expected two queued');-- runtime.cancelOperation(second.operationId);- runtime.cancelOperation(second.operationId + 10_000);- runtime.cancelOperation(second.operationId + 10_001);- expect(runtime.cancelledOperationCount).toBe(2);-- await waitForRuntime();- implementation.pending[0]?.();- await waitForRuntime();-- const startedIds = implementation.started.map((command) => command.operationId);- expect(startedIds).toContain(first.operationId);- expect(startedIds).toContain(second.operationId);- });-- it('emits a queueFull-style diagnostic when a cancellation tombstone is evicted at cap', () => {- const runtime = createTestRuntime(new DeferredAllResolveImplementation(), {cancelledOperationsCap: 2});- const diagnostics: Array<VoiceEngineV2RuntimeDiagnostic> = [];- runtime.subscribeDiagnostics((diagnostic) => {- diagnostics.push(diagnostic);- });-- runtime.cancelOperation(11);- runtime.cancelOperation(12);- expect(diagnostics).toHaveLength(0);- runtime.cancelOperation(13);-- expect(diagnostics).toHaveLength(1);- const diagnostic = diagnostics[0];- if (diagnostic === undefined) throw new Error('expected an eviction diagnostic');- expect(diagnostic.kind).toBe('voiceEngineV2.queueFull');- expect(diagnostic.queue).toBe('cancelledOperations');- expect(diagnostic.cap).toBe(2);- expect(diagnostic.droppedOperationId).toBe(11);- });-- it('reports the queued command details when an evicted tombstone still targets a queued command', () => {- const implementation = new DeferredAllResolveImplementation();- const runtime = createTestRuntime(implementation, {cancelledOperationsCap: 1});- const diagnostics: Array<VoiceEngineV2RuntimeDiagnostic> = [];- runtime.subscribeDiagnostics((diagnostic) => {- diagnostics.push(diagnostic);- });-- runtime.dispatch({type: 'implementation.prewarmRequested'});- const queued = runtime.commandQueue[0];- if (queued === undefined) throw new Error('expected a queued command');- runtime.cancelOperation(queued.operationId);- runtime.cancelOperation(queued.operationId + 10_000);-- expect(diagnostics).toHaveLength(1);- const diagnostic = diagnostics[0];- if (diagnostic === undefined) throw new Error('expected an eviction diagnostic');- expect(diagnostic.queue).toBe('cancelledOperations');- expect(diagnostic.droppedOperationId).toBe(queued.operationId);- expect(diagnostic.droppedCommandType).toBe('implementation.prewarm');- expect(diagnostic.resourceKey).toBe('implementation');- });-- it('keeps a re-cancelled operationId without consuming eviction budget', () => {- const runtime = createTestRuntime(new DeferredAllResolveImplementation(), {cancelledOperationsCap: 2});- runtime.cancelOperation(7);- runtime.cancelOperation(7);- runtime.cancelOperation(8);- expect(runtime.cancelledOperationCount).toBe(2);- runtime.cancelOperation(9);- expect(runtime.cancelledOperationCount).toBe(2);- });-- it('does not retain references via the deprecated findIndex/splice path', () => {- const runtimeSource = VoiceEngineV2Runtime.prototype.toString();- expect(runtimeSource).not.toMatch(/findIndex/);- expect(runtimeSource).not.toMatch(/splice/);- });-});--describe('VoiceEngineV2Runtime programmer error propagation', () => {- it('classifies assertion failures and marked errors as programmer errors', () => {- expect(isVoiceEngineV2ProgrammerError(new assert.AssertionError({message: 'invariant broken'}))).toBe(true);- expect(isVoiceEngineV2ProgrammerError(Object.assign(new Error('boom'), {voiceEngineV2ProgrammerError: true}))).toBe(- true,- );- expect(isVoiceEngineV2ProgrammerError(new Error('operational failure'))).toBe(false);- expect(isVoiceEngineV2ProgrammerError('not an error')).toBe(false);- });-- it('rethrows an assertion failure from completion dispatch instead of converting it to a failure event', async () => {- const driver = new FakeVoiceEngineV2Driver();- const runtime = createTestRuntime(new VoiceEngineV2TestImplementation(driver));- const events: Array<string> = [];- let triggered = false;- runtime.subscribe(({event}) => {- events.push(event.type);- if (!triggered && event.type === 'connection.connectSucceeded') {- triggered = true;- assert.fail('synthetic reducer invariant violation');- }- });-- const rejections: Array<unknown> = [];- const onUnhandledRejection = (reason: unknown) => {- rejections.push(reason);- };- const previousListeners = process.listeners('unhandledRejection');- process.removeAllListeners('unhandledRejection');- process.on('unhandledRejection', onUnhandledRejection);- try {- runtime.dispatch({type: 'connection.connectRequested', options: {url: 'wss://voice', token: 't'}});- await waitForRuntime();- await new Promise((resolve) => setTimeout(resolve, 0));- await new Promise((resolve) => setTimeout(resolve, 0));- } finally {- process.removeListener('unhandledRejection', onUnhandledRejection);- for (const listener of previousListeners) {- process.on('unhandledRejection', listener);- }- }-- expect(events).toContain('connection.connectSucceeded');- expect(events).not.toContain('connection.connectFailed');- expect(rejections).toHaveLength(1);- expect(rejections[0]).toBeInstanceOf(assert.AssertionError);- });-- it('still converts an operational listener throw into the command failure event', async () => {- const driver = new FakeVoiceEngineV2Driver();- const runtime = createTestRuntime(new VoiceEngineV2TestImplementation(driver));- const events: Array<string> = [];- let triggered = false;- runtime.subscribe(({event}) => {- events.push(event.type);- if (!triggered && event.type === 'connection.connectSucceeded') {- triggered = true;- throw new Error('operational listener failure');- }- });-- runtime.dispatch({type: 'connection.connectRequested', options: {url: 'wss://voice', token: 't'}});- await waitForRuntime();-- expect(events).toContain('connection.connectFailed');- });-});--describe('VoiceEngineV2Runtime listener caps', () => {- it('caps runtime listener subscriptions at the named cap', () => {- const runtime = createTestRuntime(new DeferredAllResolveImplementation());- for (let index = 0; index < VOICE_ENGINE_V2_LISTENERS_CAP; index += 1) {- runtime.subscribe(() => {});- }- expect(() => runtime.subscribe(() => {})).toThrow(/cap/);- });-- it('caps diagnostic listener subscriptions at the named cap', () => {- const runtime = createTestRuntime(new DeferredAllResolveImplementation());- for (let index = 0; index < VOICE_ENGINE_V2_DIAGNOSTIC_LISTENERS_CAP; index += 1) {- runtime.subscribeDiagnostics(() => {});- }- expect(() => runtime.subscribeDiagnostics(() => {})).toThrow(/cap/);- });});describe('VoiceEngineV2Runtime listener-reentrant dispatch ordering', () => {diff --git a/packages/voice_engine_v2/src/runtime/eventLogRing.test.ts b/packages/voice_engine_v2/src/runtime/eventLogRing.test.tsdeleted file mode 100644index b9c0ed9d8..000000000--- a/packages/voice_engine_v2/src/runtime/eventLogRing.test.ts+++ /dev/null@@ -1,219 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import assert from 'node:assert/strict';-import {transitionVoiceEngineV2} from '@fluxer/voice_engine_v2/src/core/reducer';-import {- availableVoiceEngineV2Capabilities,- createVoiceEngineV2InitialSnapshot,- type VoiceEngineV2Snapshot,-} from '@fluxer/voice_engine_v2/src/core/state';-import type {VoiceEngineV2Event} from '@fluxer/voice_engine_v2/src/protocol/events';-import type {VoiceEngineV2InboundVideoFrame} from '@fluxer/voice_engine_v2/src/protocol/types';-import {- assertEventLogRingInvariants,- createVoiceEngineV2MemoryEventLogSpillSink,- VOICE_ENGINE_V2_EVENT_LOG_CAP,- type VoiceEngineV2EventLogEntry,- VoiceEngineV2EventLogRing,- type VoiceEngineV2EventLogSpillSink,-} from '@fluxer/voice_engine_v2/src/runtime/eventLogRing';-import {- assertEventLogInvariants,- type VoiceEngineV2EventLogEntry as RuntimeEventLogEntry,- VoiceEngineV2Runtime,-} from '@fluxer/voice_engine_v2/src/runtime/VoiceEngineV2Runtime';-import {FakeVoiceEngineV2Driver} from '@fluxer/voice_engine_v2/src/testing/FakeVoiceEngineV2Driver';-import {VoiceEngineV2TestImplementation} from '@fluxer/voice_engine_v2/src/testing/VoiceEngineV2TestImplementation';-import {describe, expect, it} from 'vitest';--function makeInboundVideoFrameEvent(timestampUs: number): VoiceEngineV2Event {- const frame: VoiceEngineV2InboundVideoFrame = {- participantSid: 'participant-1',- trackSid: `track-unknown-${timestampUs}`,- width: 1280,- height: 720,- timestampUs,- };- return {type: 'inboundVideo.frameReceived', frame};-}--function makeRuntime(options?: {- eventLogCap?: number;- spillSink?: VoiceEngineV2EventLogSpillSink;-}): VoiceEngineV2Runtime {- const driver = new FakeVoiceEngineV2Driver();- return new VoiceEngineV2Runtime(new VoiceEngineV2TestImplementation(driver), {- eventLogCap: options?.eventLogCap,- eventLogSpillSink: options?.spillSink ?? createVoiceEngineV2MemoryEventLogSpillSink(),- clock: {now: () => 0},- verifyEventLogInvariantsOnDispatch: true,- });-}--function replayBounded(- initialSnapshot: VoiceEngineV2Snapshot,- events: ReadonlyArray<VoiceEngineV2Event>,- bound?: number,-): {snapshot: VoiceEngineV2Snapshot; ring: VoiceEngineV2EventLogRing} {- const capacity = bound ?? VOICE_ENGINE_V2_EVENT_LOG_CAP;- assert.ok(capacity >= 1, 'replayBounded requires positive capacity');- const ring = new VoiceEngineV2EventLogRing(capacity);- let snapshot = initialSnapshot;- const limit = events.length;- for (let index = 0; index < limit; index += 1) {- const event = events[index];- assert.ok(event !== undefined, 'replayBounded must receive defined events');- const transition = transitionVoiceEngineV2(snapshot, event);- snapshot = transition.snapshot;- const sequence = ring.allocateSequence();- const entry: VoiceEngineV2EventLogEntry = {- sequence,- atMs: 0,- event,- commands: transition.commands,- };- ring.push(entry);- }- assertEventLogRingInvariants(ring);- return {snapshot, ring};-}--describe('VoiceEngineV2EventLogRing', () => {- it('enforces the event log cap by dropping the oldest entries', () => {- const capacity = 8;- const runtime = makeRuntime({eventLogCap: capacity});- const total = capacity * 3;- for (let index = 0; index < total; index += 1) {- runtime.dispatch(makeInboundVideoFrameEvent(index));- }- expect(runtime.eventLog).toHaveLength(capacity);- expect(runtime.eventLogCap).toBe(capacity);- expect(runtime.eventLog[0]?.sequence).toBe(total - capacity + 1);- expect(runtime.eventLog[capacity - 1]?.sequence).toBe(total);- });-- it('tracks dropped count and evicted sequence min exactly', () => {- const capacity = 4;- const runtime = makeRuntime({eventLogCap: capacity});- expect(runtime.droppedEventsCount).toBe(0);- expect(runtime.evictedSequenceMin).toBeNull();- for (let index = 0; index < capacity; index += 1) {- runtime.dispatch(makeInboundVideoFrameEvent(index));- }- expect(runtime.droppedEventsCount).toBe(0);- expect(runtime.evictedSequenceMin).toBeNull();- const overflow = 5;- for (let index = 0; index < overflow; index += 1) {- runtime.dispatch(makeInboundVideoFrameEvent(capacity + index));- }- expect(runtime.droppedEventsCount).toBe(overflow);- expect(runtime.evictedSequenceMin).toBe(1);- });-- it('preserves sequence monotonicity across eviction', () => {- const capacity = 16;- const runtime = makeRuntime({eventLogCap: capacity});- const total = capacity * 5 + 3;- for (let index = 0; index < total; index += 1) {- runtime.dispatch(makeInboundVideoFrameEvent(index));- }- const log = runtime.eventLog;- expect(log.length).toBe(capacity);- const limit = log.length;- for (let cursor = 1; cursor < limit; cursor += 1) {- const previous = log[cursor - 1]?.sequence ?? 0;- const current = log[cursor]?.sequence ?? 0;- expect(current).toBe(previous + 1);- }- expect(log[0]?.sequence).toBe(runtime.droppedEventsCount + 1);- assertEventLogInvariants(runtime);- });-- it('produces an identical final snapshot when the bound is loose enough to keep every event', () => {- const events: Array<VoiceEngineV2Event> = [];- const eventCount = 64;- for (let index = 0; index < eventCount; index += 1) {- events.push(makeInboundVideoFrameEvent(index));- }- const initialSnapshot = createVoiceEngineV2InitialSnapshot(availableVoiceEngineV2Capabilities());- const fullReplay = replayBounded(initialSnapshot, events, eventCount * 2);- const boundedReplay = replayBounded(initialSnapshot, events, eventCount);- const looseEnoughReplay = replayBounded(initialSnapshot, events, eventCount + 5);- expect(fullReplay.snapshot).toEqual(boundedReplay.snapshot);- expect(fullReplay.snapshot).toEqual(looseEnoughReplay.snapshot);- expect(fullReplay.ring.droppedEventsCount).toBe(0);- expect(looseEnoughReplay.ring.droppedEventsCount).toBe(0);- expect(boundedReplay.ring.droppedEventsCount).toBe(0);- });-- it('fires assertEventLogInvariants when the in-memory state is tampered with', () => {- const runtime = makeRuntime({eventLogCap: 8});- const eventCount = 6;- for (let index = 0; index < eventCount; index += 1) {- runtime.dispatch(makeInboundVideoFrameEvent(index));- }- assertEventLogInvariants(runtime);- const internal = runtime as unknown as {- eventLogRing: {droppedCount: number; evictedSequenceMinValue: number | null};- };- const originalDroppedCount = internal.eventLogRing.droppedCount;- const originalEvictedSequenceMinValue = internal.eventLogRing.evictedSequenceMinValue;- internal.eventLogRing.droppedCount = 3;- expect(() => assertEventLogInvariants(runtime)).toThrow();- internal.eventLogRing.droppedCount = originalDroppedCount;- internal.eventLogRing.evictedSequenceMinValue = originalEvictedSequenceMinValue;- assertEventLogInvariants(runtime);- });-- it('runs the full-window invariant scan on dispatch only when the runtime opts in', () => {- const verifyingRuntime = makeRuntime({eventLogCap: 8});- verifyingRuntime.dispatch(makeInboundVideoFrameEvent(0));- const verifyingInternal = verifyingRuntime as unknown as {- eventLogRing: {droppedCount: number};- };- verifyingInternal.eventLogRing.droppedCount = 3;- expect(() => verifyingRuntime.dispatch(makeInboundVideoFrameEvent(1))).toThrow();-- const driver = new FakeVoiceEngineV2Driver();- const productionRuntime = new VoiceEngineV2Runtime(new VoiceEngineV2TestImplementation(driver), {- eventLogCap: 8,- eventLogSpillSink: createVoiceEngineV2MemoryEventLogSpillSink(),- clock: {now: () => 0},- });- productionRuntime.dispatch(makeInboundVideoFrameEvent(0));- const productionInternal = productionRuntime as unknown as {- eventLogRing: {droppedCount: number};- };- productionInternal.eventLogRing.droppedCount = 3;- expect(() => productionRuntime.dispatch(makeInboundVideoFrameEvent(1))).not.toThrow();- expect(() => assertEventLogInvariants(productionRuntime)).toThrow();- });-- it('invokes the spill sink with each evicted entry in eviction order', async () => {- const capacity = 4;- const evictions: Array<RuntimeEventLogEntry> = [];- const sink: VoiceEngineV2EventLogSpillSink = {- write(entry: VoiceEngineV2EventLogEntry): Promise<void> {- evictions.push(entry);- return Promise.resolve();- },- };- const runtime = makeRuntime({eventLogCap: capacity, spillSink: sink});- const total = capacity + 3;- for (let index = 0; index < total; index += 1) {- runtime.dispatch(makeInboundVideoFrameEvent(index));- }- await Promise.resolve();- expect(evictions.length).toBe(total - capacity);- const limit = evictions.length;- for (let cursor = 0; cursor < limit; cursor += 1) {- expect(evictions[cursor]?.sequence).toBe(cursor + 1);- }- });-- it('still satisfies the runtime cap default at the package constant', () => {- expect(VOICE_ENGINE_V2_EVENT_LOG_CAP).toBeGreaterThanOrEqual(4096);- const runtime = makeRuntime();- expect(runtime.eventLogCap).toBe(VOICE_ENGINE_V2_EVENT_LOG_CAP);- });-});diff --git a/packages/voice_engine_v2/src/source_isolation/SourceLifecycleState.test.ts b/packages/voice_engine_v2/src/source_isolation/SourceLifecycleState.test.tsindex 43b0ff131..b149b1913 100644--- a/packages/voice_engine_v2/src/source_isolation/SourceLifecycleState.test.ts+++ b/packages/voice_engine_v2/src/source_isolation/SourceLifecycleState.test.ts@@ -159,37 +159,6 @@ describe('transitionSourceLifecycle', () => {expect(result.state).toEqual(active);expect(result.action).toBe('noop');});-- it('determinism: same (state, event, clock-output) produces same output', () => {- const stateA: SourceLifecycleState = {kind: 'active', since: 100n};- const stateB: SourceLifecycleState = {kind: 'active', since: 100n};- const clockA = makeFixedClock(200n);- const clockB = makeFixedClock(200n);- const event: SourceLifecycleEvent = {kind: 'fault', fault: 'networkError'};- const resultA = transitionSourceLifecycle(stateA, event, clockA);- const resultB = transitionSourceLifecycle(stateB, event, clockB);- expect(resultA).toEqual(resultB);- });-- it('rejects invalid state kind on entry', () => {- const clock = makeClock();- const bogus = {kind: 'bogus'} as unknown as SourceLifecycleState;- expect(() => transitionSourceLifecycle(bogus, {kind: 'recovered'}, clock)).toThrow();- });-- it('rejects invalid event kind on entry', () => {- const clock = makeClock();- const active = createInitialActiveState(clock);- const bogusEvent = {kind: 'bogus'} as unknown as SourceLifecycleEvent;- expect(() => transitionSourceLifecycle(active, bogusEvent, clock)).toThrow();- });-- it('rejects invalid fault on event entry', () => {- const clock = makeClock();- const active = createInitialActiveState(clock);- const bogusEvent = {kind: 'fault', fault: 'wat'} as unknown as SourceLifecycleEvent;- expect(() => transitionSourceLifecycle(active, bogusEvent, clock)).toThrow();- });});describe('SourceLifecycleRegistry', () => {@@ -252,17 +221,6 @@ describe('SourceLifecycleRegistry', () => {expect(second.error).toBe('duplicateSource');});- it('invalid source id is rejected', () => {- const clock = makeClock();- const registry = new SourceLifecycleRegistry(clock);- const result = registry.register('');- expect(result.ok).toBe(false);- const dispatch = registry.dispatch('', {kind: 'recovered'});- expect(dispatch.ok).toBe(false);- if (dispatch.ok) throw new Error('unreachable');- expect(dispatch.error).toBe('invalidSourceId');- });-it('remove drops a source and frees a slot for reuse', () => {const clock = makeClock();const registry = new SourceLifecycleRegistry(clock, 2);diff --git a/packages/voice_engine_v2/src/testing/conformance.test.ts b/packages/voice_engine_v2/src/testing/conformance.test.tsindex 8910e0db8..a7a4f45fe 100644--- a/packages/voice_engine_v2/src/testing/conformance.test.ts+++ b/packages/voice_engine_v2/src/testing/conformance.test.ts@@ -7,7 +7,6 @@ import {VoiceEngineV2Runtime} from '@fluxer/voice_engine_v2/src/runtime/VoiceEngimport type {VoiceEngineV2ConformanceSubject} from '@fluxer/voice_engine_v2/src/testing/conformance';import {runVoiceEngineV2ConformanceSuite, waitForRuntime} from '@fluxer/voice_engine_v2/src/testing/conformance';import {FakeVoiceEngineV2Driver} from '@fluxer/voice_engine_v2/src/testing/FakeVoiceEngineV2Driver';-import {VoiceEngineV2TestImplementation} from '@fluxer/voice_engine_v2/src/testing/VoiceEngineV2TestImplementation';import {describe, expect, it} from 'vitest';function createConformanceHostPorts(driver: FakeVoiceEngineV2Driver): VoiceEngineV2HostPorts {@@ -45,45 +44,9 @@ function createHostPortSubject(): VoiceEngineV2ConformanceSubject {return {driver, implementation: new VoiceEngineV2HostPortImplementation(createConformanceHostPorts(driver))};}-runVoiceEngineV2ConformanceSuite('test JS', () => {- const driver = new FakeVoiceEngineV2Driver();- return {driver, implementation: new VoiceEngineV2TestImplementation(driver)};-});-runVoiceEngineV2ConformanceSuite('host-port native', createHostPortSubject);-describe('VoiceEngineV2 implementation equivalence', () => {- it('produces equivalent snapshots and driver calls for test and host-port implementations', async () => {- const testDriver = new FakeVoiceEngineV2Driver();- const hostPortDriver = new FakeVoiceEngineV2Driver();- const testRuntime = new VoiceEngineV2Runtime(new VoiceEngineV2TestImplementation(testDriver), {- eventLogSpillSink: createVoiceEngineV2MemoryEventLogSpillSink(),- verifyEventLogInvariantsOnDispatch: true,- });- const hostPortRuntime = new VoiceEngineV2Runtime(- new VoiceEngineV2HostPortImplementation(createConformanceHostPorts(hostPortDriver)),- {- eventLogSpillSink: createVoiceEngineV2MemoryEventLogSpillSink(),- verifyEventLogInvariantsOnDispatch: true,- },- );-- for (const runtime of [testRuntime, hostPortRuntime]) {- runtime.dispatch({type: 'connection.connectRequested', options: {url: 'wss://voice', token: 'token'}});- await waitForRuntime();- runtime.dispatch({type: 'microphone.publishRequested', options: {deviceId: 'default'}});- runtime.dispatch({type: 'microphone.setEnabledRequested', enabled: false});- runtime.dispatch({- type: 'screen.publishRequested',- options: {captureId: 'capture-1', width: 1920, height: 1080, codec: 'h264'},- });- await waitForRuntime();- }-- expect(hostPortRuntime.snapshot).toEqual(testRuntime.snapshot);- expect(hostPortDriver.calls).toEqual(testDriver.calls);- });-+describe('VoiceEngineV2HostPortImplementation', () => {it('reports an unsupported-capability failure when the host port is absent', async () => {const runtime = new VoiceEngineV2Runtime(new VoiceEngineV2HostPortImplementation({}), {eventLogSpillSink: createVoiceEngineV2MemoryEventLogSpillSink(),