Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions scripts/live-files.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ export const LIVE_FILES = [
"tests/pack-install.test.ts",
// Runs the Linux janitor shell against per-case local API fixtures; no ports or credentials.
"tests/ci-janitor-fork-heads.test.ts",
// Heap-bounded log readers in isolated children; private files, no sockets.
"tests/web-logs-query.test.ts",
];

/** Band width per live file: the zone ladder drifts +1 per EADDRINUSE retry;
Expand Down
20 changes: 11 additions & 9 deletions src/web/logs-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ class Tail {
this.seen += 1;
}

clear(): void {
this.seen = 0;
}

/** Selected rows kept, and the number discarded by the cap. */
counts(): { kept: number; omitted: number } {
const kept = Math.min(this.seen, this.cap);
Expand Down Expand Up @@ -253,9 +257,8 @@ async function windowSelection(
readOpts: ReadLogLinesOptions,
): Promise<LogQueryResult> {
const tail = new Tail(n);
// Lead-in rows accepted by the backward walk, oldest first, discarded the
// moment a row fails the walk (an accepted lead-in is contiguous).
let leadIn: string[] = [];
// Keep pending lead-in rows in the same bounded tail. Its count includes
// discarded rows, so omitted stays exact even before the first hit.
let inherited = NaN;
let inRange = false;
let index = 0;
Expand All @@ -268,17 +271,13 @@ async function windowSelection(
if (!inRange) {
if (hit) {
inRange = true;
// Accepted lead-in rows are non-hits by construction: the hit
// branch would have consumed them otherwise.
for (const row of leadIn) tail.push(row, false);
leadIn = [];
tail.push(line, true);
} else if (Number.isFinite(ts) && ts >= loT) {
leadIn.push(line);
tail.push(line, false);
} else {
// The backward walk stops before this row: nothing held is
// contiguous with the upcoming hit any more.
leadIn = [];
tail.clear();
}
} else if (index <= lastHitIndex) {
// Span between the hits: unconditionally inside the range.
Expand All @@ -297,6 +296,9 @@ async function windowSelection(
index += 1;
}

// Rotation can remove every hit between the two passes. Pending context
// alone was never selected, even if its timestamps still fit the window.
if (!inRange) tail.clear();
const { lines, flags } = tail.take();
const { omitted } = tail.counts();
return { total, shown: lines.length, omitted, lines, isMatch: flags };
Expand Down
5 changes: 5 additions & 0 deletions tests/e2e/e2e-native-dsh-persona.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,11 @@ function buildRig(tag: string, withAutoReview: boolean): Rig {

const env: NodeJS.ProcessEnv = {
...cleanEnv(),
// Pure-sqlite default (5a80e2b8e, #6480) turns the JSON envelope
// writer OFF, but this lane asserts on the on-disk .json session
// envelope. Pin the writer ON so the envelope this test was written
// for is still produced regardless of the storage-mode default.
BILI_STORAGE_JSON_WRITER: "on",
HOME: home,
TMPDIR: tmp,
DSH_HOME: dshHome,
Expand Down
5 changes: 5 additions & 0 deletions tests/e2e/e2e-native-dsh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,11 @@ function dshRun(
cwd: ctx.dshCwd,
env: {
...cleanEnv(),
// Pure-sqlite default (5a80e2b8e, #6480) turns the JSON envelope
// writer OFF, but this lane asserts on the on-disk .json session
// file. Pin the writer ON so the envelope this test was written for
// is still produced regardless of the storage-mode default.
BILI_STORAGE_JSON_WRITER: "on",
HOME: ctx.homeDir,
TMPDIR: ctx.tmpDir,
DSH_HOME: ctx.dshHome,
Expand Down
5 changes: 5 additions & 0 deletions tests/e2e/e2e-native-opencode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,11 @@ async function ocRun(
cwd: ctx.ocCwd,
env: {
...cleanEnv(),
// Pure-sqlite default (5a80e2b8e, #6480) turns the JSON envelope
// writer OFF, but this lane asserts on the on-disk .json session
// file. Pin the writer ON so the envelope this test was written for
// is still produced regardless of the storage-mode default.
BILI_STORAGE_JSON_WRITER: "on",
HOME: ctx.homeDir,
TMPDIR: ctx.tmdir,
XDG_CONFIG_HOME: ctx.xdg.config,
Expand Down
9 changes: 7 additions & 2 deletions tests/e2e/e2e-native-pi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,8 +468,13 @@ function piRun(
// (CI sentinel incident, #4599). Pin the legacy posture so this
// coverage stays deterministic; inline posture is covered by
// tests/pi-inline-ws.test.ts and tests/pi-native.test.ts.
BILI_PI_INLINE: "0",
PI_CODING_AGENT_DIR: ctx.piAgentDir,
BILI_PI_INLINE: "0",
// Pure-sqlite default (5a80e2b8e, #6480) turns the JSON envelope
// writer OFF, but this lane asserts on the on-disk .json session
// file. Pin the writer ON so the envelope this test was written for
// is still produced regardless of the storage-mode default.
BILI_STORAGE_JSON_WRITER: "on",
PI_CODING_AGENT_DIR: ctx.piAgentDir,
XDG_CONFIG_HOME: ctx.xdg.config,
XDG_CACHE_HOME: ctx.xdg.cache,
XDG_STATE_HOME: ctx.xdg.state,
Expand Down
6 changes: 6 additions & 0 deletions tests/e2e/e2e-pi-codex-ws.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,12 @@ function piRun(
cwd: ctx.piCwd,
env: {
...cleanEnv(opts.extraEnv),
// Pure-sqlite default (5a80e2b8e, #6480) turns the JSON
// envelope writer OFF, but this lane asserts on the on-disk
// .json session file. Pin the writer ON so the envelope this
// test was written for is still produced regardless of the
// storage-mode default.
BILI_STORAGE_JSON_WRITER: "on",
PI_CODING_AGENT_DIR: ctx.piAgentDir,
XDG_CONFIG_HOME: ctx.xdg.config,
XDG_CACHE_HOME: ctx.xdg.cache,
Expand Down
5 changes: 5 additions & 0 deletions tests/e2e/e2e-subagent-sessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,11 @@ async function ocRun(
cwd: ctx.ocCwd,
env: {
...cleanEnv(),
// Pure-sqlite default (5a80e2b8e, #6480) turns the JSON envelope
// writer OFF, but this lane asserts on the on-disk .json session
// file. Pin the writer ON so the envelope this test was written for
// is still produced regardless of the storage-mode default.
BILI_STORAGE_JSON_WRITER: "on",
HOME: ctx.homeDir,
TMPDIR: ctx.tmdir,
XDG_CONFIG_HOME: ctx.xdg.config,
Expand Down
5 changes: 5 additions & 0 deletions tests/e2e/e2e-update-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,11 @@ test("self-update keeps live compression state: folds survive the OLD→NEW hop
envBase.BILI_UPDATE_POLICY_URL = "http://127.0.0.1:1/no-policy.json";
envBase.BILI_PERSIST_DEBOUNCE_MS = "200";
envBase.BILI_SESSIONS_DIR = sessionsDir;
// Pure-sqlite default (5a80e2b8e, #6480) turns the JSON envelope
// writer OFF, but this lane asserts on the on-disk .json session file
// (state survival across the update). Pin the writer ON so the
// envelope this test was written for is still produced.
envBase.BILI_STORAGE_JSON_WRITER = "on";

const port = await freePort();
proxy = spawnProxy(installDir, port, envBase);
Expand Down
6 changes: 6 additions & 0 deletions tests/fork-ccr-adoption.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ import { maybeAdoptForkBlocks } from "../src/fork-adoption.ts";
import { rmrf } from "./tmp-rm.ts";

process.env.BILI_PERSIST = "0";
// Pure-sqlite default (5a80e2b8e, #6480) turns the JSON envelope writer OFF,
// so the per-session CCR content-store sidecar (.content-store.json) this
// suite asserts on is never written. Pin the writer ON at module load (before
// any SessionStore is constructed) so the companion-envelope coverage this
// test was written for still runs regardless of the storage-mode default.
process.env.BILI_STORAGE_JSON_WRITER = "on";

const LIMIT = 200_000;
const META = { protocol: "openai" as const, upstreamOrigin: "http://upstream.example/v1" };
Expand Down
5 changes: 5 additions & 0 deletions tests/notice-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ const cfgPath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "notice-reg-cfg-
process.env.DSH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "notice-reg-dsh-"));
process.env.XDG_STATE_HOME = stateDir;
process.env.BILI_CONFIG_FILE = cfgPath;
// #4011 lesson: this suite asserts the pure-sqlite default notice is visible,
// which requires the pure-sqlite SELECTION (unified "sqlite" or absent — the
// gate is unifiedSelectionIsSqlite, not the resolved mode). The suite baseline
// preload pins "legacy" for the broad corpus, so pin the selection explicitly.
process.env.BILI_STORAGE_UNIFIED = "sqlite";

// This suite asserts the PRODUCTION default storage posture. The CI corpus
// baseline (tests/preload-storage-baseline.mjs, #2815) forces
Expand Down
12 changes: 11 additions & 1 deletion tests/plugin-fork.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,12 @@ test("HTTP CCR shared payload deletion fails closed before persistence", { timeo

for (const corruption of ["missing-ref", "missing-payload", "orphan-payload", "wrong-raw-alias", "changed-payload"] as const) {
test(`HTTP CCR ${corruption} fails closed after cold disk restore`, async () => {
// The corrupted-store detection path needs the JSON content-store
// sidecar on disk. Under the pure-sqlite default (5a80e2b8e) the
// JSON writer is OFF, so pin it ON to keep exercising the envelope
// corruption path this test was written for.
const oldJsonWriter = process.env.BILI_STORAGE_JSON_WRITER;
process.env.BILI_STORAGE_JSON_WRITER = "on";
const h = await harness(true);
try {
const parent = resolveConversation("parent").session!;
Expand Down Expand Up @@ -966,7 +972,11 @@ for (const corruption of ["missing-ref", "missing-payload", "orphan-payload", "w
assert.equal(parentState(), before);
assert.equal(readFileSync(path, "utf8"), JSON.stringify(disk));
store2.closeQuietly();
} finally { await h.close(); }
} finally {
if (oldJsonWriter === undefined) delete process.env.BILI_STORAGE_JSON_WRITER;
else process.env.BILI_STORAGE_JSON_WRITER = oldJsonWriter;
await h.close();
}
});
}

Expand Down
68 changes: 67 additions & 1 deletion tests/web-logs-query.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { tmpdir } from "node:os";
import * as path from "node:path";
import { queryLogFiles } from "../src/web/logs-query.ts";
Expand Down Expand Up @@ -159,3 +161,67 @@ test("time-window view reports each unreadable generation once across passes", a
rmSync(dir, { recursive: true, force: true });
}
});

test("time-window lead-in stays bounded when the retained log exceeds the heap", () => {
const dir = mkdtempSync(path.join(tmpdir(), "logs-window-memory-"));
try {
const file = path.join(dir, "active.log");
const before = mkLine(0, "x".repeat(990));
const hit = mkLine(0, "needle");
const batch = `${before}\n`.repeat(1000);
writeFileSync(file, "");
for (let i = 0; i < 100; i++) appendFileSync(file, batch);
appendFileSync(file, `${hit}\n`);
const source = `
import { queryLogFiles } from './src/web/logs-query.ts';
const result = await queryLogFiles([process.argv[1]], 'needle',
{ ctx: 0, winSec: Number(process.argv[2]), n: 3 });
console.log(JSON.stringify(result));
`;
const run = (winSec: number) => {
const child = spawnSync(process.execPath, [
"--max-old-space-size=64", "--import", "./tests/preload-test-env.mjs",
"--import", "tsx", "--input-type=module", "--eval", source, file, String(winSec),
], { cwd: fileURLToPath(new URL("../", import.meta.url)), encoding: "utf8", timeout: 60_000 });
assert.equal(child.error, undefined);
assert.equal(child.status, 0, child.stderr);
return JSON.parse(child.stdout) as Awaited<ReturnType<typeof queryLogFiles>>;
};
assert.deepEqual(run(0).lines, [hit], "the streaming reader fits the heap without window context");
const result = run(60);
assert.equal(result.total, 1);
assert.equal(result.shown, 3);
assert.equal(result.omitted, 99_998);
assert.deepEqual(result.lines, [before, before, hit]);
assert.deepEqual(result.isMatch, [false, false, true]);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

test("time-window drops a disconnected lead-in and its omitted count", async () => {
const rows = [mkLine(2, "old-a"), mkLine(2, "old-b"), mkLine(0, "outside"), mkLine(2, "near"), mkLine(2, "needle")];
const result = await query(rows, "needle", { ctx: 0, winSec: 60, n: 2 });
assert.deepEqual(result.lines, rows.slice(-2));
assert.equal(result.omitted, 0);
assert.deepEqual(result.isMatch, [false, true]);
});

test("time-window returns no context when rotation removes every hit between passes", async () => {
const dir = mkdtempSync(path.join(tmpdir(), "logs-window-rotation-"));
try {
const active = path.join(dir, "active.log");
const missing = path.join(dir, "missing.log");
writeFileSync(active, `${mkLine(2, "needle")}\n`);
const result = await queryLogFiles([active, missing], "needle", { ctx: 0, winSec: 60, n: 2 }, {
onError: () => writeFileSync(active, `${mkLine(2, "replacement")}\n`),
});
assert.equal(result.total, 1, "the first pass still reports its observed match count");
assert.equal(result.shown, 0);
assert.equal(result.omitted, 0);
assert.deepEqual(result.lines, []);
assert.deepEqual(result.isMatch, []);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
Loading