opencode-self-improvement 0.33.8 → 0.33.10

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.
@@ -1,5 +1,5 @@
1
1
  // decay — split from src/portable.ts. Declaration bodies are unchanged.
2
- import { open } from "node:fs/promises";
2
+ import { cmpTs } from "../core/cmp-ts.ts";
3
3
  import { loadAll } from "../store/files/load.ts";
4
4
  import { type Memory } from "../store/model/memory.ts";
5
5
  import { isInjectable } from "../store/model/predicates.ts";
@@ -7,8 +7,7 @@ import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
7
7
 
8
8
  // --- decay support --------------------------------------------------------------
9
9
 
10
- // Active open threads with ts older than `days` days, oldest first (both sides
11
- // are UTC-Z ISO strings, so plain lexicographic compare is correct).
10
+ // Legacy rows may omit milliseconds. Compare instants for both the cutoff and order.
12
11
  export async function findStaleOpen(
13
12
  days: number,
14
13
  sid?: string,
@@ -24,8 +23,8 @@ export async function findStaleOpen(
24
23
  isInjectable(m) &&
25
24
  isVisibleTo(m, reader) &&
26
25
  m.status === "open" &&
27
- m.ts < cutoff,
26
+ cmpTs(m.ts, cutoff) < 0,
28
27
  )
29
- .sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0))
28
+ .sort((a, b) => cmpTs(a.ts, b.ts))
30
29
  );
31
30
  }
@@ -11,6 +11,7 @@
11
11
  import type { Memory } from "../store/model/memory.ts";
12
12
  import { flattenMemoryText } from "../store/sanitize.ts";
13
13
  import { contentTokens } from "./dedupe.ts";
14
+ import { cmpTs } from "../core/cmp-ts.ts";
14
15
 
15
16
  /**
16
17
  * Cap on each token list. A pair that reaches the threshold while differing
@@ -25,6 +26,89 @@ function list(tokens: string[]): string {
25
26
  return `${shown.join(", ")}${held > 0 ? ` (+${held} more)` : ""}`;
26
27
  }
27
28
 
29
+ /**
30
+ * Dropped tokens that share the SAME set of older source rows, so a token several
31
+ * rows carried prints once beside all of them and a token unique to one row never
32
+ * rides along claiming a row that never held it. The sources are per group, not
33
+ * pooled across the family: in a three-member group the newest row can drop one
34
+ * token from two older rows and a different token from only one of them, and a
35
+ * single shared source list would assert the second token came from a row that
36
+ * never had it.
37
+ */
38
+ interface DropGroup {
39
+ /** Member indexes (into `members`) that held these tokens and newest lacks. */
40
+ sources: number[];
41
+ /** Tokens those rows carried and the newest row dropped. */
42
+ tokens: string[];
43
+ }
44
+
45
+ /**
46
+ * Whether the newest member of a family drops tokens an older member carries.
47
+ *
48
+ * Containment alone cannot tell the two situations apart: "the longer row adds a
49
+ * second case" and "the newer row corrected the older one" produce the same pair
50
+ * of token sets, and the marker used to resolve that in one direction for both.
51
+ * Recency does discriminate. A newer row that is wholly contained in an older
52
+ * one removed something, and a removal is exactly what a correction looks like.
53
+ *
54
+ * `sets` are the CONTENT-only token sets, not `contentTokens`: this sentence
55
+ * claims a token was dropped from text the reader is looking at, and the recall
56
+ * renderer prints `content` but never `kw`, so a keyword-only difference would
57
+ * assert a removal of a token that appears in neither rendered row.
58
+ *
59
+ * Returns null when the newest row cannot be identified — a family sharing one
60
+ * timestamp carries no direction, and guessing would be worse than the neutral
61
+ * instruction — or when no older row holds a content token the newest row lacks.
62
+ */
63
+ function droppedByNewest(
64
+ members: Memory[],
65
+ sets: Set<string>[],
66
+ ): { newest: number; groups: DropGroup[] } | null {
67
+ let newest = 0;
68
+ for (let i = 1; i < members.length; i++)
69
+ if (cmpTs(members[i]!.ts, members[newest]!.ts) > 0) newest = i;
70
+ if (
71
+ members.some(
72
+ (m, i) => i !== newest && cmpTs(m.ts, members[newest]!.ts) === 0,
73
+ )
74
+ )
75
+ return null;
76
+ const now = sets[newest]!;
77
+ // First pass: which older rows held each token the newest row dropped.
78
+ const order: string[] = [];
79
+ const byToken = new Map<string, number[]>();
80
+ sets.forEach((o, i) => {
81
+ if (i === newest || o.size <= now.size) return;
82
+ if (![...now].every((t) => o.has(t))) return;
83
+ for (const t of o) {
84
+ if (now.has(t)) continue;
85
+ let srcs = byToken.get(t);
86
+ if (!srcs) {
87
+ srcs = [];
88
+ byToken.set(t, srcs);
89
+ order.push(t);
90
+ }
91
+ if (!srcs.includes(i)) srcs.push(i);
92
+ }
93
+ });
94
+ // Second pass: collapse tokens that share a source set into one group, keeping
95
+ // first-seen order so the sentence and the cap stay stable.
96
+ const groups: DropGroup[] = [];
97
+ const at = new Map<string, number>();
98
+ for (const t of order) {
99
+ const srcs = byToken.get(t)!;
100
+ const key = srcs.join(",");
101
+ let gi = at.get(key);
102
+ if (gi === undefined) {
103
+ gi = groups.length;
104
+ at.set(key, gi);
105
+ groups.push({ sources: srcs, tokens: [] });
106
+ }
107
+ groups[gi]!.tokens.push(t);
108
+ }
109
+ return groups.length ? { newest, groups } : null;
110
+ }
111
+
28
112
  /**
29
113
  * One line for one additive family, naming each member by its 1-based position
30
114
  * in the returned window. A family is however many rows the pass kept together,
@@ -36,6 +120,13 @@ function list(tokens: string[]): string {
36
120
  */
37
121
  export function ambiguousLine(members: Memory[], positions: number[]): string {
38
122
  const sets = members.map((m) => contentTokens(m));
123
+ // The drop claim is drawn from CONTENT only. The clash test above may use
124
+ // keywords, but this sentence describes text the reader sees, and the recall
125
+ // renderer prints `content` and never `kw` — a keyword-only difference would
126
+ // assert the removal of a token that appears in neither rendered row.
127
+ const contentSets = members.map((m) =>
128
+ contentTokens({ ...m, kw: undefined }),
129
+ );
39
130
  // Each side lists what THAT member has that none of the others have, so a
40
131
  // nested chain prints one side rather than one per member: every row but the
41
132
  // largest is wholly contained in the union of the rest. The line therefore
@@ -49,18 +140,54 @@ export function ambiguousLine(members: Memory[], positions: number[]): string {
49
140
  const only = [...t].filter((tok) => !others.has(tok));
50
141
  if (only.length) sides.push(`only in ${positions[i]}: ${list(only)}`);
51
142
  });
52
- const where =
53
- positions.length === 2
54
- ? `rows ${positions[0]} and ${positions[1]}`
55
- : `rows ${positions.slice(0, -1).join(", ")} and ${positions[positions.length - 1]}`;
143
+ const rowsLabel = (idx: number[]): string =>
144
+ idx.length === 1
145
+ ? `row ${positions[idx[0]!]}`
146
+ : `rows ${idx
147
+ .slice(0, -1)
148
+ .map((i) => positions[i])
149
+ .join(", ")} and ${positions[idx[idx.length - 1]!]}`;
150
+ const where = rowsLabel(positions.map((_, i) => i));
56
151
  const rest =
57
152
  positions.length === 2
58
153
  ? "neither restates the other"
59
154
  : "none restates the others";
155
+ // Two readings fit the same token sets, and they need opposite instructions.
156
+ // When the newest row is the one that left something out, saying "neither
157
+ // supersedes the other" states as fact the one thing the text cannot
158
+ // establish, so the line names the removal and leaves the verdict open.
159
+ const drop = droppedByNewest(members, contentSets);
160
+ let action: string;
161
+ if (drop) {
162
+ // One clause per source group, capped across the whole family. With a single
163
+ // source this collapses to the original "row 2 drops python from row 1" (and
164
+ // the same list(...) form for several tokens), which the reproducer pins.
165
+ let budget = MAX_MARKER_TOKENS;
166
+ let held = 0;
167
+ const clauses: string[] = [];
168
+ for (const g of drop.groups) {
169
+ if (budget <= 0) {
170
+ held += g.tokens.length;
171
+ continue;
172
+ }
173
+ const shown = g.tokens.slice(0, budget);
174
+ budget -= shown.length;
175
+ held += g.tokens.length - shown.length;
176
+ clauses.push(`${list(shown)} from ${rowsLabel(g.sources)}`);
177
+ }
178
+ action =
179
+ `Action: ${rowsLabel([drop.newest])} drops ${clauses.join(" and ")}` +
180
+ (held > 0 ? ` (+${held} more)` : "") +
181
+ ` — that may be a correction rather than a narrower case. Verify which ` +
182
+ `before relying on either; both stay available.`;
183
+ } else {
184
+ action =
185
+ `Action: neither supersedes the other. Pick by what you are actually doing; ` +
186
+ `if both apply, use both.`;
187
+ }
60
188
  return (
61
189
  `AMBIGUOUS (${flattenMemoryText(members[0]!.scope)}): ${where} share ` +
62
190
  `shape but ${rest}${sides.length ? ` — ${sides.join("; ")}` : ""}. ` +
63
- `Action: neither supersedes the other. Pick by what you are actually doing; ` +
64
- `if both apply, use both.`
191
+ action
65
192
  );
66
193
  }
@@ -13,6 +13,7 @@ import {
13
13
  type StoreCounts,
14
14
  emptyStats,
15
15
  } from "./payload.ts";
16
+ import type { DroppedEvidenceWrites } from "../telemetry/record.ts";
16
17
  import { EVICT_MIN_RIDES } from "./store-summary.ts";
17
18
 
18
19
  function ago(iso: string): string {
@@ -215,6 +216,28 @@ export function captureLines(c: CaptureHealth): string[] {
215
216
  }
216
217
  }
217
218
 
219
+ /**
220
+ * The one report an unwritable evidence log can produce: a count kept in this
221
+ * process, never a line appended to the log that failed. Silence here means
222
+ * this process lost nothing — a store that lost writes in an earlier process
223
+ * reports nothing, because the counter lives and dies with the process that
224
+ * could still tell.
225
+ */
226
+ export function evidenceWriteLines(
227
+ evidence?: DroppedEvidenceWrites | null,
228
+ ): string[] {
229
+ if (!evidence || evidence.dropped === 0) return [];
230
+ return [
231
+ ` evidence writes dropped: ${evidence.dropped} by this process (last ${
232
+ evidence.lastEvent
233
+ }: ${evidence.lastError.slice(0, 160)})`,
234
+ // The health lines above are read back out of the log that is losing
235
+ // writes, so they under-report what ran. Without this the reader weighs a
236
+ // missing line as evidence that the pass never happened.
237
+ " capture kept running; the auto-capture lines above read from that same log and under-count it",
238
+ ];
239
+ }
240
+
218
241
  /**
219
242
  * Plain-text rendering shared by the memory_status tool (and any other chat
220
243
  * client). Sections match the terminal /memory panel one-for-one.
@@ -225,6 +248,12 @@ export function renderMemoryReport(input: {
225
248
  blocked: BlockedRow[];
226
249
  quarantined?: { ts: string; patterns: string[] }[];
227
250
  capture?: CaptureHealth;
251
+ /**
252
+ * Evidence writes this process lost for this store. The only report an
253
+ * unwritable log can produce is one that never touches the log, so it arrives
254
+ * from process memory rather than from the lines above it.
255
+ */
256
+ evidence?: DroppedEvidenceWrites | null;
228
257
  }): string {
229
258
  const { status, store, blocked } = input;
230
259
  const out: string[] = ["MEMORY STATUS", ""];
@@ -347,11 +376,15 @@ export function renderMemoryReport(input: {
347
376
  );
348
377
  }
349
378
  if (sizing.length) out.push(` ${sizing.join(" · ")}`);
350
- if (input.capture) {
379
+ const captureSection = [
380
+ ...(input.capture ? captureLines(input.capture) : []),
381
+ ...evidenceWriteLines(input.evidence),
382
+ ];
383
+ if (captureSection.length) {
351
384
  out.push(
352
385
  "",
353
386
  "AUTO-CAPTURE — is it off, misconfigured, armed, or alive?",
354
- ...captureLines(input.capture),
387
+ ...captureSection,
355
388
  );
356
389
  }
357
390
  out.push(
package/src/store/lock.ts CHANGED
@@ -98,7 +98,6 @@ import { record } from "../telemetry/record.ts";
98
98
  */
99
99
  const lockDatabaseName = (file: string): string =>
100
100
  `.store-lock.${basename(file)}.sqlite`;
101
- const DEFAULT_TIMEOUT_MS = 10_000;
102
101
  // The budget must exceed the worst LEGITIMATE wait, not just an idle section.
103
102
  // A whole-file publish inside a section can spend 2000 ms in `handoverRename`
104
103
  // retrying a rename Windows refuses while a reader holds the destination
@@ -108,24 +107,12 @@ const DEFAULT_TIMEOUT_MS = 10_000;
108
107
  // reported "locked for 5001ms" while the holder was mid-handover-retry, not
109
108
  // wedged. 10 s still fails closed and reports, but stops refusing writes that
110
109
  // were simply behind two honest retries.
111
- // the default policy is fail-closed, the policy moved every
112
- // production writer to. A writer that omits opts must refuse at the deadline,
113
- // not silently reintroduce the unlocked-proceed row loss the LOCK_WRITE
114
- // contract retired. "proceed" survives only as an explicit opt-in.
115
- const DEFAULT_ON_TIMEOUT = "fail";
110
+ const DEFAULT_TIMEOUT_MS = 10_000;
116
111
  const MIN_BACKOFF_MS = 1;
117
112
  const MAX_BACKOFF_MS = 25;
118
- // Leaving a legacy WAL journal is a once-per-process-per-lock setup step, not
119
- // the hot path, so it gets its own bound rather than the caller's budget.
113
+ // Legacy journal conversion has its own ceiling within the acquisition deadline.
120
114
  const JOURNAL_CONVERT_BUDGET_MS = 5_000;
121
115
 
122
- // The one source of the timeout policy: both give-up paths — the FIFO
123
- // hand-off and the SQLite wait — resolve through here, so the fail-closed
124
- // default cannot drift between them.
125
- function timeoutPolicy(opts: LockOptions): "proceed" | "fail" {
126
- return opts.onTimeout === "proceed" ? "proceed" : DEFAULT_ON_TIMEOUT;
127
- }
128
-
129
116
  /**
130
117
  * `timeout`: waited past the budget. `reset`: a release was refused, so the
131
118
  * connection was thrown away. SQLite should never refuse a ROLLBACK, and if it
@@ -169,18 +156,34 @@ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
169
156
  const busyMessage = (file: string, waitedMs: number): string =>
170
157
  `memory store is busy: ${basename(file)} has been locked for ${waitedMs}ms — retry`;
171
158
 
172
- // Resolves when the task stored as this key has finished, handing the turn to
173
- // whoever queued after it.
174
- const turns = new Map<string, Promise<void>>();
175
-
176
- async function timed(prev: Promise<void>, ms: number): Promise<boolean> {
177
- let timer: ReturnType<typeof setTimeout> | undefined;
178
- const gained = await Promise.race([
179
- prev.then(() => true),
180
- new Promise<boolean>((res) => (timer = setTimeout(() => res(false), ms))),
181
- ]);
182
- clearTimeout(timer);
183
- return gained;
159
+ function onLockTimeout<T>(
160
+ file: string,
161
+ fn: () => Promise<T>,
162
+ opts: LockOptions,
163
+ waited: number,
164
+ ): Promise<T> {
165
+ const ms = Math.round(waited);
166
+ opts.onEvent?.("timeout", ms);
167
+ if (opts.onTimeout === "proceed") return fn();
168
+ throw new Error(busyMessage(file, ms));
169
+ }
170
+
171
+ // An entry exists while one owner holds the turn. Waiters can leave the FIFO
172
+ // on timeout without releasing the owner or waking its successor.
173
+ const turns = new Map<string, Set<() => void>>();
174
+
175
+ function waitForTurn(waiters: Set<() => void>, ms: number): Promise<boolean> {
176
+ return new Promise((resolve) => {
177
+ const grant = () => {
178
+ clearTimeout(timer);
179
+ resolve(true);
180
+ };
181
+ const timer = setTimeout(() => {
182
+ waiters.delete(grant);
183
+ resolve(false);
184
+ }, ms);
185
+ waiters.add(grant);
186
+ });
184
187
  }
185
188
 
186
189
  /**
@@ -337,7 +340,10 @@ async function harden(dbPath: string): Promise<void> {
337
340
  await chmod(dbPath, 0o600).catch(() => undefined);
338
341
  }
339
342
 
340
- async function lockDatabase(dbPath: string): Promise<Database> {
343
+ async function lockDatabase(
344
+ dbPath: string,
345
+ deadline: number,
346
+ ): Promise<Database | undefined> {
341
347
  const cached = lockDbs.get(dbPath);
342
348
  if (cached) {
343
349
  // Touch: this directory is in use, so it moves to the protected end of the
@@ -367,7 +373,10 @@ async function lockDatabase(dbPath: string): Promise<Database> {
367
373
  // policy stays ours — async, bounded, and sharing one budget with the FIFO
368
374
  // hand-off above.
369
375
  db.run("PRAGMA busy_timeout = 0");
370
- await ensureLockJournal(db, dbPath);
376
+ if (!(await ensureLockJournal(db, dbPath, deadline))) {
377
+ db.close();
378
+ return undefined;
379
+ }
371
380
  } catch (err) {
372
381
  db.close();
373
382
  throw err;
@@ -402,14 +411,18 @@ const journalMode = (db: Database): string =>
402
411
  * LEAVE WAL is refused rather than run that way: the sidecar churn would come
403
412
  * back per store, silently.
404
413
  */
405
- async function ensureLockJournal(db: Database, dbPath: string): Promise<void> {
414
+ async function ensureLockJournal(
415
+ db: Database,
416
+ dbPath: string,
417
+ deadline: number,
418
+ ): Promise<boolean> {
419
+ const started = performance.now();
420
+ const until = Math.min(deadline, started + JOURNAL_CONVERT_BUDGET_MS);
406
421
  let backoff = MIN_BACKOFF_MS;
407
- let waited = 0;
408
422
  for (;;) {
409
- const step = Date.now();
410
423
  try {
411
424
  const mode = journalMode(db);
412
- if (mode === "delete") return;
425
+ if (mode === "delete") return true;
413
426
  db.run("PRAGMA journal_mode = DELETE");
414
427
  if (journalMode(db) === "delete") {
415
428
  // The conversion checkpoints and removes `-wal`, but `-shm` only goes
@@ -421,7 +434,7 @@ async function ensureLockJournal(db: Database, dbPath: string): Promise<void> {
421
434
  // the issue is the Windows delete this module exists to avoid.
422
435
  await unlink(`${dbPath}-wal`).catch(() => undefined);
423
436
  await unlink(`${dbPath}-shm`).catch(() => undefined);
424
- return;
437
+ return true;
425
438
  }
426
439
  } catch (err) {
427
440
  if (!contention(err)) {
@@ -431,14 +444,10 @@ async function ensureLockJournal(db: Database, dbPath: string): Promise<void> {
431
444
  );
432
445
  }
433
446
  }
434
- await sleep(backoff);
435
- waited += Date.now() - step;
447
+ const remaining = until - performance.now();
448
+ if (remaining <= 0) return false;
449
+ await sleep(Math.min(backoff, remaining));
436
450
  backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
437
- if (waited >= JOURNAL_CONVERT_BUDGET_MS) {
438
- throw new Error(
439
- `store lock could not leave write-ahead journal mode for ${dbPath} after ${waited}ms — another process is holding the lock database in a state that refuses it`,
440
- );
441
- }
442
451
  }
443
452
  }
444
453
 
@@ -458,24 +467,19 @@ function dropLockDatabase(dbPath: string): void {
458
467
  }
459
468
  }
460
469
 
461
- /**
462
- * Cross-process half: hold the lock while `fn` runs. `now` is a seam for tests
463
- * that must land the deadline inside a specific wait iteration; production
464
- * callers never pass it and the real clock is used.
465
- */
470
+ /** Cross-process acquisition uses the same monotonic deadline as the FIFO. */
466
471
  async function holdLock<T>(
467
472
  dbPath: string,
468
473
  file: string,
469
474
  fn: () => Promise<T>,
470
475
  opts: LockOptions,
471
- budgetMs: number,
472
- now: () => number = Date.now,
476
+ started: number,
477
+ deadline: number,
473
478
  ): Promise<T> {
474
- let db = await lockDatabase(dbPath);
475
- const started = now();
479
+ let db = await lockDatabase(dbPath, deadline);
476
480
  let backoff = MIN_BACKOFF_MS;
477
481
  let reconnected = false;
478
- for (;;) {
482
+ while (db) {
479
483
  try {
480
484
  db.run("BEGIN IMMEDIATE");
481
485
  break;
@@ -486,7 +490,7 @@ async function holdLock<T>(
486
490
  // try again on a fresh connection; a second failure surfaces.
487
491
  reconnected = true;
488
492
  dropLockDatabase(dbPath);
489
- db = await lockDatabase(dbPath);
493
+ db = await lockDatabase(dbPath, deadline);
490
494
  continue;
491
495
  }
492
496
  const info = err as { code?: string; errno?: number };
@@ -494,21 +498,14 @@ async function holdLock<T>(
494
498
  `[code=${info.code ?? "-"} errno=${info.errno ?? "-"}] store lock unavailable for ${basename(file)}: ${(err as Error).message}`,
495
499
  );
496
500
  }
497
- if (now() - started >= budgetMs) {
498
- opts.onEvent?.("timeout", now() - started);
499
- if (timeoutPolicy(opts) === "fail") {
500
- throw new Error(busyMessage(file, now() - started));
501
- }
502
- // Proceeding without the lock is the explicit "proceed" opt-in
503
- // (no longer the default). heldLocks is deliberately NOT touched
504
- // here: a writer that never held the lock must not let a nested call
505
- // believe it did.
506
- return await fn();
507
- }
508
- await sleep(backoff);
501
+ const remaining = deadline - performance.now();
502
+ if (remaining <= 0)
503
+ return onLockTimeout(file, fn, opts, performance.now() - started);
504
+ await sleep(Math.min(backoff, remaining));
509
505
  backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
510
506
  }
511
507
  }
508
+ if (!db) return onLockTimeout(file, fn, opts, performance.now() - started);
512
509
  await harden(dbPath);
513
510
  acquiredHook?.(file);
514
511
  // Protected from eviction for as long as the section runs: closing a
@@ -527,7 +524,7 @@ async function holdLock<T>(
527
524
  db.run("ROLLBACK");
528
525
  } catch (err) {
529
526
  dropLockDatabase(dbPath);
530
- opts.onEvent?.("reset", now() - started);
527
+ opts.onEvent?.("reset", Math.round(performance.now() - started));
531
528
  void err;
532
529
  }
533
530
  }
@@ -544,16 +541,12 @@ async function acquire<T>(
544
541
  opts: LockOptions,
545
542
  ): Promise<T> {
546
543
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
547
- const started = Date.now();
544
+ const started = performance.now();
548
545
 
549
546
  if (busyInjector?.(file)) {
550
547
  // Reported exactly as a waited-out budget would report it, so a test that
551
548
  // injects a refusal exercises the same policy and message as a real one.
552
- opts.onEvent?.("timeout", 0);
553
- if (timeoutPolicy(opts) === "fail") {
554
- throw new Error(busyMessage(file, 0));
555
- }
556
- return fn();
549
+ return onLockTimeout(file, fn, opts, 0);
557
550
  }
558
551
 
559
552
  if (heldLocks.getStore()?.has(dbPath)) {
@@ -565,40 +558,25 @@ async function acquire<T>(
565
558
  return await fn();
566
559
  }
567
560
 
568
- let releaseTurn!: () => void;
569
- const myTurnEnded = new Promise<void>((res) => (releaseTurn = res));
570
- const queuedBehind = turns.get(dbPath);
571
- turns.set(dbPath, myTurnEnded);
572
-
573
- const finish = () => {
574
- releaseTurn();
575
- if (turns.get(dbPath) === myTurnEnded) turns.delete(dbPath);
576
- };
577
-
578
- if (queuedBehind) {
579
- const gained = await timed(queuedBehind, timeoutMs);
580
- if (!gained) {
581
- // Give up our place in line rather than park everyone behind us on a
582
- // writer that is not going to finish.
583
- finish();
584
- opts.onEvent?.("timeout", Date.now() - started);
585
- if (timeoutPolicy(opts) === "fail") {
586
- throw new Error(busyMessage(file, Date.now() - started));
587
- }
588
- return fn();
589
- }
561
+ let waiters = turns.get(dbPath);
562
+ if (waiters) {
563
+ if (!(await waitForTurn(waiters, timeoutMs)))
564
+ return onLockTimeout(file, fn, opts, performance.now() - started);
565
+ } else {
566
+ waiters = new Set();
567
+ turns.set(dbPath, waiters);
590
568
  }
591
569
 
592
570
  try {
593
- return await holdLock(
594
- dbPath,
595
- file,
596
- fn,
597
- opts,
598
- timeoutMs - (Date.now() - started),
599
- );
571
+ return await holdLock(dbPath, file, fn, opts, started, started + timeoutMs);
600
572
  } finally {
601
- finish();
573
+ const next = waiters.values().next().value;
574
+ if (next) {
575
+ waiters.delete(next);
576
+ next();
577
+ } else {
578
+ turns.delete(dbPath);
579
+ }
602
580
  }
603
581
  }
604
582