|
| 1 | +// SPDX-FileCopyrightText: 2026 LiveKit, Inc. |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | +import { AudioFrame } from '@livekit/rtc-node'; |
| 5 | +import { ReadableStream } from 'node:stream/web'; |
| 6 | +import { beforeAll, describe, expect, it } from 'vitest'; |
| 7 | +import { APIError } from '../_exceptions.js'; |
| 8 | +import { initializeLogger } from '../log.js'; |
| 9 | +import type { APIConnectOptions } from '../types.js'; |
| 10 | +import { FallbackAdapter } from './fallback_adapter.js'; |
| 11 | +import { ChunkedStream, SynthesizeStream, TTS } from './tts.js'; |
| 12 | + |
| 13 | +const SAMPLE_RATE = 24000; |
| 14 | + |
| 15 | +class MockSynthesizeStream extends SynthesizeStream { |
| 16 | + label = 'mock.SynthesizeStream'; |
| 17 | + |
| 18 | + constructor( |
| 19 | + private mockTts: MockTTS, |
| 20 | + private shouldFail: boolean, |
| 21 | + connOptions?: APIConnectOptions, |
| 22 | + ) { |
| 23 | + super(mockTts, connOptions); |
| 24 | + } |
| 25 | + |
| 26 | + protected async run(): Promise<void> { |
| 27 | + if (this.shouldFail) { |
| 28 | + // Throw immediately, before any pushText has been called. |
| 29 | + // This is the scenario that previously deadlocked the FallbackAdapter: |
| 30 | + // the inner stream's mainTask finishes before forwardBufferToTTS gets |
| 31 | + // a chance to call pushText, so #monitorMetricsTask never starts and |
| 32 | + // this.output is never closed. |
| 33 | + throw new APIError('mock TTS failed immediately'); |
| 34 | + } |
| 35 | + |
| 36 | + // Happy path: read text from this.input and emit a single audio frame per token. |
| 37 | + for await (const data of this.input) { |
| 38 | + if (this.abortController.signal.aborted) break; |
| 39 | + if (data === SynthesizeStream.FLUSH_SENTINEL) continue; |
| 40 | + this.queue.put({ |
| 41 | + requestId: 'mock-req', |
| 42 | + segmentId: 'mock-seg', |
| 43 | + frame: new AudioFrame(new Int16Array(160), this.mockTts.sampleRate, 1, 160), |
| 44 | + final: false, |
| 45 | + }); |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +class MockChunkedStream extends ChunkedStream { |
| 51 | + label = 'mock.ChunkedStream'; |
| 52 | + constructor( |
| 53 | + private mockTts: MockTTS, |
| 54 | + text: string, |
| 55 | + private shouldFail: boolean, |
| 56 | + connOptions?: APIConnectOptions, |
| 57 | + ) { |
| 58 | + super(text, mockTts, connOptions); |
| 59 | + } |
| 60 | + protected async run(): Promise<void> { |
| 61 | + if (this.shouldFail) { |
| 62 | + throw new APIError('mock TTS failed immediately'); |
| 63 | + } |
| 64 | + this.queue.put({ |
| 65 | + requestId: 'mock-req', |
| 66 | + segmentId: 'mock-seg', |
| 67 | + frame: new AudioFrame(new Int16Array(160), this.mockTts.sampleRate, 1, 160), |
| 68 | + final: true, |
| 69 | + }); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +class MockTTS extends TTS { |
| 74 | + label: string; |
| 75 | + shouldFail = false; |
| 76 | + |
| 77 | + constructor(label: string, sampleRate: number = SAMPLE_RATE) { |
| 78 | + super(sampleRate, 1, { streaming: true }); |
| 79 | + this.label = label; |
| 80 | + } |
| 81 | + |
| 82 | + synthesize(text: string, connOptions?: APIConnectOptions): ChunkedStream { |
| 83 | + return new MockChunkedStream(this, text, this.shouldFail, connOptions); |
| 84 | + } |
| 85 | + |
| 86 | + stream(options?: { connOptions?: APIConnectOptions }): SynthesizeStream { |
| 87 | + return new MockSynthesizeStream(this, this.shouldFail, options?.connOptions); |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +describe('TTS FallbackAdapter', () => { |
| 92 | + beforeAll(() => { |
| 93 | + initializeLogger({ pretty: false }); |
| 94 | + // Suppress unhandled rejections from background tasks inside SynthesizeStream |
| 95 | + process.on('unhandledRejection', () => {}); |
| 96 | + }); |
| 97 | + |
| 98 | + it('should fall back to the next TTS when the primary stream fails before any pushText', async () => { |
| 99 | + const primary = new MockTTS('primary'); |
| 100 | + primary.shouldFail = true; |
| 101 | + const secondary = new MockTTS('secondary'); |
| 102 | + const adapter = new FallbackAdapter({ |
| 103 | + ttsInstances: [primary, secondary], |
| 104 | + maxRetryPerTTS: 0, |
| 105 | + recoveryDelayMs: 60_000, |
| 106 | + }); |
| 107 | + |
| 108 | + const stream = adapter.stream(); |
| 109 | + stream.updateInputStream( |
| 110 | + new ReadableStream<string>({ |
| 111 | + start(controller) { |
| 112 | + controller.enqueue('hello world'); |
| 113 | + controller.close(); |
| 114 | + }, |
| 115 | + }), |
| 116 | + ); |
| 117 | + |
| 118 | + // With the deadlock bug, this loop hangs forever because the inner |
| 119 | + // primary stream's this.output is never closed. Use a hard timeout to |
| 120 | + // turn the deadlock into a test failure. |
| 121 | + const iterate = (async () => { |
| 122 | + let frameCount = 0; |
| 123 | + for await (const event of stream) { |
| 124 | + if (event === SynthesizeStream.END_OF_STREAM) break; |
| 125 | + frameCount++; |
| 126 | + } |
| 127 | + return frameCount; |
| 128 | + })(); |
| 129 | + |
| 130 | + const timeout = new Promise<never>((_, reject) => |
| 131 | + setTimeout(() => reject(new Error('fallback adapter deadlocked')), 3000), |
| 132 | + ); |
| 133 | + |
| 134 | + const frameCount = await Promise.race([iterate, timeout]); |
| 135 | + |
| 136 | + expect(frameCount).toBeGreaterThan(0); |
| 137 | + expect(adapter.status[0]!.available).toBe(false); |
| 138 | + expect(adapter.status[1]!.available).toBe(true); |
| 139 | + |
| 140 | + stream.close(); |
| 141 | + await adapter.close(); |
| 142 | + }); |
| 143 | + |
| 144 | + it('should fall back when the primary has a mismatched sample rate and emits no audio', async () => { |
| 145 | + // Primary runs at 22050Hz, adapter aggregates at 24000Hz → a resampler is |
| 146 | + // created for the primary. The primary throws with no frames ever pushed, |
| 147 | + // so `resampler.push()` is never called. Regression test for a bug where |
| 148 | + // `resampler.flush()` on an unused resampler returned a phantom frame, |
| 149 | + // flipping `audioPushed` to true and making the adapter incorrectly |
| 150 | + // treat a silent failure as a success. |
| 151 | + const primary = new MockTTS('primary', 22050); |
| 152 | + primary.shouldFail = true; |
| 153 | + const secondary = new MockTTS('secondary', 24000); |
| 154 | + const adapter = new FallbackAdapter({ |
| 155 | + ttsInstances: [primary, secondary], |
| 156 | + maxRetryPerTTS: 0, |
| 157 | + recoveryDelayMs: 60_000, |
| 158 | + }); |
| 159 | + |
| 160 | + const stream = adapter.stream(); |
| 161 | + stream.updateInputStream( |
| 162 | + new ReadableStream<string>({ |
| 163 | + start(controller) { |
| 164 | + controller.enqueue('hello world'); |
| 165 | + controller.close(); |
| 166 | + }, |
| 167 | + }), |
| 168 | + ); |
| 169 | + |
| 170 | + const iterate = (async () => { |
| 171 | + let frameCount = 0; |
| 172 | + for await (const event of stream) { |
| 173 | + if (event === SynthesizeStream.END_OF_STREAM) break; |
| 174 | + frameCount++; |
| 175 | + } |
| 176 | + return frameCount; |
| 177 | + })(); |
| 178 | + |
| 179 | + const timeout = new Promise<never>((_, reject) => |
| 180 | + setTimeout(() => reject(new Error('fallback adapter deadlocked')), 3000), |
| 181 | + ); |
| 182 | + |
| 183 | + const frameCount = await Promise.race([iterate, timeout]); |
| 184 | + |
| 185 | + expect(frameCount).toBeGreaterThan(0); |
| 186 | + expect(adapter.status[0]!.available).toBe(false); |
| 187 | + expect(adapter.status[1]!.available).toBe(true); |
| 188 | + |
| 189 | + stream.close(); |
| 190 | + await adapter.close(); |
| 191 | + }); |
| 192 | + |
| 193 | + it('should fall back in the non-streaming (synthesize) path with mismatched sample rates', async () => { |
| 194 | + // FallbackChunkedStream has the same phantom-flush vulnerability as |
| 195 | + // FallbackSynthesizeStream: when the primary's sample rate differs from |
| 196 | + // the adapter's output rate a resampler is created, and flushing an |
| 197 | + // unused resampler can return a ghost frame that masks a silent |
| 198 | + // failure. Exercise the non-streaming adapter.synthesize() path. |
| 199 | + const primary = new MockTTS('primary', 22050); |
| 200 | + primary.shouldFail = true; |
| 201 | + const secondary = new MockTTS('secondary', 24000); |
| 202 | + const adapter = new FallbackAdapter({ |
| 203 | + ttsInstances: [primary, secondary], |
| 204 | + maxRetryPerTTS: 0, |
| 205 | + recoveryDelayMs: 60_000, |
| 206 | + }); |
| 207 | + |
| 208 | + const chunked = adapter.synthesize('hello world'); |
| 209 | + |
| 210 | + const iterate = (async () => { |
| 211 | + let frameCount = 0; |
| 212 | + for await (const _event of chunked) { |
| 213 | + frameCount++; |
| 214 | + } |
| 215 | + return frameCount; |
| 216 | + })(); |
| 217 | + |
| 218 | + const timeout = new Promise<never>((_, reject) => |
| 219 | + setTimeout(() => reject(new Error('fallback adapter deadlocked')), 3000), |
| 220 | + ); |
| 221 | + |
| 222 | + const frameCount = await Promise.race([iterate, timeout]); |
| 223 | + |
| 224 | + expect(frameCount).toBeGreaterThan(0); |
| 225 | + expect(adapter.status[0]!.available).toBe(false); |
| 226 | + expect(adapter.status[1]!.available).toBe(true); |
| 227 | + |
| 228 | + await adapter.close(); |
| 229 | + }); |
| 230 | +}); |
0 commit comments