@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
@@ -5,24 +5,24 @@ import { join } from "node:path";
5
5
  import {
6
6
  beginSqliteWriterAsync,
7
7
  Database,
8
- isTransientSqliteError,
8
+ guardSqliteTransformPass,
9
9
  SqliteAcquisitionBusyError,
10
10
  withAsyncPrivilegedWriter,
11
11
  withPrivilegedWriter,
12
12
  withSqliteBackgroundWriter,
13
13
  withSqliteTransformPass,
14
14
  } from "./sqlite";
15
- import { startSqliteWriteLocker } from "./sqlite-write-locker-test-support";
15
+ import { observeSqliteBusy, startSqliteRetryClock } from "./sqlite-busy-test-support";
16
+ import { startGatedSqliteWriteLocker } from "./sqlite-write-locker-test-support";
16
17
  import { createTestTempDirFromPath } from "./test-temp-dir";
17
18
 
18
19
  function fixture() {
19
20
  const dir = createTestTempDirFromPath(join(tmpdir(), "mc-busy-yield-"));
20
21
  const path = join(dir, "context.db");
21
22
  const db = new Database(path);
22
- db.exec(
23
- "PRAGMA journal_mode=WAL; CREATE TABLE context_privilege_state(id INTEGER PRIMARY KEY, enabled INTEGER)",
24
- );
25
- db.exec("PRAGMA busy_timeout=5000");
23
+ db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;
24
+ CREATE TABLE context_privilege_state(id INTEGER PRIMARY KEY, enabled INTEGER);
25
+ CREATE TABLE result(value TEXT)`);
26
26
  return {
27
27
  db,
28
28
  path,
@@ -33,122 +33,159 @@ function fixture() {
33
33
  };
34
34
  }
35
35
 
36
- test("tool-style transaction outside a pass waits for a brief lock", async () => {
36
+ async function withHeldWriter(
37
+ run: (fixture: {
38
+ db: Database;
39
+ timeouts: number[];
40
+ release: () => Promise<void>;
41
+ write: () => void;
42
+ rows: () => unknown;
43
+ }) => Promise<void>,
44
+ ) {
45
+ const probe = observeSqliteBusy(
46
+ (sql, method) => method === "exec" && sql === "BEGIN IMMEDIATE",
47
+ );
37
48
  const { db, path, close } = fixture();
38
- const locker = await startSqliteWriteLocker(path, 300);
49
+ const locker = await startGatedSqliteWriteLocker(path);
50
+ const release = async () => {
51
+ locker.release();
52
+ expect(await locker.exited).toBe(0);
53
+ };
39
54
  try {
40
- const start = performance.now();
41
- db.transaction(() =>
42
- db.prepare("INSERT INTO context_privilege_state(id, enabled) VALUES (1, 0)").run(),
43
- ).immediate();
44
- expect(performance.now() - start).toBeGreaterThanOrEqual(250);
45
- expect(db.prepare("SELECT COUNT(*) AS count FROM context_privilege_state").get()).toEqual({
46
- count: 1,
55
+ await run({
56
+ db,
57
+ timeouts: probe.timeouts,
58
+ release,
59
+ write: () => void db.exec("INSERT INTO result VALUES ('once')"),
60
+ rows: () => db.prepare("SELECT * FROM result").all(),
47
61
  });
48
- expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
49
62
  } finally {
63
+ locker.release();
50
64
  await locker.exited;
51
65
  close();
66
+ probe.restore();
52
67
  }
53
- }, 30000);
68
+ }
54
69
 
55
- test("named background acquisition gives up quickly and leaves work for retry", () => {
56
- const { db, path, close } = fixture();
57
- const blocker = new Database(path);
58
- blocker.exec("BEGIN IMMEDIATE");
59
- let calls = 0;
60
- let retryQueued = false;
61
- try {
62
- const start = performance.now();
63
- try {
64
- withSqliteBackgroundWriter(() => db.transaction(() => calls++)());
65
- } catch (error) {
66
- if (!isTransientSqliteError(error)) throw error;
67
- retryQueued = true;
68
- }
69
- expect(performance.now() - start).toBeLessThan(250);
70
- expect(retryQueued).toBe(true);
71
- expect(calls).toBe(0);
70
+ test("tool-style transaction outside a pass inherits the production wait", async () => {
71
+ await withHeldWriter(async ({ db, timeouts, release, write, rows }) => {
72
+ const transaction = db.transaction(write).immediate;
73
+ expect(transaction).toThrow(expect.objectContaining({ code: "SQLITE_BUSY" }));
74
+ expect(timeouts).toEqual([5000]);
75
+ expect(rows()).toEqual([]);
72
76
  expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
73
- } finally {
74
- blocker.exec("ROLLBACK");
75
- blocker.close();
76
- close();
77
- }
77
+ await release();
78
+ transaction();
79
+ expect(rows()).toEqual([{ value: "once" }]);
80
+ });
81
+ });
82
+
83
+ test("named background acquisition uses a short wait and leaves work for retry", async () => {
84
+ await withHeldWriter(async ({ db, timeouts, release, write, rows }) => {
85
+ const attempt = () => withSqliteBackgroundWriter(() => db.transaction(write)());
86
+ expect(attempt).toThrow(expect.objectContaining({ code: "SQLITE_BUSY" }));
87
+ expect(timeouts).toEqual([25]);
88
+ expect(rows()).toEqual([]);
89
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
90
+ await release();
91
+ attempt();
92
+ expect(rows()).toEqual([{ value: "once" }]);
93
+ });
78
94
  });
79
95
 
80
96
  test("foreground admission keeps the loop ticking while a separate writer holds the lock", async () => {
81
- const { db, path, close } = fixture();
82
- const locker = await startSqliteWriteLocker(path, 650);
83
- let timerFired = false;
84
- let calls = 0;
85
- try {
86
- setTimeout(() => {
87
- timerFired = true;
88
- }, 100);
89
- await withSqliteTransformPass(() =>
90
- withAsyncPrivilegedWriter(db, () => {
91
- calls++;
92
- }),
97
+ await withHeldWriter(async ({ db, timeouts, release, write, rows }) => {
98
+ const clock = startSqliteRetryClock();
99
+ const abort = new AbortController();
100
+ const heartbeat = new Promise<void>((resolve) => setImmediate(resolve));
101
+ const pending = withSqliteTransformPass(() =>
102
+ withAsyncPrivilegedWriter(db, write, { signal: abort.signal }),
93
103
  );
94
- expect(timerFired).toBe(true);
95
- expect(calls).toBe(1);
96
- expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
97
- } finally {
98
- await locker.exited;
99
- close();
100
- }
101
- }, 30000);
104
+ void pending.catch(() => {});
105
+ try {
106
+ await heartbeat;
107
+ expect(timeouts).toEqual([25]);
108
+ expect(rows()).toEqual([]);
109
+ await release();
110
+ await clock.advance(500);
111
+ expect(timeouts).toEqual([25, 25]);
112
+ await pending;
113
+ expect(rows()).toEqual([{ value: "once" }]);
114
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
115
+ } finally {
116
+ abort.abort();
117
+ await pending.catch(() => {});
118
+ clock.restore();
119
+ }
120
+ });
121
+ });
102
122
 
103
- test("a foreground in-pass writer has bounded 2000ms tolerance and restores its timeout", () => {
104
- const { db, path, close } = fixture();
105
- const blocker = new Database(path);
106
- blocker.exec("BEGIN IMMEDIATE");
107
- try {
108
- const start = performance.now();
109
- expect(() =>
110
- withSqliteTransformPass(() => withPrivilegedWriter(db, () => undefined)),
111
- ).toThrow(SqliteAcquisitionBusyError);
112
- expect(performance.now() - start).toBeGreaterThanOrEqual(1900);
113
- expect(performance.now() - start).toBeLessThan(2500);
123
+ test("a foreground in-pass writer has bounded 2000ms tolerance and restores its timeout", async () => {
124
+ await withHeldWriter(async ({ db, timeouts, release, write, rows }) => {
125
+ const attempt = () => withSqliteTransformPass(() => withPrivilegedWriter(db, write));
126
+ expect(attempt).toThrow(SqliteAcquisitionBusyError);
127
+ expect(timeouts).toEqual([2000]);
128
+ expect(rows()).toEqual([]);
114
129
  expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
115
- } finally {
116
- blocker.exec("ROLLBACK");
117
- blocker.close();
118
- close();
119
- }
120
- }, 30000);
130
+ await release();
131
+ attempt();
132
+ expect(rows()).toEqual([{ value: "once" }]);
133
+ });
134
+ });
121
135
 
122
136
  test("ready background publication retries on a timer and retains its write", async () => {
123
- const { db, path, close } = fixture();
124
- const locker = await startSqliteWriteLocker(path, 650);
125
- let ticked = false;
126
- try {
127
- setTimeout(() => {
128
- ticked = true;
129
- }, 100);
130
- await beginSqliteWriterAsync(db, "historian-publish");
131
- db.prepare("INSERT INTO context_privilege_state(id, enabled) VALUES (1, 0)").run();
132
- db.exec("COMMIT");
133
- expect(ticked).toBe(true);
134
- expect(db.prepare("SELECT COUNT(*) AS count FROM context_privilege_state").get()).toEqual({
135
- count: 1,
137
+ await withHeldWriter(async ({ db, timeouts, release, write, rows }) => {
138
+ const clock = startSqliteRetryClock();
139
+ const begin = () => beginSqliteWriterAsync(db, "historian-publish");
140
+ let refusal: unknown;
141
+ void begin().catch((error: unknown) => {
142
+ refusal = error;
136
143
  });
137
- expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
138
- } finally {
139
- await locker.exited;
140
- close();
141
- }
142
- }, 30000);
144
+ try {
145
+ await clock.advance(499);
146
+ expect(timeouts).toEqual([25]);
147
+ await clock.advance(1);
148
+ expect(timeouts).toEqual([25, 25]);
149
+ for (let retry = 0; retry < 15; retry++) await clock.advance(1000);
150
+ await clock.advance(999);
151
+ expect(refusal).toBeUndefined();
152
+ expect(timeouts).toEqual(Array(17).fill(25));
153
+ await clock.advance(1);
154
+ expect(refusal).toMatchObject({ code: "SQLITE_BUSY" });
155
+ expect(timeouts).toEqual(Array(18).fill(25));
156
+ expect(db.inTransaction).toBe(false);
157
+ expect(rows()).toEqual([]);
158
+ const pending = begin();
159
+ void pending.catch(() => {});
160
+ await release();
161
+ await clock.advance(499);
162
+ expect(db.inTransaction).toBe(false);
163
+ await clock.advance(1);
164
+ expect(timeouts).toEqual(Array(20).fill(25));
165
+ await pending;
166
+ write();
167
+ db.exec("COMMIT");
168
+ expect(rows()).toEqual([{ value: "once" }]);
169
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
170
+ } finally {
171
+ clock.restore();
172
+ }
173
+ });
174
+ });
143
175
 
144
- test("an in-pass BEGIN tolerates a sibling writer that releases within 250ms", async () => {
145
- const { db, path, close } = fixture();
146
- const locker = await startSqliteWriteLocker(path, 150);
147
- try {
148
- withSqliteTransformPass(() => withPrivilegedWriter(db, () => undefined));
176
+ test("an in-pass BEGIN allows 250ms for an independently held writer", async () => {
177
+ await withHeldWriter(async ({ db, timeouts, release, write, rows }) => {
178
+ const attempt = () =>
179
+ withSqliteTransformPass(() => {
180
+ guardSqliteTransformPass({ assert() {}, remainingMs: () => 250 });
181
+ withPrivilegedWriter(db, write);
182
+ });
183
+ expect(attempt).toThrow(SqliteAcquisitionBusyError);
184
+ expect(timeouts).toEqual([250]);
185
+ expect(rows()).toEqual([]);
149
186
  expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 5000 });
150
- } finally {
151
- await locker.exited;
152
- close();
153
- }
154
- }, 30000);
187
+ await release();
188
+ attempt();
189
+ expect(rows()).toEqual([{ value: "once" }]);
190
+ });
191
+ });
@@ -9,60 +9,44 @@ import {
9
9
  withoutSqliteTransformPass,
10
10
  withSqliteTurnDeadline,
11
11
  } from "./sqlite";
12
+ import { observeSqliteBusy } from "./sqlite-busy-test-support";
13
+ import { startGatedSqliteLocker } from "./sqlite-write-locker-test-support";
12
14
  import { createTestTempDirFromPath } from "./test-temp-dir";
13
15
 
14
- async function fixture(run: (db: Database, path: string) => Promise<void>) {
16
+ const readSql = "SELECT * FROM t";
17
+ const busy = expect.objectContaining({ code: "SQLITE_BUSY" });
18
+
19
+ async function fixture(
20
+ matches: Parameters<typeof observeSqliteBusy>[0],
21
+ run: (db: Database, path: string, timeouts: number[]) => Promise<void>,
22
+ ) {
15
23
  const root = createTestTempDirFromPath(join(tmpdir(), "sqlite-turn-deadline-"));
16
24
  const path = join(root, "context.db");
25
+ const probe = observeSqliteBusy(matches);
17
26
  const db = createSqliteTurnDatabase(path);
18
27
  db.exec(
19
28
  "PRAGMA journal_mode=DELETE; PRAGMA busy_timeout=900; CREATE TABLE t(value); INSERT INTO t VALUES(1)",
20
29
  );
21
30
  try {
22
- await run(db, path);
31
+ await run(db, path, probe.timeouts);
23
32
  } finally {
24
33
  db.close();
34
+ probe.restore();
25
35
  rmSync(root, { recursive: true, force: true });
26
36
  }
27
37
  }
28
38
 
29
39
  async function hold(path: string, reader = false) {
30
- const child = Bun.spawn(
31
- [
32
- process.execPath,
33
- "-e",
34
- `
35
- const { Database } = require('bun:sqlite');
36
- const db = new Database(process.argv[1]);
37
- db.exec(${JSON.stringify(reader ? "BEGIN; SELECT * FROM t" : "BEGIN EXCLUSIVE")});
38
- console.log('HELD');
39
- setInterval(() => {}, 1000);
40
- `,
41
- path,
42
- ],
43
- { stdout: "pipe", stderr: "pipe", windowsHide: true },
44
- );
45
- const output = child.stdout.getReader();
46
- const first = await output.read();
47
- output.releaseLock();
48
- if (!new TextDecoder().decode(first.value).includes("HELD")) {
49
- child.kill();
50
- throw new Error(`holder failed: ${await new Response(child.stderr).text()}`);
51
- }
40
+ const locker = await startGatedSqliteLocker(path, reader ? { read: readSql } : "exclusive");
52
41
  return async () => {
53
- child.kill();
54
- await child.exited;
42
+ locker.release();
43
+ expect(await locker.exited).toBe(0);
55
44
  };
56
45
  }
57
46
 
58
- function bounded(operation: () => unknown) {
59
- const start = performance.now();
60
- expect(() =>
61
- withSqliteTurnDeadline(() => Math.max(0, 80 - (performance.now() - start)), operation),
62
- ).toThrow(/locked|busy/i);
63
- // The connection allows 900 ms; a late turn has only 80 ms left for this wait.
64
- expect(performance.now() - start).toBeLessThan(400);
65
- expect(performance.now() - start).toBeGreaterThan(40);
47
+ function bounded(operation: () => unknown, timeouts: number[]) {
48
+ expect(() => withSqliteTurnDeadline(() => 80, operation)).toThrow(busy);
49
+ expect(timeouts).toEqual([80]);
66
50
  }
67
51
 
68
52
  test("ordinary connections keep native cached SELECT methods", () => {
@@ -118,22 +102,26 @@ test("native deadlines read the connection timeout once, not per cached executio
118
102
  });
119
103
 
120
104
  test("timeout cache follows scripts, prepared setters, comments and failed prefixes", async () => {
121
- await fixture(async (db, path) => {
122
- db.exec(
123
- "PRAGMA main.busy_timeout(900); SELECT '; PRAGMA busy_timeout=0;'; -- PRAGMA busy_timeout=1",
124
- );
125
- db.prepare("PRAGMA busy_timeout=800").get();
126
- expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 800 });
127
- expect(() => db.exec("PRAGMA busy_timeout=700; SELECT * FROM missing_table")).toThrow();
128
- const read = db.prepare("SELECT * FROM t");
129
- const release = await hold(path);
130
- try {
131
- bounded(() => read.get());
132
- expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 700 });
133
- } finally {
134
- await release();
135
- }
136
- });
105
+ await fixture(
106
+ (sql, method) => sql === readSql && method === "get",
107
+ async (db, path, timeouts) => {
108
+ db.exec(
109
+ "PRAGMA main.busy_timeout(900); SELECT '; PRAGMA busy_timeout=0;'; -- PRAGMA busy_timeout=1",
110
+ );
111
+ db.prepare("PRAGMA busy_timeout=800").get();
112
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 800 });
113
+ expect(() => db.exec("PRAGMA busy_timeout=700; SELECT * FROM missing_table")).toThrow();
114
+ const read = db.prepare(readSql);
115
+ const release = await hold(path);
116
+ try {
117
+ bounded(() => read.get(), timeouts);
118
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 700 });
119
+ } finally {
120
+ await release();
121
+ }
122
+ expect(read.get()).toEqual({ value: 1 });
123
+ },
124
+ );
137
125
  });
138
126
 
139
127
  test("timeout cache follows prepare-time PRAGMA effects", () => {
@@ -173,98 +161,135 @@ test("timeout cache follows prepare-time PRAGMA effects", () => {
173
161
 
174
162
  for (const method of ["get", "all", "run", "values", "iterate"] as const) {
175
163
  test(`turn deadline bounds cached SELECT ${method}`, async () => {
176
- await fixture(async (db, path) => {
177
- const statement = db.prepare("SELECT * FROM t") as any;
164
+ const nativeMethod = method === "iterate" ? "iterate.next" : method;
165
+ await fixture(
166
+ (sql, api) => sql === readSql && api === nativeMethod,
167
+ async (db, path, timeouts) => {
168
+ const statement = db.prepare(readSql) as unknown as ReturnType<
169
+ NativeDatabase["prepare"]
170
+ >;
171
+ const release = await hold(path);
172
+ try {
173
+ bounded(
174
+ () =>
175
+ method === "iterate" ? statement.iterate().next() : statement[method](),
176
+ timeouts,
177
+ );
178
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 900 });
179
+ } finally {
180
+ await release();
181
+ }
182
+ expect(statement.get()).toEqual({ value: 1 });
183
+ },
184
+ );
185
+ });
186
+ }
187
+
188
+ test("turn deadline bounds native exec reads", async () => {
189
+ await fixture(
190
+ (sql, method) => sql === readSql && method === "exec",
191
+ async (db, path, timeouts) => {
178
192
  const release = await hold(path);
179
193
  try {
180
- bounded(() =>
181
- method === "iterate" ? statement.iterate().next() : statement[method](),
182
- );
194
+ bounded(() => db.exec(readSql), timeouts);
183
195
  expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 900 });
184
196
  } finally {
185
197
  await release();
186
198
  }
187
- });
188
- });
189
- }
190
-
191
- test("turn deadline bounds native exec reads", async () => {
192
- await fixture(async (db, path) => {
193
- const release = await hold(path);
194
- try {
195
- bounded(() => db.exec("SELECT * FROM t"));
196
- } finally {
197
- await release();
198
- }
199
- });
199
+ db.exec(readSql);
200
+ },
201
+ );
200
202
  });
201
203
 
202
204
  test("turn deadline bounds native schema preparation", async () => {
203
- await fixture(async (_db, path) => {
204
- const release = await hold(path);
205
- const fresh = createSqliteTurnDatabase(path);
206
- fresh.exec("PRAGMA busy_timeout=900");
207
- try {
208
- bounded(() => fresh.prepare("SELECT * FROM t"));
209
- } finally {
210
- fresh.close();
211
- await release();
212
- }
213
- });
205
+ await fixture(
206
+ (sql, method) => sql === readSql && method === "prepare",
207
+ async (_db, path, timeouts) => {
208
+ const release = await hold(path);
209
+ const fresh = createSqliteTurnDatabase(path);
210
+ fresh.exec("PRAGMA busy_timeout=900");
211
+ try {
212
+ try {
213
+ bounded(() => fresh.prepare(readSql), timeouts);
214
+ expect(fresh.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 900 });
215
+ } finally {
216
+ await release();
217
+ }
218
+ expect(fresh.prepare(readSql).get()).toEqual({ value: 1 });
219
+ } finally {
220
+ fresh.close();
221
+ }
222
+ },
223
+ );
214
224
  });
215
225
 
216
226
  test("turn deadline bounds COMMIT waiting for a reader", async () => {
217
- await fixture(async (db, path) => {
218
- db.exec("BEGIN IMMEDIATE; UPDATE t SET value=2");
219
- const release = await hold(path, true);
220
- try {
221
- bounded(() => db.exec("COMMIT"));
222
- expect(db.inTransaction).toBe(true);
223
- db.exec("ROLLBACK");
224
- } finally {
225
- await release();
226
- }
227
- });
227
+ await fixture(
228
+ (sql, method) => sql === "COMMIT" && method === "exec",
229
+ async (db, path, timeouts) => {
230
+ db.exec("BEGIN IMMEDIATE; UPDATE t SET value=value+1");
231
+ const release = await hold(path, true);
232
+ try {
233
+ bounded(() => db.exec("COMMIT"), timeouts);
234
+ expect(db.inTransaction).toBe(true);
235
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 900 });
236
+ } finally {
237
+ await release();
238
+ }
239
+ db.exec("COMMIT");
240
+ expect(db.prepare(readSql).all()).toEqual([{ value: 2 }]);
241
+ },
242
+ );
228
243
  });
229
244
 
230
245
  test("turn deadline bounds execution inside a deferred transaction", async () => {
231
- await fixture(async (db, path) => {
232
- const read = db.prepare("SELECT * FROM t");
233
- db.exec("BEGIN DEFERRED");
234
- const release = await hold(path);
235
- try {
236
- bounded(() => read.get());
237
- } finally {
246
+ await fixture(
247
+ (sql, method) => sql === readSql && method === "get",
248
+ async (db, path, timeouts) => {
249
+ const read = db.prepare(readSql);
250
+ db.exec("BEGIN DEFERRED");
251
+ const release = await hold(path);
252
+ try {
253
+ bounded(() => read.get(), timeouts);
254
+ expect(db.inTransaction).toBe(true);
255
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 900 });
256
+ } finally {
257
+ await release();
258
+ }
259
+ expect(read.get()).toEqual({ value: 1 });
238
260
  db.exec("ROLLBACK");
239
- await release();
240
- }
241
- });
261
+ },
262
+ );
242
263
  });
243
264
 
244
265
  test("turn deadline preserves zero-timeout probes and detached work", async () => {
245
- await fixture(async (db, path) => {
246
- const read = db.prepare("SELECT * FROM t");
247
- const release = await hold(path);
248
- try {
249
- withSqliteTurnDeadline(
250
- () => 80,
251
- () => {
252
- db.exec("PRAGMA busy_timeout=0");
253
- expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 0 });
254
- expect(() => read.get()).toThrow(/locked|busy/i);
255
- db.exec("PRAGMA busy_timeout=900");
256
- },
257
- );
258
- const start = performance.now();
259
- expect(() =>
266
+ await fixture(
267
+ (sql, method) => sql === readSql && method === "get",
268
+ async (db, path, timeouts) => {
269
+ const read = db.prepare(readSql);
270
+ const release = await hold(path);
271
+ try {
260
272
  withSqliteTurnDeadline(
261
- () => 0,
262
- () => withoutSqliteTransformPass(() => read.get()),
263
- ),
264
- ).toThrow(/locked|busy/i);
265
- expect(performance.now() - start).toBeGreaterThan(700);
266
- } finally {
267
- await release();
268
- }
269
- });
273
+ () => 80,
274
+ () => {
275
+ db.exec("PRAGMA busy_timeout=0");
276
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 0 });
277
+ expect(() => read.get()).toThrow(busy);
278
+ db.exec("PRAGMA busy_timeout=900");
279
+ },
280
+ );
281
+ expect(() =>
282
+ withSqliteTurnDeadline(
283
+ () => 0,
284
+ () => withoutSqliteTransformPass(() => read.get()),
285
+ ),
286
+ ).toThrow(busy);
287
+ expect(timeouts).toEqual([0, 900]);
288
+ expect(db.prepare("PRAGMA busy_timeout").get()).toEqual({ timeout: 900 });
289
+ } finally {
290
+ await release();
291
+ }
292
+ expect(read.get()).toEqual({ value: 1 });
293
+ },
294
+ );
270
295
  });