A local-first multi-agent app development platform, built on PenguinHarness
fix(server): trace index gate misses compaction-rotated shards in non-newest date dirs (#271)
Ufodar9c88a849e0a8
diff --git a/changelog/unreleased/2026-08-11-trace-index-compaction-rotate.md b/changelog/unreleased/2026-08-11-trace-index-compaction-rotate.mdnew file mode 100644index 00000000..134f3ef6--- /dev/null+++ b/changelog/unreleased/2026-08-11-trace-index-compaction-rotate.md@@ -0,0 +1,48 @@+# Trace index: mtime gate catches compaction-rotated shards in non-newest date dirs++## The bug++Context compaction calls `TraceWriter.rotate()` to split the Trace into a new shard+(`_002`). The new file is written in the session's **original** date directory (the+Writer's `dateDir` is fixed at construction and never changes), which may be older than+the newest date directory on disk.++The `TraceIndexService` mtime gate optimized its hot path by stat-checking **only the+newest date directory** after confirming the root mtime was unchanged. The comment assumed+"in practice always the newest one (the Writer names dirs by current local date)."+Compaction's `rotate()` breaks this assumption: the new shard lands in an older dir whose+mtime the gate never checks, so the index never registers it.++`locateAll()` only force-reconciles when the index returns **zero** rows for a session;+since `_001` is already indexed (`rows.length = 1`), the force path never triggers. The+result: `GET /messages` returns messages only up to `compaction_end`, and the UI stays+stuck on the "compaction complete" banner. The shard stayed missing until anything else+tripped the gate for that Agent — the next day's first Session (a new date dir moves the+root mtime), any new shard in the newest dir, an import or Session delete, or a forced+pass — because the diff loop's skip test fails for the rotate-touched dir once it does+look. In practice that bounded the window at midnight, not at the next restart.++## The fix++The gate now stats **every known date directory** instead of only the newest. The newest+dir is stat-checked first, so the common case (a fresh shard in today's dir) still settles+in one stat; the remaining dirs are stat-checked concurrently and only decide the rotate+case. This stays readdir-free, and the unchanged-tree fast path still returns early.++The trade this makes explicit: the quiet hot path is no longer a constant two stats but+one root stat plus one stat per date directory, and a date directory is created per+calendar day the Agent runs, with no pruning — so N grows with the Agent's lifetime+rather than being "a handful". The stats run concurrently, and callers that fan out over+Agents or subagent children multiply it. This supersedes the hot-path description in+`changelog/0.2.1/2026-08-04-traces-page-scaling.md` ("The hot path is two stats — an mtime+gate on the traces root and the newest date dir"), which that frozen entry still states.++Two blind spots survive, both inherent to gating on directory mtimes rather than file+ones: an **in-place append** moves no directory mtime at all (only creating or removing a+directory entry does), which is what a resumed Session does — core pins the shard and date+dir, so the run grows an existing file and its recorded `size_bytes` goes stale; and a+**backdated write**, where an external process changes a file and then resets its+directory's mtime to the cached value. `locateAll()`'s force-retry fires only on a+whole-session miss (zero indexed rows), so neither is covered for a session that already+has shards indexed: it stays stale until an unrelated force, an explicit forced+reconciliation, or a restart.diff --git a/changelog/unreleased/README.md b/changelog/unreleased/README.mdindex 3c9b8c12..ed2321f3 100644--- a/changelog/unreleased/README.md+++ b/changelog/unreleased/README.md@@ -3,3 +3,4 @@- [2026-08-14] Match the macOS app icon's visual size to neighbouring apps. ([details](2026-08-14-macos-app-icon-size.md))- [2026-08-14] Unknown model IDs can be moved to Custom with the OpenAI-compatible client. ([details](2026-08-14-model-group-protocol.md))- [2026-08-11] CLI: `penguin config model remove --model-id <id> --provider <group>` deletes a model entry and the credential inlined on it, matched on the exact pair so a same-id entry under another group is left alone; the `default_model` / `vision_model` settings are cleared when they named the removed entry, matching what the Web App's models page already does on delete. ([details](2026-08-11-cli-model-remove.md))+- [2026-08-11] Server: the Trace index's mtime gate now stats every known date directory instead of only the newest, so a compaction-rotated shard (`rotate()` writes to the session's original date dir, not necessarily the newest) is registered instead of silently missing — `GET /messages` returns the full post-compaction conversation instead of stopping at `compaction_end`. ([details](2026-08-11-trace-index-compaction-rotate.md))diff --git a/packages/server/src/services/trace-index.ts b/packages/server/src/services/trace-index.tsindex ca525e20..2737a18f 100644--- a/packages/server/src/services/trace-index.ts+++ b/packages/server/src/services/trace-index.ts@@ -12,18 +12,27 @@* Writer without telling the server which shard rotated — those land via the* reconciler like external writes (the run bumps the date-dir mtime).* - mtime-gated reconciliation (reconcileAgent): the hot path stats the Agent's- * traces root plus its newest known date dir (TWO stat calls, no readdir; a new- * date dir bumps the root's mtime, a new file in the current date dir bumps that- * dir's mtime). Only on a change does it readdir — and only the date dirs whose- * mtime moved — registering new shards and classifying each new Session ONCE- * (bounded head-read of the earliest shard for origin/workspace/title). Restart- * forgets the in-memory gate, so the first request per Agent after an upgrade or- * restart runs one full diff (this is also how the index first populates: no- * migration step needed).- * - Forced reconciliation (`force`): ignores the gate and diffs every date dir —- * the miss-retry path for gate blind spots (e.g. an external write into an OLD- * date dir moves neither gated mtime). A stale index therefore degrades to one- * extra scan, never to a false 404.+ * traces root plus every known date dir (N stat calls, no readdir; a new+ * date dir bumps the root's mtime, a new file in any existing date dir bumps+ * that dir's mtime — including compaction's rotate() which writes to the+ * session's original date dir, not necessarily the newest). Only on a change+ * does it readdir — and only the date dirs whose mtime moved — registering+ * new shards and classifying each new Session ONCE (bounded head-read of the+ * earliest shard for origin/workspace/title). Restart forgets the in-memory+ * gate, so the first request per Agent after an upgrade or restart runs one+ * full diff (this is also how the index first populates: no migration step+ * needed).+ * - Forced reconciliation (`force`): ignores the gate and diffs every date dir.+ * Two blind spots survive, both inherent to gating on DIRECTORY mtimes: an+ * in-place append moves no directory mtime at all (only creating or removing an+ * entry does), which is the normal resume path — core pins dateDir/startIndex, so+ * a resumed Session grows an EXISTING shard and its size_bytes goes stale; and a+ * backdated write, where an external process changes a file and then resets its+ * directory's mtime to the cached value. locateAll() forces only on a whole-session+ * miss (zero indexed rows), so neither is covered for a session that already has+ * indexed rows: it stays stale until an unrelated force, an explicit forced+ * reconciliation, or a restart. A stale index therefore degrades to one extra scan,+ * never to a false 404.** Single-flight per Agent: concurrent requests share one in-flight reconcile instead* of stampeding the directory.@@ -121,9 +130,10 @@ export class TraceIndexService {) {}/**- * Brings one Agent's index in step with disk. Hot path (nothing changed): two stat- * calls, zero readdir. `force` ignores the mtime gate and diffs every date dir (the- * consumers' miss-retry path).+ * Brings one Agent's index in step with disk. Hot path: one root stat, then the+ * newest date dir — a change there short-circuits — else the remaining N-1 date dirs+ * concurrently; zero readdir either way. `force` ignores the mtime gate and diffs+ * every date dir (the consumers' miss-retry path).*/reconcileAgent(projectId: string,@@ -166,16 +176,28 @@ export class TraceIndexService {return;}if (!force && cached && cached.root === rootMtime) {- // Root unchanged (no date dir created/removed). The one blind spot on this level is- // a new file inside an EXISTING date dir — in practice always the newest one (the- // Writer names dirs by current local date) — so gate on that single dir's mtime too.+ // Root unchanged (no date dir created/removed). A new file inside an EXISTING date+ // dir moves that dir's mtime — but not necessarily the newest one: Trace Writer's+ // rotate() (compaction) creates a new shard in the session's ORIGINAL date dir,+ // which may be older than the newest dir. So every known date dir is gated, still+ // readdir-free. Newest first — a fresh shard almost always lands in today's dir,+ // so that one stat usually settles the gate — then the rest concurrently, so the+ // older dirs never cost a serial round trip each. `cached.dates` is in readdir+ // order, so sort: date dirs are YYYY-MM-DD, lexicographic order is chronological.// Cached sentinels (-1: the dir was fresh when last seen) never match, forcing a// re-diff until the tree has been quiet (see mtime-gate's FRESH_MS).- const newest = [...cached.dates.keys()].sort().at(-1);+ const dates = [...cached.dates.keys()].sort();+ const newest = dates.pop();if (newest === undefined) return;this.counters.gateStats += 1;- const m = await statMtime(path.join(dir, newest));- if (m !== null && m === cached.dates.get(newest)) return;+ const newestMtime = await statMtime(path.join(dir, newest));+ let changed = newestMtime === null || newestMtime !== cached.dates.get(newest);+ if (!changed && dates.length > 0) {+ this.counters.gateStats += dates.length;+ const older = await Promise.all(dates.map((d) => statMtime(path.join(dir, d))));+ changed = older.some((m, i) => m === null || m !== cached.dates.get(dates[i]!));+ }+ if (!changed) return;}// Change detected / first look / force: diff date dirs (readdir only the changed ones).diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.tsindex c43c2b6c..b5b92d30 100644--- a/packages/server/src/services/trace-service.ts+++ b/packages/server/src/services/trace-service.ts@@ -160,8 +160,10 @@ export class TraceService {/*** All of this Session's Trace files (sorted by index ascending), served from the* index. An empty answer force-reconciles once and retries before being believed:- * disk is the source of truth, and a gate blind spot (an external write into an old- * date dir) must cost one extra scan, never a false 404.+ * disk is the source of truth, and a gate blind spot (a backdated write, or an+ * in-place append, which moves no directory mtime — see trace-index's header) must+ * cost one extra scan, never a false 404. Note this retry only covers a WHOLE-session+ * miss: a session with some shards indexed and a later one missed is served as-is.*/private async locateAll(projectId: string,diff --git a/packages/server/test/trace-index.test.ts b/packages/server/test/trace-index.test.tsindex 6ba2c9c0..9fe2578d 100644--- a/packages/server/test/trace-index.test.ts+++ b/packages/server/test/trace-index.test.ts@@ -22,9 +22,10 @@ const OLD = "session-2026-07-01-08-00-00-aabb0003";* assertions first make the tree look quiet, exactly like a tree written minutes ago.*/async function backdate(...paths: string[]): Promise<void> {- // A FIXED past instant, so repeated backdates are idempotent: the blind-spot test- // resets a changed dir to exactly the mtime the gate cached, which is precisely the- // "old dir changed without moving any gated mtime" scenario.+ // A FIXED past instant, so repeated backdates are idempotent. Every date dir is now+ // gated, so the blind-spot test relies on that idempotence rather than on an unwatched+ // dir: it resets a CHANGED dir to exactly the mtime the gate already cached, which is+ // the surviving "backdated write" scenario.const old = new Date("2026-01-01T00:00:00.000Z");for (const p of paths) {await fs.utimes(p, old, old);@@ -83,11 +84,15 @@ describe("trace-index", () => {expect(h.traceIndex.counters.headReads).toBe(1);// Steady state: reconciling an unchanged tree is pure gate stats — no readdir, no reads.+ // gateStats is pinned too: the gate costs one root stat plus one per date dir, and+ // only one date dir exists here. Without this the hot path could grow silently.const scans = h.traceIndex.counters.dirScans;+ const gate = h.traceIndex.counters.gateStats;await h.traceIndex.reconcileAgent(P, A);await h.traceIndex.reconcileAgent(P, A);expect(h.traceIndex.counters.dirScans).toBe(scans);expect(h.traceIndex.counters.headReads).toBe(1);+ expect(h.traceIndex.counters.gateStats).toBe(gate + 2 * (1 + 1));// A new shard in the same (newest) date dir moves that dir's mtime: the gate notices.await writeTraceFile(root, P, A, "2026-07-05", S2, 1, [@@ -100,8 +105,46 @@ describe("trace-index", () => {expect(h.traceIndex.repo.getSession(S2)?.metaRead).toBe(true);});- it("a write into an OLD date dir slips past the gate; the consumers' force-retry (locateAll) recovers it", async () => {- // Two date dirs indexed; the gate then watches the root + the NEWEST dir only.+ it("a new shard (compaction rotate) in a NON-newest date dir is caught by the gate", async () => {+ // Simulates compaction: session starts in 2026-07-05, then rotate() creates _002+ // in the SAME date dir — but a newer date dir (2026-07-06) already exists.+ await writeTraceFile(root, P, A, "2026-07-05", S1, 1, [userText("first turn")]);+ await writeTraceFile(root, P, A, "2026-07-06", S2, 1, [userText("other session next day")]);+ await backdate(+ tracesRoot(root),+ path.join(tracesRoot(root), "2026-07-05"),+ path.join(tracesRoot(root), "2026-07-06"),+ );+ await h.traceIndex.reconcileAgent(P, A);+ expect(h.traceIndex.repo.listFilesBySession(P, A, S1)).toHaveLength(1);++ // Compaction rotate: new shard in the OLD date dir (2026-07-05), not the newest (2026-07-06).+ await writeTraceFile(root, P, A, "2026-07-05", S1, 2, [userText("post-compaction turn")]);+ await h.traceIndex.reconcileAgent(P, A);+ // The gate must catch the change in the non-newest dir and register the new shard.+ expect(h.traceIndex.repo.listFilesBySession(P, A, S1)).toHaveLength(2);++ // The newest dir is gated FIRST and short-circuits: with the tree quiet again, a+ // change confined to the newest dir must settle the gate in one date-dir stat, so+ // the older dirs stay off the hot path however many of them accumulate.+ await backdate(+ tracesRoot(root),+ path.join(tracesRoot(root), "2026-07-05"),+ path.join(tracesRoot(root), "2026-07-06"),+ );+ await h.traceIndex.reconcileAgent(P, A);+ const gate = h.traceIndex.counters.gateStats;+ await writeTraceFile(root, P, A, "2026-07-06", S2, 2, [userText("newest dir moves")]);+ await h.traceIndex.reconcileAgent(P, A);+ expect(h.traceIndex.repo.listFilesBySession(P, A, S2)).toHaveLength(2);+ expect(h.traceIndex.counters.gateStats).toBe(gate + 2); // root + newest only+ });++ it("a write into an OLD date dir with backdated mtime slips past the gate; the consumers' force-retry (locateAll) recovers it", async () => {+ // Two date dirs indexed; the gate now watches the root + ALL date dirs.+ // A normal write moves the old dir's mtime and is caught (covered by the test above).+ // The remaining blind spot is a backdated write: the external writer changes the+ // old dir but then resets its mtime to the cached value, making the change invisible.await writeTraceFile(root, P, A, "2026-07-01", OLD, 1, [userText("old day")]);await writeTraceFile(root, P, A, "2026-07-05", S1, 1, [userText("new day")]);await backdate(