Skip to content

Commit 70d6fb6

Browse files
steipetesunlit-deng
andcommitted
fix(voice-call): stream diagnostic logs with backpressure
Co-authored-by: sunlit-deng <[email protected]>
1 parent c50533f commit 70d6fb6

5 files changed

Lines changed: 431 additions & 94 deletions

File tree

‎docs/cli/voicecall.md‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,13 @@ openclaw voicecall status --call-id <id>
171171

172172
### `tail`
173173

174-
Tail the voice-call JSONL log. Prints the last `--since` lines on start, then
175-
streams new lines as they are written.
174+
Tail persisted voice-call records from SQLite: print the last `--since` records
175+
initially, then only new snapshots (`--since 0` starts with new snapshots only).
176+
With an existing custom `--file`
177+
whose basename is not `calls.jsonl`, prints the last `--since` nonempty complete
178+
lines on start, then streams new complete lines. Partial lines wait for a newline;
179+
file replacement or observed truncation starts a fresh stream. Slow output pipes
180+
pause reading instead of accumulating the rest of the log in memory.
176181

177182
| Flag | Default | Description |
178183
| --------------- | -------------------------- | ------------------------------ |
@@ -182,8 +187,15 @@ streams new lines as they are written.
182187

183188
### `latency`
184189

185-
Summarize turn-latency and listen-wait metrics from `calls.jsonl`. Output is
186-
JSON with `recordsScanned`, `turnLatency`, and `listenWait` summaries.
190+
Summarize turn-latency and listen-wait metrics from SQLite or an existing custom
191+
log selected with `--file`. Output is JSON with `recordsScanned`, `turnLatency`,
192+
and `listenWait` summaries.
193+
194+
Custom logs are scanned incrementally without a byte cap on requested history.
195+
`latency` selects the last N nonempty records, skips malformed JSON, and accepts
196+
a final JSON record without a newline. It parses one selected record at a time;
197+
memory still scales with the largest selected JSON record and the requested
198+
number of metric samples.
187199

188200
| Flag | Default | Description |
189201
| --------------- | -------------------------- | ------------------------------------ |

‎docs/plugins/voice-call.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -832,8 +832,9 @@ delegate to the Gateway-owned voice-call runtime so the CLI does not bind a
832832
second webhook server. If no Gateway is reachable, the commands fall back to
833833
a standalone CLI runtime.
834834

835-
`latency` reads `calls.jsonl` from the default voice-call storage path. Use
836-
`--file <path>` to point at a different log and `--last <n>` to limit
835+
`latency` reads persisted call records from SQLite by default. Use
836+
`--file <path>` to read an existing custom JSONL log (with a basename other than
837+
`calls.jsonl`) and `--last <n>` to limit
837838
analysis to the last N records (default 200). Output includes min/max/avg,
838839
p50, and p95 for turn latency and listen-wait times.
839840

Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { Command } from "commander";
5+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
6+
import { tempWorkspace } from "openclaw/plugin-sdk/temp-path";
7+
import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";
8+
9+
const { sleepMock, historyMock } = vi.hoisted(() => ({
10+
sleepMock: vi.fn(),
11+
historyMock: vi.fn(),
12+
}));
13+
vi.mock("../api.js", async (importOriginal) => ({
14+
...(await importOriginal<typeof import("../api.js")>()),
15+
sleep: sleepMock,
16+
}));
17+
vi.mock("./manager/store.js", async (importOriginal) => ({
18+
...(await importOriginal<typeof import("./manager/store.js")>()),
19+
getCallHistoryFromStore: historyMock,
20+
}));
21+
22+
import { registerVoiceCallLogs } from "./cli-call-log.js";
23+
24+
describe("voice-call diagnostic stream ownership", () => {
25+
let workspace: Awaited<ReturnType<typeof tempWorkspace>>;
26+
let file: string;
27+
let output: Buffer[];
28+
let stdout: MockInstance<typeof process.stdout.write>;
29+
const stopped = new Error("diagnostic test finished");
30+
31+
beforeEach(async () => {
32+
workspace = await tempWorkspace({ rootDir: os.tmpdir(), prefix: "voice-call-log-" });
33+
file = await workspace.write("diagnostics.jsonl", "");
34+
output = [];
35+
sleepMock.mockReset().mockRejectedValue(stopped);
36+
historyMock.mockReset().mockResolvedValue([]);
37+
stdout = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
38+
output.push(Buffer.isBuffer(chunk) ? Buffer.from(chunk) : Buffer.from(String(chunk)));
39+
return true;
40+
});
41+
});
42+
43+
afterEach(async () => {
44+
vi.restoreAllMocks();
45+
await workspace.cleanup();
46+
});
47+
48+
function command(...args: string[]) {
49+
const program = new Command();
50+
registerVoiceCallLogs({ root: program, defaultFile: file, ensureHistoryStateRuntime() {} });
51+
return program.parseAsync(args, { from: "user" });
52+
}
53+
54+
function text() {
55+
return Buffer.concat(output).toString("utf8");
56+
}
57+
58+
it.each(["tail", "latency"])(
59+
"preserves requested %s history beyond one megabyte without reading the whole file",
60+
async (mode) => {
61+
const records = [120, 240, 360].map((latency) =>
62+
JSON.stringify({ metadata: { lastTurnLatencyMs: latency }, padding: "x".repeat(600_000) }),
63+
);
64+
fs.writeFileSync(file, `${records.join("\n")}\n`);
65+
const readFile = vi.spyOn(fs, "readFileSync");
66+
if (mode === "tail") {
67+
await expect(command("tail", "--since", "3")).rejects.toBe(stopped);
68+
expect(text()).toBe(`${records.join("\n")}\n`);
69+
} else {
70+
await command("latency", "--last", "3");
71+
expect(JSON.parse(text())).toMatchObject({
72+
recordsScanned: 3,
73+
turnLatency: { count: 3, avgMs: 240, minMs: 120, maxMs: 360 },
74+
});
75+
}
76+
expect(readFile.mock.calls.filter(([target]) => target === file)).toEqual([]);
77+
},
78+
);
79+
80+
it("bounds follow reads while retaining every record and the unfinished suffix", async () => {
81+
const records = Array.from({ length: 2048 }, (_, seq) =>
82+
JSON.stringify({ seq, text: "é".repeat(512) }),
83+
);
84+
const read = vi.spyOn(fs, "readSync");
85+
sleepMock
86+
.mockResolvedValueOnce(undefined)
87+
.mockImplementationOnce(async () => {
88+
fs.appendFileSync(file, `${records.join("\n")}\n{"seq":2048`);
89+
})
90+
.mockImplementationOnce(async () => {
91+
fs.appendFileSync(file, "}\n");
92+
});
93+
await expect(command("tail", "--since", "0")).rejects.toBe(stopped);
94+
expect(text()).toBe(`${records.join("\n")}\n{"seq":2048}\n`);
95+
const requested = read.mock.calls.map(([, buffer]) => buffer.byteLength);
96+
expect(requested.length).toBeGreaterThan(0);
97+
expect(requested.every((length) => length <= 64 * 1024)).toBe(true);
98+
});
99+
100+
it("does not join a pending record to a larger replacement file", async () => {
101+
fs.writeFileSync(file, '{"seq":0}\n{"retired":');
102+
const replacement = `${JSON.stringify({ seq: 1, text: "fresh".repeat(64) })}\n`;
103+
sleepMock.mockImplementationOnce(async () => {
104+
const next = await workspace.write("replacement.jsonl", replacement);
105+
fs.renameSync(next, file);
106+
});
107+
await expect(command("tail", "--since", "1")).rejects.toBe(stopped);
108+
expect(text()).toBe(`{"seq":0}\n${replacement}`);
109+
});
110+
111+
it("stops producing until stdout drains", async () => {
112+
fs.writeFileSync(file, '{"seq":0}\n{"seq":1}\n');
113+
const blocked = createDeferred<void>();
114+
let rejectWrites = true;
115+
stdout.mockImplementation((chunk) => {
116+
output.push(Buffer.isBuffer(chunk) ? Buffer.from(chunk) : Buffer.from(String(chunk)));
117+
if (rejectWrites) {
118+
blocked.resolve();
119+
return false;
120+
}
121+
return true;
122+
});
123+
const running = command("tail", "--since", "2").catch((error: unknown) => error);
124+
await blocked.promise;
125+
try {
126+
expect(text()).not.toContain('"seq":1');
127+
expect(sleepMock).not.toHaveBeenCalled();
128+
} finally {
129+
rejectWrites = false;
130+
process.stdout.emit("drain");
131+
expect(await running).toBe(stopped);
132+
}
133+
expect(text()).toBe('{"seq":0}\n{"seq":1}\n');
134+
});
135+
136+
it("streams a large record across polls without breaking UTF-8 or dropping its prefix", async () => {
137+
const record = JSON.stringify({ text: "é".repeat(700_000) });
138+
const bytes = Buffer.from(record);
139+
fs.writeFileSync(file, bytes.subarray(0, 600_001));
140+
sleepMock.mockImplementationOnce(async () => {
141+
fs.appendFileSync(file, Buffer.concat([bytes.subarray(600_001), Buffer.from("\n")]));
142+
});
143+
const read = vi.spyOn(fs, "readSync");
144+
await expect(command("tail", "--since", "0")).rejects.toBe(stopped);
145+
expect(Buffer.concat(output)).toEqual(Buffer.concat([bytes, Buffer.from("\n")]));
146+
expect(read.mock.calls.every(([, buffer]) => buffer.byteLength <= 64 * 1024)).toBe(true);
147+
});
148+
149+
it("keeps latency record selection, envelopes, malformed JSON and final EOF semantics", async () => {
150+
fs.writeFileSync(
151+
file,
152+
[
153+
'{"metadata":{"lastTurnLatencyMs":900}}',
154+
"",
155+
'{"call":{"metadata":{"lastTurnLatencyMs":100,"lastTurnListenWaitMs":20}}}',
156+
"invalid JSON",
157+
"null",
158+
'{"metadata":{"lastTurnLatencyMs":300,"lastTurnLatencyMs":200}}',
159+
].join("\n"),
160+
);
161+
await command("latency", "--last", "4");
162+
expect(JSON.parse(text())).toMatchObject({
163+
recordsScanned: 2,
164+
turnLatency: { count: 2, minMs: 100, maxMs: 200, avgMs: 150 },
165+
listenWait: { count: 1, avgMs: 20 },
166+
});
167+
});
168+
169+
it("closes the active descriptor and stops when blocked stdout fails", async () => {
170+
fs.writeFileSync(file, '{"seq":0}\n');
171+
const drainListeners = process.stdout.listenerCount("drain");
172+
const blocked = createDeferred<void>();
173+
const failed = new Error("output pipe failed");
174+
stdout.mockImplementation(() => {
175+
blocked.resolve();
176+
return false;
177+
});
178+
const open = vi.spyOn(fs, "openSync");
179+
const running = command("tail", "--since", "1").catch((error: unknown) => error);
180+
await blocked.promise;
181+
const index = open.mock.calls.findIndex(([target]) => target === file);
182+
const opened = open.mock.results[index];
183+
if (opened?.type !== "return") {
184+
throw new Error("diagnostic command did not open its log");
185+
}
186+
const fd = opened.value;
187+
expect(fs.fstatSync(fd).isFile()).toBe(true);
188+
process.stdout.emit("error", failed);
189+
expect(await running).toBe(failed);
190+
expect(() => fs.fstatSync(fd)).toThrow();
191+
expect(sleepMock).not.toHaveBeenCalled();
192+
expect(process.stdout.listenerCount("drain")).toBe(drainListeners);
193+
});
194+
195+
it("deduplicates retained SQLite snapshots without retaining retired history forever", async () => {
196+
file = path.join(workspace.dir, "calls.jsonl");
197+
const first = { callId: "first", state: "completed" };
198+
const second = { callId: "second", state: "completed" };
199+
historyMock
200+
.mockResolvedValueOnce([first])
201+
.mockResolvedValueOnce([first, second])
202+
.mockResolvedValueOnce([second])
203+
.mockResolvedValueOnce([first])
204+
.mockResolvedValueOnce([first]);
205+
sleepMock
206+
.mockResolvedValueOnce(undefined)
207+
.mockResolvedValueOnce(undefined)
208+
.mockResolvedValueOnce(undefined);
209+
await expect(command("tail", "--since", "1")).rejects.toBe(stopped);
210+
expect(
211+
text()
212+
.trim()
213+
.split("\n")
214+
.map((line) => JSON.parse(line)),
215+
).toEqual([first, second, first]);
216+
});
217+
});

0 commit comments

Comments
 (0)