@cortexkit/opencode-magic-context 0.49.104 → 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 (149) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +8 -5
  3. package/dist/{context-7hbmnpe8.js → context-wtnrsjkp.js} +113 -136
  4. package/dist/{embedding-backfill-aratv25b.js → embedding-backfill-kqwx0vhj.js} +4 -4
  5. package/dist/features/magic-context/chunk-embedding-write-worker-install-failure.fixture.d.ts +2 -0
  6. package/dist/features/magic-context/chunk-embedding-write-worker-install-failure.fixture.d.ts.map +1 -0
  7. package/dist/features/magic-context/chunk-scope-repair-revision.d.ts +16 -1
  8. package/dist/features/magic-context/chunk-scope-repair-revision.d.ts.map +1 -1
  9. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  10. package/dist/features/magic-context/dreamer/verify-checkout.d.ts +2 -0
  11. package/dist/features/magic-context/dreamer/verify-checkout.d.ts.map +1 -0
  12. package/dist/features/magic-context/memory/embedding-worker-observer.fixture.d.ts +26 -0
  13. package/dist/features/magic-context/memory/embedding-worker-observer.fixture.d.ts.map +1 -0
  14. package/dist/features/magic-context/message-fts-rowid-map-startup-worker-test-support.d.ts +2 -0
  15. package/dist/features/magic-context/message-fts-rowid-map-startup-worker-test-support.d.ts.map +1 -0
  16. package/dist/features/magic-context/project-embedding-registry.d.ts +5 -0
  17. package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
  18. package/dist/features/magic-context/search-pool-fixture.d.ts +15 -0
  19. package/dist/features/magic-context/search-pool-fixture.d.ts.map +1 -1
  20. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  22. package/dist/hooks/magic-context/compartment-runner-types.d.ts +4 -1
  23. package/dist/hooks/magic-context/compartment-runner-types.d.ts.map +1 -1
  24. package/dist/hooks/magic-context/compartment-runner.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/history-boundary-repair.d.ts +7 -2
  26. package/dist/hooks/magic-context/history-boundary-repair.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/transform-compartment-phase.d.ts +1 -0
  28. package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
  29. package/dist/hooks/magic-context/transform.d.ts +1 -0
  30. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  31. package/dist/{index-3nxhxeeg.js → index-1j4q0bd6.js} +4 -4
  32. package/dist/{index-fd3hkyk1.js → index-42fsf88t.js} +1 -1
  33. package/dist/{index-jjxpmypb.js → index-7z5cvfpg.js} +1 -1
  34. package/dist/{index-a9wn0d9h.js → index-8vv7axxg.js} +3 -3
  35. package/dist/{index-8yj4vd7k.js → index-92p5yfpp.js} +1 -1
  36. package/dist/{index-sqvkh5d0.js → index-9m2b5mwf.js} +20 -7
  37. package/dist/{index-mwjvjn0p.js → index-a3t1ck7g.js} +6 -6
  38. package/dist/{index-4ba3zp54.js → index-as8bg7eh.js} +365 -113
  39. package/dist/{index-8eke8yh2.js → index-cxh5g5bt.js} +1 -1
  40. package/dist/{index-vegw385y.js → index-cy5fn70d.js} +89 -1
  41. package/dist/{index-4dywj733.js → index-dzb1yc9w.js} +1 -1
  42. package/dist/{index-tvh3y650.js → index-edafv9d7.js} +5 -5
  43. package/dist/{index-8gzmeyae.js → index-ff1hqh4a.js} +3 -3
  44. package/dist/{index-ke0mkz7g.js → index-g1h1efr0.js} +1 -1
  45. package/dist/{index-f455a0g3.js → index-k37h4yrb.js} +5 -3
  46. package/dist/{index-3rp2b482.js → index-mg6cwqw2.js} +217 -24
  47. package/dist/{index-4536jdzj.js → index-xzs1fxzz.js} +2 -2
  48. package/dist/{index-hyvxmz3e.js → index-y1875y4h.js} +1 -1
  49. package/dist/{index-4v50y0jr.js → index-ydevzvfs.js} +1 -1
  50. package/dist/{index-ab86c21b.js → index-zj0ra8vs.js} +1 -1
  51. package/dist/index.js +50 -59
  52. package/dist/migration-worker.js +3 -3
  53. package/dist/{project-embedding-registry-1n4cexsv.js → project-embedding-registry-0z0nd73p.js} +3 -3
  54. package/dist/raw-ordinal-warmup-worker.js +2 -2
  55. package/dist/{recomp-orchestrator-16rs8aty.js → recomp-orchestrator-zagjzbz5.js} +12 -12
  56. package/dist/{render-f32trg2t.js → render-vwp72qd0.js} +6 -6
  57. package/dist/{search-v9ywqb4f.js → search-7e1rcqb7.js} +9 -9
  58. package/dist/{search-archive-yh6xtvrx.js → search-archive-6tr0gcf7.js} +2 -2
  59. package/dist/shared/sqlite-busy-test-support.d.ts +21 -0
  60. package/dist/shared/sqlite-busy-test-support.d.ts.map +1 -0
  61. package/dist/shared/sqlite-write-locker-test-support.d.ts +12 -0
  62. package/dist/shared/sqlite-write-locker-test-support.d.ts.map +1 -1
  63. package/dist/{store-wpx314rk.js → store-4eeezg83.js} +2 -2
  64. package/dist/{store-reader-c5fwa9qx.js → store-reader-g8w2wp88.js} +1 -1
  65. package/dist/{transform-postprocess-phase-yef4mxk3.js → transform-postprocess-phase-v3p3q2gf.js} +13 -13
  66. package/dist/v2/auto-search-worker.js +3 -3
  67. package/dist/v2/chunk-embedding-write-worker.js +8 -5
  68. package/dist/v2/{context-mk2h2ven.js → context-fbdac7qt.js} +163 -147
  69. package/dist/v2/{embedding-backfill-kyn5sv0f.js → embedding-backfill-e44pv5db.js} +4 -4
  70. package/dist/v2/event-subscription.fixture.d.ts +9 -0
  71. package/dist/v2/event-subscription.fixture.d.ts.map +1 -0
  72. package/dist/v2/hidden-model-activity.d.ts +13 -0
  73. package/dist/v2/hidden-model-activity.d.ts.map +1 -1
  74. package/dist/v2/hooks/context.d.ts +1 -0
  75. package/dist/v2/hooks/context.d.ts.map +1 -1
  76. package/dist/v2/hooks/dream-trigger.d.ts +2 -1
  77. package/dist/v2/hooks/dream-trigger.d.ts.map +1 -1
  78. package/dist/v2/hooks/event-subscription-worker.d.ts +11 -0
  79. package/dist/v2/hooks/event-subscription-worker.d.ts.map +1 -0
  80. package/dist/v2/hooks/types.d.ts +1 -0
  81. package/dist/v2/hooks/types.d.ts.map +1 -1
  82. package/dist/v2/hooks/update-check.d.ts +1 -0
  83. package/dist/v2/hooks/update-check.d.ts.map +1 -1
  84. package/dist/v2/{message-index-bounded-j1sxtefe.js → message-index-bounded-nwqfb1p5.js} +3 -3
  85. package/dist/v2/migration-worker.js +3 -3
  86. package/dist/v2/{project-embedding-registry-1jv2rxhb.js → project-embedding-registry-rhzjnypp.js} +3 -3
  87. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  88. package/dist/v2/{read-session-chunk-p6z3kmdj.js → read-session-chunk-brqatg83.js} +2 -2
  89. package/dist/v2/{recomp-orchestrator-5t2csd46.js → recomp-orchestrator-1ech6k2n.js} +14 -14
  90. package/dist/v2/{render-jpj43axy.js → render-pfe3smhx.js} +10 -10
  91. package/dist/v2/{search-archive-wbhxp0p1.js → search-archive-r8krrz47.js} +5 -5
  92. package/dist/v2/{search-w9m2fd5c.js → search-sffewrs4.js} +12 -12
  93. package/dist/v2/{server-47ajg9xc.js → server-16115spd.js} +1 -1
  94. package/dist/v2/server-28jqb7s0.js +6 -0
  95. package/dist/v2/{server-qg8jyfxa.js → server-5xx10mqe.js} +1 -1
  96. package/dist/v2/{server-t45hgcsg.js → server-7jw608jk.js} +2 -2
  97. package/dist/v2/{server-8f92sd2r.js → server-7pxjk184.js} +6 -4
  98. package/dist/v2/{server-3mb205v9.js → server-83rjf4df.js} +1 -1
  99. package/dist/v2/{server-3gnpqjez.js → server-9t4yjj20.js} +26 -11
  100. package/dist/v2/{server-ga6y57vh.js → server-c32505fr.js} +6 -4
  101. package/dist/v2/{server-8m5wk6aq.js → server-cpb7b1f9.js} +5 -5
  102. package/dist/v2/{server-qdpd8h27.js → server-fn6k1ack.js} +1 -1
  103. package/dist/v2/{server-zsbc0n4v.js → server-ghb2q1z9.js} +1 -1
  104. package/dist/v2/{server-af51b1zg.js → server-hqcdvs2n.js} +11 -11
  105. package/dist/v2/{server-9ms9b75c.js → server-j00jprwm.js} +4 -6
  106. package/dist/v2/{server-xpy46ddq.js → server-jtd5vq5e.js} +3 -3
  107. package/dist/v2/{server-b01a7dhj.js → server-kk2kbzq3.js} +1 -1
  108. package/dist/v2/{server-mc5t7k8v.js → server-ma0qhqg9.js} +1 -1
  109. package/dist/v2/{server-x22jtpna.js → server-n3bfqd0j.js} +4 -2
  110. package/dist/v2/{server-wmpgvvc4.js → server-pjvqyg6g.js} +365 -113
  111. package/dist/v2/{server-jrs4gny6.js → server-qtajgx1e.js} +89 -1
  112. package/dist/v2/server-t104h957.js +177 -0
  113. package/dist/v2/{server-j09jx1n9.js → server-v2r04xds.js} +1 -1
  114. package/dist/v2/{server-7c5p0bh1.js → server-z77hman6.js} +1 -1
  115. package/dist/v2/server.js +31 -40
  116. package/dist/v2/{storage-tags-s7nvvyg8.js → storage-tags-ee72g2zv.js} +1 -1
  117. package/dist/v2/{store-mba47sxn.js → store-9rsrj5pt.js} +2 -2
  118. package/dist/v2/{store-reader-w7w8vfsy.js → store-reader-tb0f9621.js} +1 -1
  119. package/dist/v2/store-reader.d.ts +1 -1
  120. package/dist/v2/store-reader.d.ts.map +1 -1
  121. package/dist/v2/tui/index.d.ts.map +1 -1
  122. package/dist/v2/{v2-archive-reader-5njmg3a3.js → v2-archive-reader-0xysfgxh.js} +1 -1
  123. package/dist/v2/{wrapup-orchestrator-ykgx8hw8.js → wrapup-orchestrator-8d4ak3x3.js} +14 -14
  124. package/dist/{v2-archive-reader-y38khjax.js → v2-archive-reader-fac1zmhj.js} +1 -1
  125. package/dist/{wrapup-orchestrator-a9tshrp4.js → wrapup-orchestrator-wz10b94c.js} +13 -13
  126. package/package.json +1 -1
  127. package/src/config/migrate-config-location.test.ts +41 -29
  128. package/src/shared/model-suggestion-retry.test.ts +137 -90
  129. package/src/shared/off-thread-migration-clock.test.ts +19 -9
  130. package/src/shared/prompt-async-transport.test.ts +125 -42
  131. package/src/shared/rpc-async-probes.test.ts +56 -36
  132. package/src/shared/rpc-client.test.ts +51 -18
  133. package/src/shared/sqlite-acquisition-routing.test.ts +79 -22
  134. package/src/shared/sqlite-busy-budget-review.test.ts +129 -111
  135. package/src/shared/sqlite-busy-test-support.ts +154 -0
  136. package/src/shared/sqlite-foreground-wait.test.ts +213 -156
  137. package/src/shared/sqlite-pass-scope.test.ts +142 -105
  138. package/src/shared/sqlite-turn-deadline.test.ts +149 -124
  139. package/src/shared/sqlite-write-locker-test-support.ts +44 -12
  140. package/src/shared/stable-json-linear.test.ts +29 -11
  141. package/src/shared/startup-maintenance-policy.test.ts +72 -2
  142. package/src/shared/storage-busy.test.ts +45 -18
  143. package/src/shared/storage-file-mutex-review.test.ts +65 -51
  144. package/src/shared/tui-preferences.test.ts +15 -5
  145. package/src/shared/worker-shutdown.test.ts +26 -20
  146. package/src/tui/data/notification-socket.test.ts +220 -108
  147. package/src/v2/tui/index.ts +5 -1
  148. package/src/v2/tui/status-dialog-fallback.test.ts +23 -1
  149. package/dist/v2/server-84w6rvvf.js +0 -14
@@ -1,4 +1,4 @@
1
- import { expect, test } from "bun:test";
1
+ import { expect, spyOn, test } from "bun:test";
2
2
  import { rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
@@ -9,7 +9,8 @@ import {
9
9
  withPrivilegedWriter,
10
10
  withSqliteTransformPass,
11
11
  } from "./sqlite";
12
- import { startSqliteWriteLocker } from "./sqlite-write-locker-test-support";
12
+ import { observeSqliteBusy, startSqliteRetryClock } from "./sqlite-busy-test-support";
13
+ import { startGatedSqliteWriteLocker } from "./sqlite-write-locker-test-support";
13
14
  import { createTestTempDirFromPath } from "./test-temp-dir";
14
15
 
15
16
  test("async writer never retries callback acquisition errors after work began", async () => {
@@ -33,11 +34,18 @@ for (const mode of ["default", "immediate", "exclusive", "literal"] as const) {
33
34
  test(`shared SQLite retries ${mode} acquisition before running any writes`, async () => {
34
35
  const dir = createTestTempDirFromPath(join(tmpdir(), "mc-routed-acquisition-"));
35
36
  const path = join(dir, "context.db");
37
+ const begins: string[] = [];
38
+ const probe = observeSqliteBusy(
39
+ (sql, method) => method === "exec" && sql.startsWith("BEGIN "),
40
+ (_, sql) => begins.push(sql),
41
+ );
36
42
  const db = new Database(path);
37
43
  db.exec(
38
44
  "PRAGMA journal_mode=WAL; PRAGMA busy_timeout=50; CREATE TABLE result(value TEXT); CREATE TABLE context_privilege_state(id INTEGER PRIMARY KEY, enabled INTEGER)",
39
45
  );
40
- const locker = await startSqliteWriteLocker(path, 650);
46
+ const locker = await startGatedSqliteWriteLocker(path);
47
+ const clock = startSqliteRetryClock();
48
+ const abort = new AbortController();
41
49
  let calls = 0;
42
50
  const write = () => {
43
51
  calls++;
@@ -46,7 +54,24 @@ for (const mode of ["default", "immediate", "exclusive", "literal"] as const) {
46
54
  };
47
55
  try {
48
56
  await withSqliteTransformPass(async () => {
49
- await withAsyncPrivilegedWriter(db, () => undefined);
57
+ const admission = withAsyncPrivilegedWriter(db, () => undefined, {
58
+ signal: abort.signal,
59
+ });
60
+ void admission.catch(() => {});
61
+ try {
62
+ await clock.advance(0);
63
+ await clock.advance(499);
64
+ expect(probe.timeouts).toEqual([25]);
65
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([]);
66
+ locker.release();
67
+ expect(await locker.exited).toBe(0);
68
+ await clock.advance(1);
69
+ expect(probe.timeouts).toEqual([25, 25]);
70
+ await admission;
71
+ } finally {
72
+ abort.abort();
73
+ await admission.catch(() => {});
74
+ }
50
75
  if (mode === "literal") {
51
76
  db.exec("BEGIN IMMEDIATE");
52
77
  write();
@@ -59,13 +84,22 @@ for (const mode of ["default", "immediate", "exclusive", "literal"] as const) {
59
84
  }
60
85
  });
61
86
  expect(calls).toBe(1);
87
+ expect(probe.timeouts).toEqual([25, 25, 2000]);
88
+ expect(begins).toEqual([
89
+ "BEGIN IMMEDIATE",
90
+ "BEGIN IMMEDIATE",
91
+ mode === "exclusive" ? "BEGIN EXCLUSIVE" : "BEGIN IMMEDIATE",
92
+ ]);
62
93
  expect(db.prepare("SELECT * FROM result").all()).toEqual([{ value: "once" }]);
63
94
  } finally {
95
+ clock.restore();
96
+ locker.release();
64
97
  await locker.exited;
65
98
  db.close();
99
+ probe.restore();
66
100
  rmSync(dir, { recursive: true, force: true });
67
101
  }
68
- }, 30000);
102
+ });
69
103
  }
70
104
 
71
105
  test("routed transactions preserve nesting, receiver, arguments and rollback without callback retries", () => {
@@ -93,16 +127,18 @@ test("routed transactions preserve nesting, receiver, arguments and rollback wit
93
127
  }
94
128
  });
95
129
 
96
- test("exhausted routed acquisition never enters the callback or multiplies privileged retries", () => {
130
+ test("exhausted routed acquisition never enters the callback or multiplies privileged retries", async () => {
97
131
  const dir = createTestTempDirFromPath(join(tmpdir(), "mc-routed-exhaustion-"));
98
132
  const path = join(dir, "context.db");
99
- const blocker = new Database(path);
133
+ const probe = observeSqliteBusy(
134
+ (sql, method) => method === "exec" && sql === "BEGIN IMMEDIATE",
135
+ );
100
136
  const db = new Database(path);
101
- blocker.exec(
137
+ db.exec(
102
138
  "PRAGMA journal_mode=WAL; CREATE TABLE result(value TEXT); CREATE TABLE context_privilege_state(id INTEGER PRIMARY KEY, enabled INTEGER)",
103
139
  );
104
140
  db.exec("PRAGMA busy_timeout=0");
105
- blocker.exec("BEGIN IMMEDIATE");
141
+ const locker = await startGatedSqliteWriteLocker(path);
106
142
  let callbacks = 0;
107
143
  try {
108
144
  for (const run of [
@@ -112,26 +148,42 @@ test("exhausted routed acquisition never enters the callback or multiplies privi
112
148
  expect(() => withSqliteTransformPass(run)).toThrow("acquisition remained busy");
113
149
  expect(callbacks).toBe(0);
114
150
  }
151
+ expect(probe.timeouts).toEqual([2000, 2000]);
152
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([]);
153
+ locker.release();
154
+ expect(await locker.exited).toBe(0);
155
+ expect(withSqliteTransformPass(() => db.transaction(() => callbacks++)())).toBe(0);
156
+ expect(callbacks).toBe(1);
115
157
  } finally {
116
- blocker.exec("ROLLBACK");
117
- blocker.close();
158
+ locker.release();
159
+ await locker.exited;
118
160
  db.close();
161
+ probe.restore();
119
162
  rmSync(dir, { recursive: true, force: true });
120
163
  }
121
- }, 30_000);
164
+ });
122
165
 
123
166
  for (const mode of ["run", "get", "all", "exec"] as const) {
124
- test(`foreground ${mode} autocommit waits share one turn budget and restore production timeout`, () => {
167
+ test(`foreground ${mode} autocommit waits share one turn budget and restore production timeout`, async () => {
125
168
  const dir = createTestTempDirFromPath(join(tmpdir(), "mc-autocommit-budget-"));
126
169
  const path = join(dir, "context.db");
170
+ let now = 0;
171
+ const charges = [1999, 1];
172
+ const probe = observeSqliteBusy(
173
+ (sql, method) =>
174
+ (method === mode && sql.includes("'blocked'")) ||
175
+ (method === "exec" && sql === "BEGIN IMMEDIATE"),
176
+ (timeout) => {
177
+ if (timeout > 0) now += charges.shift() ?? 0;
178
+ },
179
+ );
127
180
  const db = new Database(path);
128
181
  db.exec(
129
182
  "PRAGMA journal_mode=WAL; CREATE TABLE result(value TEXT); PRAGMA busy_timeout=5000",
130
183
  );
131
- const blocker = new Database(path);
132
- blocker.exec("BEGIN IMMEDIATE");
184
+ const locker = await startGatedSqliteWriteLocker(path);
185
+ const clock = spyOn(performance, "now").mockImplementation(() => now);
133
186
  try {
134
- const started = performance.now();
135
187
  withSqliteTransformPass(() => {
136
188
  for (let attempt = 0; attempt < 3; attempt++) {
137
189
  // Nested foreground wrappers must reuse the turn's remaining budget.
@@ -147,18 +199,23 @@ for (const mode of ["run", "get", "all", "exec"] as const) {
147
199
  }
148
200
  expect(() => db.exec("BEGIN IMMEDIATE")).toThrow("acquisition remained busy");
149
201
  });
150
- expect(performance.now() - started).toBeGreaterThanOrEqual(1900);
151
- expect(performance.now() - started).toBeLessThan(2600);
202
+ // At 1999ms one millisecond remains; at 2000ms neither SQL nor BEGIN may wait.
203
+ expect(probe.timeouts).toEqual(
204
+ mode === "exec" ? [2000, 1, 0, 0] : [0, 2000, 0, 1, 0, 0, 0],
205
+ );
152
206
  expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
153
207
  expect(db.prepare("SELECT * FROM result").all()).toEqual([]);
154
- blocker.exec("ROLLBACK");
208
+ locker.release();
209
+ expect(await locker.exited).toBe(0);
155
210
  withSqliteTransformPass(() => db.prepare("INSERT INTO result VALUES ('free')").run());
156
211
  expect(db.prepare("SELECT * FROM result").all()).toEqual([{ value: "free" }]);
157
212
  } finally {
158
- if (blocker.inTransaction) blocker.exec("ROLLBACK");
159
- blocker.close();
213
+ clock.mockRestore();
214
+ locker.release();
215
+ await locker.exited;
160
216
  db.close();
217
+ probe.restore();
161
218
  rmSync(dir, { recursive: true, force: true });
162
219
  }
163
- }, 30_000);
220
+ });
164
221
  }
@@ -1,3 +1,4 @@
1
+ import { Database as NativeDatabase } from "bun:sqlite";
1
2
  import { expect, test } from "bun:test";
2
3
  import { rmSync } from "node:fs";
3
4
  import { tmpdir } from "node:os";
@@ -9,6 +10,11 @@ import {
9
10
  withSqliteBackgroundWriter,
10
11
  withSqliteTransformPass,
11
12
  } from "./sqlite";
13
+ import { observeSqliteBusy } from "./sqlite-busy-test-support";
14
+ import {
15
+ startGatedSqliteLocker,
16
+ startGatedSqliteWriteLocker,
17
+ } from "./sqlite-write-locker-test-support";
12
18
  import { createTestTempDirFromPath } from "./test-temp-dir";
13
19
 
14
20
  function fixture() {
@@ -27,91 +33,100 @@ function fixture() {
27
33
  };
28
34
  }
29
35
 
30
- async function lock(path: string, mode: "read" | "write" | "exclusive", holdMs: number) {
31
- const child = Bun.spawn(
32
- [
33
- "bun",
34
- "--eval",
35
- `import { Database } from "bun:sqlite";
36
- const db = new Database(process.argv[1]);
37
- db.exec("PRAGMA busy_timeout = 5000");
38
- db.exec(process.argv[2] === "read" ? "BEGIN; SELECT * FROM result"
39
- : process.argv[2] === "write" ? "BEGIN IMMEDIATE" : "BEGIN EXCLUSIVE");
40
- console.log("LOCKED");
41
- Bun.sleepSync(Number(process.argv[3]));
42
- db.exec("COMMIT");
43
- db.close();`,
44
- path,
45
- mode,
46
- String(holdMs),
47
- ],
48
- { stdout: "pipe", stderr: "pipe", windowsHide: true },
49
- );
50
- const reader = child.stdout.getReader();
51
- let output = "";
52
- while (!output.includes("LOCKED\n")) {
53
- const chunk = await reader.read();
54
- if (chunk.done) {
55
- const [exitCode, stderr] = await Promise.all([
56
- child.exited,
57
- new Response(child.stderr).text(),
58
- ]);
59
- throw new Error(`locker failed (exit ${exitCode}): ${stderr.trim() || "<no stderr>"}`);
60
- }
61
- output += new TextDecoder().decode(chunk.value);
62
- }
63
- reader.releaseLock();
64
- return { exited: child.exited };
65
- }
66
-
67
- for (const method of ["run", "get", "all", "exec"] as const) {
68
- test(`a rollback-journal commit BUSY retries ${method} exactly once after the reader leaves`, async () => {
36
+ for (const method of ["run", "get", "all"] as const) {
37
+ test(`a rollback-journal commit BUSY retries ${method} exactly once after the reader leaves`, () => {
38
+ const sql = "UPDATE result SET n = n + 1 WHERE id = 1 RETURNING n";
39
+ let reader: NativeDatabase | undefined;
40
+ const probe = observeSqliteBusy(
41
+ (statement, api) => statement === sql && api === method,
42
+ (timeout) => {
43
+ // End the reader between the real zero-wait failure and the native retry.
44
+ if (timeout === 2000) reader?.exec("COMMIT");
45
+ },
46
+ );
69
47
  const { db, path, close } = fixture();
70
- const sql = "UPDATE result SET n = n + 1 WHERE id = 1";
71
- const statement = db.prepare(`${sql} RETURNING n`);
72
- const { exited } = await lock(path, "read", 150);
48
+ const statement = db.prepare(sql);
49
+ reader = new NativeDatabase(path);
50
+ reader.exec("BEGIN; SELECT * FROM result");
73
51
  try {
74
- await withSqliteTransformPass(() => {
75
- if (method === "exec") db.exec(sql);
76
- else statement[method]();
77
- });
52
+ expect(() => withSqliteTransformPass(() => statement[method]())).not.toThrow();
53
+ expect(probe.timeouts).toEqual([0, 2000]);
54
+ expect(reader.inTransaction).toBe(false);
78
55
  expect(db.prepare("SELECT * FROM result").all()).toEqual([{ id: 1, n: 1 }]);
79
56
  expect(db.inTransaction).toBe(false);
80
57
  } finally {
81
- expect(await exited).toBe(0);
58
+ reader.close();
82
59
  close();
60
+ probe.restore();
83
61
  }
84
62
  });
85
63
  }
86
64
 
65
+ test("a rollback-journal commit BUSY runs exec once and can be retried after the reader leaves", async () => {
66
+ const sql = "UPDATE result SET n = n + 1 WHERE id = 1";
67
+ const probe = observeSqliteBusy((statement, method) => statement === sql && method === "exec");
68
+ const { db, path, close } = fixture();
69
+ const locker = await startGatedSqliteLocker(path, { read: "SELECT * FROM result" });
70
+ try {
71
+ const attempt = () => withSqliteTransformPass(() => db.exec(sql));
72
+ expect(attempt).toThrow(SqliteAcquisitionBusyError);
73
+ expect(probe.timeouts).toEqual([2000]);
74
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([{ id: 1, n: 0 }]);
75
+ expect(db.inTransaction).toBe(false);
76
+ locker.release();
77
+ expect(await locker.exited).toBe(0);
78
+ attempt();
79
+ expect(db.prepare("SELECT * FROM result").all()).toEqual([{ id: 1, n: 1 }]);
80
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
81
+ } finally {
82
+ locker.release();
83
+ await locker.exited;
84
+ close();
85
+ probe.restore();
86
+ }
87
+ });
88
+
87
89
  for (const scope of ["foreground", "background", "unscoped"] as const) {
88
90
  test(`exec in ${scope} does not wait on an unrelated attached database schema`, async () => {
91
+ const probe = observeSqliteBusy(
92
+ (sql, method) => method === "exec" && sql.includes("UPDATE "),
93
+ );
89
94
  const main = fixture();
90
95
  const aux = fixture();
91
96
  main.db.prepare("ATTACH DATABASE ? AS aux").run(aux.path);
92
- const { exited } = await lock(aux.path, "exclusive", 2500);
97
+ const locker = await startGatedSqliteLocker(aux.path, "exclusive");
93
98
  try {
94
- const started = performance.now();
99
+ expect(() => main.db.exec("UPDATE aux.result SET n = n + 1")).toThrow(
100
+ expect.objectContaining({ code: "SQLITE_BUSY" }),
101
+ );
95
102
  const operation = () => main.db.exec("UPDATE main.result SET n = n + 1");
96
- if (scope === "foreground") {
97
- await withSqliteTransformPass(() => {
98
- guardSqliteTransformPass({ assert() {}, remainingMs: () => 75 });
99
- operation();
100
- });
101
- } else if (scope === "background") withSqliteBackgroundWriter(operation);
102
- else operation();
103
- expect(performance.now() - started).toBeLessThan(1500);
103
+ expect(() => {
104
+ if (scope === "foreground") {
105
+ withSqliteTransformPass(() => {
106
+ guardSqliteTransformPass({ assert() {}, remainingMs: () => 75 });
107
+ operation();
108
+ });
109
+ } else if (scope === "background") withSqliteBackgroundWriter(operation);
110
+ else operation();
111
+ }).not.toThrow();
104
112
  expect(main.db.prepare("SELECT n FROM main.result").get()).toEqual({ n: 1 });
113
+ locker.release();
114
+ expect(await locker.exited).toBe(0);
115
+ expect(aux.db.prepare("SELECT n FROM result").get()).toEqual({ n: 0 });
105
116
  } finally {
106
- expect(await exited).toBe(0);
117
+ locker.release();
118
+ await locker.exited;
107
119
  main.close();
108
120
  aux.close();
121
+ probe.restore();
109
122
  }
110
- }, 10_000);
123
+ });
111
124
  }
112
125
 
113
126
  for (const location of ["main", "aux"] as const) {
114
127
  test(`BUSY retries leave single-statement effects atomic in ${location}, including AFTER triggers`, async () => {
128
+ let activeSql: string | undefined;
129
+ const probe = observeSqliteBusy((sql, method) => sql === activeSql && method === "all");
115
130
  const main = fixture();
116
131
  const aux = fixture();
117
132
  main.db.prepare("ATTACH DATABASE ? AS aux").run(aux.path);
@@ -132,35 +147,31 @@ for (const location of ["main", "aux"] as const) {
132
147
  ];
133
148
  try {
134
149
  for (const sql of forms) {
135
- const statement = main.db.prepare(`${sql} RETURNING *`);
136
- const blocker = new Database(location === "main" ? main.path : aux.path);
137
- blocker.exec("BEGIN IMMEDIATE");
138
- main.db.exec("PRAGMA busy_timeout=0");
150
+ activeSql = `${sql} RETURNING *`;
151
+ const statement = main.db.prepare(activeSql);
152
+ probe.timeouts.length = 0;
153
+ const locker = await startGatedSqliteWriteLocker(
154
+ location === "main" ? main.path : aux.path,
155
+ );
139
156
  const before = main.db
140
157
  .prepare(`SELECT * FROM ${location}.result ORDER BY id`)
141
158
  .all();
142
159
  const beforeAudit = main.db.prepare("SELECT * FROM audit").all();
143
160
  try {
144
- expect(() => statement.all()).toThrow("locked");
161
+ expect(() => withSqliteTransformPass(() => statement.all())).toThrow(
162
+ SqliteAcquisitionBusyError,
163
+ );
164
+ expect(probe.timeouts).toEqual([0, 2000]);
145
165
  expect(
146
166
  main.db.prepare(`SELECT * FROM ${location}.result ORDER BY id`).all(),
147
167
  ).toEqual(before);
148
168
  expect(main.db.prepare("SELECT * FROM audit").all()).toEqual(beforeAudit);
149
169
  expect(main.db.inTransaction).toBe(false);
150
170
  } finally {
151
- blocker.exec("ROLLBACK");
152
- blocker.close();
153
- }
154
- const { exited } = await lock(
155
- location === "main" ? main.path : aux.path,
156
- "write",
157
- 60,
158
- );
159
- try {
160
- await withSqliteTransformPass(() => statement.all());
161
- } finally {
162
- expect(await exited).toBe(0);
171
+ locker.release();
172
+ expect(await locker.exited).toBe(0);
163
173
  }
174
+ await withSqliteTransformPass(() => statement.all());
164
175
  }
165
176
  expect(main.db.prepare(`SELECT * FROM ${location}.result ORDER BY id`).all()).toEqual([
166
177
  { id: 1, n: 0 },
@@ -175,52 +186,56 @@ for (const location of ["main", "aux"] as const) {
175
186
  } finally {
176
187
  main.close();
177
188
  aux.close();
189
+ probe.restore();
178
190
  }
179
- }, 10_000);
191
+ });
180
192
  }
181
193
 
182
- test("an attached DML-only committed prefix is not replayed after a later BUSY", () => {
194
+ test("an attached DML-only committed prefix is not replayed after a later BUSY", async () => {
195
+ const sql = "UPDATE free.result SET n=n+1; UPDATE blocked.result SET n=n+1";
196
+ const probe = observeSqliteBusy((statement, method) => statement === sql && method === "exec");
183
197
  const main = fixture();
184
198
  const free = fixture();
185
199
  const blocked = fixture();
200
+ main.db.prepare("ATTACH DATABASE ? AS free").run(free.path);
201
+ main.db.prepare("ATTACH DATABASE ? AS blocked").run(blocked.path);
202
+ const locker = await startGatedSqliteWriteLocker(blocked.path);
186
203
  try {
187
- main.db.prepare("ATTACH DATABASE ? AS free").run(free.path);
188
- main.db.prepare("ATTACH DATABASE ? AS blocked").run(blocked.path);
189
- blocked.db.exec("BEGIN IMMEDIATE");
190
204
  withSqliteTransformPass(() => {
191
- expect(() =>
192
- main.db.exec("UPDATE free.result SET n=n+1; UPDATE blocked.result SET n=n+1"),
193
- ).toThrow(SqliteAcquisitionBusyError);
205
+ expect(() => main.db.exec(sql)).toThrow(SqliteAcquisitionBusyError);
194
206
  });
195
207
  expect(main.db.prepare("SELECT n FROM free.result").get()).toEqual({ n: 1 });
196
208
  expect(main.db.prepare("SELECT n FROM blocked.result").get()).toEqual({ n: 0 });
209
+ expect(probe.timeouts).toEqual([2000]);
197
210
  } finally {
198
- blocked.db.exec("ROLLBACK");
211
+ locker.release();
212
+ expect(await locker.exited).toBe(0);
199
213
  main.close();
200
214
  free.close();
201
215
  blocked.close();
216
+ probe.restore();
202
217
  }
203
218
  });
204
219
 
205
220
  for (const location of ["main", "free"] as const) {
206
- test(`an ignored AUTOINCREMENT prefix in ${location} is committed only once before a later BUSY`, () => {
221
+ test(`an ignored AUTOINCREMENT prefix in ${location} is committed only once before a later BUSY`, async () => {
222
+ const sql = `INSERT OR IGNORE INTO ${location}.numbered(value) VALUES ('existing'); UPDATE blocked.result SET n=n+1`;
223
+ const probe = observeSqliteBusy(
224
+ (statement, method) => statement === sql && method === "exec",
225
+ );
207
226
  const main = fixture();
208
227
  const free = fixture();
209
228
  const blocked = fixture();
210
- try {
211
- main.db.prepare("ATTACH DATABASE ? AS free").run(free.path);
212
- main.db.exec(`CREATE TABLE ${location}.numbered(id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT UNIQUE);
229
+ main.db.prepare("ATTACH DATABASE ? AS free").run(free.path);
230
+ main.db.exec(`CREATE TABLE ${location}.numbered(id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT UNIQUE);
213
231
  INSERT INTO ${location}.numbered(value) VALUES ('existing')`);
214
- main.db.prepare("ATTACH DATABASE ? AS blocked").run(blocked.path);
215
- blocked.db.exec("BEGIN IMMEDIATE");
232
+ main.db.prepare("ATTACH DATABASE ? AS blocked").run(blocked.path);
233
+ const locker = await startGatedSqliteWriteLocker(blocked.path);
234
+ try {
216
235
  const before = main.db.prepare("SELECT total_changes() AS n").get();
217
236
  withSqliteTransformPass(() => {
218
237
  guardSqliteTransformPass({ assert() {}, remainingMs: () => 50 });
219
- expect(() =>
220
- main.db.exec(
221
- `INSERT OR IGNORE INTO ${location}.numbered(value) VALUES ('existing'); UPDATE blocked.result SET n=n+1`,
222
- ),
223
- ).toThrow(SqliteAcquisitionBusyError);
238
+ expect(() => main.db.exec(sql)).toThrow(SqliteAcquisitionBusyError);
224
239
  });
225
240
  expect(main.db.prepare("SELECT total_changes() AS n").get()).toEqual(before);
226
241
  expect(
@@ -231,11 +246,14 @@ for (const location of ["main", "free"] as const) {
231
246
  expect(main.db.prepare(`SELECT * FROM ${location}.numbered`).all()).toEqual([
232
247
  { id: 1, value: "existing" },
233
248
  ]);
249
+ expect(probe.timeouts).toEqual([50]);
234
250
  } finally {
235
- blocked.db.exec("ROLLBACK");
251
+ locker.release();
252
+ expect(await locker.exited).toBe(0);
236
253
  main.close();
237
254
  free.close();
238
255
  blocked.close();
256
+ probe.restore();
239
257
  }
240
258
  });
241
259
  }
@@ -261,6 +279,8 @@ test("a WAL BUSY_SNAPSHOT in an explicit read transaction is not retried", () =>
261
279
  });
262
280
 
263
281
  test("a BUSY from an AFTER trigger writing an attached database rolls back the outer statement", async () => {
282
+ const sql = "UPDATE main.result SET n=n+1 RETURNING n";
283
+ const probe = observeSqliteBusy((statement, method) => statement === sql && method === "all");
264
284
  const main = fixture();
265
285
  const aux = fixture();
266
286
  main.db.prepare("ATTACH DATABASE ? AS aux").run(aux.path);
@@ -269,28 +289,26 @@ test("a BUSY from an AFTER trigger writing an attached database rolls back the o
269
289
  main.db.exec("ALTER TABLE aux.result RENAME TO attached_result");
270
290
  main.db.exec(`CREATE TEMP TRIGGER update_aux AFTER UPDATE ON main.result
271
291
  BEGIN UPDATE attached_result SET n=n+1 WHERE id=1; END`);
272
- const statement = main.db.prepare("UPDATE main.result SET n=n+1 RETURNING n");
273
- const blocker = new Database(aux.path);
292
+ const statement = main.db.prepare(sql);
293
+ const locker = await startGatedSqliteWriteLocker(aux.path);
274
294
  try {
275
- blocker.exec("BEGIN IMMEDIATE");
276
- main.db.exec("PRAGMA busy_timeout=0");
277
- expect(() => statement.all()).toThrow("locked");
295
+ expect(() => withSqliteTransformPass(() => statement.all())).toThrow(
296
+ SqliteAcquisitionBusyError,
297
+ );
298
+ expect(probe.timeouts).toEqual([0, 2000]);
278
299
  expect(main.db.prepare("SELECT n FROM main.result").get()).toEqual({ n: 0 });
279
300
  expect(main.db.prepare("SELECT n FROM aux.attached_result").get()).toEqual({ n: 0 });
280
301
  expect(main.db.inTransaction).toBe(false);
281
- blocker.exec("ROLLBACK");
282
- const { exited } = await lock(aux.path, "write", 100);
283
- try {
284
- await withSqliteTransformPass(() => statement.all());
285
- } finally {
286
- expect(await exited).toBe(0);
287
- }
302
+ locker.release();
303
+ expect(await locker.exited).toBe(0);
304
+ await withSqliteTransformPass(() => statement.all());
288
305
  expect(main.db.prepare("SELECT n FROM main.result").get()).toEqual({ n: 1 });
289
306
  expect(main.db.prepare("SELECT n FROM aux.attached_result").get()).toEqual({ n: 1 });
290
307
  } finally {
291
- if (blocker.inTransaction) blocker.exec("ROLLBACK");
292
- blocker.close();
308
+ locker.release();
309
+ await locker.exited;
293
310
  main.close();
294
311
  aux.close();
312
+ probe.restore();
295
313
  }
296
314
  });