From 9590e9bdf55d012bf04c098295af036f4e6d9db4 Mon Sep 17 00:00:00 2001 From: Connor Burgess Date: Wed, 2 Dec 2026 13:04:46 +0700 Subject: [PATCH 1/3] store: an append after one that was cut short starts on a line of its own Symptom: an append to a session's events file that was cut short (a full disk, a file-size limit, the process killed mid-write) leaves a line with no end. After a restart the store wrote the next event straight onto it. The event was accepted and shown live, but the next restart dropped it with the cut line: a whole event lost, nothing logged, and the outbox source's offset already past it. Cause: `EventFiles.append` (server/store/files.ts) appended at the size the store last recorded, without looking at the file's last byte, and `readLines` skips a line that does not parse while counting its bytes. The recorded offsets came from that size too, so a write that failed part-way left them off from the real end of the file and `readAt` returned the wrong event or none. Fix: `append` opens the file once, takes the offsets from its real end (fstat), reads the last byte and begins with a newline when it is not one, in the same write. The cut line ends there and only its event is lost. The `size` argument stays on `EventLog` for MemoryLog. This is the fix core made for its outbox in spacesheep-dev/sessionpipe@87441b9 (spacesheep-dev/sessionpipe#202). Since the store's storage figure adds what each append returns less the size it knew, a file boot counted that holds no event yet (a first append cut short) now gives its new session that size, so its bytes are not counted twice; forgetting that session takes all of them off. Signed-off-by: Connor Burgess --- server/store/core.ts | 11 +++- server/store/files.test.ts | 117 +++++++++++++++++++++++++++++++++++++ server/store/files.ts | 42 +++++++++---- server/store/log.ts | 3 +- 4 files changed, 158 insertions(+), 15 deletions(-) create mode 100644 server/store/files.test.ts diff --git a/server/store/core.ts b/server/store/core.ts index db66a742..8a6f1048 100644 --- a/server/store/core.ts +++ b/server/store/core.ts @@ -133,6 +133,9 @@ export class StoreCore { private latencies: number[] = []; private arrivals: number[] = []; private storageBytes = 0; + /** Files boot counted in storageBytes that hold no event yet (a first append cut short): + * a session that later appends to one starts from that size, so it is not counted twice. */ + private readonly unreadSizes = new Map(); private readonly machinesSent = new Map(); /** Machines whose lastAt moved since their last frame; sent together by flushMachines. */ private readonly machinesDue = new Set(); @@ -170,7 +173,10 @@ export class StoreCore { }); for (const f of files) { this.storageBytes += f.size; - if (!f.lines) continue; + if (!f.lines) { + this.unreadSizes.set(sessionKey(f.harness, f.id), f.size); + continue; + } const entry = this.entry(f.harness, f.id, f.firstArrivedAt ?? new Date().toISOString(), "outbox"); entry.size = f.size; } @@ -269,7 +275,8 @@ export class StoreCore { const key = sessionKey(harness, id); let e = this.sessions.get(key); if (!e) { - e = { ...newRecord(harness, id, at, source), recs: [], seqs: new Set(), size: 0 }; + e = { ...newRecord(harness, id, at, source), recs: [], seqs: new Set(), size: this.unreadSizes.get(key) ?? 0 }; + this.unreadSizes.delete(key); const kids = this.childrenOf.get(key); if (kids) { e.childKeys = kids; diff --git a/server/store/files.test.ts b/server/store/files.test.ts new file mode 100644 index 00000000..af34a390 --- /dev/null +++ b/server/store/files.test.ts @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 +import { appendFileSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { type StoredEvent, sessionKey } from "../../shared/api.js"; +import { Session, SID, tempDir } from "../../test/events.js"; +import { EventFiles } from "./files.js"; +import { Store } from "./store.js"; + +let tmp: { dir: string; cleanup: () => void }; + +beforeEach(() => { + tmp = tempDir(); +}); +afterEach(() => { + tmp.cleanup(); +}); + +const stored = (s: Session, type: string): StoredEvent => + ({ ...s.ev(type), arrivedAt: new Date().toISOString(), source: "http" }) as StoredEvent; +const seqs = (files: EventFiles) => { + const out: number[] = []; + files.scanEach((_f, line) => out.push(line.event.session.seq)); + return out; +}; + +describe("EventFiles.append after one that was cut short", () => { + it("starts on a line of its own, so only the cut event is lost", () => { + const files = new EventFiles(tmp.dir); + const s = new Session(); + const first = files.append("claude-code", SID, [stored(s, "session.started")], 0); + const file = files.file("claude-code", SID); + const cut = JSON.stringify(stored(s, "turn.started")).slice(0, 40); + appendFileSync(file, cut); + const a = stored(s, "turn.ended"); + const b = stored(s, "session.ended"); + // The store's own idea of the size is what it was before the cut write. + const r = files.append("claude-code", SID, [a, b], first.size); + const lines = readFileSync(file, "utf8").split("\n"); + expect(lines[1]).toBe(cut); + expect(lines.map((l) => l.length > 0)).toEqual([true, true, true, true, false]); + expect(seqs(files)).toEqual([0, 2, 3]); + expect(r.size).toBe(statSync(file).size); + expect(files.readAt("claude-code", SID, r.lines).map((e) => e?.id)).toEqual([a.id, b.id]); + }); + + it("takes its offsets from the file's end, not from a size that a failed write left behind", () => { + const files = new EventFiles(tmp.dir); + const s = new Session(); + files.append("claude-code", SID, [stored(s, "session.started")], 0); + const file = files.file("claude-code", SID); + // A write that failed part-way (a full disk) put whole lines down that the caller never counted. + const lost = stored(s, "turn.started"); + appendFileSync(file, `${JSON.stringify(lost)}\n`); + const a = stored(s, "turn.ended"); + const r = files.append("claude-code", SID, [a], 0); + expect(r.size).toBe(statSync(file).size); + expect(files.readAt("claude-code", SID, r.lines).map((e) => e?.id)).toEqual([a.id]); + }); + + it("adds no blank line to a file that is empty or ends a line", () => { + const files = new EventFiles(tmp.dir); + const s = new Session(); + const file = files.file("claude-code", SID); + files.append("claude-code", SID, [stored(s, "session.started")], 0); + writeFileSync(file, ""); + files.append("claude-code", SID, [stored(s, "turn.started")], 0); + files.append("claude-code", SID, [stored(s, "turn.ended")], 0); + expect( + readFileSync(file, "utf8") + .split("\n") + .map((l) => l.length > 0), + ).toEqual([true, true, false]); + }); + + it("a store reopened over a cut line keeps every whole event it accepts, across another restart", async () => { + const s = new Session(); + const key = sessionKey("claude-code", SID); + let store = new Store(tmp.dir, { tickMs: 1_000, statsMs: 1_000 }); + store.ingest([s.ev("session.started"), s.ev("turn.started", { turn_id: "t1" })], "http"); + await store.close(); + const file = path.join(tmp.dir, "events", "claude-code", `${SID}.jsonl`); + appendFileSync(file, JSON.stringify(s.ev("tool.started")).slice(0, 40)); + store = new Store(tmp.dir, { tickMs: 1_000, statsMs: 1_000 }); + const ended = s.ev("turn.ended", { turn_id: "t1" }); + const gone = s.ev("session.ended"); + expect(store.ingest([ended, gone], "outbox").accepted).toBe(2); + expect(store.sessionDetail(key)?.events.map((e) => e.id)).toContain(ended.id); + await store.close(); + store = new Store(tmp.dir, { tickMs: 1_000, statsMs: 1_000 }); + try { + expect(store.sessionDetail(key)?.events.map((e) => e.session.seq)).toEqual([0, 1, 3, 4]); + expect(store.stats().storageBytes).toBe(statSync(file).size); + } finally { + await store.close(); + } + }); + + it("a session whose only line was cut is counted once in the storage figure when it appends again", async () => { + const s = new Session(); + const key = sessionKey("claude-code", SID); + const file = path.join(tmp.dir, "events", "claude-code", `${SID}.jsonl`); + new EventFiles(tmp.dir).append("claude-code", SID, [], 0); + appendFileSync(file, JSON.stringify(s.ev("session.started")).slice(0, 40)); + const store = new Store(tmp.dir, { tickMs: 1_000, statsMs: 1_000 }); + try { + expect(store.stats().storageBytes).toBe(40); + expect(store.ingest([s.ev("turn.started", { turn_id: "t1" })], "outbox").accepted).toBe(1); + expect(store.stats().storageBytes).toBe(statSync(file).size); + expect(store.sessionDetail(key)?.events.map((e) => e.session.seq)).toEqual([1]); + expect(store.forget(key)).toBe(true); + expect(store.stats().storageBytes).toBe(0); + } finally { + await store.close(); + } + }); +}); diff --git a/server/store/files.ts b/server/store/files.ts index 410e1df1..18fa3483 100644 --- a/server/store/files.ts +++ b/server/store/files.ts @@ -6,6 +6,7 @@ import { appendFileSync, closeSync, existsSync, + fstatSync, mkdirSync, openSync, readdirSync, @@ -163,21 +164,38 @@ export class EventFiles { }); } - /** Append events to a session's file; returns each line's offset and length. */ - append(harness: string, id: string, events: StoredEvent[], size: number): { lines: Line[]; size: number } { + /** Append events to a session's file; returns each line's offset and length, and the + * file's new size. The offsets come from the file's real end, not from the `size` the + * store last saw, so an earlier write that failed part-way cannot shift them. An append that + * was cut short (a full disk, a file-size limit, a killed process) leaves a line with no + * end: this one starts on a line of its own, in the same write, so only the cut event is + * lost and not the whole one written after it. */ + append(harness: string, id: string, events: StoredEvent[], _size?: number): { lines: Line[]; size: number } { const file = this.file(harness, id); mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); - const lines: Line[] = []; - const parts: Buffer[] = []; - let pos = size; - for (const event of events) { - const b = Buffer.from(`${JSON.stringify(event)}\n`); - lines.push({ event, offset: pos, bytes: b.length - 1 }); - parts.push(b); - pos += b.length; + const fd = openSync(file, "a+", 0o600); + try { + let pos = fstatSync(fd).size; + const parts: Buffer[] = []; + if (pos) { + const last = Buffer.alloc(1); + if (readSync(fd, last, 0, 1, pos - 1) === 1 && last[0] !== 10) { + parts.push(Buffer.from("\n")); + pos++; + } + } + const lines: Line[] = []; + for (const event of events) { + const b = Buffer.from(`${JSON.stringify(event)}\n`); + lines.push({ event, offset: pos, bytes: b.length - 1 }); + parts.push(b); + pos += b.length; + } + appendFileSync(fd, Buffer.concat(parts)); + return { lines, size: pos }; + } finally { + closeSync(fd); } - appendFileSync(file, Buffer.concat(parts), { mode: 0o600 }); - return { lines, size: pos }; } /** Read full events back by offset. A line that cannot be read yields undefined. */ diff --git a/server/store/log.ts b/server/store/log.ts index 9464d8f3..fd398796 100644 --- a/server/store/log.ts +++ b/server/store/log.ts @@ -28,7 +28,8 @@ export interface LogFileInfo { export interface EventLog { /** Every kept event, one line at a time, at boot; then what each session holds. */ scanEach(visit: (file: LogFileInfo, line: LogLine) => void): LogFileInfo[]; - /** Append to a session; `size` is the session's size before, and the answer its size after. */ + /** Append to a session; `size` is the session's size before, as the store last saw it, and + * the answer its size after (the files read their real end instead: EventFiles.append). */ append(harness: string, id: string, events: StoredEvent[], size: number): { lines: LogLine[]; size: number }; /** Full events back by the places `append` and `scanEach` gave; undefined where one cannot be read. */ readAt(harness: string, id: string, at: { offset: number; bytes: number }[]): (StoredEvent | undefined)[]; From 066bc4a32920822465bd0c307d52e658e77e2efe Mon Sep 17 00:00:00 2001 From: Connor Burgess Date: Wed, 2 Dec 2026 13:52:29 +0700 Subject: [PATCH 2/3] server: a cut first line under a renamed file is counted once too Symptom: a session whose harness or id holds a character outside [A-Za-z0-9_.-], or is longer than 160 characters, still had its cut first line counted twice in storageBytes after a restart, and its unreadSizes entry was never cleared. Cause: boot keyed unreadSizes by the folder and file name, which went through safeName, while entry() looked it up by the raw harness and id. Fix: key unreadSizes by the session's file name on both sides (unreadKey). safeName moves to log.ts, which has no Node in it, so the store's core can use it and still bundle for the browser; files.ts re-exports it. Signed-off-by: Connor Burgess --- server/store/core.ts | 19 +++++++++++++------ server/store/files.test.ts | 21 +++++++++++++++++++++ server/store/files.ts | 7 ++----- server/store/log.ts | 7 +++++++ 4 files changed, 43 insertions(+), 11 deletions(-) diff --git a/server/store/core.ts b/server/store/core.ts index 8a6f1048..f7472458 100644 --- a/server/store/core.ts +++ b/server/store/core.ts @@ -29,7 +29,7 @@ import { splitKey, } from "../../shared/api.js"; import { decodeCursor, encodeCursor } from "./cursor.js"; -import type { EventLog } from "./log.js"; +import { type EventLog, safeName } from "./log.js"; import { applyEvent, newRecord, refreshFlags, refreshState, type SessionRecord, settleAgents } from "./readings.js"; import { digest, filesChanged, type ReviewIndex, search } from "./review.js"; import { type SlimEvent, slimEvent, trimPreview } from "./slim.js"; @@ -116,6 +116,10 @@ const DETAIL_MAX = 1000; const LATENCY_WINDOW = 200; /** How long a machine frame that only moves `lastAt` may wait, so a burst of events is one frame. */ const MACHINE_LASTAT_MS = 1_000; +/** The file a session's events go to, as a key: the names after safeName, which is all a + * file with no valid line can tell (files.ts scanEach). safeName leaves a safe name as it is. */ +const unreadKey = (harness: string, id: string): string => `${safeName(harness)}/${safeName(id)}`; + const withoutLastAt = (json: string): string => json.replace(/"lastAt":"[^"]*",?/, ""); export class StoreCore { @@ -134,8 +138,10 @@ export class StoreCore { private arrivals: number[] = []; private storageBytes = 0; /** Files boot counted in storageBytes that hold no event yet (a first append cut short): - * a session that later appends to one starts from that size, so it is not counted twice. */ - private readonly unreadSizes = new Map(); + * a session that later appends to one starts from that size, so it is not counted twice. + * Keyed by the file's name (unreadKey): such a file has no event to give the real harness + * and id, only its folder and file name, which went through safeName. */ + private readonly unreadSizes = new Map(); private readonly machinesSent = new Map(); /** Machines whose lastAt moved since their last frame; sent together by flushMachines. */ private readonly machinesDue = new Set(); @@ -174,7 +180,7 @@ export class StoreCore { for (const f of files) { this.storageBytes += f.size; if (!f.lines) { - this.unreadSizes.set(sessionKey(f.harness, f.id), f.size); + this.unreadSizes.set(unreadKey(f.harness, f.id), f.size); continue; } const entry = this.entry(f.harness, f.id, f.firstArrivedAt ?? new Date().toISOString(), "outbox"); @@ -275,8 +281,9 @@ export class StoreCore { const key = sessionKey(harness, id); let e = this.sessions.get(key); if (!e) { - e = { ...newRecord(harness, id, at, source), recs: [], seqs: new Set(), size: this.unreadSizes.get(key) ?? 0 }; - this.unreadSizes.delete(key); + const unread = unreadKey(harness, id); + e = { ...newRecord(harness, id, at, source), recs: [], seqs: new Set(), size: this.unreadSizes.get(unread) ?? 0 }; + this.unreadSizes.delete(unread); const kids = this.childrenOf.get(key); if (kids) { e.childKeys = kids; diff --git a/server/store/files.test.ts b/server/store/files.test.ts index af34a390..b6ebacb7 100644 --- a/server/store/files.test.ts +++ b/server/store/files.test.ts @@ -114,4 +114,25 @@ describe("EventFiles.append after one that was cut short", () => { await store.close(); } }); + + it("so is one whose harness and id the file name had to change (safeName), and forget takes the figure back to 0", async () => { + const id = `ses:${"x".repeat(170)} /1`; + const s = new Session(id, "my harness"); + const key = sessionKey("my harness", id); + const files = new EventFiles(tmp.dir); + files.append("my harness", id, [], 0); + const file = files.file("my harness", id); + expect(path.basename(file)).not.toBe(`${id}.jsonl`); + appendFileSync(file, JSON.stringify(s.ev("session.started")).slice(0, 40)); + const store = new Store(tmp.dir, { tickMs: 1_000, statsMs: 1_000 }); + try { + expect(store.stats().storageBytes).toBe(40); + expect(store.ingest([s.ev("turn.started", { turn_id: "t1" })], "outbox").accepted).toBe(1); + expect(store.stats().storageBytes).toBe(statSync(file).size); + expect(store.forget(key)).toBe(true); + expect(store.stats().storageBytes).toBe(0); + } finally { + await store.close(); + } + }); }); diff --git a/server/store/files.ts b/server/store/files.ts index 18fa3483..4e1d37dc 100644 --- a/server/store/files.ts +++ b/server/store/files.ts @@ -16,12 +16,9 @@ import { } from "node:fs"; import path from "node:path"; import type { StoredEvent } from "../../shared/api.js"; +import { safeName } from "./log.js"; -/** A file-name-safe id (the same rule as sessionpipe-core's safeId). */ -export const safeName = (s: string): string => - String(s) - .replace(/[^A-Za-z0-9_.-]/g, "_") - .slice(0, 160); +export { safeName }; export interface Line { event: StoredEvent; diff --git a/server/store/log.ts b/server/store/log.ts index fd398796..266d9f7e 100644 --- a/server/store/log.ts +++ b/server/store/log.ts @@ -37,6 +37,13 @@ export interface EventLog { remove(harness: string, id: string): void; } +/** A file-name-safe id (the same rule as sessionpipe-core's safeId). Here, with no Node in + * it, so the store's core can name a session's file too (core.ts unreadKey). */ +export const safeName = (s: string): string => + String(s) + .replace(/[^A-Za-z0-9_.-]/g, "_") + .slice(0, 160); + /** UTF-8 length of a string: what Buffer.byteLength gives, without Buffer. */ export function utf8Bytes(s: string): number { let n = 0; From 444ea7644b3dc6645f16c736fde96c4241cc11b7 Mon Sep 17 00:00:00 2001 From: Connor Burgess Date: Sat, 5 Dec 2026 07:19:26 +0700 Subject: [PATCH 3/3] docs: record the fix under Unreleased Signed-off-by: Connor Burgess --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5299e266..0f6ce824 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to `sessionpipe-gui`. The format follows ## [Unreleased] +### Fixed + +- An event appended after a truncated write starts on its own line, with correct offsets and storage accounting. + ## [0.8.18] - 2026-12-04 ### Fixed