@cortexkit/opencode-magic-context 0.49.103 → 0.49.105

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 (166) hide show
  1. package/dist/auto-search-worker.js +5 -5
  2. package/dist/chunk-embedding-write-worker.js +8 -5
  3. package/dist/{context-jk7bgc3s.js → context-wtnrsjkp.js} +116 -139
  4. package/dist/{embedding-backfill-anty7zdf.js → embedding-backfill-kqwx0vhj.js} +6 -6
  5. package/dist/{v2/embedding-cache-dveynq4m.js → embedding-cache-fhdkn9nc.js} +3 -1
  6. package/dist/embedding-worker.js +1 -1
  7. package/dist/features/magic-context/chunk-embedding-write-worker-install-failure.fixture.d.ts +2 -0
  8. package/dist/features/magic-context/chunk-embedding-write-worker-install-failure.fixture.d.ts.map +1 -0
  9. package/dist/features/magic-context/chunk-scope-repair-revision.d.ts +16 -1
  10. package/dist/features/magic-context/chunk-scope-repair-revision.d.ts.map +1 -1
  11. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  12. package/dist/features/magic-context/dreamer/verify-checkout.d.ts +2 -0
  13. package/dist/features/magic-context/dreamer/verify-checkout.d.ts.map +1 -0
  14. package/dist/features/magic-context/memory/embedding-cache.d.ts +1 -0
  15. package/dist/features/magic-context/memory/embedding-cache.d.ts.map +1 -1
  16. package/dist/features/magic-context/memory/embedding-worker-client.d.ts.map +1 -1
  17. package/dist/features/magic-context/memory/embedding-worker-loop.d.ts +9 -1
  18. package/dist/features/magic-context/memory/embedding-worker-loop.d.ts.map +1 -1
  19. package/dist/features/magic-context/memory/embedding-worker-observer.fixture.d.ts +26 -0
  20. package/dist/features/magic-context/memory/embedding-worker-observer.fixture.d.ts.map +1 -0
  21. package/dist/features/magic-context/message-fts-rowid-map-startup-worker-test-support.d.ts +2 -0
  22. package/dist/features/magic-context/message-fts-rowid-map-startup-worker-test-support.d.ts.map +1 -0
  23. package/dist/features/magic-context/project-embedding-registry.d.ts +5 -0
  24. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  25. package/dist/features/magic-context/search-pool-fixture.d.ts +15 -0
  26. package/dist/features/magic-context/search-pool-fixture.d.ts.map +1 -1
  27. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  28. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/compartment-runner-types.d.ts +4 -1
  30. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
  32. package/dist/hooks/magic-context/history-boundary-repair.d.ts +7 -2
  33. package/dist/hooks/magic-context/history-boundary-repair.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +1 -0
  35. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/transform.d.ts +1 -0
  37. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  38. package/dist/{index-3nxhxeeg.js → index-1j4q0bd6.js} +4 -4
  39. package/dist/{index-fd3hkyk1.js → index-42fsf88t.js} +1 -1
  40. package/dist/{v2/server-qbydvfev.js → index-6xg55350.js} +15 -11
  41. package/dist/{index-jjxpmypb.js → index-7z5cvfpg.js} +1 -1
  42. package/dist/{index-jg5whyrd.js → index-8vv7axxg.js} +3 -3
  43. package/dist/{index-42fg6tzz.js → index-92p5yfpp.js} +4 -4
  44. package/dist/{index-7jvc0rhh.js → index-9m2b5mwf.js} +21 -8
  45. package/dist/{index-9mxkvdtp.js → index-a3t1ck7g.js} +8 -8
  46. package/dist/{index-vhx6yph7.js → index-as8bg7eh.js} +367 -115
  47. package/dist/{index-jyj9jg9f.js → index-cxh5g5bt.js} +2 -2
  48. package/dist/{index-vegw385y.js → index-cy5fn70d.js} +89 -1
  49. package/dist/{index-4dywj733.js → index-dzb1yc9w.js} +1 -1
  50. package/dist/{index-t2h3484a.js → index-edafv9d7.js} +5 -5
  51. package/dist/{index-6t6v8prs.js → index-ff1hqh4a.js} +3 -3
  52. package/dist/{index-ke0mkz7g.js → index-g1h1efr0.js} +1 -1
  53. package/dist/{index-f455a0g3.js → index-k37h4yrb.js} +5 -3
  54. package/dist/{index-mes48s7a.js → index-mg6cwqw2.js} +220 -27
  55. package/dist/{index-nyjztqyj.js → index-p5ey52j9.js} +32 -5
  56. package/dist/{index-pw1f07vg.js → index-srpghrje.js} +1 -1
  57. package/dist/{index-4536jdzj.js → index-xzs1fxzz.js} +2 -2
  58. package/dist/{index-hyvxmz3e.js → index-y1875y4h.js} +1 -1
  59. package/dist/{index-4v50y0jr.js → index-ydevzvfs.js} +1 -1
  60. package/dist/{index-ab86c21b.js → index-zj0ra8vs.js} +1 -1
  61. package/dist/index.js +53 -62
  62. package/dist/migration-worker.js +3 -3
  63. package/dist/{project-embedding-registry-4cv7n37m.js → project-embedding-registry-0z0nd73p.js} +5 -5
  64. package/dist/raw-ordinal-warmup-worker.js +2 -2
  65. package/dist/{recomp-orchestrator-vg4cxyp7.js → recomp-orchestrator-zagjzbz5.js} +15 -15
  66. package/dist/{render-f32trg2t.js → render-vwp72qd0.js} +6 -6
  67. package/dist/{search-ygtyb91s.js → search-7e1rcqb7.js} +12 -12
  68. package/dist/{search-archive-yh6xtvrx.js → search-archive-6tr0gcf7.js} +2 -2
  69. package/dist/shared/sqlite-busy-test-support.d.ts +21 -0
  70. package/dist/shared/sqlite-busy-test-support.d.ts.map +1 -0
  71. package/dist/shared/sqlite-write-locker-test-support.d.ts +12 -0
  72. package/dist/shared/sqlite-write-locker-test-support.d.ts.map +1 -1
  73. package/dist/{storage-memory-p91f7b5h.js → storage-memory-24hsvzy8.js} +2 -2
  74. package/dist/{store-wpx314rk.js → store-4eeezg83.js} +2 -2
  75. package/dist/{store-reader-c5fwa9qx.js → store-reader-g8w2wp88.js} +1 -1
  76. package/dist/{transform-postprocess-phase-958fmjs5.js → transform-postprocess-phase-v3p3q2gf.js} +16 -16
  77. package/dist/v2/auto-search-worker.js +5 -5
  78. package/dist/v2/chunk-embedding-write-worker.js +8 -5
  79. package/dist/v2/{context-3g3jvxg8.js → context-fbdac7qt.js} +166 -150
  80. package/dist/v2/{embedding-backfill-ra9gbbs4.js → embedding-backfill-e44pv5db.js} +6 -6
  81. package/dist/{embedding-cache-dveynq4m.js → v2/embedding-cache-fhdkn9nc.js} +3 -1
  82. package/dist/v2/embedding-worker.js +1 -1
  83. package/dist/v2/event-subscription.fixture.d.ts +9 -0
  84. package/dist/v2/event-subscription.fixture.d.ts.map +1 -0
  85. package/dist/v2/hidden-model-activity.d.ts +13 -0
  86. package/dist/v2/hidden-model-activity.d.ts.map +1 -1
  87. package/dist/v2/hooks/context.d.ts +1 -0
  88. package/dist/v2/hooks/context.d.ts.map +1 -1
  89. package/dist/v2/hooks/dream-trigger.d.ts +2 -1
  90. package/dist/v2/hooks/dream-trigger.d.ts.map +1 -1
  91. package/dist/v2/hooks/event-subscription-worker.d.ts +11 -0
  92. package/dist/v2/hooks/event-subscription-worker.d.ts.map +1 -0
  93. package/dist/v2/hooks/types.d.ts +1 -0
  94. package/dist/v2/hooks/types.d.ts.map +1 -1
  95. package/dist/v2/hooks/update-check.d.ts +1 -0
  96. package/dist/v2/hooks/update-check.d.ts.map +1 -1
  97. package/dist/v2/{message-index-bounded-j1sxtefe.js → message-index-bounded-nwqfb1p5.js} +3 -3
  98. package/dist/v2/migration-worker.js +3 -3
  99. package/dist/v2/{project-embedding-registry-gdaqb7h0.js → project-embedding-registry-rhzjnypp.js} +5 -5
  100. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  101. package/dist/v2/{read-session-chunk-p6z3kmdj.js → read-session-chunk-brqatg83.js} +2 -2
  102. package/dist/v2/{recomp-orchestrator-29m3cc5b.js → recomp-orchestrator-1ech6k2n.js} +17 -17
  103. package/dist/v2/{render-jpj43axy.js → render-pfe3smhx.js} +10 -10
  104. package/dist/v2/{search-archive-wbhxp0p1.js → search-archive-r8krrz47.js} +5 -5
  105. package/dist/v2/{search-ybyc7vmx.js → search-sffewrs4.js} +15 -15
  106. package/dist/v2/{server-kx5egpt7.js → server-16115spd.js} +4 -4
  107. package/dist/v2/server-28jqb7s0.js +6 -0
  108. package/dist/v2/{server-qg8jyfxa.js → server-5xx10mqe.js} +1 -1
  109. package/dist/{index-qbydvfev.js → v2/server-6xg55350.js} +15 -11
  110. package/dist/v2/{server-t45hgcsg.js → server-7jw608jk.js} +2 -2
  111. package/dist/v2/{server-8f92sd2r.js → server-7pxjk184.js} +6 -4
  112. package/dist/v2/{server-3mb205v9.js → server-83rjf4df.js} +1 -1
  113. package/dist/v2/{server-df5scn4q.js → server-9t4yjj20.js} +27 -12
  114. package/dist/v2/{server-ga6y57vh.js → server-c32505fr.js} +6 -4
  115. package/dist/v2/{server-8m5wk6aq.js → server-cpb7b1f9.js} +5 -5
  116. package/dist/v2/{server-qdpd8h27.js → server-fn6k1ack.js} +1 -1
  117. package/dist/v2/{server-1qxdyz4p.js → server-ghb2q1z9.js} +2 -2
  118. package/dist/v2/{server-pqgnjf38.js → server-gkb0y83n.js} +32 -5
  119. package/dist/v2/{server-r851hxn5.js → server-hqcdvs2n.js} +13 -13
  120. package/dist/v2/{server-9ms9b75c.js → server-j00jprwm.js} +4 -6
  121. package/dist/v2/{server-xpy46ddq.js → server-jtd5vq5e.js} +3 -3
  122. package/dist/v2/{server-b01a7dhj.js → server-kk2kbzq3.js} +1 -1
  123. package/dist/v2/{server-mc5t7k8v.js → server-ma0qhqg9.js} +1 -1
  124. package/dist/v2/{server-x22jtpna.js → server-n3bfqd0j.js} +4 -2
  125. package/dist/v2/{server-fagcnt6j.js → server-pjvqyg6g.js} +367 -115
  126. package/dist/v2/{server-jrs4gny6.js → server-qtajgx1e.js} +89 -1
  127. package/dist/v2/{server-pw1f07vg.js → server-srpghrje.js} +1 -1
  128. package/dist/v2/server-t104h957.js +177 -0
  129. package/dist/v2/{server-j09jx1n9.js → server-v2r04xds.js} +1 -1
  130. package/dist/v2/{server-7c5p0bh1.js → server-z77hman6.js} +1 -1
  131. package/dist/v2/server.js +31 -40
  132. package/dist/v2/{storage-memory-p91f7b5h.js → storage-memory-24hsvzy8.js} +2 -2
  133. package/dist/v2/{storage-tags-s7nvvyg8.js → storage-tags-ee72g2zv.js} +1 -1
  134. package/dist/v2/{store-mba47sxn.js → store-9rsrj5pt.js} +2 -2
  135. package/dist/v2/{store-reader-w7w8vfsy.js → store-reader-tb0f9621.js} +1 -1
  136. package/dist/v2/store-reader.d.ts +1 -1
  137. package/dist/v2/store-reader.d.ts.map +1 -1
  138. package/dist/v2/tui/index.d.ts.map +1 -1
  139. package/dist/v2/{v2-archive-reader-5njmg3a3.js → v2-archive-reader-0xysfgxh.js} +1 -1
  140. package/dist/v2/{wrapup-orchestrator-ahkq8a61.js → wrapup-orchestrator-8d4ak3x3.js} +17 -17
  141. package/dist/{v2-archive-reader-y38khjax.js → v2-archive-reader-fac1zmhj.js} +1 -1
  142. package/dist/{wrapup-orchestrator-gjqaac65.js → wrapup-orchestrator-wz10b94c.js} +16 -16
  143. package/package.json +1 -1
  144. package/src/config/migrate-config-location.test.ts +41 -29
  145. package/src/shared/model-suggestion-retry.test.ts +137 -90
  146. package/src/shared/off-thread-migration-clock.test.ts +19 -9
  147. package/src/shared/prompt-async-transport.test.ts +125 -42
  148. package/src/shared/rpc-async-probes.test.ts +56 -36
  149. package/src/shared/rpc-client.test.ts +51 -18
  150. package/src/shared/sqlite-acquisition-routing.test.ts +79 -22
  151. package/src/shared/sqlite-busy-budget-review.test.ts +129 -111
  152. package/src/shared/sqlite-busy-test-support.ts +154 -0
  153. package/src/shared/sqlite-foreground-wait.test.ts +213 -156
  154. package/src/shared/sqlite-pass-scope.test.ts +142 -105
  155. package/src/shared/sqlite-turn-deadline.test.ts +149 -124
  156. package/src/shared/sqlite-write-locker-test-support.ts +44 -12
  157. package/src/shared/stable-json-linear.test.ts +29 -11
  158. package/src/shared/startup-maintenance-policy.test.ts +72 -2
  159. package/src/shared/storage-busy.test.ts +45 -18
  160. package/src/shared/storage-file-mutex-review.test.ts +65 -51
  161. package/src/shared/tui-preferences.test.ts +15 -5
  162. package/src/shared/worker-shutdown.test.ts +26 -20
  163. package/src/tui/data/notification-socket.test.ts +220 -108
  164. package/src/v2/tui/index.ts +5 -1
  165. package/src/v2/tui/status-dialog-fallback.test.ts +23 -1
  166. package/dist/v2/server-84w6rvvf.js +0 -14
@@ -0,0 +1,154 @@
1
+ import { Database as NativeDatabase, type SQLQueryBindings } from "bun:sqlite";
2
+
3
+ type Method = "exec" | "prepare" | "run" | "get" | "all" | "values" | "iterate.next";
4
+
5
+ /**
6
+ * Install before opening the connection: the router captures the native methods
7
+ * when it opens. Match only the SQL under test. Each matched native call sees a
8
+ * zero timeout so the real lock can return BUSY immediately; `timeouts` records
9
+ * the policy value before that change. Restore the spy after closing the fixture.
10
+ */
11
+ export function observeSqliteBusy(
12
+ matches: (sql: string, method: Method, db: NativeDatabase) => boolean,
13
+ onAttempt?: (timeout: number, sql: string) => void,
14
+ onBusy?: (timeout: number, sql: string) => void,
15
+ ) {
16
+ const timeouts: number[] = [];
17
+ const errors: unknown[] = [];
18
+ const prototype = NativeDatabase.prototype;
19
+ const { exec, prepare } = prototype;
20
+ const execProperty = Object.getOwnPropertyDescriptor(prototype, "exec");
21
+ const prepareProperty = Object.getOwnPropertyDescriptor(prototype, "prepare");
22
+ if (!execProperty || !prepareProperty) throw new Error("Missing native SQLite methods");
23
+ let active = true;
24
+ function probe<T>(db: NativeDatabase, sql: string, operation: () => T): T {
25
+ if (!active) return operation();
26
+ const pragma = prepare.call(db, "PRAGMA busy_timeout");
27
+ const { timeout } = pragma.get() as { timeout: number };
28
+ pragma.finalize();
29
+ timeouts.push(timeout);
30
+ onAttempt?.(timeout, sql);
31
+ if (timeout !== 0) exec.call(db, "PRAGMA busy_timeout=0");
32
+ try {
33
+ return operation();
34
+ } catch (error) {
35
+ // Some callers catch a busy error themselves and answer with
36
+ // something else (a "not written" value, or the previous request
37
+ // sent again). Keep every native error, and report a busy or
38
+ // locked one at once, so a test sees it before it is translated.
39
+ errors.push(error);
40
+ const code = (error as { code?: unknown })?.code;
41
+ if (
42
+ typeof code === "string" &&
43
+ (code.startsWith("SQLITE_BUSY") || code.startsWith("SQLITE_LOCKED"))
44
+ )
45
+ onBusy?.(timeout, sql);
46
+ throw error;
47
+ } finally {
48
+ if (timeout !== 0) exec.call(db, `PRAGMA busy_timeout=${timeout}`);
49
+ }
50
+ }
51
+ const testExec: typeof exec = function (this: NativeDatabase, sql, ...params) {
52
+ const operation = () => exec.call(this, sql, ...params);
53
+ return matches(sql, "exec", this) ? probe(this, sql, operation) : operation();
54
+ };
55
+ const testPrepare: typeof prepare = function <
56
+ Row,
57
+ Params extends SQLQueryBindings | SQLQueryBindings[],
58
+ >(this: NativeDatabase, sql: string, params?: Params) {
59
+ const native = prepare.bind(this) as typeof prepare;
60
+ const operation = () => native<Row, Params>(sql, params);
61
+ if (!active) return operation();
62
+ const statement = matches(sql, "prepare", this) ? probe(this, sql, operation) : operation();
63
+ for (const method of ["run", "get", "all", "values"] as const) {
64
+ if (!matches(sql, method, this)) continue;
65
+ const execute = statement[method].bind(statement);
66
+ Object.defineProperty(statement, method, {
67
+ configurable: true,
68
+ value: (...args: Parameters<typeof execute>) =>
69
+ probe(this, sql, () => execute(...args)),
70
+ });
71
+ }
72
+ if (matches(sql, "iterate.next", this)) {
73
+ const iterate = statement.iterate.bind(statement);
74
+ Object.defineProperty(statement, "iterate", {
75
+ configurable: true,
76
+ value: (...args: Parameters<typeof iterate>) => {
77
+ const iterator = iterate(...args);
78
+ const next = iterator.next.bind(iterator);
79
+ iterator.next = () => probe(this, sql, next);
80
+ return iterator;
81
+ },
82
+ });
83
+ }
84
+ return statement;
85
+ };
86
+ // Connections opened by the caller may retain the bound wrappers after
87
+ // restoration. Keep those wrappers callable, but stop observing them.
88
+ Object.defineProperty(prototype, "exec", { ...execProperty, value: testExec });
89
+ Object.defineProperty(prototype, "prepare", { ...prepareProperty, value: testPrepare });
90
+ return {
91
+ timeouts,
92
+ errors,
93
+ restore() {
94
+ active = false;
95
+ Object.defineProperty(prototype, "prepare", prepareProperty);
96
+ Object.defineProperty(prototype, "exec", execProperty);
97
+ },
98
+ };
99
+ }
100
+
101
+ /** Freeze the monotonic clock and advance retry timers one boundary at a time. */
102
+ export function startSqliteRetryClock(onSchedule?: (delay: number) => void) {
103
+ // Load the test runner only for the clock. Real worker entry fixtures can
104
+ // install the SQLite probe without running inside `bun test` themselves.
105
+ const { spyOn } = require("bun:test") as typeof import("bun:test");
106
+ let now = 0;
107
+ let nextId = 0;
108
+ const pending = new Map<number, { due: number; fire: () => void }>();
109
+ const monotonic = spyOn(performance, "now").mockImplementation(() => now);
110
+ const schedule = spyOn(globalThis, "setTimeout").mockImplementation(((
111
+ callback: (...args: unknown[]) => void,
112
+ delay = 0,
113
+ ...args: unknown[]
114
+ ) => {
115
+ const id = ++nextId;
116
+ pending.set(id, { due: now + delay, fire: () => callback(...args) });
117
+ onSchedule?.(delay);
118
+ // A virtual timer never keeps the process alive. Keep the handle methods
119
+ // used by callers that unref their real background timers.
120
+ return {
121
+ [Symbol.toPrimitive]: () => id,
122
+ ref() {
123
+ return this;
124
+ },
125
+ unref() {
126
+ return this;
127
+ },
128
+ };
129
+ }) as unknown as typeof setTimeout);
130
+ const cancel = spyOn(globalThis, "clearTimeout").mockImplementation((id) => {
131
+ pending.delete(Number(id));
132
+ });
133
+ return {
134
+ // Synchronous work can cross a deadline without letting its timer run.
135
+ elapse(ms: number) {
136
+ now += ms;
137
+ },
138
+ async advance(ms: number) {
139
+ now += ms;
140
+ for (const [id, timer] of [...pending]) {
141
+ if (timer.due > now || !pending.delete(id)) continue;
142
+ timer.fire();
143
+ }
144
+ // A retry can itself suspend before scheduling the following timer.
145
+ await Promise.resolve();
146
+ },
147
+ restore() {
148
+ cancel.mockRestore();
149
+ schedule.mockRestore();
150
+ monotonic.mockRestore();
151
+ pending.clear();
152
+ },
153
+ };
154
+ }
@@ -13,7 +13,8 @@ import {
13
13
  withPrivilegedWriter,
14
14
  withSqliteTransformPass,
15
15
  } from "./sqlite";
16
- import { type SqliteWriteLocker, startSqliteWriteLocker } from "./sqlite-write-locker-test-support";
16
+ import { observeSqliteBusy } from "./sqlite-busy-test-support";
17
+ import { startGatedSqliteWriteLocker } from "./sqlite-write-locker-test-support";
17
18
  import { createTestTempDirFromPath } from "./test-temp-dir";
18
19
 
19
20
  function fixture() {
@@ -36,87 +37,117 @@ function fixture() {
36
37
  };
37
38
  }
38
39
 
39
- for (const holdMs of [1000, 2500]) {
40
- test(holdMs === 1000
41
- ? "a transform commits and serves managed output after a 1s in-pass writer lock"
42
- : "a transform refuses a 2.5s in-pass writer lock without raw fallback and logs the real wait", async () => {
43
- const { db, path, close } = fixture();
44
- const sessionId = `foreground-wait-${holdMs}`;
45
- const output = {
46
- messages: [
47
- {
48
- info: { id: "u", sessionID: sessionId, role: "user" },
49
- parts: [{ type: "text", text: "raw input must not be served on failure" }],
40
+ for (const refused of [false, true]) {
41
+ test(
42
+ refused
43
+ ? "a transform refuses exhausted in-pass writer acquisition without raw fallback and logs the wait"
44
+ : "a transform commits and serves managed output after a contended in-pass writer releases",
45
+ async () => {
46
+ let now = 0;
47
+ let watched: unknown;
48
+ const probe = observeSqliteBusy(
49
+ (sql, method, connection) =>
50
+ connection === watched && sql === "BEGIN IMMEDIATE" && method === "exec",
51
+ () => {
52
+ now += refused ? 2000 : 1000;
50
53
  },
51
- ],
52
- };
53
- let locker: SqliteWriteLocker | undefined;
54
- let refusals = 0;
55
- let served = false;
56
- let waitedMs = 0;
57
- const diagnostics: string[] = [];
58
- registerSqliteDiagnosticSink((line) => diagnostics.push(line));
59
- const handler = createMessagesTransformHandler({
60
- onRefusal: async (id) => {
61
- expect(id).toBe(sessionId);
62
- refusals++;
63
- },
64
- magicContext: {
65
- "experimental.chat.messages.transform": async (_input, result) => {
66
- // Start the competing writer only once the transform callback begins;
67
- // otherwise the wrapper's yielding lock check would absorb the wait.
68
- locker = await startSqliteWriteLocker(path, holdMs);
69
- const started = performance.now();
70
- try {
71
- withPrivilegedWriter(db, () => {
72
- db.prepare("INSERT INTO result VALUES ('managed')").run();
73
- });
74
- } finally {
75
- waitedMs = performance.now() - started;
76
- }
77
- (result.messages[0].parts[0] as { text: string }).text = "managed output";
54
+ );
55
+ const { db, path, close } = fixture();
56
+ watched = db;
57
+ const sessionId = `foreground-wait-${refused}`;
58
+ const output = {
59
+ messages: [
60
+ {
61
+ info: { id: "u", sessionID: sessionId, role: "user" },
62
+ parts: [{ type: "text", text: "raw input must not be served on failure" }],
63
+ },
64
+ ],
65
+ };
66
+ let locker: Awaited<ReturnType<typeof startGatedSqliteWriteLocker>> | undefined;
67
+ let refusals = 0;
68
+ let served = false;
69
+ const clock = spyOn(performance, "now").mockImplementation(() => now);
70
+ const diagnostics: string[] = [];
71
+ registerSqliteDiagnosticSink((line) => diagnostics.push(line));
72
+ const handler = createMessagesTransformHandler({
73
+ onRefusal: async (id) => {
74
+ expect(id).toBe(sessionId);
75
+ refusals++;
76
+ },
77
+ magicContext: {
78
+ "experimental.chat.messages.transform": async (_input, result) => {
79
+ // Start the competing writer only once the transform callback begins;
80
+ // otherwise the wrapper's yielding lock check would absorb the wait.
81
+ locker = await startGatedSqliteWriteLocker(path);
82
+ const write = () =>
83
+ withPrivilegedWriter(db, () => {
84
+ db.prepare("INSERT INTO result VALUES ('managed')").run();
85
+ });
86
+ if (refused) write();
87
+ else {
88
+ expect(write).toThrow(SqliteAcquisitionBusyError);
89
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([]);
90
+ locker.release();
91
+ expect(await locker.exited).toBe(0);
92
+ write();
93
+ }
94
+ (result.messages[0].parts[0] as { text: string }).text = "managed output";
95
+ },
78
96
  },
79
- },
80
- });
81
- try {
82
- const pass = handler({}, output as Parameters<typeof handler>[1]).then((messages) => {
83
- served = true;
84
- return messages;
85
97
  });
86
- if (holdMs === 1000) {
87
- await pass;
88
- expect(served).toBe(true);
89
- expect(refusals).toBe(0);
90
- expect(output.messages[0].parts[0].text).toBe("managed output");
91
- expect(db.prepare("SELECT * FROM result").all()).toEqual([{ value: "managed" }]);
92
- expect(waitedMs).toBeGreaterThanOrEqual(900);
93
- } else {
94
- await expect(pass).rejects.toBeInstanceOf(StorageBusyRefusalError);
95
- expect(served).toBe(false);
96
- expect(refusals).toBe(1);
97
- expect(db.prepare("SELECT * FROM result").all()).toEqual([]);
98
- expect(waitedMs).toBeGreaterThanOrEqual(1900);
99
- expect(waitedMs).toBeLessThan(2400);
100
- const busy = diagnostics.filter((line) => line.includes("outcome=busy"));
101
- expect(busy).toHaveLength(1);
102
- expect(busy[0]).toContain("lane=foreground");
103
- const reportedMs = Number(/acquire_ms=(\d+)/.exec(busy[0])?.[1]);
104
- expect(Math.abs(reportedMs - waitedMs)).toBeLessThan(100);
98
+ try {
99
+ const pass = handler({}, output as Parameters<typeof handler>[1]).then(
100
+ (messages) => {
101
+ served = true;
102
+ return messages;
103
+ },
104
+ );
105
+ if (!refused) {
106
+ await pass;
107
+ expect(served).toBe(true);
108
+ expect(refusals).toBe(0);
109
+ expect(output.messages[0].parts[0].text).toBe("managed output");
110
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([
111
+ { value: "managed" },
112
+ ]);
113
+ expect(probe.timeouts).toEqual([2000, 1000]);
114
+ } else {
115
+ await expect(pass).rejects.toBeInstanceOf(StorageBusyRefusalError);
116
+ expect(served).toBe(false);
117
+ expect(refusals).toBe(1);
118
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([]);
119
+ expect(probe.timeouts).toEqual([2000]);
120
+ const busy = diagnostics.filter((line) => line.includes("outcome=busy"));
121
+ expect(busy).toHaveLength(1);
122
+ expect(busy[0]).toContain("lane=foreground");
123
+ expect(busy[0]).toContain("acquire_ms=2000 attempts=1");
124
+ }
125
+ expect(db.inTransaction).toBe(false);
126
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
127
+ } finally {
128
+ registerSqliteDiagnosticSink(log);
129
+ clock.mockRestore();
130
+ locker?.release();
131
+ if (locker) expect(await locker.exited).toBe(0);
132
+ close();
133
+ probe.restore();
105
134
  }
106
- expect(db.inTransaction).toBe(false);
107
- expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
108
- } finally {
109
- registerSqliteDiagnosticSink(log);
110
- if (locker) expect(await locker.exited).toBe(0);
111
- close();
112
- }
113
- }, 30_000);
135
+ },
136
+ );
114
137
  }
115
138
 
116
- for (const holdMs of [1000, 2500]) {
117
- test(`slow uncontended SQL preserves admission for a ${holdMs}ms autocommit lock`, async () => {
139
+ for (const refused of [false, true]) {
140
+ test(`slow uncontended SQL preserves the autocommit budget before ${refused ? "refusal" : "success after release"}`, async () => {
141
+ let now = 0;
142
+ const probe = observeSqliteBusy(
143
+ (sql, method) => method === "run" && sql.startsWith("INSERT INTO result"),
144
+ () => {
145
+ now += 3000;
146
+ },
147
+ );
118
148
  const { db, path, close } = fixture();
119
- let locker: SqliteWriteLocker | undefined;
149
+ let locker: Awaited<ReturnType<typeof startGatedSqliteWriteLocker>> | undefined;
150
+ const clock = spyOn(performance, "now").mockImplementation(() => now);
120
151
  let served = false;
121
152
  let refusals = 0;
122
153
  const output = {
@@ -133,21 +164,23 @@ for (const holdMs of [1000, 2500]) {
133
164
  },
134
165
  magicContext: {
135
166
  "experimental.chat.messages.transform": async (_input, result) => {
136
- // Spend three seconds inside successful SQL, not between writes.
137
- // Recursive work keeps this independent of CPU speed and UDF APIs.
138
- const cte =
139
- "WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<1000000)";
140
- const slowWrite = db.prepare(
141
- `${cte} INSERT INTO result SELECT sum(x) FROM n RETURNING value`,
142
- );
143
- const slowRead = db.prepare(`${cte} SELECT sum(x) FROM n`);
144
- const started = performance.now();
145
- do {
146
- slowWrite.all();
147
- slowRead.all();
148
- } while (performance.now() - started < 3000);
149
- locker = await startSqliteWriteLocker(path, holdMs);
150
- db.prepare("INSERT INTO result VALUES ('managed')").run();
167
+ // This write succeeds without contention, and the stubbed
168
+ // `performance.now` jumps forward when it enters SQLite, so it
169
+ // looks slow. Time a statement spends executing must not be
170
+ // charged to the lock-wait allowance; only waiting for a lock is.
171
+ db.prepare("INSERT INTO result VALUES ('uncontended')").run();
172
+ locker = await startGatedSqliteWriteLocker(path);
173
+ const write = () => db.prepare("INSERT INTO result VALUES ('managed')").run();
174
+ if (refused) write();
175
+ else {
176
+ expect(write).toThrow(SqliteAcquisitionBusyError);
177
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([
178
+ { value: "uncontended" },
179
+ ]);
180
+ locker.release();
181
+ expect(await locker.exited).toBe(0);
182
+ write();
183
+ }
151
184
  (result.messages[0].parts[0] as { text: string }).text = "managed";
152
185
  },
153
186
  },
@@ -156,7 +189,7 @@ for (const holdMs of [1000, 2500]) {
156
189
  const pass = handler({}, output as Parameters<typeof handler>[1]).then(() => {
157
190
  served = true;
158
191
  });
159
- if (holdMs === 1000) {
192
+ if (!refused) {
160
193
  await pass;
161
194
  expect(served).toBe(true);
162
195
  expect(refusals).toBe(0);
@@ -167,17 +200,28 @@ for (const holdMs of [1000, 2500]) {
167
200
  expect(refusals).toBe(1);
168
201
  expect(output.messages[0].parts[0].text).toBe("raw");
169
202
  }
170
- expect(
171
- db.prepare("SELECT count(*) AS n FROM result WHERE value = 'managed'").get(),
172
- ).toEqual({ n: holdMs === 1000 ? 1 : 0 });
203
+ expect(probe.timeouts).toEqual(refused ? [0, 0, 2000] : [0, 0, 2000, 0]);
204
+ expect(db.prepare("SELECT * FROM result ORDER BY rowid").all()).toEqual(
205
+ refused
206
+ ? [{ value: "uncontended" }]
207
+ : [{ value: "uncontended" }, { value: "managed" }],
208
+ );
209
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
173
210
  } finally {
211
+ clock.mockRestore();
212
+ locker?.release();
174
213
  if (locker) expect(await locker.exited).toBe(0);
175
214
  close();
215
+ probe.restore();
176
216
  }
177
- }, 30_000);
217
+ });
178
218
  }
179
219
 
180
220
  test("BUSY autocommit probes do not double-apply INSERT OR IGNORE, UPSERT or RETURNING", async () => {
221
+ let activeSql: string | undefined;
222
+ const probe = observeSqliteBusy(
223
+ (sql, method) => sql === activeSql && ["run", "get", "all"].includes(method),
224
+ );
181
225
  const { db, path, close } = fixture();
182
226
  db.exec(
183
227
  "CREATE TABLE counter(id INTEGER PRIMARY KEY, n INTEGER); INSERT INTO counter VALUES (1, 0)",
@@ -193,24 +237,24 @@ test("BUSY autocommit probes do not double-apply INSERT OR IGNORE, UPSERT or RET
193
237
  ] as const;
194
238
  try {
195
239
  for (const [sql, method] of forms) {
196
- const blocker = new Database(path);
197
- blocker.exec("BEGIN IMMEDIATE");
198
- db.exec("PRAGMA busy_timeout=0");
240
+ activeSql = sql;
241
+ const statement = db.prepare(sql);
242
+ probe.timeouts.length = 0;
243
+ const locker = await startGatedSqliteWriteLocker(path);
199
244
  const before = db.prepare("SELECT * FROM counter ORDER BY id").all();
200
245
  try {
201
- expect(() => db.prepare(sql)[method]()).toThrow("locked");
246
+ expect(() => withSqliteTransformPass(() => statement[method]())).toThrow(
247
+ SqliteAcquisitionBusyError,
248
+ );
249
+ expect(probe.timeouts).toEqual([0, 2000]);
202
250
  expect(db.prepare("SELECT * FROM counter ORDER BY id").all()).toEqual(before);
203
251
  expect(db.inTransaction).toBe(false);
252
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
204
253
  } finally {
205
- blocker.exec("ROLLBACK");
206
- blocker.close();
207
- }
208
- const locker = await startSqliteWriteLocker(path, 100);
209
- try {
210
- await withSqliteTransformPass(() => db.prepare(sql)[method]());
211
- } finally {
254
+ locker.release();
212
255
  expect(await locker.exited).toBe(0);
213
256
  }
257
+ await withSqliteTransformPass(() => statement[method]());
214
258
  }
215
259
  expect(db.prepare("SELECT * FROM counter ORDER BY id").all()).toEqual([
216
260
  { id: 1, n: 3 },
@@ -218,54 +262,50 @@ test("BUSY autocommit probes do not double-apply INSERT OR IGNORE, UPSERT or RET
218
262
  ]);
219
263
  } finally {
220
264
  close();
265
+ probe.restore();
221
266
  }
222
- }, 30_000);
267
+ });
223
268
 
224
269
  test("many contended autocommit writes share at most two seconds of lock waiting", async () => {
270
+ let now = 0;
271
+ const probe = observeSqliteBusy(
272
+ (sql, method) => method === "run" && sql.includes("'one'"),
273
+ (timeout) => {
274
+ if (timeout !== 0) now += 400;
275
+ },
276
+ );
225
277
  const { db, path, close } = fixture();
226
- const blocker = new Database(path);
227
- blocker.exec("BEGIN IMMEDIATE");
228
- const timeouts: number[] = [];
229
- const nativeExec = db.exec.bind(db);
230
- const exec = spyOn(db, "exec").mockImplementation((sql) => {
231
- const timeout = /^PRAGMA busy_timeout=(\d+)$/.exec(sql);
232
- if (timeout) timeouts.push(Number(timeout[1]));
233
- return nativeExec(sql);
234
- });
278
+ const locker = await startGatedSqliteWriteLocker(path);
279
+ const clock = spyOn(performance, "now").mockImplementation(() => now);
235
280
  try {
236
- await withSqliteTransformPass(() => {
237
- // Use real BUSY failures but a controlled accounting clock: each
238
- // retry costs 400ms regardless of runner scheduling. The deadline
239
- // keeps the real waits short without hiding lease exhaustion.
281
+ await withSqliteTransformPass(async () => {
240
282
  guardSqliteTransformPass({ assert() {}, remainingMs: () => 10 });
241
- let now = 0;
242
- const clock = spyOn(performance, "now").mockImplementation(() => (now += 400));
243
- try {
244
- for (let i = 0; i < 8; i++) {
245
- expect(() => db.prepare("INSERT INTO result VALUES ('one')").run()).toThrow(
246
- SqliteAcquisitionBusyError,
247
- );
248
- }
249
- } finally {
250
- clock.mockRestore();
283
+ for (let i = 0; i < 8; i++) {
284
+ expect(() => db.prepare("INSERT INTO result VALUES ('one')").run()).toThrow(
285
+ SqliteAcquisitionBusyError,
286
+ );
251
287
  }
252
288
  // Five charged retries exhaust 2000ms. All later retries must have
253
289
  // zero timeout even though the deadline still offers another 10ms.
254
- expect(timeouts).toEqual([
255
- ...Array.from({ length: 5 }, () => [0, 10, 5000]).flat(),
256
- ...Array.from({ length: 3 }, () => [0, 0, 5000]).flat(),
290
+ expect(probe.timeouts).toEqual([
291
+ ...Array.from({ length: 5 }, () => [0, 10]).flat(),
292
+ ...Array(6).fill(0),
257
293
  ]);
258
- blocker.exec("ROLLBACK");
294
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([]);
295
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
296
+ locker.release();
297
+ expect(await locker.exited).toBe(0);
259
298
  db.prepare("INSERT INTO result VALUES ('uncontended')").run();
260
299
  });
261
300
  expect(db.prepare("SELECT * FROM result").all()).toEqual([{ value: "uncontended" }]);
262
301
  } finally {
263
- exec.mockRestore();
264
- if (blocker.inTransaction) blocker.exec("ROLLBACK");
265
- blocker.close();
302
+ clock.mockRestore();
303
+ locker.release();
304
+ await locker.exited;
266
305
  close();
306
+ probe.restore();
267
307
  }
268
- }, 30_000);
308
+ });
269
309
 
270
310
  test("an exec script charges its single attempt without a zero-wait probe", () => {
271
311
  const { db, path, close } = fixture();
@@ -328,39 +368,52 @@ test("an explicit transaction keeps its timeout and never probes or retries", ()
328
368
  });
329
369
 
330
370
  for (const mode of ["BEGIN", "autocommit"]) {
331
- test(`foreground ${mode} wait is capped by the pass deadline`, () => {
371
+ test(`foreground ${mode} wait is capped by the pass deadline`, async () => {
372
+ const sql = "INSERT INTO result VALUES ('late')";
373
+ const probe = observeSqliteBusy((statement, method) =>
374
+ mode === "BEGIN"
375
+ ? method === "exec" && statement === "BEGIN IMMEDIATE"
376
+ : method === "run" && statement === sql,
377
+ );
332
378
  const { db, path, close } = fixture();
333
- const blocker = new Database(path);
334
- blocker.exec("BEGIN IMMEDIATE");
335
- try {
336
- const started = performance.now();
379
+ const locker = await startGatedSqliteWriteLocker(path);
380
+ const write = () => db.prepare(sql).run();
381
+ const attempt = () =>
337
382
  withSqliteTransformPass(() => {
338
383
  guardSqliteTransformPass({ assert() {}, remainingMs: () => 100 });
339
- expect(() => {
340
- if (mode === "BEGIN") withPrivilegedWriter(db, () => undefined);
341
- else db.prepare("INSERT INTO result VALUES ('late')").run();
342
- }).toThrow(SqliteAcquisitionBusyError);
384
+ if (mode === "BEGIN") withPrivilegedWriter(db, write);
385
+ else write();
343
386
  });
344
- expect(performance.now() - started).toBeGreaterThanOrEqual(75);
345
- expect(performance.now() - started).toBeLessThan(700);
387
+ try {
388
+ expect(attempt).toThrow(SqliteAcquisitionBusyError);
389
+ expect(probe.timeouts).toEqual(mode === "BEGIN" ? [100] : [0, 100]);
346
390
  expect(db.prepare("SELECT * FROM result").all()).toEqual([]);
347
391
  expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
392
+ locker.release();
393
+ expect(await locker.exited).toBe(0);
394
+ attempt();
395
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([{ value: "late" }]);
348
396
  } finally {
349
- blocker.exec("ROLLBACK");
350
- blocker.close();
397
+ locker.release();
398
+ await locker.exited;
351
399
  close();
400
+ probe.restore();
352
401
  }
353
402
  });
354
403
  }
355
404
 
356
- test("an autocommit exec script never replays a committed prefix after BUSY", () => {
405
+ test("an autocommit exec script never replays a committed prefix after BUSY", async () => {
406
+ const probe = observeSqliteBusy(
407
+ (sql, method) => method === "exec" && sql.includes("'blocked'"),
408
+ );
357
409
  const main = fixture();
358
410
  const auxiliary = fixture();
359
411
  const free = fixture();
412
+ main.db.prepare("ATTACH DATABASE ? AS aux").run(auxiliary.path);
413
+ main.db.prepare("ATTACH DATABASE ? AS free").run(free.path);
414
+ const locker = await startGatedSqliteWriteLocker(auxiliary.path);
415
+ const clock = spyOn(performance, "now").mockReturnValue(0);
360
416
  try {
361
- main.db.prepare("ATTACH DATABASE ? AS aux").run(auxiliary.path);
362
- main.db.prepare("ATTACH DATABASE ? AS free").run(free.path);
363
- auxiliary.db.exec("BEGIN IMMEDIATE");
364
417
  withSqliteTransformPass(() => {
365
418
  guardSqliteTransformPass({ assert() {}, remainingMs: () => 100 });
366
419
  expect(() =>
@@ -379,14 +432,18 @@ test("an autocommit exec script never replays a committed prefix after BUSY", ()
379
432
  ),
380
433
  ).toThrow(SqliteAcquisitionBusyError);
381
434
  });
435
+ expect(probe.timeouts).toEqual([100, 100, 100]);
382
436
  expect(main.db.prepare("SELECT * FROM main.result").all()).toEqual([{ value: "prefix" }]);
383
437
  expect(
384
438
  main.db.prepare("SELECT name FROM sqlite_schema WHERE name='applied_once'").all(),
385
439
  ).toHaveLength(1);
386
440
  } finally {
387
- auxiliary.db.exec("ROLLBACK");
441
+ clock.mockRestore();
442
+ locker.release();
443
+ expect(await locker.exited).toBe(0);
388
444
  auxiliary.close();
389
445
  main.close();
390
446
  free.close();
447
+ probe.restore();
391
448
  }
392
449
  });