|
| 1 | +// SPDX-FileCopyrightText: 2026 LiveKit, Inc. |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | +import type { AddressInfo } from 'node:net'; |
| 5 | +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; |
| 6 | +import { WebSocketServer } from 'ws'; |
| 7 | +import type { WebSocket as WsSocket } from 'ws'; |
| 8 | +import { initializeLogger } from '../log.js'; |
| 9 | +import { TTS } from './tts.js'; |
| 10 | + |
| 11 | +/** |
| 12 | + * Pins the user-visible invariant: a reply must never inherit the audio a previous, dropped |
| 13 | + * session never finished delivering. |
| 14 | + * |
| 15 | + * `session.closed` is the only route that reaches that leak. Once the `session.closed` |
| 16 | + * handler rejects the attempt instead of resolving it, the exception path in |
| 17 | + * `ConnectionPool.withConnection` evicts the socket by itself and this test passes with or |
| 18 | + * without the `sessionDrained` eviction in `SynthesizeStream.run`. Read it as coverage of |
| 19 | + * the behaviour, not of that eviction. |
| 20 | + */ |
| 21 | + |
| 22 | +initializeLogger({ pretty: false }); |
| 23 | + |
| 24 | +const SAMPLE_RATE = 16000; |
| 25 | +const FRAME_MS = 20; |
| 26 | +const SAMPLES_PER_FRAME = (SAMPLE_RATE * FRAME_MS) / 1000; |
| 27 | + |
| 28 | +/** Audio from the session that gets dropped and audio from a healthy session carry |
| 29 | + * distinct constant samples so the test can tell, per frame, which session's synthesis a |
| 30 | + * frame actually came from. */ |
| 31 | +const DROPPED_SESSION_SAMPLE = 1000; |
| 32 | +const HEALTHY_SESSION_SAMPLE = 2000; |
| 33 | + |
| 34 | +/** ~6s of already-synthesized audio the gateway still owes after it drops the session. */ |
| 35 | +const BACKLOG_FRAMES = 300; |
| 36 | +const OWN_FRAMES = 25; |
| 37 | + |
| 38 | +function audioEvent(sessionId: string, sample: number): string { |
| 39 | + const pcm = Buffer.alloc(SAMPLES_PER_FRAME * 2); |
| 40 | + for (let i = 0; i < SAMPLES_PER_FRAME; i++) { |
| 41 | + pcm.writeInt16LE(sample, i * 2); |
| 42 | + } |
| 43 | + return JSON.stringify({ |
| 44 | + type: 'output_audio', |
| 45 | + session_id: sessionId, |
| 46 | + audio: pcm.toString('base64'), |
| 47 | + }); |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Gateway stand-in for the production trace in which the first reply's session was dropped |
| 52 | + * with `session.closed` while ~90s of synthesis was still outstanding. On the first |
| 53 | + * connection it streams a short prefix, drops the session without a `done`, then keeps |
| 54 | + * flushing the rest of the backlog onto the same socket. Any later connection behaves |
| 55 | + * normally. |
| 56 | + */ |
| 57 | +async function startFakeGateway() { |
| 58 | + const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' }); |
| 59 | + await new Promise<void>((resolve) => wss.once('listening', () => resolve())); |
| 60 | + let connections = 0; |
| 61 | + const sockets: WsSocket[] = []; |
| 62 | + |
| 63 | + wss.on('connection', (ws: WsSocket) => { |
| 64 | + sockets.push(ws); |
| 65 | + const index = ++connections; |
| 66 | + const sessionId = `session-${index}`; |
| 67 | + const sample = index === 1 ? DROPPED_SESSION_SAMPLE : HEALTHY_SESSION_SAMPLE; |
| 68 | + let dropped = false; |
| 69 | + |
| 70 | + const send = (payload: string) => { |
| 71 | + if (ws.readyState === ws.OPEN) ws.send(payload); |
| 72 | + }; |
| 73 | + |
| 74 | + ws.on('message', async (raw: Buffer) => { |
| 75 | + const event = JSON.parse(raw.toString()) as { type: string }; |
| 76 | + if (event.type === 'session.create') { |
| 77 | + send(JSON.stringify({ type: 'session.created', session_id: sessionId })); |
| 78 | + return; |
| 79 | + } |
| 80 | + if (event.type !== 'session.flush') return; |
| 81 | + |
| 82 | + // A healthy session serves every reply it is asked for, so a pooled socket can be |
| 83 | + // reused across replies. |
| 84 | + if (index > 1) { |
| 85 | + for (let i = 0; i < OWN_FRAMES; i++) send(audioEvent(sessionId, sample)); |
| 86 | + send(JSON.stringify({ type: 'done', session_id: sessionId })); |
| 87 | + return; |
| 88 | + } |
| 89 | + |
| 90 | + if (dropped) return; |
| 91 | + dropped = true; |
| 92 | + |
| 93 | + // Reply 1: hand over a short prefix, then drop the session mid-synthesis. |
| 94 | + for (let i = 0; i < OWN_FRAMES; i++) send(audioEvent(sessionId, sample)); |
| 95 | + send(JSON.stringify({ type: 'session.closed', session_id: sessionId })); |
| 96 | + // The synthesis that was already in flight keeps arriving on this socket. |
| 97 | + await new Promise((resolve) => setTimeout(resolve, 20)); |
| 98 | + for (let i = 0; i < BACKLOG_FRAMES; i++) send(audioEvent(sessionId, sample)); |
| 99 | + send(JSON.stringify({ type: 'done', session_id: sessionId })); |
| 100 | + }); |
| 101 | + }); |
| 102 | + |
| 103 | + const { port } = wss.address() as AddressInfo; |
| 104 | + return { |
| 105 | + baseURL: `http://127.0.0.1:${port}/v1`, |
| 106 | + get connections() { |
| 107 | + return connections; |
| 108 | + }, |
| 109 | + close: () => { |
| 110 | + for (const socket of sockets) socket.terminate(); |
| 111 | + return new Promise<void>((resolve) => wss.close(() => resolve())); |
| 112 | + }, |
| 113 | + }; |
| 114 | +} |
| 115 | + |
| 116 | +async function synthesize(tts: TTS<string>, text: string) { |
| 117 | + const stream = tts.stream(); |
| 118 | + stream.pushText(text); |
| 119 | + stream.endInput(); |
| 120 | + |
| 121 | + const samples = new Set<number>(); |
| 122 | + let frames = 0; |
| 123 | + for await (const event of stream) { |
| 124 | + if (typeof event === 'symbol' || event.frame.samplesPerChannel === 0) continue; |
| 125 | + frames++; |
| 126 | + samples.add(event.frame.data[0]!); |
| 127 | + } |
| 128 | + await stream.close(); |
| 129 | + return { frames, samples }; |
| 130 | +} |
| 131 | + |
| 132 | +describe('inference TTS pooled socket reuse', () => { |
| 133 | + let gateway: Awaited<ReturnType<typeof startFakeGateway>>; |
| 134 | + |
| 135 | + beforeEach(async () => { |
| 136 | + gateway = await startFakeGateway(); |
| 137 | + }); |
| 138 | + |
| 139 | + afterEach(async () => { |
| 140 | + await gateway.close(); |
| 141 | + }); |
| 142 | + |
| 143 | + it('does not hand a dropped session\u2019s outstanding audio to the next reply', async () => { |
| 144 | + const tts = new TTS({ |
| 145 | + model: 'inworld/inworld-tts-2', |
| 146 | + voice: 'Sarah', |
| 147 | + sampleRate: SAMPLE_RATE, |
| 148 | + baseURL: gateway.baseURL, |
| 149 | + apiKey: 'devkey', |
| 150 | + apiSecret: 'secret'.padEnd(32, 'x'), |
| 151 | + }); |
| 152 | + |
| 153 | + // The dropped session fails the attempt, so the first reply is the prefix it did |
| 154 | + // deliver plus the audio from the retry that finishes it on a healthy session. |
| 155 | + const first = await synthesize(tts, 'Tell me a long story about the lighthouse.'); |
| 156 | + expect(first.samples).toEqual(new Set([DROPPED_SESSION_SAMPLE, HEALTHY_SESSION_SAMPLE])); |
| 157 | + |
| 158 | + const second = await synthesize(tts, 'Tell me a long joke about skeletons.'); |
| 159 | + |
| 160 | + // The second reply must speak only its own synthesis, and must not inherit the |
| 161 | + // seconds of audio the first session never finished delivering. |
| 162 | + expect(second.samples).toEqual(new Set([HEALTHY_SESSION_SAMPLE])); |
| 163 | + expect(second.frames).toBeLessThan(BACKLOG_FRAMES); |
| 164 | + expect(gateway.connections).toBe(2); |
| 165 | + |
| 166 | + await tts.close(); |
| 167 | + }, 20_000); |
| 168 | +}); |
0 commit comments