Skip to content

fix(voice-call): bound diagnostic JSONL reads to prevent OOM on large logs - #111759

Closed
sunlit-deng wants to merge 3 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/local-voice-call-bounded
Closed

sunlit-deng wants to merge 3 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/local-voice-call-bounded

Conversation

@sunlit-deng

@sunlit-deng sunlit-deng commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

openclaw voicecall tail --file <path> bounded its initial JSONL read, but a file growing by more than 1 MB between polls still allocated the entire appended range at once. A partial final JSONL record also needed to survive into the next poll.

Why This Change Was Made

The follow path now reads fixed 64 KiB chunks, emits complete records incrementally, and carries one unfinished record as raw bytes between reads, so UTF-8 code points split at a chunk boundary are decoded only after the complete JSONL record arrives. A single record larger than the existing 1 MB diagnostic limit is discarded through its next newline, keeping retained memory bounded. Initial and follow reads identify the file through fstat on the same descriptor used for reading. When that identity changes, or the same file is truncated, the offset, pending record, and discard state are reset before reading the new contents. The cap applies to existing custom files whose basename is not calls.jsonl; the managed calls.jsonl path continues to use SQLite-backed history.
Every capped omission is now visible: a follow-mode record that crosses the 1 MB cap, an initial read that omits older complete records, and an initial read that starts inside a partial record all emit concise stderr warnings while stdout JSONL stays intact. If the initial retained window is still inside an oversized unfinished record, follow mode keeps discarding through that record's next newline before emitting later complete records.

User Impact

Voice-call diagnostics remain responsive when logs grow quickly, without losing ordinary records that cross chunk or poll boundaries or joining a stale partial record to a replacement file. When eligible custom diagnostic history is omitted by the 1 MB retained window, the operator sees a stderr warning instead of silently incomplete output. This intentionally changes eligible custom-file tail and latency from full-history reads to the newest 1 MB retained window; the filename-gated calls.jsonl SQLite path is unchanged.

Evidence

  • Production CLI proof: ./node_modules/.bin/tsx proof-live.ts registered the real voice-call CLI, started tail, appended 1,150,906 bytes after startup, and completed a JSON record in a later poll.
  • Replacement proof: ./node_modules/.bin/tsx proof-rotation.ts ran the same production CLI, atomically renamed a larger replacement over a file containing an unfinished record, and emitted only the old complete record plus the new file's record.
  • UTF-8 boundary proof: ./node_modules/.bin/tsx proof-utf8.ts placed the first byte of 中 at offset 65,535 of the follow window and verified the production CLI emitted the exact original text after two bounded reads.
  • Cap-omission proof: ./node_modules/.bin/tsx proof-cap-warning.ts ran the same production CLI against a >1 MB follow record and against a file whose last 1 MB starts mid-record; stdout remained valid JSONL and stderr carried exactly one warning per omission path.
  • Initial-window proof: ./node_modules/.bin/tsx proof-initial-window.ts ran the same production CLI at 8c23fcc4858b8beef166ed782a3123c5f8fbd288; a record-boundary cutoff warned about omitted complete history, and an unfinished oversized initial record was discarded through its later newline without emitting its suffix.
  • node scripts/run-vitest.mjs extensions/voice-call/src/cli.test.ts: 21 tests passed, including the >1 MB append, larger replacement identity, split UTF-8, record-boundary omission warning, initial oversized-record discard, and stderr omission-warning regressions.
  • pnpm run lint:plugins:no-extension-test-core-imports, pnpm run test:extensions:package-boundary:compile, and node scripts/report-test-temp-creations.mjs --base 98b222ded8a003a5376c06158d889adf4d8f7f16 --head HEAD --fail-on-findings: passed.
  • pnpm docs:list: passed.
$ ./node_modules/.bin/tsx proof-live.ts
appendedBytes=1150906
tailLines=2002
tailAllValidJson=true
tailFirstSeq=0
tailLastSeq=2001
proof-live.ts
import { spawn } from "node:child_process";
import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { Command } from "commander";
import { registerVoiceCallCli } from "./extensions/voice-call/src/cli.js";

function buildProgram(): Command {
  const program = new Command();
  registerVoiceCallCli({
    program,
    config: {} as never,
    ensureRuntime: async () => ({ manager: {} }) as never,
    logger: { info() {}, warn() {}, error() {}, debug() {} } as never,
  });
  return program;
}

if (process.argv[2] === "--tail" && process.argv[3]) {
  await buildProgram().parseAsync(
    ["voicecall", "tail", "--file", process.argv[3], "--since", "10", "--poll", "50"],
    { from: "user" },
  );
  process.exit(0);
}

const tempRoot = mkdtempSync(path.join(os.tmpdir(), "openclaw-voice-call-follow-proof-"));
const file = path.join(tempRoot, "diagnostics.jsonl");
writeFileSync(file, `${JSON.stringify({ seq: 0 })}\n`, "utf8");

try {
  const records = Array.from({ length: 2_000 }, (_, index) =>
    JSON.stringify({ seq: index + 1, padding: "x".repeat(550) }),
  );
  const appended = `${records.join("\n")}\n`;
  const partial = '{"seq":2001';
  let bulkAppended = false;
  let partialCompleted = false;
  let stdout = "";
  let stderr = "";

  const lines = await new Promise<string[]>((resolve, reject) => {
    const child = spawn(process.execPath, ["--import", "tsx", "proof-live.ts", "--tail", file], {
      stdio: ["ignore", "pipe", "pipe"],
    });
    const timer = setTimeout(() => {
      child.kill("SIGTERM");
      reject(new Error(`tail proof timed out: ${stderr}`));
    }, 15_000);
    child.stdout.on("data", (chunk) => {
      stdout += String(chunk);
      const currentLines = stdout.trim().split("\n").filter(Boolean);
      if (!bulkAppended && currentLines.length >= 1) {
        bulkAppended = true;
        appendFileSync(file, appended + partial, "utf8");
      }
      if (!partialCompleted && currentLines.length >= 2_001) {
        partialCompleted = true;
        appendFileSync(file, "}\n", "utf8");
      }
      if (currentLines.length >= 2_002) {
        child.kill("SIGTERM");
      }
    });
    child.stderr.on("data", (chunk) => {
      stderr += String(chunk);
    });
    child.on("error", reject);
    child.on("close", () => {
      clearTimeout(timer);
      resolve(stdout.trim().split("\n").filter(Boolean));
    });
  });

  const parsed = lines.map((line) => JSON.parse(line) as { seq: number });
  console.log(`appendedBytes=${Buffer.byteLength(appended + partial + "}\n")}`);
  console.log(`tailLines=${lines.length}`);
  console.log(`tailAllValidJson=${parsed.length === lines.length}`);
  console.log(`tailFirstSeq=${parsed.at(0)?.seq}`);
  console.log(`tailLastSeq=${parsed.at(-1)?.seq}`);
} finally {
  rmSync(tempRoot, { recursive: true, force: true });
}
$ ./node_modules/.bin/tsx proof-rotation.ts
replacementDetected=true
replacementLarger=true
tailLines=2
tailAllValidJson=true
tailSeqs=0,1
proof-rotation.ts
import { spawn } from "node:child_process";
import { mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { Command } from "commander";
import { registerVoiceCallCli } from "./extensions/voice-call/src/cli.js";

function buildProgram(): Command {
  const program = new Command();
  registerVoiceCallCli({
    program,
    config: {} as never,
    ensureRuntime: async () => ({ manager: {} }) as never,
    logger: { info() {}, warn() {}, error() {}, debug() {} } as never,
  });
  return program;
}

if (process.argv[2] === "--tail" && process.argv[3]) {
  await buildProgram().parseAsync(
    ["voicecall", "tail", "--file", process.argv[3], "--since", "1", "--poll", "50"],
    { from: "user" },
  );
  process.exit(0);
}

const tempRoot = mkdtempSync(path.join(os.tmpdir(), "openclaw-voice-call-rotation-proof-"));
const file = path.join(tempRoot, "diagnostics.jsonl");
const replacement = path.join(tempRoot, "replacement.jsonl");
const initial = `${JSON.stringify({ seq: 0 })}\n{"old":"unfinished`;
const replacementRecord = JSON.stringify({ seq: 1, padding: "x".repeat(256) });
writeFileSync(file, initial, "utf8");

try {
  let replaced = false;
  let stdout = "";
  let stderr = "";
  const lines = await new Promise<string[]>((resolve, reject) => {
    const child = spawn(
      process.execPath,
      ["--import", "tsx", "proof-rotation.ts", "--tail", file],
      { stdio: ["ignore", "pipe", "pipe"] },
    );
    const timer = setTimeout(() => {
      child.kill("SIGTERM");
      reject(new Error(`rotation proof timed out: ${stderr}`));
    }, 10_000);
    child.stdout.on("data", (chunk) => {
      stdout += String(chunk);
      const currentLines = stdout.trim().split("\n").filter(Boolean);
      if (!replaced && currentLines.length >= 1) {
        replaced = true;
        writeFileSync(replacement, `${replacementRecord}\n`, "utf8");
        renameSync(replacement, file);
      }
      if (currentLines.length >= 2) {
        child.kill("SIGTERM");
      }
    });
    child.stderr.on("data", (chunk) => {
      stderr += String(chunk);
    });
    child.on("error", reject);
    child.on("close", () => {
      clearTimeout(timer);
      resolve(stdout.trim().split("\n").filter(Boolean));
    });
  });

  const parsed = lines.map((line) => JSON.parse(line) as { seq: number });
  console.log(`replacementDetected=${replaced}`);
  console.log(`replacementLarger=${Buffer.byteLength(replacementRecord) > Buffer.byteLength(initial)}`);
  console.log(`tailLines=${lines.length}`);
  console.log(`tailAllValidJson=${parsed.length === lines.length}`);
  console.log(`tailSeqs=${parsed.map((entry) => entry.seq).join(",")}`);
} finally {
  rmSync(tempRoot, { recursive: true, force: true });
}
$ ./node_modules/.bin/tsx proof-utf8.ts
utf8BoundaryByteOffset=65535
tailLines=2
tailAllValidJson=true
tailTextExact=true
tailTextEndsWith=中
proof-utf8.ts
import { spawn } from "node:child_process";
import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { Command } from "commander";
import { registerVoiceCallCli } from "./extensions/voice-call/src/cli.js";

function buildProgram(): Command {
  const program = new Command();
  registerVoiceCallCli({
    program,
    config: {} as never,
    ensureRuntime: async () => ({ manager: {} }) as never,
    logger: { info() {}, warn() {}, error() {}, debug() {} } as never,
  });
  return program;
}

if (process.argv[2] === "--tail" && process.argv[3]) {
  await buildProgram().parseAsync(
    ["voicecall", "tail", "--file", process.argv[3], "--since", "1", "--poll", "50"],
    { from: "user" },
  );
  process.exit(0);
}

const tempRoot = mkdtempSync(path.join(os.tmpdir(), "openclaw-voice-call-utf8-proof-"));
const file = path.join(tempRoot, "diagnostics.jsonl");
const recordPrefix = '{"seq":1,"text":"';
const boundaryByteOffset = 64 * 1024 - 1;
const text = `${"x".repeat(boundaryByteOffset - Buffer.byteLength(recordPrefix))}中`;
const record = `${recordPrefix}${text}"}`;
writeFileSync(file, `${JSON.stringify({ seq: 0 })}\n`, "utf8");

try {
  let appended = false;
  let stdout = "";
  let stderr = "";
  const lines = await new Promise<string[]>((resolve, reject) => {
    const child = spawn(process.execPath, ["--import", "tsx", "proof-utf8.ts", "--tail", file], {
      stdio: ["ignore", "pipe", "pipe"],
    });
    child.stdout.setEncoding("utf8");
    child.stderr.setEncoding("utf8");
    const timer = setTimeout(() => {
      child.kill("SIGTERM");
      reject(new Error(`UTF-8 proof timed out: ${stderr}`));
    }, 10_000);
    child.stdout.on("data", (chunk) => {
      stdout += chunk;
      const currentLines = stdout.trim().split("\n").filter(Boolean);
      if (!appended && currentLines.length >= 1) {
        appended = true;
        appendFileSync(file, `${record}\n`, "utf8");
      }
      if (currentLines.length >= 2) {
        child.kill("SIGTERM");
      }
    });
    child.stderr.on("data", (chunk) => {
      stderr += chunk;
    });
    child.on("error", reject);
    child.on("close", () => {
      clearTimeout(timer);
      resolve(stdout.trim().split("\n").filter(Boolean));
    });
  });

  const parsed = lines.map((line) => JSON.parse(line) as { seq: number; text?: string });
  console.log(`utf8BoundaryByteOffset=${boundaryByteOffset}`);
  console.log(`tailLines=${lines.length}`);
  console.log(`tailAllValidJson=${parsed.length === lines.length}`);
  console.log(`tailTextExact=${parsed[1]?.text === text}`);
  console.log(`tailTextEndsWith=${parsed[1]?.text?.at(-1)}`);
} finally {
  rmSync(tempRoot, { recursive: true, force: true });
}
$ ./node_modules/.bin/tsx proof-cap-warning.ts
followOversizedRecordBytes=1100023
followDiscardWarnings=1
followDiscardWarning=voicecall: discarding a JSONL record larger than 1000000 bytes while following <tmp>/diagnostics.jsonl
followTailLines=2
followTailAllValidJson=true
followTailSeqs=0,2
latencyWarnings=1
latencyWarning=voicecall: skipped 999904 bytes of a partial JSONL record at the start of the capped read (<tmp>/crossing.jsonl)
latencyRecordsScanned=2
tailWarnings=1
tailWarning=voicecall: skipped 999904 bytes of a partial JSONL record at the start of the capped read (<tmp>/crossing.jsonl)
tailLines=2
tailAllValidJson=true
proof-cap-warning.ts
import { spawn } from "node:child_process";
import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { Command } from "commander";
import { registerVoiceCallCli } from "./extensions/voice-call/src/cli.js";

function buildProgram(): Command {
  const program = new Command();
  registerVoiceCallCli({
    program,
    config: {} as never,
    ensureRuntime: async () => ({ manager: {} }) as never,
    logger: { info() {}, warn() {}, error() {}, debug() {} } as never,
  });
  return program;
}

if (process.argv[2] === "--tail" && process.argv[3]) {
  const since = process.argv[4] === "--since" ? process.argv[5] : "1";
  await buildProgram().parseAsync(
    ["voicecall", "tail", "--file", process.argv[3], "--since", since, "--poll", "50"],
    { from: "user" },
  );
  process.exit(0);
}

if (process.argv[2] === "--latency" && process.argv[3]) {
  await buildProgram().parseAsync(["voicecall", "latency", "--file", process.argv[3]], {
    from: "user",
  });
  process.exit(0);
}

function runCli(
  args: string[],
  onOutput: (lines: string[], stderr: string, kill: () => void) => void,
): Promise<{ stdout: string; stderr: string }> {
  return new Promise((resolve, reject) => {
    const child = spawn(
      process.execPath,
      ["--import", "tsx", "proof-cap-warning.ts", ...args],
      { stdio: ["ignore", "pipe", "pipe"] },
    );
    child.stdout.setEncoding("utf8");
    child.stderr.setEncoding("utf8");
    let stdout = "";
    let stderr = "";
    const timer = setTimeout(() => {
      child.kill("SIGTERM");
      reject(new Error(`cap-warning proof timed out: ${stderr}`));
    }, 15_000);
    const emit = () =>
      onOutput(stdout.trim().split("\n").filter(Boolean), stderr, () => child.kill("SIGTERM"));
    child.stdout.on("data", (chunk) => {
      stdout += chunk;
      emit();
    });
    child.stderr.on("data", (chunk) => {
      stderr += chunk;
      emit();
    });
    child.on("error", reject);
    child.on("close", () => {
      clearTimeout(timer);
      resolve({ stdout, stderr });
    });
  });
}

const tempRoot = mkdtempSync(path.join(os.tmpdir(), "openclaw-voice-call-cap-warning-proof-"));
const file = path.join(tempRoot, "diagnostics.jsonl");
const crossingFile = path.join(tempRoot, "crossing.jsonl");
const oversizedRecord = `${JSON.stringify({ seq: 1, padding: "x".repeat(1_100_000) })}\n`;
const tailRecord = `${JSON.stringify({ seq: 2 })}\n`;
const crossingRecord = JSON.stringify({ padding: "x".repeat(1_000_000) });
const completeRecords = [
  JSON.stringify({ call: { metadata: { lastTurnLatencyMs: 120 } } }),
  JSON.stringify({ call: { metadata: { lastTurnLatencyMs: 240 } } }),
];

try {
  writeFileSync(file, `${JSON.stringify({ seq: 0 })}\n`, "utf8");
  writeFileSync(crossingFile, [crossingRecord, ...completeRecords].join("\n") + "\n", "utf8");

  let discarded = false;
  let tailWritten = false;
  const follow = await runCli(["--tail", file], (lines, stderr, kill) => {
    if (!discarded && lines.length >= 1) {
      discarded = true;
      appendFileSync(file, oversizedRecord, "utf8");
    }
    if (!tailWritten && stderr.includes("discarding a JSONL record larger than")) {
      tailWritten = true;
      appendFileSync(file, tailRecord, "utf8");
    }
    if (lines.length >= 2) {
      kill();
    }
  });

  const followLines = follow.stdout.trim().split("\n").filter(Boolean);
  const followWarnings = follow.stderr
    .split("\n")
    .filter((line) => line.includes("discarding a JSONL record larger than"));
  const parsedFollow = followLines.map((line) => JSON.parse(line) as { seq: number });

  const latency = await runCli(["--latency", crossingFile], () => {});
  const latencyParsed = JSON.parse(latency.stdout.trim()) as { recordsScanned: number };
  const latencyWarnings = latency.stderr
    .split("\n")
    .filter((line) => line.includes("of a partial JSONL record at the start of the capped read"));

  const tail = await runCli(["--tail", crossingFile, "--since", "10"], (lines, _stderr, kill) => {
    if (lines.length >= 2) {
      kill();
    }
  });
  const tailLines = tail.stdout.trim().split("\n").filter(Boolean);
  const tailWarnings = tail.stderr
    .split("\n")
    .filter((line) => line.includes("of a partial JSONL record at the start of the capped read"));

  console.log(`followOversizedRecordBytes=${Buffer.byteLength(oversizedRecord)}`);
  console.log(`followDiscardWarnings=${followWarnings.length}`);
  console.log(`followDiscardWarning=${followWarnings.at(0) ?? ""}`);
  console.log(`followTailLines=${followLines.length}`);
  console.log(`followTailAllValidJson=${parsedFollow.length === followLines.length}`);
  console.log(`followTailSeqs=${parsedFollow.map((entry) => entry.seq).join(",")}`);
  console.log(`latencyWarnings=${latencyWarnings.length}`);
  console.log(`latencyWarning=${latencyWarnings.at(0) ?? ""}`);
  console.log(`latencyRecordsScanned=${latencyParsed.recordsScanned}`);
  console.log(`tailWarnings=${tailWarnings.length}`);
  console.log(`tailWarning=${tailWarnings.at(0) ?? ""}`);
  console.log(`tailLines=${tailLines.length}`);
  console.log(`tailAllValidJson=${tailLines.every((line) => JSON.parse(line))}`);
} finally {
  rmSync(tempRoot, { recursive: true, force: true });
}
$ ./node_modules/.bin/tsx proof-initial-window.ts
headSha=8c23fcc4858b8beef166ed782a3123c5f8fbd288
latencyBoundaryRecordsScanned=1
latencyBoundaryTurnLatencyCount=1
latencyBoundaryWarnedWholeOmission=true
latencyBoundaryWarnedPartialRecord=false
initialDiscardLines=1
initialDiscardAllValidJson=true
initialDiscardSeqs=1
initialDiscardEmittedOversizedSuffix=false
initialDiscardWarnedPartialRecord=true
proof-initial-window.ts
import { execFileSync, spawn } from "node:child_process";
import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { Command } from "commander";
import { registerVoiceCallCli } from "./extensions/voice-call/src/cli.js";

function buildProgram(): Command {
  const program = new Command();
  registerVoiceCallCli({
    program,
    config: {} as never,
    ensureRuntime: async () => ({ manager: {} }) as never,
    logger: { info() {}, warn() {}, error() {}, debug() {} } as never,
  });
  return program;
}

if (process.argv[2] === "--tail" && process.argv[3]) {
  await buildProgram().parseAsync(
    ["voicecall", "tail", "--file", process.argv[3], "--since", "10", "--poll", "50"],
    { from: "user" },
  );
  process.exit(0);
}

async function runLatencyBoundaryProof(tempRoot: string): Promise<void> {
  const file = path.join(tempRoot, "boundary.jsonl");
  const oldRecord = JSON.stringify({ call: { metadata: { lastTurnLatencyMs: 999 } } });
  const retainedPrefix = '{"call":{"metadata":{"lastTurnLatencyMs":120},"padding":"';
  const retainedSuffix = '"}}\n';
  const retainedRecord = `${retainedPrefix}${"x".repeat(
    1_000_000 -
      Buffer.byteLength(retainedPrefix, "utf8") -
      Buffer.byteLength(retainedSuffix, "utf8"),
  )}${retainedSuffix}`;
  writeFileSync(file, `${oldRecord}\n${retainedRecord}`, "utf8");

  let stdout = "";
  let stderr = "";
  const originalStdoutWrite = process.stdout.write.bind(process.stdout);
  const originalStderrWrite = process.stderr.write.bind(process.stderr);
  process.stdout.write = ((chunk: unknown) => {
    stdout += String(chunk);
    return true;
  }) as typeof process.stdout.write;
  process.stderr.write = ((chunk: unknown) => {
    stderr += String(chunk);
    return true;
  }) as typeof process.stderr.write;
  try {
    await buildProgram().parseAsync(["voicecall", "latency", "--file", file], { from: "user" });
  } finally {
    process.stdout.write = originalStdoutWrite;
    process.stderr.write = originalStderrWrite;
  }

  const parsed = JSON.parse(stdout) as {
    recordsScanned?: number;
    turnLatency?: { count?: number };
  };
  console.log(`latencyBoundaryRecordsScanned=${parsed.recordsScanned}`);
  console.log(`latencyBoundaryTurnLatencyCount=${parsed.turnLatency?.count}`);
  console.log(`latencyBoundaryWarnedWholeOmission=${stderr.includes("earlier JSONL bytes")}`);
  console.log(`latencyBoundaryWarnedPartialRecord=${stderr.includes("partial JSONL record")}`);
}

async function runInitialDiscardProof(tempRoot: string): Promise<void> {
  const file = path.join(tempRoot, "initial-discard.jsonl");
  writeFileSync(file, `{"padding":"${"x".repeat(1_100_000)}`, "utf8");

  let stdout = "";
  let stderr = "";
  const lines = await new Promise<string[]>((resolve, reject) => {
    const child = spawn(
      process.execPath,
      ["--import", "tsx", "proof-initial-window.ts", "--tail", file],
      { stdio: ["ignore", "pipe", "pipe"] },
    );
    const appendTimer = setTimeout(() => {
      appendFileSync(file, `"}\n${JSON.stringify({ seq: 1 })}\n`, "utf8");
    }, 200);
    const stopTimer = setTimeout(() => {
      child.kill("SIGTERM");
      reject(new Error(`initial discard proof timed out: ${stderr}`));
    }, 10_000);
    child.stdout.on("data", (chunk) => {
      stdout += String(chunk);
      const currentLines = stdout.trim().split("\n").filter(Boolean);
      if (currentLines.length >= 1) {
        child.kill("SIGTERM");
      }
    });
    child.stderr.on("data", (chunk) => {
      stderr += String(chunk);
    });
    child.on("error", reject);
    child.on("close", () => {
      clearTimeout(appendTimer);
      clearTimeout(stopTimer);
      resolve(stdout.trim().split("\n").filter(Boolean));
    });
  });

  const parsed = lines.map((line) => JSON.parse(line) as { seq?: number });
  console.log(`initialDiscardLines=${lines.length}`);
  console.log(`initialDiscardAllValidJson=${parsed.length === lines.length}`);
  console.log(`initialDiscardSeqs=${parsed.map((entry) => entry.seq).join(",")}`);
  console.log(`initialDiscardEmittedOversizedSuffix=${stdout.includes("padding")}`);
  console.log(`initialDiscardWarnedPartialRecord=${stderr.includes("partial JSONL record")}`);
}

const tempRoot = mkdtempSync(path.join(os.tmpdir(), "openclaw-voice-call-initial-window-proof-"));
try {
  console.log(`headSha=${execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim()}`);
  await runLatencyBoundaryProof(tempRoot);
  await runInitialDiscardProof(tempRoot);
} finally {
  rmSync(tempRoot, { recursive: true, force: true });
}

AI-assisted: built with Codex

@openclaw-barnacle openclaw-barnacle Bot added channel: voice-call Channel integration: voice-call size: XS labels Jul 20, 2026
@sunlit-deng
sunlit-deng marked this pull request as draft July 20, 2026 09:09
@sunlit-deng
sunlit-deng marked this pull request as ready for review July 20, 2026 09:09
@sunlit-deng
sunlit-deng force-pushed the sunlit/fix/local-voice-call-bounded branch from f04505a to 5195abc Compare July 20, 2026 09:24
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 20, 2026
@clawsweeper

clawsweeper Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 25, 2026, 4:05 AM ET / 08:05 UTC.

ClawSweeper review

What this changes

The PR caps custom voice-call diagnostic JSONL reads at 1 MB, follows appended records in 64 KiB chunks, and warns operators when retained history omits data.

Regression provenance

Possible regression — probable (reviewed change; reproduction). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open. Current main still reads whole custom diagnostic files, while this PR bounds both startup and follow-mode reads; the latest docs fix the prior filename-sentinel finding and no new blocking correctness defect was found.

Priority: P2
Reviewed head: 8c23fcc4858b8beef166ed782a3123c5f8fbd288

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The bounded-reader patch has direct terminal proof and focused behavior coverage, with only the deliberate retained-history compatibility tradeoff remaining for merge validation.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR body includes after-fix terminal evidence from the registered production voice-call CLI for oversized appends, rotation, UTF-8 chunk boundaries, and capped-history warnings.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body includes after-fix terminal evidence from the registered production voice-call CLI for oversized appends, rotation, UTF-8 chunk boundaries, and capped-history warnings.
Evidence reviewed 7 items Current-main behavior: Current main loads an entire existing custom file with readFileSync, and follow mode allocates the full appended range from stat.size - offset; this leaves both paths unbounded.
Bounded reader: The PR reads the initial retained window through one descriptor and caps follow reads to 64 KiB chunks, retaining raw bytes only until a complete JSONL record is available.
Owner boundary and compatibility routing: Only existing custom paths whose basename is not calls.jsonl take the bounded file reader; the managed path retains the established SQLite-history flow.
Findings None None.
Security None None.

Live Verification

Command: pnpm openclaw voicecall tail --help

Result: FAIL (partial) — step 2 expect_output --poll ‹ms›: expected terminal output was not visible within 30 seconds: "--poll ‹ms›"

pnpm openclaw voicecall tail --helprunner@runnervm76f27:/tmp/clawsweeper-live-proof-111759-CCrhlj/target$ pnpm openclaw voicecall tail --help
pnpm openclaw voicecall tail --help
$ node scripts/run-node.mjs voicecall tail --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 400.66 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 105.10 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

[tsdown-build] invocation 2/2 finished in 13.7s
[plugin-control-plane-loads] verified 36 built modules with native require and checked doctor closures
runtime-postbuild: 10 phases completed in 4192ms (slowest: built plugin control-plane loads 3482ms)
│
◇
The ˋopenclaw voicecallˋ command is provided by the "voice-call" plugin, but that bundled plugin is disabled by default. Run ˋopenclaw plugins enable voice-call
ˋ to enable that CLI surface.
[ELIFECYCLE] Command failed with exit code 1.
runner@runnervm76f27:/tmp/clawsweeper-live-proof-111759-CCrhlj/target$ pnpm openclaw voicecall tail --help
$ node scripts/run-node.mjs voicecall tail --help
│
◇
The ˋopenclaw voicecallˋ co
… output truncated …

Assertions:

  • FAIL expect_output: --poll ‹ms›

How this fits together

The voice-call plugin registers tail and latency CLI commands. Managed calls.jsonl paths use SQLite-backed call history, while existing custom files are parsed as diagnostic JSONL and printed as records or latency summaries.

flowchart LR
  A[Operator CLI command] --> B[Voice-call diagnostic command]
  B --> C{Managed calls.jsonl path?}
  C -->|Yes| D[SQLite-backed call history]
  C -->|No| E[Custom JSONL reader]
  E --> F[Bounded chunk and record handling]
  D --> G[CLI JSON or JSONL output]
  F --> G
Loading

Before merge

  • Resolve merge risk (P1) - Merging intentionally changes existing custom diagnostic-file tail and latency commands from full-history reads to the newest 1 MB; operators with older relevant records receive a stderr warning but no longer see those records.
  • Resolve merge risk (P1) - The PR is behind current main, so merge-read and exact-head CI must validate the final merged result; GitHub currently reports it cleanly mergeable.
  • Complete next step (P2) - No mechanical repair is needed: the reviewed branch has no blocking finding, while CI and the documented compatibility tradeoff remain normal merge gates.
Agent review details

Security

None.

PR surface

Source +214, Tests +293, Docs +13. Total +520 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 241 27 +214
Tests 1 293 0 +293
Docs 1 13 0 +13
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 547 27 +520

Review metrics

Metric Value Why it matters
Production versus test LOC production +241/-27 (net +214); docs +13; tests +293 The production growth implements bounded reads, rotation handling, and operator warnings; the expanded regression coverage exercises the new record-boundary cases.

Merge-risk options

Maintainer options:

  1. Accept the documented retained-window behavior (recommended)
    Merge after exact-head validation, accepting that custom diagnostic files retain only their newest 1 MB while managed SQLite history remains unchanged.
  2. Keep full custom-file history
    Pause this PR if preserving complete history for arbitrary custom diagnostic files outweighs the bounded-memory guarantee.

Technical review

Best possible solution:

Retain the documented SQLite/custom-file split and land the bounded reader once the final merge result has green exact-head checks.

Do we have a high-confidence way to reproduce the issue?

Yes: current main's custom-file path directly performs whole-file and whole-appended-range allocations, and the PR body supplies after-fix terminal traces for a larger-than-1-MB append and partial-record completion.

Is this the best way to solve the issue?

Yes: bounding reads at the custom-file CLI owner preserves the managed SQLite path and handles partial records, UTF-8, truncation, and replacement files without adding a new configuration surface.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 876f2de46f1a.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes after-fix terminal evidence from the registered production voice-call CLI for oversized appends, rotation, UTF-8 chunk boundaries, and capped-history warnings.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This prevents an operator-triggered diagnostic memory blowup on a limited custom-file CLI path.
  • merge-risk: 🚨 compatibility: Existing custom diagnostic files change from complete-history reads to a documented newest-1-MB retained window.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes after-fix terminal evidence from the registered production voice-call CLI for oversized appends, rotation, UTF-8 chunk boundaries, and capped-history warnings.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes after-fix terminal evidence from the registered production voice-call CLI for oversized appends, rotation, UTF-8 chunk boundaries, and capped-history warnings.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Current-main blame and recent history place the prior custom-log implementation and later voice-call CLI maintenance in this area. (role: recent area contributor; confidence: high; commits: 0a79ae5fd040, 75fcaba9191e; files: extensions/voice-call/src/cli-call-log.ts, extensions/voice-call/src/cli.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Let exact-head checks complete against the final merge result.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (28 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-03T15:49:10.503Z sha 7f0b4811ae083e3aabeebe68a6ef59ef209db642 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-04T03:25:57.627Z sha a436f88ea27961dc5e8d197b64d840315dbef8b1 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-10T17:02:02.911Z sha 646db9f5a042fedbae472011b1da4a3939e1d5b1 :: found issues before merge. :: [P1] Keep discarding an initial oversized record until its newline | [P2] Report whole-record omissions from capped initial reads
  • reviewed 2026-08-11T06:10:31.569Z sha 852a9c85d76faf9db88df67878dc2e8b74fd787b :: needs maintainer review before merge. :: none
  • reviewed 2026-08-16T08:14:36.301Z sha 2a2b7c8754c96d952378a1f18dff97acf0eb55f5 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-19T02:15:33.725Z sha a9c9ff5 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-25T03:47:55.993Z sha a9c9ff5 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-25T03:52:55.943Z sha a9c9ff5 :: needs changes before merge. :: [P2] Qualify the custom-file claim by the filename sentinel

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 20, 2026
@sunlit-deng
sunlit-deng force-pushed the sunlit/fix/local-voice-call-bounded branch from 5195abc to a9a1294 Compare July 20, 2026 14:11
@sunlit-deng

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 20, 2026
@sunlit-deng
sunlit-deng force-pushed the sunlit/fix/local-voice-call-bounded branch 3 times, most recently from 3129517 to ea238b2 Compare July 24, 2026 03:04
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jul 25, 2026
@clawsweeper

clawsweeper Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 3, 2026
@sunlit-deng
sunlit-deng force-pushed the sunlit/fix/local-voice-call-bounded branch 2 times, most recently from a436f88 to 646db9f Compare August 10, 2026 15:21
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 10, 2026
@sunlit-deng
sunlit-deng force-pushed the sunlit/fix/local-voice-call-bounded branch from 646db9f to 852a9c8 Compare August 11, 2026 05:38
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: L and removed size: M labels Aug 11, 2026
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 11, 2026
@sunlit-deng
sunlit-deng force-pushed the sunlit/fix/local-voice-call-bounded branch from 852a9c8 to 2a2b7c8 Compare August 16, 2026 08:08
@sunlit-deng
sunlit-deng force-pushed the sunlit/fix/local-voice-call-bounded branch from 2a2b7c8 to a9c9ff5 Compare August 19, 2026 02:07
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 25, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Superseded by #134838, now landed in 9607d302c6f. Thanks @sunlit-deng for identifying the diagnostic allocation problem; your contribution is credited in the replacement.

The shared reader covers custom-log startup and follow reads, partial UTF-8 records, replacement/observed truncation, and stdout backpressure. It preserves requested history instead of introducing the proposed 1 MB history/record cap, so cap-omission warnings are intentionally not carried forward. The same repair also bounds SQLite tail deduplication and fixes initial --since 0/--since 1 backfill.

Proof includes 41 owner/store/CLI cases, failure-first regressions, exact-output real CLI ordering, and a paused stdout pipe: the same 8,481,706-byte append produced identical output while queued bytes fell from 4,242,477 to 66,207. Final CI and independent review passed. This proves the diagnostic allocation/backpressure repair, not a measured OOM or carrier-call result.

Closing this older implementation now that the underlying problem is handled by the canonical reader on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: voice-call Channel integration: voice-call docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L stale Marked as stale due to inactivity status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants