From 67f8e89405b412d7c3c99269906c20238b3e3a71 Mon Sep 17 00:00:00 2001 From: ci-check Date: Fri, 30 Oct 2026 20:11:06 +0800 Subject: [PATCH 1/7] test(#5140): pin the unified storage mode the cold raw-tail proof requires (#4599) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #5140 recovery test proves forkSnapshot reconstructs a non-retained parent's raw tail from the UNIFIED index — but it never pinned its own storage mode. Under the CI storage baseline (preload-storage-baseline.mjs sets BILI_STORAGE_UNIFIED=legacy for the broad corpus) no unified rows exist, so the reconstruction has no source and forkSnapshot fails closed with 409 SNAPSHOT_UNAVAILABLE. Deterministic, not a flake: reproduces 100% on master and any merged branch with BILI_STORAGE_UNIFIED=legacy, passes without it (default shadow). Pin full like the sibling persist tests and restore the ambient value afterwards. --- tests/plugin-fork.test.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/plugin-fork.test.ts b/tests/plugin-fork.test.ts index 5e77c14886..9c0fa4915a 100644 --- a/tests/plugin-fork.test.ts +++ b/tests/plugin-fork.test.ts @@ -1462,6 +1462,10 @@ test("HTTP a mid-history rewrite replaces the snapshot wholesale with an exact b }); test("HTTP a cold-restored non-retained parent serves its intact raw tail immediately (#5140)", { timeout: 60_000 }, async () => { + // Pin the mode this raw-tail proof requires: under the runner's legacy + // baseline no unified rows exist and forkSnapshot fails closed (#4599). + const oldMode = process.env.BILI_STORAGE_UNIFIED; + process.env.BILI_STORAGE_UNIFIED = "full"; const h = await harness(true); try { const parent = resolveConversation("parent").session!; @@ -1480,7 +1484,11 @@ test("HTTP a cold-restored non-retained parent serves its intact raw tail immedi await sendModel(h, "parent", h.messages); assert.equal((await h.request("/__bili/plugin/snapshot?conversationId=parent")).status, 200); assert.equal(resolveConversation("parent").session!.pluginSnapshot!.length, 3); - } finally { await h.close(); } + } finally { + await h.close(); + if (oldMode === undefined) delete process.env.BILI_STORAGE_UNIFIED; + else process.env.BILI_STORAGE_UNIFIED = oldMode; + } }); test("fork protocol v2: snapshot serves the light revision, a stale v1 whole-store revision is still accepted (#2671 Phase 2b)", { timeout: 60_000 }, async () => { From 897756a7a9f9abc2ebd5db313263554974983f97 Mon Sep 17 00:00:00 2001 From: ci-check Date: Fri, 30 Oct 2026 20:41:03 +0800 Subject: [PATCH 2/7] fix: read the checkpoint tip-seq as one MAX(seq) aggregate, not a full-log scan MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found while working #4739 (reported in its thread and in PR #4765's review notes): UnifiedShadow.sessionTipSeq / sessionTipSeqAsync materialized the session's entire message log (every row + one content-CAS read + media hydration per row) just to reduce it to max(seq)+1 — the checkpoint insert's seq_at. O(N) row materialization per checkpoint on the write path. Rewire both legs onto #4730's existing lastLiveSeq (SELECT MAX(seq) over live rows; store/backend/mysql already carry it end-to-end): identical value (same live-row filter, empty log -> tip 0), fail-fast error propagation unchanged, zero new interface surface. tests/storage-tipseq-narrow-read.test.ts pins both halves: tip == max live seq + 1 AND zero message rows materialized (proven failing on the old scan). --- src/storage/shadow.ts | 13 ++-- tests/storage-tipseq-narrow-read.test.ts | 82 ++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 7 deletions(-) create mode 100644 tests/storage-tipseq-narrow-read.test.ts diff --git a/src/storage/shadow.ts b/src/storage/shadow.ts index b9dd9f19dc..a13bc5529b 100644 --- a/src/storage/shadow.ts +++ b/src/storage/shadow.ts @@ -726,13 +726,13 @@ export class UnifiedShadow { } /** Absolute-seq tip of the session's message log (+1 = next free seq). - * Used as a checkpoint's seq_at. */ + * Used as a checkpoint's seq_at. #4739 follow-up: one MAX(seq) aggregate + * over live rows (#4730's lastLiveSeq) instead of materializing the whole + * log (rows + CAS reads + media hydration) just to reduce it to a scalar. */ sessionTipSeq(sessionId: string): number { if (this.sync === null) return 0; this.assertLive(); - let tip = 0; - for (const m of this.sync.getMessages(sessionId)) if (m.seq + 1 > tip) tip = m.seq + 1; - return tip; + return (this.sync.lastLiveSeq(sessionId) ?? -1) + 1; } /** #3301: message rows for specific ids (+ seq±1 neighbors) — stored @@ -1191,9 +1191,8 @@ export class UnifiedShadow { sessionTipSeqAsync(sessionId: string): Promise { return this.viaAsync(0, () => this.sessionTipSeq(sessionId), async () => { - let tip = 0; - for (const m of await this.backend!.getMessages(sessionId)) if (m.seq + 1 > tip) tip = m.seq + 1; - return tip; + const max = await this.backend!.lastLiveSeq(sessionId); + return (max ?? -1) + 1; }); } diff --git a/tests/storage-tipseq-narrow-read.test.ts b/tests/storage-tipseq-narrow-read.test.ts new file mode 100644 index 0000000000..4fafec2b2a --- /dev/null +++ b/tests/storage-tipseq-narrow-read.test.ts @@ -0,0 +1,82 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { SessionStore } from "../src/persist.ts"; +import type { Session } from "../src/session.ts"; +import { snapshotMessages } from "../src/session.ts"; +import { createInitialState, type CoreMessage } from "acp-kernel"; +import { UnifiedStore, messageRowReads } from "../src/storage/store.ts"; +import type { UnifiedShadow } from "../src/storage/shadow.ts"; +import { rmrf } from "./tmp-rm.ts"; + +// #4739 follow-up (adjacent finding from the #4765 review): the checkpoint +// tip-seq read must be ONE MAX(seq) aggregate over live rows — not a full +// materialization of the message log (rows + content-CAS reads + media +// hydration) reduced to a scalar. The old scan cost O(N) per checkpoint +// insert on the write path. + +process.env.BILI_PERSIST_ZSTD = "0"; +process.env.BILI_CONFIG_FILE = path.join( + fs.mkdtempSync(path.join(os.tmpdir(), "bili-tipseq-hermetic-")), + "no-config.json", +); +process.env.BILI_STORAGE_UNIFIED = "full"; + +function makeSession(id: string): Session { + return { + id, + meta: { label: id, protocol: "openai", upstreamOrigin: "http://up:1" }, + stats: { requests: 3, tokensSaved: 0, inputTokens: 10, cachedTokens: 0, outputTokens: 5, cacheSamples: 0, lastInputTokens: 10, contextTokens: 1000, compressCreditTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 }, + metadata: {}, + state: createInitialState(), + createdAt: Date.now() - 1000, + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + pendingRetrievals: [], + }; +} + +function rawTail(n: number): CoreMessage[] { + const out: CoreMessage[] = []; + for (let i = 0; i < n; i++) { + out.push({ id: `tip${i}`, contentType: "text", role: i % 2 === 0 ? "user" : "assistant", text: `tip-seq probe message number ${i} with filler words to spend tokens` }); + } + return out; +} + +test("sessionTipSeq is max live seq + 1 and materializes zero message rows", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-tipseq-")); + const store = new SessionStore({ dir, debounceMs: 60_000, enabled: true }); + try { + const s = makeSession("tip-1"); + const N = 300; + snapshotMessages(s, rawTail(N)); + await store.writeNow(s); + + const sh = (store as unknown as { shadow?: UnifiedShadow }).shadow; + assert.ok(sh && sh.readsUnified, "full-mode sidecar live"); + + // Reference value computed with the OLD algorithm's input set (live + // rows only) — taken BEFORE the narrowness window opens. + const direct = UnifiedStore.open(path.join(dir, "index.db")); + const rows = direct.getMessages("tip-1"); + assert.equal(rows.length, N, "generation 1 ingested the full history"); + const expectedTip = rows[rows.length - 1]!.seq + 1; + direct.close(); + + assert.equal(sh.sessionTipSeq("no-such-session"), 0, "no live rows → tip 0 (as before)"); + + const before = messageRowReads.count; + assert.equal(sh.sessionTipSeq("tip-1"), expectedTip, "tip = max live seq + 1"); + assert.equal(messageRowReads.count - before, 0, `no message rows materialized (old scan read ${N})`); + + assert.equal(await sh.sessionTipSeqAsync("tip-1"), expectedTip, "async twin agrees"); + } finally { + store.cancelAll(); + rmrf(dir); + } +}); From 1ed74400d75a0ec3289f7bde3620c298871f9e08 Mon Sep 17 00:00:00 2001 From: ci-sync Date: Fri, 30 Oct 2026 22:44:30 +0800 Subject: [PATCH 3/7] =?UTF-8?q?fix(test):=20pin=20the=20#5140=20cold-resto?= =?UTF-8?q?re=20snapshot=20test=20to=20unified-full=20=E2=80=94=20under=20?= =?UTF-8?q?the=20global=20legacy=20test=20baseline=20its=20sidecar=20never?= =?UTF-8?q?=20opens=20and=20the=20index=20reconstruction=20gate=20can=20ne?= =?UTF-8?q?ver=20pass?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/plugin-fork.test.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/plugin-fork.test.ts b/tests/plugin-fork.test.ts index 96d9dfeb0f..f07ad30158 100644 --- a/tests/plugin-fork.test.ts +++ b/tests/plugin-fork.test.ts @@ -1477,6 +1477,12 @@ test("HTTP a mid-history rewrite replaces the snapshot wholesale with an exact b }); test("HTTP a cold-restored non-retained parent serves its intact raw tail immediately (#5140)", { timeout: 60_000 }, async () => { + // The reconstruction path reads the unified index, so this test must run + // under unified-full — the global test baseline pins BILI_STORAGE_UNIFIED= + // "legacy" for non-storage suites, under which the sidecar never opens and + // replicasAvailable() is structurally false (a bare sidecar-missing 409). + const oldMode = process.env.BILI_STORAGE_UNIFIED; + process.env.BILI_STORAGE_UNIFIED = "full"; const h = await harness(true); try { const parent = resolveConversation("parent").session!; @@ -1495,7 +1501,10 @@ test("HTTP a cold-restored non-retained parent serves its intact raw tail immedi await sendModel(h, "parent", h.messages); assert.equal((await h.request("/__bili/plugin/snapshot?conversationId=parent")).status, 200); assert.equal(resolveConversation("parent").session!.pluginSnapshot!.length, 3); - } finally { await h.close(); } + } finally { + await h.close(); + if (oldMode === undefined) delete process.env.BILI_STORAGE_UNIFIED; else process.env.BILI_STORAGE_UNIFIED = oldMode; + } }); test("fork protocol v2: snapshot serves the light revision, a stale v1 whole-store revision is still accepted (#2671 Phase 2b)", { timeout: 60_000 }, async () => { From 421026da9f98551cb347163d5762f39fc3e42bcc Mon Sep 17 00:00:00 2001 From: Louie0806 Date: Sat, 31 Oct 2026 02:06:53 +0800 Subject: [PATCH 4/7] fix(#4599): converge the four remaining master-red lanes onto ci-fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ci-fixes at 67f8e894 still leaves four Windows shards red, and all four deltas already exist on PR #5178. This ports the missing hunks so the convergence branch actually converges. 1. `test (windows-latest, 2x, 3)` — #5103. `UnifiedShadow` builds its db path as `${dir}/index.db`, so the open-failure warning reads `C:\...\sessions/index.db`. `issue5103` asserts the warning contains `path.join(dir, "index.db")` — `...\index.db` on win32 — so a mixed separator never matches. `path` is already imported at :30 and the db is opened through the same join, so POSIX output is byte-identical. 2. `test (windows-latest, 22, 4)` + the 4788 leg — #4739/#4788 teardown. The suites arm a real `SessionStorage` under `BILI_STORAGE_UNIFIED=full`, so the sidecar is still open at teardown. `cancelAll()` clears timers and the build map but never closes the shadow; Windows refuses to unlink a directory holding an open file (`EBUSY`/`EPERM` on `index.db`). Use `closeQuietly()` — cancel, then close — in the short-lived-store teardown. 3. `test (ubuntu-latest, 24, 3)` + `(windows-latest, 22, 2)` — #5155. Both cold-rebuild cases waited for the debounced durable flush with a fixed `setTimeout(20)`. A millisecond budget is a deadline a loaded runner can miss, and the miss is an honest `409 !== 200` from a one-turn-stale table. Await the settle itself: `afterNextFlush("conv-ptrs")` resolves once the armed save lands. 4. `test (ubuntu-latest, 22, 3)` — #4788 verdict deadlock. `afterNextFlush` parks a resolver in `flushWaiters`, and the only thing that drains it is the debounce timer — which is armed `unref?.()`. Once that timer is the last pending handle the loop drains, the promise never settles, and node reports `Promise resolution is still pending but the event loop has already resolved`. Keep the timer referenced exactly while a waiter exists (`ref()` on waiter registration; the host-upkeep default stays unref'd). Both view hunks and the two test-teardown hunks are byte-identical to the ones already on PR #5178, so this converges the branches instead of inventing a third variant. Verified locally: `npx tsc --noEmit` clean; issue4788 0/4 -> 4/4; issue4739 4/4; issue5103 5/5; inc-canonical-pointers 3/3. The `cancelAll` -> `closeQuietly` hunk has no local negative control: reverting it keeps Linux green because `EBUSY`/`EPERM` only fire where an open handle blocks unlink. That control can only run on a Windows lane — stated rather than papered over. The #4788 arm's own reader is confirmed instead: `cancelAll()` leaves `index.db`, `index.db-shm`, `index.db-wal` in `/proc/self/fd` while `closeQuietly()` leaves none (probed directly). --- src/persist.ts | 13 ++++++++++++- src/storage/shadow.ts | 4 ++-- tests/inc-canonical-pointers.test.ts | 8 ++++++-- tests/issue4739-bounded-session-load.test.ts | 4 ++-- tests/issue4788-resident-minimal.test.ts | 13 +++++++++---- 5 files changed, 31 insertions(+), 11 deletions(-) diff --git a/src/persist.ts b/src/persist.ts index 1586370479..315810d969 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -2766,7 +2766,14 @@ export class SessionStore { this.drainFlushWaiters(id, this.lastSaveLanded.get(id) === true); }); }, this.debounceMs); - timer.unref?.(); + // #4788: the debounce timer is host-owned periodic upkeep and must not + // pin a process open on its own -- so it is unref'd. But `afterNextFlush` + // makes it a HOST: a caller that awaits a verdict has no other handle + // guaranteed to fire, and an unref'd timer is not a reason for Node to + // stay alive. Awaiting then exits the loop with the promise unresolved + // (`Promise resolution is still pending but the event loop has already + // resolved`). Keep the timer referenced exactly while someone waits. + if (!this.flushWaiters.has(id)) timer.unref?.(); this.saveTimers.set(id, timer); } @@ -2787,6 +2794,10 @@ export class SessionStore { const ws = this.flushWaiters.get(sessionId) ?? []; ws.push((ok: boolean): void => { resolve(ok); }); this.flushWaiters.set(sessionId, ws); + // #4788: the timer was armed unref'd (no waiter existed then). The + // waiter now holds the promise open, so the timer must hold the loop + // open too -- otherwise the process drains and the verdict is lost. + this.saveTimers.get(sessionId)?.ref?.(); }); } diff --git a/src/storage/shadow.ts b/src/storage/shadow.ts index b9dd9f19dc..4656314ced 100644 --- a/src/storage/shadow.ts +++ b/src/storage/shadow.ts @@ -300,12 +300,12 @@ export class UnifiedShadow { : "; delete the file to reset the index"; loggerLog( "warn", - `[storage] unified sidecar failed to open ${dir}/index.db (${errStr}) — staying legacy-only${tail}`, + `[storage] unified sidecar failed to open ${path.join(dir, "index.db")} (${errStr}) — staying legacy-only${tail}`, ); recordSidecarOpenFailure(errStr); return null; } - const shadow = new UnifiedShadow(mode, store, legacyLoad ?? (() => null), undefined, `${dir}/index.db`); + const shadow = new UnifiedShadow(mode, store, legacyLoad ?? (() => null), undefined, path.join(dir, "index.db")); recordSidecarInstance(shadow); const engineTag = ` [engine: ${store.engine}/${store.engineSource}]`; const walTag = ` [wal-cap: ${walLimit}]`; diff --git a/tests/inc-canonical-pointers.test.ts b/tests/inc-canonical-pointers.test.ts index e0210b8d4f..bdc730e143 100644 --- a/tests/inc-canonical-pointers.test.ts +++ b/tests/inc-canonical-pointers.test.ts @@ -105,7 +105,11 @@ test("cold canonical rebuild: identical resync keeps the shared prefix; delta as // #5155: the wrap-up defers the durable flush (debounced) — let the // rows settle before dropping the resident caches, or the cold // rebuild reads a one-turn-stale table and honestly 409s. - await new Promise((resolve) => setTimeout(resolve, 20)); + // Await the settle itself (afterNextFlush resolves once the armed save + // lands) instead of a fixed sleep: the settle is a real condition, and + // a magic millisecond budget is a deadline a loaded windows-latest + // runner can miss — the 409 flake this replaces. + assert.equal(await getStore().afterNextFlush("conv-ptrs"), true, "the turn's durable save must land before the cold reset"); __resetIncrementalLaneForTests(); const delta = await h.turn({ sinceSeq: 3, messages: [core("u4", "four")] }); @@ -135,7 +139,7 @@ test("cold canonical rebuild: edited-tail resync keeps the shared prefix, drops await h.turn({ sinceSeq: 0, resync: true, messages: [core("u1", "one"), core("u2", "two-EDITED")] }); await __incrementalPtrChainForTests("conv-ptrs"); // #5155: settle the debounced flush before the cold reset (see above). - await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(await getStore().afterNextFlush("conv-ptrs"), true, "the resync's durable save must land before the cold reset"); __resetIncrementalLaneForTests(); const delta = await h.turn({ sinceSeq: 2, messages: [core("u3", "three")] }); assert.equal(delta.status, 200); diff --git a/tests/issue4739-bounded-session-load.test.ts b/tests/issue4739-bounded-session-load.test.ts index bc9906b5f0..bf91303252 100644 --- a/tests/issue4739-bounded-session-load.test.ts +++ b/tests/issue4739-bounded-session-load.test.ts @@ -139,7 +139,7 @@ test("full mode: viewFor decodes only pointer rows and matches the full-log deco assert.deepEqual(via, reference, "bounded decode byte-equal to the full-log decode"); assert.equal(delta, expectedPointers, `viewFor read ${delta} message rows for ${expectedPointers} pointer seqs (full log = ${liveSeqs.size})`); } finally { - store.cancelAll(); + store.closeQuietly(); if (prev === undefined) delete process.env.BILI_STORAGE_UNIFIED; else process.env.BILI_STORAGE_UNIFIED = prev; rmrf(dir); @@ -178,7 +178,7 @@ test("full mode: dropped metadata restores from the index alone (narrow read, no assert.ok(again, "envelope rewritten by later save"); assert.deepEqual(Object.keys(JSON.parse(fs.readFileSync(again, "utf8")).payload.metadata as object).sort(), persistedKeys); } finally { - store.cancelAll(); + store.closeQuietly(); if (prev === undefined) delete process.env.BILI_STORAGE_UNIFIED; else process.env.BILI_STORAGE_UNIFIED = prev; rmrf(dir); diff --git a/tests/issue4788-resident-minimal.test.ts b/tests/issue4788-resident-minimal.test.ts index 5f20c83aa8..488ff932b9 100644 --- a/tests/issue4788-resident-minimal.test.ts +++ b/tests/issue4788-resident-minimal.test.ts @@ -129,7 +129,12 @@ test("(a) between-turns drop: every landed request-end boundary discharges dropp assert.ok((s.blockContents as LazyBlockContents).isDropped, "still folded after the second boundary"); assert.ok(isDroppedMetadata(s.metadata)); } finally { - store.cancelAll(); + // #4739/#5140 family: the suite arms a real SessionStorage under + // BILI_STORAGE_UNIFIED=full, so the sidecar handle is still open here. + // cancelAll() clears timers and the build map but never closes the + // shadow; Windows then refuses to unlink the directory (EBUSY/EPERM). + // Close the short-lived store first: cancel, then close. + store.closeQuietly(); rmrf(dir); } }); @@ -164,7 +169,7 @@ test("(b) narrow-read reconstruction deepEquals the pre-drop reference", async ( const rec = (parsed.payload ?? parsed) as Record; assert.equal(Object.keys((rec.blockContents ?? {}) as object).length, Object.keys(refBlocks).length, "full set round-trips through the envelope"); } finally { - store.cancelAll(); + store.closeQuietly(); rmrf(dir); } }); @@ -203,7 +208,7 @@ test("(c) hard cap under sustained activity: boundaries drop, in-flight skips, w process.env.BILI_SESSION_RESIDENT_HARD_MAX_BYTES = saved; } } finally { - store.cancelAll(); + store.closeQuietly(); rmrf(dir); } }); @@ -246,7 +251,7 @@ test("(d) envelope-frozen routing is unchanged AND gets equivalent drops", async assert.equal(s.blockContents.size, 21, "all entries resident again after reconstruction"); } finally { process.env.BILI_STORAGE_UNIFIED = "legacy"; - store.cancelAll(); + store.closeQuietly(); rmrf(dir); } }); From a3019b05628e47a3c67137734297a1c6ed1ff956 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 02:25:48 +0800 Subject: [PATCH 5/7] test(#4788): keep the event loop alive across the unref debounced-save settle (#4599) The turn() helper arms scheduleSave whose debounce timer is unref by design (persist.ts: a pending save must not hold the process open at shutdown) and then awaits afterNextFlush. Nothing else in that await is refd, so in a node:test child whose only surviving handles are unref sockets the event loop drains before the 50 ms debounce fires and the settle promise never resolves: all four subtests fail with "Promise resolution is still pending but the event loop has already resolved" / cancelledByParent. Reproduced deterministically on master 44067a5b AND on pre-merge ci-fixes 67f8e894 (standalone run, exact CI preload chain), while the same file has passed some CI legs by ambient-liveness luck - a born-flake per section 7.2 (no environmental luck). The pin at 67f8e894 does not touch this path. Fix: arm a refd 25 ms keep-alive interval around the afterNextFlush await (cleared in finally) so the debounce fires deterministically on every host. Test-only diff; production settle semantics untouched. --- tests/issue4788-resident-minimal.test.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/issue4788-resident-minimal.test.ts b/tests/issue4788-resident-minimal.test.ts index 5f20c83aa8..a02ae2c4a5 100644 --- a/tests/issue4788-resident-minimal.test.ts +++ b/tests/issue4788-resident-minimal.test.ts @@ -86,7 +86,19 @@ async function turn(store: SessionStore, s: Session, midFlight?: boolean): Promi if (midFlight) s.inFlight = 1; s.revisionEpoch = (s.revisionEpoch ?? 0) + 1; store.scheduleSave(s); - const landed = await store.afterNextFlush(s.id); + // The debounced-save timer is unref'd by design (persist.ts: a pending save + // must not hold the process open at shutdown), so this await keeps NOTHING + // else alive: in a node:test child whose only surviving handles are unref'd + // sockets the event loop drains before the 50 ms debounce fires and + // afterNextFlush never settles (born-flake, §7.2 no environmental luck). + // A ref'd keep-alive makes the settle deterministic regardless of host. + const keepAlive = setInterval((): void => {}, 25); + let landed: boolean; + try { + landed = await store.afterNextFlush(s.id); + } finally { + clearInterval(keepAlive); + } if (midFlight) s.inFlight = 0; return landed; } From 06ad804ac067d8e166b6b28f6dcaf3019660dd83 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sat, 31 Oct 2026 03:11:28 +0800 Subject: [PATCH 6/7] test(#4788): drop the test-side keep-alive superseded by the persist.ts ref-tracking fix (#4599) PR #5262 fixes #4788 at the source: scheduleSave now leaves the debounce timer refd while flush waiters exist (and afterNextFlush refs a pending unrefd timer when a waiter registers), so the settle is deterministic for EVERY caller on every host. The 25 ms keep-alive interval added in a3019b05 only patched this one test file and is redundant now; removing it leaves one mechanism instead of two. The comment stays: without it a future reader re-adds the interval or deletes the persist.ts tracking as dead weight. --- tests/issue4788-resident-minimal.test.ts | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/tests/issue4788-resident-minimal.test.ts b/tests/issue4788-resident-minimal.test.ts index bc3a6088d8..c96e38ec54 100644 --- a/tests/issue4788-resident-minimal.test.ts +++ b/tests/issue4788-resident-minimal.test.ts @@ -86,19 +86,11 @@ async function turn(store: SessionStore, s: Session, midFlight?: boolean): Promi if (midFlight) s.inFlight = 1; s.revisionEpoch = (s.revisionEpoch ?? 0) + 1; store.scheduleSave(s); - // The debounced-save timer is unref'd by design (persist.ts: a pending save - // must not hold the process open at shutdown), so this await keeps NOTHING - // else alive: in a node:test child whose only surviving handles are unref'd - // sockets the event loop drains before the 50 ms debounce fires and - // afterNextFlush never settles (born-flake, §7.2 no environmental luck). - // A ref'd keep-alive makes the settle deterministic regardless of host. - const keepAlive = setInterval((): void => {}, 25); - let landed: boolean; - try { - landed = await store.afterNextFlush(s.id); - } finally { - clearInterval(keepAlive); - } + // #4788: while a caller awaits afterNextFlush, persist.ts keeps the pending + // debounce timer ref'd, so this settle is deterministic even in a node:test + // child whose only surviving handles are unref'd sockets — no test-side + // keep-alive needed here anymore. + const landed = await store.afterNextFlush(s.id); if (midFlight) s.inFlight = 0; return landed; } From bc8c5491913df1eff73676a3a5bda700fccec9d6 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 31 Oct 2026 04:18:23 +0800 Subject: [PATCH 7/7] fix(test): close the unified store handle before rmrf in the tipseq suite (review fix #5239) The new suite's finally block called only cancelAll(), leaving the SessionStore's unified index.db connection open. On Windows an open SQLite file cannot be unlinked, so rmrf threw EBUSY and the subtest failed in teardown (CI run 41081054054, win22-s4/s5 family). closeQuietly is the documented short-lived-store close (cancels saves + closes the sidecar handle) and never throws. --- tests/storage-tipseq-narrow-read.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/storage-tipseq-narrow-read.test.ts b/tests/storage-tipseq-narrow-read.test.ts index 4fafec2b2a..649b43b709 100644 --- a/tests/storage-tipseq-narrow-read.test.ts +++ b/tests/storage-tipseq-narrow-read.test.ts @@ -76,7 +76,9 @@ test("sessionTipSeq is max live seq + 1 and materializes zero message rows", asy assert.equal(await sh.sessionTipSeqAsync("tip-1"), expectedTip, "async twin agrees"); } finally { - store.cancelAll(); + // release the unified index.db handle before rmrf — Windows cannot + // unlink an open SQLite file (the #4599 tmp-rm EBUSY family) + store.closeQuietly(); rmrf(dir); } });