Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.19] - 2026-12-04

### Added
Expand Down
20 changes: 17 additions & 3 deletions server/store/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 {
Expand All @@ -133,6 +137,11 @@ 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.
* 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<string, number>();
private readonly machinesSent = new Map<string, string>();
/** Machines whose lastAt moved since their last frame; sent together by flushMachines. */
private readonly machinesDue = new Set<string>();
Expand Down Expand Up @@ -170,7 +179,10 @@ export class StoreCore {
});
for (const f of files) {
this.storageBytes += f.size;
if (!f.lines) continue;
if (!f.lines) {
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");
entry.size = f.size;
}
Expand Down Expand Up @@ -269,7 +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: 0 };
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;
Expand Down
138 changes: 138 additions & 0 deletions server/store/files.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// 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();
}
});

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();
}
});
});
49 changes: 32 additions & 17 deletions server/store/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
appendFileSync,
closeSync,
existsSync,
fstatSync,
mkdirSync,
openSync,
readdirSync,
Expand All @@ -15,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;
Expand Down Expand Up @@ -163,21 +161,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. */
Expand Down
10 changes: 9 additions & 1 deletion server/store/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,22 @@ 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)[];
/** Forget a session's events. */
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;
Expand Down