@spooky-sync/core 1.0.0-beta.10 → 1.0.0-beta.12

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.
@@ -81,14 +81,32 @@ const ROWS_READ_OPS: ReadonlySet<string> = new Set([
81
81
  const PAINT_MAX_KEYS = 64;
82
82
  const PAINT_MAX_ENTRY_CHARS = 256_000;
83
83
  const PAINT_FLUSH_MS = 1500;
84
+ /** What a kept read starts with: this layout. A copy that starts otherwise is another release's, and is not read. */
85
+ const PAINT_FORMAT = '2';
84
86
 
85
87
  interface PaintEntry {
86
88
  tables: string[];
87
- /** `0` or `1` (bytes to revive), then the rows as JSON text. */
89
+ /** {@link PAINT_FORMAT}, the header (see {@link paintHead}), a newline, then the rows as JSON text. */
88
90
  text: string;
89
91
  dirty: boolean;
90
92
  }
91
93
 
94
+ /** A table and its mark (see {@link PaintCache}) at the time a read of it was kept. */
95
+ type PaintMark = [table: string, mark: string | null];
96
+
97
+ /** A kept read's header: whether it holds bytes to revive, the marks it was read under, and where its rows start. */
98
+ function paintHead(text: string): { u8: boolean; marks: PaintMark[]; body: number } | null {
99
+ if (text[0] !== PAINT_FORMAT) return null;
100
+ const end = text.indexOf('\n');
101
+ if (end < 0) return null;
102
+ try {
103
+ const [u8, marks] = JSON.parse(text.slice(1, end)) as [number, PaintMark[]];
104
+ return Array.isArray(marks) ? { u8: u8 === 1, marks, body: end + 1 } : null;
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
92
110
  function hashKey(text: string): string {
93
111
  let a = 0x811c9dc5;
94
112
  let b = 0x01000193;
@@ -108,25 +126,48 @@ function hashKey(text: string): string {
108
126
  * while the store opens.
109
127
  *
110
128
  * What it holds is a copy, and the contract says so: a peek is something to
111
- * paint from, the read that follows is the answer. The copy is dropped the
112
- * moment this tab writes to a table it came from, and written again from the
113
- * next read of the same thing, so in practice the two agree; when they do not
114
- * (another tab wrote, the browser died before the drop reached the disk) the
115
- * read that follows corrects the screen a few milliseconds later.
129
+ * paint from, the read that follows is the answer.
130
+ *
131
+ * Several tabs keep copies in the same place and write to the same store
132
+ * (shared tabs), so a copy says what it was read under. Every table has a
133
+ * mark in localStorage, and a tab that writes to a table leaves a new one
134
+ * there, once before the write is sent and once after the store has taken it.
135
+ * A copy carries the marks its tables had when it was read and is handed out
136
+ * only while they still stand, whichever tab wrote. The same marks tell a tab
137
+ * that a read of its own was overtaken by another tab's write (see
138
+ * {@link stamp}). What is left is a tab that dies between a write and its
139
+ * second mark, a write given up on (its deadline passed) that the store takes
140
+ * after all, and a browser that dies before a mark reaches the disk: the read
141
+ * that follows the peek then corrects the screen a moment later.
142
+ *
143
+ * A tab that is alone in the store (no shared tabs) leaves no marks: nobody
144
+ * else writes to it, and dropping its own copies as it writes is enough.
116
145
  */
117
146
  export class PaintCache {
118
147
  private entries = new Map<string, PaintEntry>();
119
148
  /** Reads this session made at startup: the ones worth keeping a copy of, whenever they run again. */
120
149
  private known = new Set<string>();
121
- /** table -> keys, for the entries of earlier sessions too. */
150
+ /** table -> keys, for the entries of earlier sessions and of other tabs too. */
122
151
  private byTable: Map<string, Set<string>> | null = null;
123
- /** table -> writes this tab made to it, to tell a read sent before a write from one sent after. */
152
+ /** table -> writes this tab knows of: its own, and another tab's each time the table's mark was found moved. */
124
153
  private writes = new Map<string, number>();
154
+ /** table -> its mark as this tab last read it. */
155
+ private seen = new Map<string, string | null>();
156
+ /** table -> the mark this tab last left there. */
157
+ private mine = new Map<string, string>();
158
+ private readonly tab = Math.random().toString(36).slice(2, 10);
159
+ private marked = 0;
160
+ /** Moves with the bucket, so a read sent under one is never kept under the next. */
161
+ private era = 0;
125
162
  private timer: ReturnType<typeof setTimeout> | null = null;
126
163
  private bucket = '';
127
164
  private since = 0;
128
165
 
129
- constructor(private maxChars: number) {
166
+ /** `shared`: other tabs write to the same store, so writes are marked for them. */
167
+ constructor(
168
+ private maxChars: number,
169
+ private shared = true
170
+ ) {
130
171
  if (typeof addEventListener === 'function') {
131
172
  // localStorage is synchronous, so the last state can still be saved as the page goes.
132
173
  addEventListener('pagehide', () => this.flush());
@@ -142,32 +183,68 @@ export class PaintCache {
142
183
  start(bucket: string): void {
143
184
  if (bucket !== this.bucket) {
144
185
  this.flush();
145
- this.entries.clear();
146
- this.known.clear();
147
- this.byTable = null;
186
+ this.forget();
148
187
  }
149
188
  this.bucket = bucket;
150
189
  this.since = Date.now();
151
190
  }
152
191
 
192
+ /**
193
+ * {@link start} for a tab that is handed its store more than once (shared
194
+ * tabs: a new role over the same bucket). Only the first hand-over of a
195
+ * bucket starts a session; what the tab reads after a later one is not what
196
+ * it reads at startup.
197
+ */
198
+ adopt(bucket: string): void {
199
+ if (bucket !== this.bucket || this.since === 0) this.start(bucket);
200
+ }
201
+
202
+ /** The store turned out to live in memory: nothing read from it is worth showing next time. */
203
+ stop(): void {
204
+ if (this.timer) clearTimeout(this.timer);
205
+ this.timer = null;
206
+ this.forget();
207
+ this.bucket = '';
208
+ this.since = 0;
209
+ }
210
+
211
+ private forget(): void {
212
+ this.entries.clear();
213
+ this.known.clear();
214
+ this.byTable = null;
215
+ this.seen.clear();
216
+ this.mine.clear();
217
+ this.era++;
218
+ }
219
+
153
220
  private name(key: string): string {
154
221
  return `sp00ky.paint.${this.bucket}.${key}`;
155
222
  }
156
223
 
224
+ /** Where `table`'s mark is kept. A key is a hash and has no dot, so the two never meet. */
225
+ private markName(table: string): string {
226
+ return `sp00ky.paint.${this.bucket}.t.${table}`;
227
+ }
228
+
157
229
  private index(): Map<string, Set<string>> {
158
230
  if (this.byTable) return this.byTable;
159
231
  this.byTable = new Map();
232
+ this.readIndex();
233
+ return this.byTable;
234
+ }
235
+
236
+ /** Take in the keys kept by earlier sessions, and by other tabs since this one last looked. */
237
+ private readIndex(): void {
160
238
  try {
161
239
  const saved = JSON.parse(localStorage.getItem(`sp00ky.paint.${this.bucket}`) ?? '{}') as Record<string, string[]>;
162
- for (const [key, tables] of Object.entries(saved)) this.link(key, tables);
240
+ for (const [key, tables] of Object.entries(saved)) if (Array.isArray(tables)) this.link(key, tables);
163
241
  } catch {
164
242
  /* an unreadable index only means nothing gets dropped that is not there */
165
243
  }
166
- return this.byTable;
167
244
  }
168
245
 
169
246
  private link(key: string, tables: string[]): void {
170
- const index = this.byTable!;
247
+ const index = this.index();
171
248
  for (const table of tables) {
172
249
  let keys = index.get(table);
173
250
  if (!keys) index.set(table, (keys = new Set()));
@@ -175,25 +252,114 @@ export class PaintCache {
175
252
  }
176
253
  }
177
254
 
255
+ /**
256
+ * Read `table`'s mark. One that moved, and not to what this tab left there,
257
+ * is another tab's write.
258
+ */
259
+ private look(table: string): void {
260
+ let now: string | null = null;
261
+ try {
262
+ now = localStorage.getItem(this.markName(table));
263
+ } catch {
264
+ /* no storage: no other tab to hear from */
265
+ }
266
+ if (now === (this.seen.get(table) ?? null)) return;
267
+ this.seen.set(table, now);
268
+ if (now !== this.mine.get(table)) this.writes.set(table, (this.writes.get(table) ?? 0) + 1);
269
+ }
270
+
271
+ /** Leave a new mark on `table`: every copy read under the old one is void, in every tab. */
272
+ private leave(table: string): void {
273
+ if (!this.shared) return;
274
+ // Another tab's write is counted before its mark is covered.
275
+ this.look(table);
276
+ let mark: string | null = `${this.tab}.${++this.marked}`;
277
+ try {
278
+ try {
279
+ localStorage.setItem(this.markName(table), mark);
280
+ } catch {
281
+ // No room for it. The copies are what fills the room and what the mark
282
+ // protects: without them it fits, and there is nothing left to go stale.
283
+ this.empty();
284
+ localStorage.setItem(this.markName(table), mark);
285
+ }
286
+ } catch {
287
+ // Still none (the storage is someone else's, or gone). Taking the old mark away says as much.
288
+ mark = null;
289
+ try {
290
+ localStorage.removeItem(this.markName(table));
291
+ } catch {
292
+ /* no storage: no other tab reads it either */
293
+ }
294
+ }
295
+ if (mark === null) this.mine.delete(table);
296
+ else this.mine.set(table, mark);
297
+ this.seen.set(table, mark);
298
+ }
299
+
300
+ /** Every copy kept for this bucket, by any tab, whether the index knows it or not. Marks stay. */
301
+ private copies(): string[] {
302
+ const prefix = `sp00ky.paint.${this.bucket}.`;
303
+ const out: string[] = [];
304
+ for (let i = 0; i < localStorage.length; i++) {
305
+ const name = localStorage.key(i);
306
+ if (name !== null && name.startsWith(prefix) && !name.startsWith(prefix + 't.')) out.push(name.slice(prefix.length));
307
+ }
308
+ return out;
309
+ }
310
+
311
+ /** Let go of every copy of this bucket, this tab's and the others'. */
312
+ private empty(): void {
313
+ this.entries.clear();
314
+ this.byTable = new Map();
315
+ try {
316
+ for (const key of this.copies()) localStorage.removeItem(this.name(key));
317
+ localStorage.removeItem(`sp00ky.paint.${this.bucket}`);
318
+ } catch {
319
+ /* no storage */
320
+ }
321
+ }
322
+
323
+ /** Whether no tab has written to these tables since they were read. Throws without storage. */
324
+ private holds(marks: PaintMark[]): boolean {
325
+ for (const [table, mark] of marks) if (localStorage.getItem(this.markName(table)) !== mark) return false;
326
+ return true;
327
+ }
328
+
178
329
  get(key: string, revive: (b64: string) => Uint8Array): Row[] | null {
179
330
  if (!this.bucket) return null;
180
331
  try {
181
- const text = this.entries.get(key)?.text ?? localStorage.getItem(this.name(key));
182
- if (!text) return null;
183
- if (text[0] === '0') return JSON.parse(text.slice(1)) as Row[];
184
- return JSON.parse(text.slice(1), (_k, v) =>
185
- v && typeof v === 'object' && typeof (v as { __u8?: unknown }).__u8 === 'string' ? revive((v as { __u8: string }).__u8) : v
186
- ) as Row[];
332
+ // This tab's own copy first. When that one no longer stands, another tab may have kept a newer one.
333
+ const own = this.entries.get(key)?.text;
334
+ for (const text of own ? [own, null] : [null]) {
335
+ const kept = text ?? localStorage.getItem(this.name(key));
336
+ const head = kept ? paintHead(kept) : null;
337
+ if (!kept || !head || !this.holds(head.marks)) continue;
338
+ const rows = kept.slice(head.body);
339
+ if (!head.u8) return JSON.parse(rows) as Row[];
340
+ return JSON.parse(rows, (_k, v) =>
341
+ v && typeof v === 'object' && typeof (v as { __u8?: unknown }).__u8 === 'string' ? revive((v as { __u8: string }).__u8) : v
342
+ ) as Row[];
343
+ }
344
+ return null;
187
345
  } catch {
188
346
  return null;
189
347
  }
190
348
  }
191
349
 
192
- /** How many writes `tables` have seen: taken when a read is sent, checked when it answers. */
193
- stamp(tables: string[]): number {
350
+ /**
351
+ * What is known of the writes to `tables`: taken when a read is sent,
352
+ * checked when it answers. It moves with every write this tab sends and
353
+ * with every write of another tab that this one has seen the mark of.
354
+ */
355
+ stamp(tables: string[]): string {
356
+ if (!this.bucket) return '';
194
357
  let n = 0;
195
- for (const table of tables) n += this.writes.get(table) ?? 0;
196
- return n;
358
+ for (const table of tables) {
359
+ this.look(table);
360
+ n += this.writes.get(table) ?? 0;
361
+ }
362
+ return `${this.era}.${n}`;
197
363
  }
198
364
 
199
365
  /**
@@ -201,22 +367,35 @@ export class PaintCache {
201
367
  * before. `sentAt` is {@link stamp} from when it was sent; a write to its
202
368
  * tables since then means the answer may already be old, and it is let go.
203
369
  */
204
- note(key: string, tables: string[], rows: string, u8: boolean, sentAt: number): void {
370
+ note(key: string, tables: string[], rows: string, u8: boolean, sentAt: string): void {
205
371
  if (!this.bucket || sentAt !== this.stamp(tables)) return;
206
372
  if (!this.known.has(key)) {
207
373
  if (Date.now() - this.since > PAINT_CAPTURE_MS || this.known.size >= PAINT_MAX_KEYS) return;
208
374
  this.known.add(key);
209
375
  }
210
376
  if (rows.length > PAINT_MAX_ENTRY_CHARS) return;
211
- this.entries.set(key, { tables, text: (u8 ? '1' : '0') + rows, dirty: true });
377
+ // `stamp` has just read every one of these marks.
378
+ const head = JSON.stringify([u8 ? 1 : 0, tables.map((table): PaintMark => [table, this.seen.get(table) ?? null])]);
379
+ this.entries.set(key, { tables, text: `${PAINT_FORMAT}${head}\n${rows}`, dirty: true });
380
+ this.link(key, tables);
212
381
  this.timer ??= setTimeout(() => this.flush(), PAINT_FLUSH_MS);
213
382
  }
214
383
 
215
- /** This tab is about to write to `tables`: what was read from them is no longer what they hold. */
216
- touch(tables: Iterable<string>): void {
384
+ /**
385
+ * This tab writes to `tables`: what was read from them is no longer what
386
+ * they hold. Called as the write is sent, and again with `done` once the
387
+ * store has answered it. The first call drops this tab's copies and fails
388
+ * its reads still on their way. The second only leaves a new mark: a tab
389
+ * that read between the two (it saw the first mark, the store had not yet
390
+ * taken the write) holds a copy that mark makes void, while this tab's own
391
+ * reads, queued behind its write and answered after it, are kept.
392
+ */
393
+ touch(tables: Iterable<string>, done = false): void {
217
394
  if (!this.bucket) return;
218
- const index = this.index();
395
+ const index = done ? null : this.index();
219
396
  for (const table of tables) {
397
+ this.leave(table);
398
+ if (!index) continue;
220
399
  this.writes.set(table, (this.writes.get(table) ?? 0) + 1);
221
400
  const keys = index.get(table);
222
401
  if (!keys || keys.size === 0) continue;
@@ -232,35 +411,72 @@ export class PaintCache {
232
411
  }
233
412
  }
234
413
 
235
- /** Write what changed, newest reads first, up to the budget. */
414
+ /**
415
+ * Write what changed, newest reads first, up to the budget, and clear out
416
+ * what no longer stands: the budget is one for all tabs of the bucket.
417
+ */
236
418
  flush(): void {
237
419
  if (this.timer) clearTimeout(this.timer);
238
420
  this.timer = null;
239
421
  if (!this.bucket) return;
422
+ const known = this.byTable !== null;
240
423
  const index = this.index();
424
+ if (known) this.readIndex();
241
425
  try {
242
426
  let used = 0;
243
427
  const kept: Record<string, string[]> = {};
244
428
  for (const [key, entry] of [...this.entries].reverse()) {
429
+ // Written to by another tab since: whatever sits under the key now is judged below.
430
+ if (!this.holds(paintHead(entry.text)?.marks ?? [])) {
431
+ this.entries.delete(key);
432
+ continue;
433
+ }
245
434
  if (used + entry.text.length > this.maxChars) {
246
435
  this.entries.delete(key);
247
436
  localStorage.removeItem(this.name(key));
437
+ for (const keys of index.values()) keys.delete(key);
248
438
  continue;
249
439
  }
250
- used += entry.text.length;
251
- kept[key] = entry.tables;
252
440
  if (entry.dirty) {
253
- localStorage.setItem(this.name(key), entry.text);
254
- entry.dirty = false;
255
- this.link(key, entry.tables);
441
+ try {
442
+ localStorage.setItem(this.name(key), entry.text);
443
+ entry.dirty = false;
444
+ } catch {
445
+ // No room for this one. It must not cost the others their place in the index.
446
+ this.entries.delete(key);
447
+ localStorage.removeItem(this.name(key));
448
+ for (const keys of index.values()) keys.delete(key);
449
+ continue;
450
+ }
256
451
  }
452
+ used += entry.text.length;
453
+ kept[key] = entry.tables;
454
+ }
455
+ // Copies this tab does not hold: other tabs', earlier sessions' that this
456
+ // one never read again, and any the index lost track of (two tabs saving
457
+ // at once), which nothing else would ever let go of.
458
+ const others = new Set<string>();
459
+ for (const keys of index.values()) for (const key of keys) if (!(key in kept)) others.add(key);
460
+ // Without marks nothing says whether such a stray is still true: it goes.
461
+ const strays = new Set<string>();
462
+ for (const key of this.copies()) {
463
+ if (key in kept || others.has(key)) continue;
464
+ if (this.shared) others.add(key);
465
+ else strays.add(key);
257
466
  }
258
- // Entries of earlier sessions that this one never read again stay until a write drops them.
259
- for (const [table, keys] of index) {
260
- for (const key of keys) {
261
- const tables = (kept[key] ??= []);
262
- if (!tables.includes(table)) tables.push(table);
467
+ for (const key of strays) localStorage.removeItem(this.name(key));
468
+ for (const key of others) {
469
+ const text = localStorage.getItem(this.name(key));
470
+ const head = text ? paintHead(text) : null;
471
+ if (!text || !head || !this.holds(head.marks) || used + text.length > this.maxChars) {
472
+ if (text) localStorage.removeItem(this.name(key));
473
+ for (const keys of index.values()) keys.delete(key);
474
+ continue;
263
475
  }
476
+ used += text.length;
477
+ const tables = head.marks.map((mark) => mark[0]);
478
+ kept[key] = tables;
479
+ this.link(key, tables);
264
480
  }
265
481
  localStorage.setItem(`sp00ky.paint.${this.bucket}`, JSON.stringify(kept));
266
482
  } catch {
@@ -405,9 +621,11 @@ export class RowsCacheEngine extends SqliteCacheEngine {
405
621
  override readonly engineKind = 'rows' as const;
406
622
  /** The transport in use wraps a worker `prewarmRows` started. */
407
623
  private adopted = false;
624
+ /** Drops what the adopted worker read ahead of the app, while any of it is still held. */
625
+ private forgetAhead: (() => void) | null = null;
408
626
  /** Last-seen startup reads, for {@link peekByIds} / {@link peekSelect}. Off for a memory store. */
409
627
  private paint: PaintCache | null =
410
- this.useOpfs && this.config.paintCache !== false && typeof localStorage !== 'undefined' ? new PaintCache(1_000_000) : null;
628
+ this.useOpfs && this.config.paintCache !== false && typeof localStorage !== 'undefined' ? new PaintCache(1_000_000, this.shared) : null;
411
629
 
412
630
  protected override createTransport(): SqliteTransport {
413
631
  const pre = takePrewarmed();
@@ -427,6 +645,7 @@ export class RowsCacheEngine extends SqliteCacheEngine {
427
645
  ahead?.drop();
428
646
  ahead = null;
429
647
  };
648
+ this.forgetAhead = forget;
430
649
  if (ahead) background(setTimeout(forget, PAINT_CAPTURE_MS));
431
650
  let opens = 0;
432
651
  // Every open is checked: a worker from another release must not be talked to.
@@ -434,19 +653,23 @@ export class RowsCacheEngine extends SqliteCacheEngine {
434
653
  transport.call = async <T>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> => {
435
654
  if (type === 'open') {
436
655
  // The prewarm's work stands only for the first open, of the store it
437
- // was started on, with nothing more asked of the worker (under a
438
- // role's lock other tabs write through this worker too).
656
+ // was started on. Under a role's lock too (a shared-tabs leader): the
657
+ // worker keeps the store it has open, and until a follower's port is
658
+ // handed to it (`exposeClientPort`) nobody else writes through it.
439
659
  const asked = payload as { dbName: string; useOpfs: boolean; workerLockName?: string; share?: boolean };
440
660
  // A leader whose followers read the file themselves opens it for sharing.
441
661
  if (asked.workerLockName && asked.useOpfs && this.config.followerReads === 'direct') {
442
662
  asked.share = true;
443
663
  }
444
- const mine = ahead !== null && opens++ === 0 && asked.useOpfs && asked.dbName === pre!.bucket && !asked.workerLockName;
664
+ const mine = ahead !== null && opens++ === 0 && asked.useOpfs && asked.dbName === pre!.bucket;
445
665
  const answered = pre?.opened as (OpenReply & { ok?: boolean }) | undefined;
446
666
  if (pre) pre.opened = undefined;
447
667
  if (!mine) forget();
448
- else if (answered?.persisted) {
668
+ else if (answered?.persisted && !asked.workerLockName && !this.shared) {
449
669
  // The worker answered this very open already: no need to ask again.
670
+ // Never with shared tabs: there the open is also what takes the
671
+ // role's lock, and what tells the worker that its store, which it
672
+ // would give up to another tab's leader, has an owner.
450
673
  this.opened(transport, asked, answered);
451
674
  return answered as T;
452
675
  }
@@ -495,7 +718,7 @@ export class RowsCacheEngine extends SqliteCacheEngine {
495
718
  this.paint?.start(bucketId);
496
719
  try {
497
720
  await super.connect(bucketId);
498
- this.beginStartupReads();
721
+ this.sessionBegan();
499
722
  } catch (error) {
500
723
  if (!this.adopted) throw error;
501
724
  this.adopted = false;
@@ -510,7 +733,7 @@ export class RowsCacheEngine extends SqliteCacheEngine {
510
733
  );
511
734
  await this.close();
512
735
  await super.connect(bucketId);
513
- this.beginStartupReads();
736
+ this.sessionBegan();
514
737
  }
515
738
  }
516
739
 
@@ -518,6 +741,19 @@ export class RowsCacheEngine extends SqliteCacheEngine {
518
741
  this.dropReader('bucket switch');
519
742
  await super.switchBucket(bucketId);
520
743
  this.paint?.start(bucketId);
744
+ this.sessionBegan();
745
+ }
746
+
747
+ /**
748
+ * The store is open. One that fell back to memory keeps no copies: its rows
749
+ * are gone with the tab, and it must not write over what a tab with the
750
+ * real store has kept.
751
+ */
752
+ private sessionBegan(): void {
753
+ if (this.useOpfs && this.storageHealth.status !== 'persistent') {
754
+ this.paint?.stop();
755
+ return;
756
+ }
521
757
  this.beginStartupReads();
522
758
  }
523
759
 
@@ -529,10 +765,12 @@ export class RowsCacheEngine extends SqliteCacheEngine {
529
765
  ): Promise<void> {
530
766
  takePrewarmed()?.worker.terminate();
531
767
  this.dropReader('attaching to a leader');
768
+ const durable = this.useOpfs && snapshot.storageHealth.status === 'persistent';
769
+ // Before the port is in use, as in `connect`: a peek needs no store.
770
+ if (durable) this.paint?.adopt(snapshot.bucketId);
532
771
  await super.adoptAttached(dbPort, snapshot, onPortDead);
533
- if (this.config.followerReads === 'direct' && this.useOpfs && snapshot.storageHealth.status === 'persistent') {
534
- await this.startReader(snapshot.bucketId);
535
- }
772
+ this.sessionBegan();
773
+ if (this.config.followerReads === 'direct' && durable) await this.startReader(snapshot.bucketId);
536
774
  }
537
775
 
538
776
  // ---- a follower's own reader ------------------------------------------------
@@ -604,9 +842,41 @@ export class RowsCacheEngine extends SqliteCacheEngine {
604
842
  .finally(() => clearTimeout(timer));
605
843
  }
606
844
 
845
+ /**
846
+ * A leader's store is this tab's own worker, as alone: one started ahead of
847
+ * the app is adopted (`createTransport`), and replaced when it turns out to
848
+ * be another release's.
849
+ */
607
850
  override async adoptOwner(...args: Parameters<SqliteCacheEngine['adoptOwner']>): ReturnType<SqliteCacheEngine['adoptOwner']> {
608
851
  this.dropReader('becoming the leader');
609
- return super.adoptOwner(...args);
852
+ this.paint?.adopt(args[0]);
853
+ let health: StorageHealth;
854
+ try {
855
+ health = await super.adoptOwner(...args);
856
+ } catch (error) {
857
+ // Only when the worker itself is the trouble: a lock or a file that
858
+ // cannot be had would fail a second worker the same way.
859
+ if (!this.adopted || !String(error).includes('worker protocol')) throw error;
860
+ this.adopted = false;
861
+ try {
862
+ localStorage.removeItem(ROWS_PREWARM_KEY);
863
+ } catch {
864
+ /* ignore */
865
+ }
866
+ this.logger.warn(
867
+ { error, Category: 'sp00ky-client::RowsCacheEngine::adoptOwner' },
868
+ 'Prewarmed row worker was unusable; starting a fresh one'
869
+ );
870
+ health = await super.adoptOwner(...args);
871
+ }
872
+ this.sessionBegan();
873
+ return health;
874
+ }
875
+
876
+ /** Another tab is about to write through this worker: what it read ahead of the app no longer stands. */
877
+ override async exposeClientPort(clientId: string, port: MessagePort): Promise<void> {
878
+ this.forgetAhead?.();
879
+ return super.exposeClientPort(clientId, port);
610
880
  }
611
881
 
612
882
  override async releaseOwnership(): Promise<void> {
@@ -638,11 +908,15 @@ export class RowsCacheEngine extends SqliteCacheEngine {
638
908
  private startupUntil = 0;
639
909
  private startupTimer: ReturnType<typeof setTimeout> | null = null;
640
910
  private startupHooked = false;
911
+ /** The bucket whose startup reads were last begun. */
912
+ private startupBucket: string | null = null;
641
913
 
642
914
  private beginStartupReads(): void {
643
- // Not with shared tabs: other tabs write through the leader's worker, and
644
- // an answer read ahead of them could be older than what they wrote.
645
- if (!this.useOpfs || this.shared || typeof localStorage === 'undefined') return;
915
+ if (!this.useOpfs || typeof localStorage === 'undefined') return;
916
+ // With shared tabs a tab is handed its store again with every change of
917
+ // role. Only the first time is a session's start.
918
+ if (this.shared && this.startupBucket === this.bucketId) return;
919
+ this.startupBucket = this.bucketId;
646
920
  if (!this.startupHooked && typeof addEventListener === 'function') {
647
921
  // localStorage is synchronous, so the list can still be saved as the page goes.
648
922
  addEventListener('pagehide', () => this.saveStartupReads());
@@ -681,7 +955,7 @@ export class RowsCacheEngine extends SqliteCacheEngine {
681
955
 
682
956
  /** A read that answers rows. `paint` names it for the paint cache, when it is worth keeping. */
683
957
  private async rows(type: string, payload: unknown, paint?: { key: string; tables: string[] }): Promise<Row[]> {
684
- const sentAt = paint && this.paint ? this.paint.stamp(paint.tables) : 0;
958
+ const sentAt = paint && this.paint ? this.paint.stamp(paint.tables) : '';
685
959
  const reply = await this.call<RowsReply>(type, payload);
686
960
  this.noteStartupRead(type, payload, reply.buf?.byteLength ?? 0);
687
961
  if (!reply.buf) return [];
@@ -718,9 +992,10 @@ export class RowsCacheEngine extends SqliteCacheEngine {
718
992
  /**
719
993
  * What `select(plan, params)` answered the last time the app asked at
720
994
  * startup, synchronously, or `null`. Available as soon as `connect` was
721
- * CALLED: it reads localStorage, not the store. Paint from it, then run the
722
- * real `select`, which is the answer; they differ only when something wrote
723
- * to these tables that this tab did not see.
995
+ * CALLED (or a role was handed over, or `expectBucket` said which bucket):
996
+ * it reads localStorage, not the store. Paint from it, then run the real
997
+ * `select`, which is the answer. A copy is not handed out once any tab has
998
+ * written to a table it read (see {@link PaintCache}).
724
999
  */
725
1000
  peekSelect(plan: QueryPlan, params: Record<string, unknown> = {}, opts?: { paintKey?: string }): Row[] | null {
726
1001
  if (!this.paint) return null;
@@ -729,12 +1004,9 @@ export class RowsCacheEngine extends SqliteCacheEngine {
729
1004
  return this.paint.get(this.selectKey(payload, opts), fromBase64);
730
1005
  }
731
1006
 
732
- /**
733
- * See `LocalStore.expectBucket`. Not with shared tabs: the paint cache is
734
- * not kept there (other tabs write to the store unseen by this one).
735
- */
1007
+ /** See `LocalStore.expectBucket`. */
736
1008
  expectBucket(bucketId: string): void {
737
- if (!this.shared) this.paint?.expect(bucketId);
1009
+ this.paint?.expect(bucketId);
738
1010
  }
739
1011
 
740
1012
  /** {@link peekSelect} for `selectByIds`. */
@@ -790,7 +1062,11 @@ export class RowsCacheEngine extends SqliteCacheEngine {
790
1062
  const plan = planColumnReset(stored, fingerprints, new Set(tables), keep);
791
1063
  if (plan.statements.length === 0) return plan.changed;
792
1064
  this.paint?.touch(plan.changed);
793
- if (plan.changed.length > 0) await this.call('reset-versions', { tables: plan.changed, keep: [...keep] });
1065
+ try {
1066
+ if (plan.changed.length > 0) await this.call('reset-versions', { tables: plan.changed, keep: [...keep] });
1067
+ } finally {
1068
+ this.paint?.touch(plan.changed, true);
1069
+ }
794
1070
  // Recorded last: a tab that dies between the two redoes the reset, which is harmless.
795
1071
  const body = encoder.encode(JSON.stringify(fingerprints));
796
1072
  const buf = body.buffer as ArrayBuffer;
@@ -839,8 +1115,14 @@ export class RowsCacheEngine extends SqliteCacheEngine {
839
1115
  private async write(items: WriteItem[]): Promise<void> {
840
1116
  const { wire, buf, sync } = packWrites(items);
841
1117
  if (wire.length === 0) return;
842
- this.paint?.touch(new Set(items.map((item) => item.table)));
843
- await this.call('write', { ops: wire, buf, sync }, buf ? [buf] : undefined);
1118
+ const tables = new Set(items.map((item) => item.table));
1119
+ this.paint?.touch(tables);
1120
+ try {
1121
+ await this.call('write', { ops: wire, buf, sync }, buf ? [buf] : undefined);
1122
+ } finally {
1123
+ // Whether or not it was taken: other tabs are told once more, now that it is over.
1124
+ this.paint?.touch(tables, true);
1125
+ }
844
1126
  }
845
1127
 
846
1128
  protected override runWriteBatch(ops: SqlOp[]): Promise<void> {