@remnic/core 10.0.139 → 10.0.141

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/dist/access-admin-ops-surface.js +44 -44
  2. package/dist/access-cli.js +44 -44
  3. package/dist/access-extraction-force-flush-preempt.js +44 -44
  4. package/dist/access-extraction-force-flush.js +44 -44
  5. package/dist/access-http-briefing.js +44 -44
  6. package/dist/access-http-query.js +44 -44
  7. package/dist/access-http.js +44 -44
  8. package/dist/access-identity-continuity-surface.js +44 -44
  9. package/dist/access-lcm-surface.js +44 -44
  10. package/dist/access-mcp.js +44 -44
  11. package/dist/access-observe-write-surface.js +44 -44
  12. package/dist/access-operations-batch.js +44 -44
  13. package/dist/access-operations.js +44 -44
  14. package/dist/access-recall-concurrency.js +44 -44
  15. package/dist/access-recall-response.js +44 -44
  16. package/dist/access-recall-surface.js +44 -44
  17. package/dist/access-service.js +44 -44
  18. package/dist/active-recall.js +6 -6
  19. package/dist/briefing.js +7 -7
  20. package/dist/buffer-persistence.d.ts +44 -1
  21. package/dist/buffer-persistence.d.ts.map +1 -1
  22. package/dist/buffer-persistence.js +5 -1
  23. package/dist/buffer-turn-helpers.d.ts +8 -1
  24. package/dist/buffer-turn-helpers.d.ts.map +1 -1
  25. package/dist/buffer-turn-helpers.js +5 -1
  26. package/dist/buffer.d.ts +11 -4
  27. package/dist/buffer.d.ts.map +1 -1
  28. package/dist/buffer.js +6 -6
  29. package/dist/causal-consolidation.js +8 -8
  30. package/dist/{chunk-MP6V4CLP.js → chunk-27N6SGEY.js} +2 -2
  31. package/dist/{chunk-AV6R66KO.js → chunk-2HI22OK7.js} +2 -2
  32. package/dist/{chunk-A33VT7GC.js → chunk-342VFB56.js} +2 -2
  33. package/dist/{chunk-NB2BKYUS.js → chunk-3GHQCNNG.js} +2 -2
  34. package/dist/{chunk-LT35JWKZ.js → chunk-3RJU7QFE.js} +2 -2
  35. package/dist/{chunk-JEAMQL63.js → chunk-4IMMF5W6.js} +3 -3
  36. package/dist/chunk-4Y26S76X.js +109 -0
  37. package/dist/chunk-4Y26S76X.js.map +1 -0
  38. package/dist/{chunk-EEY326VH.js → chunk-63JPXUFA.js} +2 -2
  39. package/dist/{chunk-OFMK76LD.js → chunk-6WV76JHC.js} +2 -2
  40. package/dist/{chunk-VF3EVRUN.js → chunk-7NSGKXFD.js} +2 -2
  41. package/dist/{chunk-KCLHHANX.js → chunk-7YD5XSJK.js} +2 -2
  42. package/dist/{chunk-KCVPKFDG.js → chunk-AA6G3W3B.js} +2 -2
  43. package/dist/{chunk-2UW3EM3U.js → chunk-AZFQXYIJ.js} +45 -2
  44. package/dist/chunk-AZFQXYIJ.js.map +1 -0
  45. package/dist/{chunk-66MBMBSH.js → chunk-BDIXKROL.js} +78 -73
  46. package/dist/chunk-BDIXKROL.js.map +1 -0
  47. package/dist/{chunk-VRWQUUZ7.js → chunk-BYWNF25B.js} +2 -2
  48. package/dist/{chunk-NOZDET3Q.js → chunk-DGLNT6VO.js} +3 -3
  49. package/dist/{chunk-HOSS72UP.js → chunk-EGDUG2ZX.js} +2 -2
  50. package/dist/{chunk-GOYLBPSW.js → chunk-EIZUL6JC.js} +2 -2
  51. package/dist/{chunk-YMNFHNZH.js → chunk-F476AJQJ.js} +2 -2
  52. package/dist/{chunk-POB7N5UM.js → chunk-FJTRNFI4.js} +2 -2
  53. package/dist/{chunk-PQ5FYNY2.js → chunk-FONPAA43.js} +2 -2
  54. package/dist/{chunk-JG6AHBJW.js → chunk-FREKFMCA.js} +2 -2
  55. package/dist/{chunk-N7IJEGSE.js → chunk-GNIMBEOK.js} +2 -2
  56. package/dist/{chunk-YDOLJQ55.js → chunk-H6VQ7L5D.js} +6 -6
  57. package/dist/{chunk-LEH4FVBJ.js → chunk-IUXTKLZY.js} +3 -3
  58. package/dist/{chunk-OJJ73HLA.js → chunk-JCBKGPFE.js} +3 -3
  59. package/dist/{chunk-QZ5JZNXN.js → chunk-JLD44JR7.js} +37 -37
  60. package/dist/{chunk-PNT3SZRY.js → chunk-K5CM4M65.js} +7 -7
  61. package/dist/{chunk-3BRHOVRU.js → chunk-LPDOCXHH.js} +2 -2
  62. package/dist/{chunk-MXE42X3I.js → chunk-NCS2NXSP.js} +3 -3
  63. package/dist/{chunk-DI2QWY6J.js → chunk-NM6UL4W5.js} +7 -7
  64. package/dist/{chunk-N6JGLQV7.js → chunk-QZUT4VTV.js} +2 -2
  65. package/dist/{chunk-F4DXTUHY.js → chunk-SZ6QV3DY.js} +2 -2
  66. package/dist/{chunk-OI3UMEW3.js → chunk-UF5RTFN3.js} +2 -2
  67. package/dist/{chunk-SRW4IKHM.js → chunk-UM22PKA3.js} +2 -2
  68. package/dist/{chunk-U3GJUARA.js → chunk-USVA4XWY.js} +2 -2
  69. package/dist/{chunk-PKV3NNM2.js → chunk-UX7KPVAM.js} +2 -2
  70. package/dist/{chunk-2DWTO7XP.js → chunk-VH4UCI3R.js} +92 -38
  71. package/dist/chunk-VH4UCI3R.js.map +1 -0
  72. package/dist/{chunk-JCWI43TO.js → chunk-VRBGYSSQ.js} +2 -2
  73. package/dist/{chunk-LUDXM7MD.js → chunk-WBOJMAAV.js} +78 -25
  74. package/dist/chunk-WBOJMAAV.js.map +1 -0
  75. package/dist/{chunk-JY327EH4.js → chunk-WGM2KSWN.js} +2 -2
  76. package/dist/{chunk-K4DBE5MH.js → chunk-WIV37T4U.js} +2 -2
  77. package/dist/{chunk-VSZEV7HG.js → chunk-XOOYE37V.js} +2 -2
  78. package/dist/{chunk-JVQNRSWO.js → chunk-YCNSMVWG.js} +2 -2
  79. package/dist/{chunk-CKG7T4AD.js → chunk-YXFY4YOF.js} +2 -2
  80. package/dist/cli.js +44 -44
  81. package/dist/coding/export-okf-codegraph.js +6 -6
  82. package/dist/compounding/engine.js +8 -8
  83. package/dist/config.js +6 -6
  84. package/dist/connectors/codex-materialize-runner.js +7 -7
  85. package/dist/connectors/index.js +7 -7
  86. package/dist/convergence-refresh.js +9 -9
  87. package/dist/corpus-watermark.js +9 -9
  88. package/dist/entity-retrieval.js +7 -7
  89. package/dist/explicit-capture.js +44 -44
  90. package/dist/extraction.js +11 -11
  91. package/dist/harmonic-retrieval.js +7 -7
  92. package/dist/index.js +44 -44
  93. package/dist/location/index.js +8 -8
  94. package/dist/maintenance/memory-governance.js +7 -7
  95. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +7 -7
  96. package/dist/maintenance/rebuild-memory-projection-runner.js +9 -9
  97. package/dist/maintenance/rebuild-memory-projection.js +8 -8
  98. package/dist/memory-browse.js +4 -4
  99. package/dist/namespaces/migrate.js +8 -8
  100. package/dist/namespaces/search.js +3 -3
  101. package/dist/namespaces/storage.js +7 -7
  102. package/dist/operator-doctor-corpus.js +10 -10
  103. package/dist/operator-toolkit.js +13 -13
  104. package/dist/orchestration/backlog-scheduler.js +45 -45
  105. package/dist/orchestration/buffer-drain-runner.js +45 -45
  106. package/dist/orchestration/maintenance.js +15 -15
  107. package/dist/orchestrator.js +44 -44
  108. package/dist/qmd.d.ts +15 -0
  109. package/dist/qmd.d.ts.map +1 -1
  110. package/dist/qmd.js +3 -1
  111. package/dist/recall-navigation.js +44 -44
  112. package/dist/recall-state-view-admission.js +4 -4
  113. package/dist/recall-why-service.js +4 -4
  114. package/dist/rerank.d.ts +8 -8
  115. package/dist/rerank.d.ts.map +1 -1
  116. package/dist/rerank.js +11 -3
  117. package/dist/resume-bundles.js +6 -6
  118. package/dist/schemas.d.ts +4 -4
  119. package/dist/search/factory.js +2 -2
  120. package/dist/search/index.js +2 -2
  121. package/dist/semantic-consolidation.js +8 -8
  122. package/dist/semantic-rule-promotion.js +7 -7
  123. package/dist/semantic-rule-verifier.js +7 -7
  124. package/dist/source-agent-qualifier.js +10 -10
  125. package/dist/standup/build.js +7 -7
  126. package/dist/storage/buffer-drain-claims.js +2 -2
  127. package/dist/storage/buffer-session-files.js +2 -2
  128. package/dist/storage.js +6 -6
  129. package/dist/transfer/export-okf.js +7 -7
  130. package/dist/verified-recall.js +7 -7
  131. package/dist/who-knows-cli.js +8 -8
  132. package/dist/who-knows.js +7 -7
  133. package/package.json +2 -2
  134. package/src/buffer-large-session-defer.test.ts +472 -0
  135. package/src/buffer-persistence.ts +100 -7
  136. package/src/buffer-turn-helpers.ts +72 -1
  137. package/src/buffer.ts +103 -102
  138. package/src/qmd-client.test.ts +26 -15
  139. package/src/qmd-daemon-congestion.test.ts +233 -0
  140. package/src/qmd-mcp-cancel.test.ts +3 -3
  141. package/src/qmd.ts +149 -45
  142. package/src/rerank.test.ts +162 -25
  143. package/src/rerank.ts +102 -24
  144. package/dist/chunk-2DWTO7XP.js.map +0 -1
  145. package/dist/chunk-2UW3EM3U.js.map +0 -1
  146. package/dist/chunk-66MBMBSH.js.map +0 -1
  147. package/dist/chunk-LUDXM7MD.js.map +0 -1
  148. package/dist/chunk-XO23OKMK.js +0 -67
  149. package/dist/chunk-XO23OKMK.js.map +0 -1
  150. /package/dist/{chunk-MP6V4CLP.js.map → chunk-27N6SGEY.js.map} +0 -0
  151. /package/dist/{chunk-AV6R66KO.js.map → chunk-2HI22OK7.js.map} +0 -0
  152. /package/dist/{chunk-A33VT7GC.js.map → chunk-342VFB56.js.map} +0 -0
  153. /package/dist/{chunk-NB2BKYUS.js.map → chunk-3GHQCNNG.js.map} +0 -0
  154. /package/dist/{chunk-LT35JWKZ.js.map → chunk-3RJU7QFE.js.map} +0 -0
  155. /package/dist/{chunk-JEAMQL63.js.map → chunk-4IMMF5W6.js.map} +0 -0
  156. /package/dist/{chunk-EEY326VH.js.map → chunk-63JPXUFA.js.map} +0 -0
  157. /package/dist/{chunk-OFMK76LD.js.map → chunk-6WV76JHC.js.map} +0 -0
  158. /package/dist/{chunk-VF3EVRUN.js.map → chunk-7NSGKXFD.js.map} +0 -0
  159. /package/dist/{chunk-KCLHHANX.js.map → chunk-7YD5XSJK.js.map} +0 -0
  160. /package/dist/{chunk-KCVPKFDG.js.map → chunk-AA6G3W3B.js.map} +0 -0
  161. /package/dist/{chunk-VRWQUUZ7.js.map → chunk-BYWNF25B.js.map} +0 -0
  162. /package/dist/{chunk-NOZDET3Q.js.map → chunk-DGLNT6VO.js.map} +0 -0
  163. /package/dist/{chunk-HOSS72UP.js.map → chunk-EGDUG2ZX.js.map} +0 -0
  164. /package/dist/{chunk-GOYLBPSW.js.map → chunk-EIZUL6JC.js.map} +0 -0
  165. /package/dist/{chunk-YMNFHNZH.js.map → chunk-F476AJQJ.js.map} +0 -0
  166. /package/dist/{chunk-POB7N5UM.js.map → chunk-FJTRNFI4.js.map} +0 -0
  167. /package/dist/{chunk-PQ5FYNY2.js.map → chunk-FONPAA43.js.map} +0 -0
  168. /package/dist/{chunk-JG6AHBJW.js.map → chunk-FREKFMCA.js.map} +0 -0
  169. /package/dist/{chunk-N7IJEGSE.js.map → chunk-GNIMBEOK.js.map} +0 -0
  170. /package/dist/{chunk-YDOLJQ55.js.map → chunk-H6VQ7L5D.js.map} +0 -0
  171. /package/dist/{chunk-LEH4FVBJ.js.map → chunk-IUXTKLZY.js.map} +0 -0
  172. /package/dist/{chunk-OJJ73HLA.js.map → chunk-JCBKGPFE.js.map} +0 -0
  173. /package/dist/{chunk-QZ5JZNXN.js.map → chunk-JLD44JR7.js.map} +0 -0
  174. /package/dist/{chunk-PNT3SZRY.js.map → chunk-K5CM4M65.js.map} +0 -0
  175. /package/dist/{chunk-3BRHOVRU.js.map → chunk-LPDOCXHH.js.map} +0 -0
  176. /package/dist/{chunk-MXE42X3I.js.map → chunk-NCS2NXSP.js.map} +0 -0
  177. /package/dist/{chunk-DI2QWY6J.js.map → chunk-NM6UL4W5.js.map} +0 -0
  178. /package/dist/{chunk-N6JGLQV7.js.map → chunk-QZUT4VTV.js.map} +0 -0
  179. /package/dist/{chunk-F4DXTUHY.js.map → chunk-SZ6QV3DY.js.map} +0 -0
  180. /package/dist/{chunk-OI3UMEW3.js.map → chunk-UF5RTFN3.js.map} +0 -0
  181. /package/dist/{chunk-SRW4IKHM.js.map → chunk-UM22PKA3.js.map} +0 -0
  182. /package/dist/{chunk-U3GJUARA.js.map → chunk-USVA4XWY.js.map} +0 -0
  183. /package/dist/{chunk-PKV3NNM2.js.map → chunk-UX7KPVAM.js.map} +0 -0
  184. /package/dist/{chunk-JCWI43TO.js.map → chunk-VRBGYSSQ.js.map} +0 -0
  185. /package/dist/{chunk-JY327EH4.js.map → chunk-WGM2KSWN.js.map} +0 -0
  186. /package/dist/{chunk-K4DBE5MH.js.map → chunk-WIV37T4U.js.map} +0 -0
  187. /package/dist/{chunk-VSZEV7HG.js.map → chunk-XOOYE37V.js.map} +0 -0
  188. /package/dist/{chunk-JVQNRSWO.js.map → chunk-YCNSMVWG.js.map} +0 -0
  189. /package/dist/{chunk-CKG7T4AD.js.map → chunk-YXFY4YOF.js.map} +0 -0
@@ -0,0 +1,472 @@
1
+ /**
2
+ * Large-session rewrite deferral (issue #3389).
3
+ *
4
+ * A session file grows without bound while its session stays hot; the daemon
5
+ * had a ~44 MB session receiving a turn on nearly every observe. Every
6
+ * mutation then queued a whole-file rewrite on the serialized persist pass,
7
+ * and `durable-bufferMs` measured ~99% of observe time (worst ~10 min).
8
+ *
9
+ * The fix rate-limits REWRITES of large session files on steady-state passes:
10
+ * a dirty session at or above `BUFFER_SESSION_DEFER_MIN_BYTES` that was
11
+ * persisted less than `BUFFER_SESSION_DEFER_INTERVAL_MS` ago stays dirty for
12
+ * the next pass instead of being rewritten. Bounds, each pinned by a test:
13
+ *
14
+ * - a session never persisted before is always written (first durability);
15
+ * - a drain-claimed session is never deferred (the claim must receive the
16
+ * entry now, or the drain stalls);
17
+ * - durability barriers (buffer.save, flushPendingSave throwOnFailure,
18
+ * extraction-trigger saves) do not defer;
19
+ * - small sessions keep the legacy write-every-dirty-flush cadence.
20
+ */
21
+ import test from "node:test";
22
+ import assert from "node:assert/strict";
23
+
24
+ import {
25
+ BufferSessionPersistence,
26
+ BUFFER_SESSION_DEFER_MIN_BYTES,
27
+ BUFFER_SESSION_DEFER_INTERVAL_MS,
28
+ } from "./buffer-persistence.js";
29
+ import { SmartBuffer } from "./buffer.js";
30
+ import { parseConfig } from "./config.js";
31
+ import type { BufferEntryState, BufferState, BufferTurn } from "./types.js";
32
+
33
+ const BIG_CONTENT = "x".repeat(BUFFER_SESSION_DEFER_MIN_BYTES);
34
+
35
+ function bigEntry(): BufferEntryState {
36
+ return {
37
+ turns: [makeTurn("big", BIG_CONTENT)],
38
+ lastExtractionAt: null,
39
+ extractionCount: 0,
40
+ };
41
+ }
42
+
43
+ function makeTurn(sessionKey: string, content: string): BufferTurn {
44
+ return {
45
+ role: "user",
46
+ content,
47
+ timestamp: "2026-11-18T12:00:00.000Z",
48
+ sessionKey,
49
+ };
50
+ }
51
+
52
+ function emptyState(): BufferState {
53
+ return { turns: [], lastExtractionAt: null, extractionCount: 0 };
54
+ }
55
+
56
+ /** Storage double recording per-session writes; optional claim flag. */
57
+ class DeferStorage {
58
+ readonly writes = new Map<string, number>();
59
+ claimed = new Set<string>();
60
+ private initial: BufferState;
61
+
62
+ constructor(initial: BufferState) {
63
+ this.initial = initial;
64
+ }
65
+
66
+ async loadBuffer(): Promise<BufferState> {
67
+ return structuredClone(this.initial);
68
+ }
69
+
70
+ async saveBuffer(state: BufferState): Promise<void> {
71
+ this.initial = structuredClone(state);
72
+ }
73
+
74
+ async saveBufferSession(key: string, entry: BufferEntryState): Promise<void> {
75
+ this.writes.set(key, (this.writes.get(key) ?? 0) + 1);
76
+ void entry;
77
+ }
78
+
79
+ async deleteBufferSession(): Promise<void> {}
80
+
81
+ isBufferSessionClaimed(key: string): boolean {
82
+ return this.claimed.has(key);
83
+ }
84
+
85
+ writeCount(key: string): number {
86
+ return this.writes.get(key) ?? 0;
87
+ }
88
+ }
89
+
90
+ test("#3389 a large session persisted recently is deferred, not rewritten", async () => {
91
+ const storage = new DeferStorage(emptyState());
92
+ const entries = new Map<string, BufferEntryState>([["big", bigEntry()]]);
93
+ const peek = (key: string) => entries.get(key);
94
+ const persistence = new BufferSessionPersistence();
95
+ let now = 1_000;
96
+ const clock = () => now;
97
+
98
+ persistence.markDirty("big");
99
+ await persistence.persist(storage, emptyState(), peek, undefined, {
100
+ now: clock,
101
+ allowDeferral: true,
102
+ });
103
+ assert.equal(storage.writeCount("big"), 1, "first write must land");
104
+
105
+ persistence.markDirty("big");
106
+ now += 1_000; // still within the defer interval
107
+ await persistence.persist(storage, emptyState(), peek, undefined, {
108
+ now: clock,
109
+ allowDeferral: true,
110
+ });
111
+ assert.equal(storage.writeCount("big"), 1, "recent large rewrite must defer");
112
+ assert.equal(persistence.hasPending(), true, "deferred session stays dirty");
113
+ });
114
+
115
+ test("#3389 a large session writes again once the interval elapsed", async () => {
116
+ const storage = new DeferStorage(emptyState());
117
+ const entries = new Map<string, BufferEntryState>([["big", bigEntry()]]);
118
+ const peek = (key: string) => entries.get(key);
119
+ const persistence = new BufferSessionPersistence();
120
+ let now = 1_000;
121
+ const clock = () => now;
122
+
123
+ persistence.markDirty("big");
124
+ await persistence.persist(storage, emptyState(), peek, undefined, {
125
+ now: clock,
126
+ allowDeferral: true,
127
+ });
128
+
129
+ persistence.markDirty("big");
130
+ now += BUFFER_SESSION_DEFER_INTERVAL_MS + 1;
131
+ await persistence.persist(storage, emptyState(), peek, undefined, {
132
+ now: clock,
133
+ allowDeferral: true,
134
+ });
135
+ assert.equal(storage.writeCount("big"), 2, "stale large session must write");
136
+ assert.equal(persistence.hasPending(), false);
137
+ });
138
+
139
+ test("#3389 a small session is never deferred no matter how recent", async () => {
140
+ const storage = new DeferStorage(emptyState());
141
+ const entries = new Map<string, BufferEntryState>([
142
+ ["small", { turns: [makeTurn("small", "tiny")], lastExtractionAt: null, extractionCount: 0 }],
143
+ ]);
144
+ const peek = (key: string) => entries.get(key);
145
+ const persistence = new BufferSessionPersistence();
146
+ let now = 1_000;
147
+ const clock = () => now;
148
+
149
+ for (const _ of [1, 2, 3]) {
150
+ persistence.markDirty("small");
151
+ await persistence.persist(storage, emptyState(), peek, undefined, {
152
+ now: clock,
153
+ allowDeferral: true,
154
+ });
155
+ now += 1;
156
+ }
157
+ assert.equal(storage.writeCount("small"), 3, "small sessions keep per-flush durability");
158
+ });
159
+
160
+ test("#3389 a drain-claimed session is never deferred", async () => {
161
+ const storage = new DeferStorage(emptyState());
162
+ storage.claimed.add("big");
163
+ const entries = new Map<string, BufferEntryState>([["big", bigEntry()]]);
164
+ const peek = (key: string) => entries.get(key);
165
+ const persistence = new BufferSessionPersistence();
166
+ let now = 1_000;
167
+ const clock = () => now;
168
+
169
+ persistence.markDirty("big");
170
+ await persistence.persist(storage, emptyState(), peek, undefined, {
171
+ now: clock,
172
+ allowDeferral: true,
173
+ });
174
+ persistence.markDirty("big");
175
+ now += 1;
176
+ await persistence.persist(storage, emptyState(), peek, undefined, {
177
+ now: clock,
178
+ allowDeferral: true,
179
+ });
180
+ assert.equal(storage.writeCount("big"), 2, "a claim must receive the entry now");
181
+ });
182
+
183
+ test("#3389 a durability-barrier pass never defers", async () => {
184
+ const storage = new DeferStorage(emptyState());
185
+ const entries = new Map<string, BufferEntryState>([["big", bigEntry()]]);
186
+ const peek = (key: string) => entries.get(key);
187
+ const persistence = new BufferSessionPersistence();
188
+ let now = 1_000;
189
+ const clock = () => now;
190
+
191
+ persistence.markDirty("big");
192
+ await persistence.persist(storage, emptyState(), peek, undefined, {
193
+ now: clock,
194
+ allowDeferral: true,
195
+ });
196
+ persistence.markDirty("big");
197
+ now += 1;
198
+ // No allowDeferral: barrier pass (save / flushPendingSave / trigger).
199
+ await persistence.persist(storage, emptyState(), peek, undefined, { now: clock });
200
+ assert.equal(storage.writeCount("big"), 2, "barrier passes always write");
201
+ });
202
+
203
+ test("#3389 SmartBuffer: a hot large session stops rewriting per turn (debounce off)", async () => {
204
+ const state = emptyState();
205
+ state.entries = { big: bigEntry() };
206
+ const storage = new DeferStorage(state);
207
+ const buffer = new SmartBuffer(
208
+ parseConfig({ triggerMode: "every_n", bufferMaxTurns: 1_000, bufferSaveDebounceMs: 0 }),
209
+ storage,
210
+ );
211
+
212
+ // First turn lands the session file (never-persisted → always written).
213
+ await buffer.addTurn("big", makeTurn("big", "more"));
214
+ assert.equal(storage.writeCount("big"), 1, "first write must land");
215
+
216
+ // The hot session keeps buffering; its file must NOT be rewritten per turn.
217
+ await buffer.addTurn("big", makeTurn("big", "more"));
218
+ await buffer.addTurn("big", makeTurn("big", "more"));
219
+ assert.equal(storage.writeCount("big"), 1, "large session rewrite must be rate-limited");
220
+
221
+ // A small session alongside keeps per-turn durability.
222
+ await buffer.addTurn("small", makeTurn("small", "a"));
223
+ await buffer.addTurn("small", makeTurn("small", "b"));
224
+ assert.equal(storage.writeCount("small"), 2, "small sessions keep per-turn durability");
225
+
226
+ // A durability barrier flushes the deferred session now.
227
+ await buffer.save();
228
+ assert.equal(storage.writeCount("big"), 2, "barrier pass writes the deferred session");
229
+ });
230
+
231
+ test("#3389 SmartBuffer: an extraction-trigger turn stays durable on a large session", async () => {
232
+ const state = emptyState();
233
+ state.entries = { big: bigEntry() };
234
+ const storage = new DeferStorage(state);
235
+ const buffer = new SmartBuffer(
236
+ parseConfig({ triggerMode: "every_n", bufferMaxTurns: 2, bufferSaveDebounceMs: 0 }),
237
+ storage,
238
+ );
239
+
240
+ await buffer.addTurn("big", makeTurn("big", "more"));
241
+ assert.equal(storage.writeCount("big"), 1);
242
+ // This turn triggers extraction (turns >= bufferMaxTurns): the triggering
243
+ // turn must be durable before extraction runs — no deferral.
244
+ const decision = await buffer.addTurn("big", makeTurn("big", "trigger"));
245
+ assert.equal(decision, "extract_batch");
246
+ assert.equal(storage.writeCount("big"), 2, "the durability barrier must not defer");
247
+ });
248
+
249
+ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
250
+
251
+ /**
252
+ * Real-time-linked fake clock for the SmartBuffer-level deferral tests: the
253
+ * deferred-retry timer is a real setTimeout, so the persistence clock must
254
+ * advance with wall time while staying in a small testable domain.
255
+ */
256
+ function realtimeClock(offset = 1_000): () => number {
257
+ const t0 = performance.now();
258
+ return () => offset + (performance.now() - t0);
259
+ }
260
+
261
+ test("#3389 a deferred large session lands when its interval elapses — no new turn required", async () => {
262
+ // Review round 2 (PR 3481): after a deferred pass the buffer cleared
263
+ // pendingSave and armed nothing, so the tail of a burst sat in memory until
264
+ // the next turn or barrier — wider than the sanctioned crash-loss window.
265
+ // Debounce off: the keep_buffering path saves inline and opts into deferral,
266
+ // so the second turn defers and the armed retry must land it at eligibility.
267
+ const state = emptyState();
268
+ state.entries = { big: bigEntry() };
269
+ const storage = new DeferStorage(state);
270
+ const persistence = new BufferSessionPersistence({
271
+ now: realtimeClock(),
272
+ deferIntervalMs: 120,
273
+ });
274
+ const buffer = new SmartBuffer(
275
+ parseConfig({ triggerMode: "every_n", bufferMaxTurns: 1_000, bufferSaveDebounceMs: 0 }),
276
+ storage,
277
+ null,
278
+ { persistence },
279
+ );
280
+
281
+ await buffer.addTurn("big", makeTurn("big", "more"));
282
+ assert.equal(storage.writeCount("big"), 1, "first write must land");
283
+
284
+ await buffer.addTurn("big", makeTurn("big", "more"));
285
+ const deadline = Date.now() + 2_000;
286
+ while (storage.writeCount("big") < 2 && Date.now() < deadline) await sleep(20);
287
+ assert.equal(
288
+ storage.writeCount("big"),
289
+ 2,
290
+ "the deferred session must persist once its interval elapses, without another turn",
291
+ );
292
+ });
293
+
294
+ test("#3389 a backend without isBufferSessionClaimed is never deferred (claim state unknown)", async () => {
295
+ // isBufferSessionClaimed is optional; a session-capable backend that omits
296
+ // it cannot prove a session is unclaimed, so deferral must fail closed.
297
+ class ClaimlessStorage {
298
+ readonly writes = new Map<string, number>();
299
+ private initial: BufferState;
300
+ constructor(initial: BufferState) {
301
+ this.initial = initial;
302
+ }
303
+ async loadBuffer(): Promise<BufferState> {
304
+ return structuredClone(this.initial);
305
+ }
306
+ async saveBuffer(next: BufferState): Promise<void> {
307
+ this.initial = structuredClone(next);
308
+ }
309
+ async saveBufferSession(key: string, entry: BufferEntryState): Promise<void> {
310
+ this.writes.set(key, (this.writes.get(key) ?? 0) + 1);
311
+ void entry;
312
+ }
313
+ async deleteBufferSession(): Promise<void> {}
314
+ }
315
+ const storage = new ClaimlessStorage(emptyState());
316
+ const entries = new Map<string, BufferEntryState>([["big", bigEntry()]]);
317
+ const peek = (key: string) => entries.get(key);
318
+ const persistence = new BufferSessionPersistence();
319
+ let now = 1_000;
320
+ const clock = () => now;
321
+
322
+ persistence.markDirty("big");
323
+ await persistence.persist(storage, emptyState(), peek, undefined, {
324
+ now: clock,
325
+ allowDeferral: true,
326
+ });
327
+ assert.equal(storage.writes.get("big"), 1, "first write must land");
328
+
329
+ persistence.markDirty("big");
330
+ now += 1;
331
+ await persistence.persist(storage, emptyState(), peek, undefined, {
332
+ now: clock,
333
+ allowDeferral: true,
334
+ });
335
+ assert.equal(
336
+ storage.writes.get("big"),
337
+ 2,
338
+ "unknown claim state must not defer: a claimed session would starve its drain",
339
+ );
340
+ });
341
+
342
+ test("#3389 a debounced retry after a failed save keeps session-level deferral", async () => {
343
+ // Review round 2: the catch-path retry armed flushPendingSave() without
344
+ // opts, so the retry ran as a barrier and rewrote the large session anyway.
345
+ // The failing write belongs to a SMALL session in the same pass: while big
346
+ // sits inside its deferral window, small's transient failure makes the catch
347
+ // re-arm a retry — and that retry must still defer big.
348
+ class FlakyStorage extends DeferStorage {
349
+ private failed = false;
350
+ async saveBufferSession(key: string, entry: BufferEntryState): Promise<void> {
351
+ if (key === "small" && !this.failed) {
352
+ this.failed = true;
353
+ throw new Error("transient write failure");
354
+ }
355
+ return super.saveBufferSession(key, entry);
356
+ }
357
+ }
358
+ const state = emptyState();
359
+ state.entries = {
360
+ big: bigEntry(),
361
+ small: { turns: [makeTurn("small", "tiny")], lastExtractionAt: null, extractionCount: 0 },
362
+ };
363
+ const storage = new FlakyStorage(state);
364
+ const persistence = new BufferSessionPersistence({ now: realtimeClock() });
365
+ const buffer = new SmartBuffer(
366
+ parseConfig({ triggerMode: "every_n", bufferMaxTurns: 1_000, bufferSaveDebounceMs: 5 }),
367
+ storage,
368
+ null,
369
+ { persistence },
370
+ );
371
+
372
+ await buffer.addTurn("big", makeTurn("big", "more"));
373
+ const firstWriteDeadline = Date.now() + 2_000;
374
+ while (storage.writeCount("big") < 1 && Date.now() < firstWriteDeadline) await sleep(10);
375
+ assert.equal(storage.writeCount("big"), 1, "first write must land");
376
+
377
+ // Big gets a tail turn (deferred, inside its window) and small fails once in
378
+ // the same pass. The catch re-arms a retry; without deferral preserved it
379
+ // would rewrite big as a barrier.
380
+ await buffer.addTurn("big", makeTurn("big", "more"));
381
+ await buffer.addTurn("small", makeTurn("small", "more"));
382
+ const retryDeadline = Date.now() + 2_000;
383
+ while (storage.writeCount("small") < 1 && Date.now() < retryDeadline) await sleep(10);
384
+ assert.equal(storage.writeCount("small"), 1, "the retried small write must land");
385
+ assert.equal(
386
+ storage.writeCount("big"),
387
+ 1,
388
+ "a steady-state retry keeps deferral instead of escalating to a barrier write",
389
+ );
390
+
391
+ await buffer.save();
392
+ assert.equal(storage.writeCount("big"), 2, "the barrier still lands the session");
393
+ });
394
+
395
+ test("#3389 a session near the floor still defers once JSON overhead is counted", async () => {
396
+ // The estimate must include serialized JSON structure + escaping: content
397
+ // just under 8 MiB serializes past the floor, so a flat content sum
398
+ // under-counts and the hot file keeps being rewritten every flush.
399
+ const storage = new DeferStorage(emptyState());
400
+ const nearFloor: BufferEntryState = {
401
+ turns: [makeTurn("big", "x".repeat(7_400_000))],
402
+ lastExtractionAt: null,
403
+ extractionCount: 0,
404
+ };
405
+ const entries = new Map<string, BufferEntryState>([["big", nearFloor]]);
406
+ const peek = (key: string) => entries.get(key);
407
+ const persistence = new BufferSessionPersistence();
408
+ let now = 1_000;
409
+ const clock = () => now;
410
+
411
+ persistence.markDirty("big");
412
+ await persistence.persist(storage, emptyState(), peek, undefined, {
413
+ now: clock,
414
+ allowDeferral: true,
415
+ });
416
+ assert.equal(storage.writeCount("big"), 1, "first write must land");
417
+
418
+ persistence.markDirty("big");
419
+ now += 1;
420
+ await persistence.persist(storage, emptyState(), peek, undefined, {
421
+ now: clock,
422
+ allowDeferral: true,
423
+ });
424
+ assert.equal(
425
+ storage.writeCount("big"),
426
+ 1,
427
+ "a ~7.4 MB-content session serializes past 8 MiB and must defer",
428
+ );
429
+ });
430
+
431
+ test("#3389 a debounce-off deferred retry re-arms after a transient write failure", async () => {
432
+ // Review round 3 (PR 3481): with bufferSaveDebounceMs 0 the catch block in
433
+ // flushPendingSave armed no retry — a transient failure at the deferred
434
+ // session's eligibility time left it dirty until another turn or barrier.
435
+ class FlakyStorage extends DeferStorage {
436
+ private writesSeen = 0;
437
+ async saveBufferSession(key: string, entry: BufferEntryState): Promise<void> {
438
+ if (key === "big" && ++this.writesSeen === 2) {
439
+ throw new Error("transient write failure");
440
+ }
441
+ return super.saveBufferSession(key, entry);
442
+ }
443
+ }
444
+ const state = emptyState();
445
+ state.entries = { big: bigEntry() };
446
+ const storage = new FlakyStorage(state);
447
+ const persistence = new BufferSessionPersistence({
448
+ now: realtimeClock(),
449
+ deferIntervalMs: 120,
450
+ });
451
+ const buffer = new SmartBuffer(
452
+ parseConfig({ triggerMode: "every_n", bufferMaxTurns: 1_000, bufferSaveDebounceMs: 0 }),
453
+ storage,
454
+ null,
455
+ { persistence },
456
+ );
457
+
458
+ await buffer.addTurn("big", makeTurn("big", "more"));
459
+ assert.equal(storage.writeCount("big"), 1, "first write must land");
460
+
461
+ // Second turn defers; the eligibility-time write fails once. A retry armed
462
+ // independent of the debounce must land the session — no further turn and
463
+ // no barrier.
464
+ await buffer.addTurn("big", makeTurn("big", "more"));
465
+ const deadline = Date.now() + 3_000;
466
+ while (storage.writeCount("big") < 2 && Date.now() < deadline) await sleep(20);
467
+ assert.equal(
468
+ storage.writeCount("big"),
469
+ 2,
470
+ "a failed deferred save must re-arm a retry even with debounce off",
471
+ );
472
+ });
@@ -29,6 +29,54 @@ export interface BufferPersistOutcome {
29
29
  handedOver: string[];
30
30
  /** Per session, the turns a drain extracted, kept in their original lists. */
31
31
  drainedTurns: Map<string, DrainedTurnSets>;
32
+ /** Sessions whose rewrite this pass deferred (#3389); they stay dirty. */
33
+ deferred: string[];
34
+ /**
35
+ * Milliseconds until the earliest deferred session becomes rewrite-eligible
36
+ * (set only when `deferred` is non-empty). The caller arms a retry for this
37
+ * delay so a deferred tail of a burst lands without needing another turn.
38
+ */
39
+ deferredRetryDelayMs?: number;
40
+ }
41
+
42
+ /**
43
+ * Session files at or above this estimated serialized size get rate-limited
44
+ * rewrites on steady-state passes (issue #3389). A single hot session grew to
45
+ * ~44 MB and its whole-file rewrite dominated `durable-bufferMs` (~99% of
46
+ * observe latency, worst ~10 min) while real disk utilization sat at ~2%.
47
+ */
48
+ export const BUFFER_SESSION_DEFER_MIN_BYTES = 8 * 1024 * 1024;
49
+
50
+ /** A session past the size floor is rewritten at most once per this interval. */
51
+ export const BUFFER_SESSION_DEFER_INTERVAL_MS = 60_000;
52
+
53
+ export interface BufferPersistOptions {
54
+ /** Injectable clock (monotonic ms) for tests. */
55
+ now?: () => number;
56
+ /**
57
+ * Steady-state passes may defer rewriting a dirty session whose estimated
58
+ * size is at or above BUFFER_SESSION_DEFER_MIN_BYTES and whose last persist
59
+ * was within BUFFER_SESSION_DEFER_INTERVAL_MS. Durability barriers
60
+ * (extraction-trigger saves, explicit buffer.save / flushPendingSave,
61
+ * shutdown flushes) omit this: they always write. Deferral never applies to
62
+ * a session's first persist or to a drain-claimed session. Bounds match the
63
+ * sanctioned bufferSaveDebounceMs crash-loss window: deferred turns stay in
64
+ * memory until the next pass or a forced flush.
65
+ */
66
+ allowDeferral?: boolean;
67
+ }
68
+
69
+ /** Approximate serialized size of one session file without stringifying it. */
70
+ function estimateEntryBytes(entry: BufferEntryState): number {
71
+ // ~15% over content for JSON structure + string escaping (quotes, braces,
72
+ // key names, escape growth); the fixed per-turn overhead covers field names
73
+ // and metadata. Under-counting here biases against deferral — the exact
74
+ // case the floor exists for — so the estimate errs high.
75
+ let bytes = 256;
76
+ for (const turn of entry.turns) bytes += Math.ceil(turn.content.length * 1.15) + 128;
77
+ for (const turn of entry.retainedTurns ?? [])
78
+ bytes += Math.ceil(turn.content.length * 1.15) + 128;
79
+ return bytes;
32
80
  }
33
81
 
34
82
  /**
@@ -37,9 +85,25 @@ export interface BufferPersistOutcome {
37
85
  * Marks are cleared only after a durable write of that session. All calls
38
86
  * happen under SmartBuffer's serialized mutation chain: one writer.
39
87
  */
88
+ export interface BufferSessionPersistenceOptions {
89
+ /** Injectable clock (monotonic ms) for tests; defaults to performance.now(). */
90
+ now?: () => number;
91
+ /** Test seam: override BUFFER_SESSION_DEFER_INTERVAL_MS. */
92
+ deferIntervalMs?: number;
93
+ }
94
+
40
95
  export class BufferSessionPersistence {
41
96
  private readonly dirty = new Set<string>();
42
97
  private readonly deleted = new Set<string>();
98
+ /** Last successful session-file write per key (deferral bookkeeping, #3389). */
99
+ private readonly lastPersistedAt = new Map<string, number>();
100
+ private readonly clock: () => number;
101
+ private readonly deferIntervalMs: number;
102
+
103
+ constructor(options: BufferSessionPersistenceOptions = {}) {
104
+ this.clock = options.now ?? (() => performance.now());
105
+ this.deferIntervalMs = options.deferIntervalMs ?? BUFFER_SESSION_DEFER_INTERVAL_MS;
106
+ }
43
107
 
44
108
  markDirty(key: string): void {
45
109
  this.dirty.add(key);
@@ -49,6 +113,7 @@ export class BufferSessionPersistence {
49
113
  markDeleted(key: string): void {
50
114
  this.deleted.add(key);
51
115
  this.dirty.delete(key);
116
+ this.lastPersistedAt.delete(key);
52
117
  }
53
118
 
54
119
  /** Eviction removed `key` from memory: its session file must go, any pending write is moot. */
@@ -75,6 +140,7 @@ export class BufferSessionPersistence {
75
140
  state: BufferState,
76
141
  peekEntry: (key: string) => BufferEntryState | undefined,
77
142
  reconcile?: { key: string; drained: DrainedTurnSets },
143
+ opts?: BufferPersistOptions,
78
144
  ): Promise<BufferPersistOutcome> {
79
145
  const drainedTurns = new Map<string, DrainedTurnSets>(
80
146
  reconcile ? [[reconcile.key, reconcile.drained]] : [],
@@ -85,9 +151,12 @@ export class BufferSessionPersistence {
85
151
  await storage.saveBuffer(state);
86
152
  this.dirty.clear();
87
153
  this.deleted.clear();
88
- return { handedOver: [], drainedTurns };
154
+ return { handedOver: [], drainedTurns, deferred: [] };
89
155
  }
156
+ const now = opts?.now ?? this.clock;
90
157
  const handedOver: string[] = [];
158
+ const deferred: string[] = [];
159
+ let nextEligibleAt: number | undefined;
91
160
  for (const key of [...this.deleted]) {
92
161
  await deleteSession(key);
93
162
  this.deleted.delete(key);
@@ -100,21 +169,45 @@ export class BufferSessionPersistence {
100
169
  this.markDeleted(key);
101
170
  continue;
102
171
  }
103
- const outcome = await saveSession(key, entry);
172
+ if (opts?.allowDeferral === true && key !== reconcile?.key) {
173
+ const last = this.lastPersistedAt.get(key);
174
+ if (
175
+ last !== undefined &&
176
+ now() - last < this.deferIntervalMs &&
177
+ estimateEntryBytes(entry) >= BUFFER_SESSION_DEFER_MIN_BYTES &&
178
+ // Fail closed: a backend that omits isBufferSessionClaimed cannot
179
+ // prove the session is unclaimed, so it never defers (PR 3481 review).
180
+ storage.isBufferSessionClaimed?.(key) === false
181
+ ) {
182
+ deferred.push(key);
183
+ const eligibleAt = last + this.deferIntervalMs;
184
+ if (nextEligibleAt === undefined || eligibleAt < nextEligibleAt) {
185
+ nextEligibleAt = eligibleAt;
186
+ }
187
+ continue;
188
+ }
189
+ }
190
+ const saveOutcome = await saveSession(key, entry);
104
191
  this.dirty.delete(key);
192
+ this.lastPersistedAt.set(key, now());
105
193
  // "handed_over": the entry moved into a drain claim. Content is durable
106
194
  // in the claim, so this key's pending state is settled — the caller
107
195
  // evicts the in-memory entry on its side.
108
- if (outcome?.status === "handed_over") handedOver.push(key);
196
+ if (saveOutcome?.status === "handed_over") handedOver.push(key);
109
197
  // A drain tombstone: the turns it extracted must leave this process's
110
198
  // copy too, or the owner would extract them a second time.
111
199
  if (
112
- outcome?.drainedTurns &&
113
- (outcome.drainedTurns.turns.length > 0 || outcome.drainedTurns.retainedTurns.length > 0)
200
+ saveOutcome?.drainedTurns &&
201
+ (saveOutcome.drainedTurns.turns.length > 0 || saveOutcome.drainedTurns.retainedTurns.length > 0)
114
202
  ) {
115
- drainedTurns.set(key, outcome.drainedTurns);
203
+ drainedTurns.set(key, saveOutcome.drainedTurns);
116
204
  }
205
+ if (saveOutcome?.status === "handed_over") this.lastPersistedAt.delete(key);
206
+ }
207
+ const outcome: BufferPersistOutcome = { handedOver, drainedTurns, deferred };
208
+ if (deferred.length > 0 && nextEligibleAt !== undefined) {
209
+ outcome.deferredRetryDelayMs = Math.max(0, nextEligibleAt - now());
117
210
  }
118
- return { handedOver, drainedTurns };
211
+ return outcome;
119
212
  }
120
213
  }