Skip to content

Commit 36b80ad

Browse files
committed
Merge pull request #116935 from openclaw/fix/realtime-transcription-queue-head-ready
* commit '7820683b625b80f7aec4a3721a425961d2016324': test(realtime): guard queued audio from array shifts test(realtime): stress queued transcription audio lifecycle perf(realtime): avoid shifting queued transcription audio
2 parents 4669db2 + 7820683 commit 36b80ad

2 files changed

Lines changed: 170 additions & 10 deletions

File tree

‎src/realtime-transcription/websocket-session.test.ts‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,12 @@ function requireFirstMockArg<T>(mock: { mock: { calls: T[][] } }, label: string)
102102
return expectDefined(arg, "arg test invariant");
103103
}
104104

105+
function encodeSequence(value: number): Buffer {
106+
const frame = Buffer.allocUnsafe(2);
107+
frame.writeUInt16BE(value);
108+
return frame;
109+
}
110+
105111
describe("createRealtimeTranscriptionWebSocketSession", () => {
106112
it("flushes queued binary audio after an open-ready connection", async () => {
107113
const frames: Buffer[] = [];
@@ -133,6 +139,136 @@ describe("createRealtimeTranscriptionWebSocketSession", () => {
133139
session.close();
134140
});
135141

142+
it("drops the oldest queued audio by bytes and flushes the retained tail in order", async () => {
143+
const frames: Buffer[] = [];
144+
const framesReady = createSignal();
145+
const server = await createRealtimeServer({
146+
onBinary: (payload) => {
147+
frames.push(payload);
148+
if (frames.length === 3) {
149+
framesReady.resolve();
150+
}
151+
},
152+
});
153+
const session = createRealtimeTranscriptionWebSocketSession({
154+
providerId: "test",
155+
callbacks: {},
156+
url: server.url,
157+
maxQueuedBytes: 7,
158+
readyOnOpen: true,
159+
sendAudio: (audio, transport) => {
160+
transport.sendBinary(audio);
161+
},
162+
});
163+
164+
const shiftSpy = vi.spyOn(Array.prototype, "shift");
165+
let shiftCalls = 0;
166+
try {
167+
for (let index = 0; index < 13_000; index += 1) {
168+
session.sendAudio(encodeSequence(index));
169+
}
170+
session.sendAudio(Buffer.from([0xaa, 0xbb, 0xcc]));
171+
shiftCalls = shiftSpy.mock.calls.length;
172+
} finally {
173+
shiftSpy.mockRestore();
174+
}
175+
expect(shiftCalls).toBe(0);
176+
177+
await session.connect();
178+
await framesReady.promise;
179+
expect(frames).toEqual([
180+
encodeSequence(12_998),
181+
encodeSequence(12_999),
182+
Buffer.from([0xaa, 0xbb, 0xcc]),
183+
]);
184+
session.close();
185+
});
186+
187+
it("flushes a large retained audio tail in order after reconnect", async () => {
188+
const connections: WebSocket[] = [];
189+
const frames: Buffer[] = [];
190+
const framesReady = createSignal();
191+
const server = await createRealtimeServer({
192+
onConnection: (ws) => connections.push(ws),
193+
onBinary: (payload) => {
194+
frames.push(payload);
195+
if (frames.length === 4) {
196+
framesReady.resolve();
197+
}
198+
},
199+
});
200+
const session = createRealtimeTranscriptionWebSocketSession<{ type?: string }>({
201+
providerId: "test",
202+
callbacks: {},
203+
url: server.url,
204+
maxQueuedBytes: 8,
205+
maxReconnectAttempts: 1,
206+
reconnectDelayMs: 1,
207+
onMessage: (event, transport) => {
208+
if (event.type === "session.created") {
209+
transport.markReady();
210+
}
211+
},
212+
sendAudio: (audio, transport) => {
213+
transport.sendBinary(audio);
214+
},
215+
});
216+
217+
const connecting = session.connect();
218+
await vi.waitFor(() => expect(connections).toHaveLength(1));
219+
connections[0]?.send(JSON.stringify({ type: "session.created" }));
220+
await connecting;
221+
222+
connections[0]?.close(1011, "reconnect");
223+
await vi.waitFor(() => expect(session.isConnected()).toBe(false));
224+
await vi.waitFor(() => expect(connections).toHaveLength(2));
225+
for (let index = 0; index < 13_000; index += 1) {
226+
session.sendAudio(encodeSequence(index));
227+
}
228+
connections[1]?.send(JSON.stringify({ type: "session.created" }));
229+
230+
await framesReady.promise;
231+
expect(frames).toEqual([
232+
encodeSequence(12_996),
233+
encodeSequence(12_997),
234+
encodeSequence(12_998),
235+
encodeSequence(12_999),
236+
]);
237+
session.close();
238+
});
239+
240+
it("discards a large queued audio tail when closed before connecting", async () => {
241+
const frames: Buffer[] = [];
242+
const framesReady = createSignal();
243+
const server = await createRealtimeServer({
244+
onBinary: (payload) => {
245+
frames.push(payload);
246+
framesReady.resolve();
247+
},
248+
});
249+
const session = createRealtimeTranscriptionWebSocketSession({
250+
providerId: "test",
251+
callbacks: {},
252+
url: server.url,
253+
maxQueuedBytes: 8,
254+
readyOnOpen: true,
255+
sendAudio: (audio, transport) => {
256+
transport.sendBinary(audio);
257+
},
258+
});
259+
260+
for (let index = 0; index < 13_000; index += 1) {
261+
session.sendAudio(encodeSequence(index));
262+
}
263+
session.close();
264+
265+
await session.connect();
266+
session.sendAudio(Buffer.from("live"));
267+
await framesReady.promise;
268+
expect(frames).toEqual([Buffer.from("live")]);
269+
session.close();
270+
});
271+
136272
it("lets providers mark ready after a JSON handshake", async () => {
137273
const frames: unknown[] = [];
138274
const framesReady = createSignal();

‎src/realtime-transcription/websocket-session.ts‎

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ class WebSocketRealtimeTranscriptionSession<Event> implements RealtimeTranscript
7272
private closed = false;
7373
private connected = false;
7474
private currentUrl = "";
75-
private queuedAudio: Buffer[] = [];
75+
private queuedAudio: Array<Buffer | undefined> = [];
76+
private queuedAudioHead = 0;
7677
private queuedBytes = 0;
7778
private ready = false;
7879
private readySinceMs: number | undefined;
@@ -140,8 +141,7 @@ class WebSocketRealtimeTranscriptionSession<Event> implements RealtimeTranscript
140141
this.ready = false;
141142
this.readySinceMs = undefined;
142143
this.reconnectSupervisor.cancel();
143-
this.queuedAudio = [];
144-
this.queuedBytes = 0;
144+
this.clearQueuedAudio();
145145
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
146146
this.forceClose();
147147
return;
@@ -380,21 +380,45 @@ class WebSocketRealtimeTranscriptionSession<Event> implements RealtimeTranscript
380380
}
381381

382382
private queueAudio(audio: Buffer): void {
383-
this.queuedAudio.push(Buffer.from(audio));
384-
this.queuedBytes += audio.byteLength;
385-
while (this.queuedBytes > this.maxQueuedBytes && this.queuedAudio.length > 0) {
383+
const queued = Buffer.from(audio);
384+
this.queuedAudio.push(queued);
385+
this.queuedBytes += queued.byteLength;
386+
while (
387+
this.queuedBytes > this.maxQueuedBytes &&
388+
this.queuedAudioHead < this.queuedAudio.length
389+
) {
386390
// Keep the most recent audio when reconnects stall; old buffered audio is
387-
// less useful than avoiding unbounded memory growth.
388-
const dropped = this.queuedAudio.shift();
391+
// less useful than avoiding unbounded memory growth. Advancing a head
392+
// index keeps sustained overflow amortized O(1) instead of shifting the queue.
393+
const dropped = this.queuedAudio[this.queuedAudioHead];
394+
this.queuedAudio[this.queuedAudioHead] = undefined;
395+
this.queuedAudioHead += 1;
389396
this.queuedBytes -= dropped?.byteLength ?? 0;
390397
}
398+
this.compactQueuedAudio();
391399
}
392400

393401
private flushQueuedAudio(): void {
394-
for (const audio of this.queuedAudio) {
395-
this.options.sendAudio(audio, this.transport);
402+
for (let index = this.queuedAudioHead; index < this.queuedAudio.length; index += 1) {
403+
const audio = this.queuedAudio[index];
404+
if (audio) {
405+
this.options.sendAudio(audio, this.transport);
406+
}
407+
}
408+
this.clearQueuedAudio();
409+
}
410+
411+
private compactQueuedAudio(): void {
412+
if (this.queuedAudioHead === 0 || this.queuedAudioHead * 2 < this.queuedAudio.length) {
413+
return;
396414
}
415+
this.queuedAudio = this.queuedAudio.slice(this.queuedAudioHead);
416+
this.queuedAudioHead = 0;
417+
}
418+
419+
private clearQueuedAudio(): void {
397420
this.queuedAudio = [];
421+
this.queuedAudioHead = 0;
398422
this.queuedBytes = 0;
399423
}
400424

0 commit comments

Comments
 (0)