@opendatalabs/personal-server-ts-core 1.43.1 → 1.43.3

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 (89) hide show
  1. package/dist/additions/version-inventory.d.ts +1 -1
  2. package/dist/additions/version-inventory.d.ts.map +1 -1
  3. package/dist/additions/version-inventory.js +2 -2
  4. package/dist/additions/version-inventory.js.map +1 -1
  5. package/dist/api/owner-connector-delete.d.ts +20 -2
  6. package/dist/api/owner-connector-delete.d.ts.map +1 -1
  7. package/dist/api/owner-connector-delete.js +18 -6
  8. package/dist/api/owner-connector-delete.js.map +1 -1
  9. package/dist/api/scope-uploads.d.ts.map +1 -1
  10. package/dist/api/scope-uploads.js +9 -0
  11. package/dist/api/scope-uploads.js.map +1 -1
  12. package/dist/localdb/cycle.d.ts +7 -4
  13. package/dist/localdb/cycle.d.ts.map +1 -1
  14. package/dist/localdb/cycle.js +51 -31
  15. package/dist/localdb/cycle.js.map +1 -1
  16. package/dist/localdb/delete-status.d.ts +53 -0
  17. package/dist/localdb/delete-status.d.ts.map +1 -0
  18. package/dist/localdb/delete-status.js +19 -0
  19. package/dist/localdb/delete-status.js.map +1 -0
  20. package/dist/localdb/delete.d.ts +72 -6
  21. package/dist/localdb/delete.d.ts.map +1 -1
  22. package/dist/localdb/delete.js +595 -62
  23. package/dist/localdb/delete.js.map +1 -1
  24. package/dist/localdb/index.d.ts +2 -0
  25. package/dist/localdb/index.d.ts.map +1 -1
  26. package/dist/localdb/index.js +1 -0
  27. package/dist/localdb/index.js.map +1 -1
  28. package/dist/localdb/legacy-delete.d.ts +89 -0
  29. package/dist/localdb/legacy-delete.d.ts.map +1 -0
  30. package/dist/localdb/legacy-delete.js +279 -0
  31. package/dist/localdb/legacy-delete.js.map +1 -0
  32. package/dist/localdb/log-erase.d.ts +55 -4
  33. package/dist/localdb/log-erase.d.ts.map +1 -1
  34. package/dist/localdb/log-erase.js +76 -8
  35. package/dist/localdb/log-erase.js.map +1 -1
  36. package/dist/localdb/purge.d.ts +42 -9
  37. package/dist/localdb/purge.d.ts.map +1 -1
  38. package/dist/localdb/purge.js +38 -4
  39. package/dist/localdb/purge.js.map +1 -1
  40. package/dist/localdb/schema.d.ts.map +1 -1
  41. package/dist/localdb/schema.js +39 -0
  42. package/dist/localdb/schema.js.map +1 -1
  43. package/dist/localdb/sync.d.ts +8 -0
  44. package/dist/localdb/sync.d.ts.map +1 -1
  45. package/dist/localdb/sync.js +163 -41
  46. package/dist/localdb/sync.js.map +1 -1
  47. package/dist/policy/data-read.d.ts.map +1 -1
  48. package/dist/policy/data-read.js +3 -0
  49. package/dist/policy/data-read.js.map +1 -1
  50. package/dist/replication/host-driver.d.ts.map +1 -1
  51. package/dist/replication/host-driver.js +2 -1
  52. package/dist/replication/host-driver.js.map +1 -1
  53. package/dist/storage/adapters/rate-limit-policy.js +1 -1
  54. package/dist/storage/adapters/rate-limit-policy.js.map +1 -1
  55. package/dist/stream-sync/registry.d.ts.map +1 -1
  56. package/dist/stream-sync/registry.js +25 -0
  57. package/dist/stream-sync/registry.js.map +1 -1
  58. package/dist/sync/delete-data-port.d.ts +10 -0
  59. package/dist/sync/delete-data-port.d.ts.map +1 -1
  60. package/dist/sync/delete-data-port.js +118 -48
  61. package/dist/sync/delete-data-port.js.map +1 -1
  62. package/dist/sync/engine/sync-manager.d.ts +7 -2
  63. package/dist/sync/engine/sync-manager.d.ts.map +1 -1
  64. package/dist/sync/engine/sync-manager.js +6 -3
  65. package/dist/sync/engine/sync-manager.js.map +1 -1
  66. package/dist/sync/gateway-refusal.d.ts +36 -0
  67. package/dist/sync/gateway-refusal.d.ts.map +1 -0
  68. package/dist/sync/gateway-refusal.js +45 -0
  69. package/dist/sync/gateway-refusal.js.map +1 -0
  70. package/dist/sync/tombstone-resubmits.d.ts +3 -1
  71. package/dist/sync/tombstone-resubmits.d.ts.map +1 -1
  72. package/dist/sync/tombstone-resubmits.js.map +1 -1
  73. package/dist/sync/workers/delete.d.ts +6 -0
  74. package/dist/sync/workers/delete.d.ts.map +1 -1
  75. package/dist/sync/workers/delete.js +29 -30
  76. package/dist/sync/workers/delete.js.map +1 -1
  77. package/dist/test-support/memory-oracle.d.ts.map +1 -1
  78. package/dist/test-support/memory-oracle.js +4 -1
  79. package/dist/test-support/memory-oracle.js.map +1 -1
  80. package/dist/test-utils/legacy-delete-ports.d.ts +24 -0
  81. package/dist/test-utils/legacy-delete-ports.d.ts.map +1 -0
  82. package/dist/test-utils/legacy-delete-ports.js +91 -0
  83. package/dist/test-utils/legacy-delete-ports.js.map +1 -0
  84. package/dist/test-utils/legacy-gateway-fake.d.ts +88 -0
  85. package/dist/test-utils/legacy-gateway-fake.d.ts.map +1 -0
  86. package/dist/test-utils/legacy-gateway-fake.js +243 -0
  87. package/dist/test-utils/legacy-gateway-fake.js.map +1 -0
  88. package/dist-test/tsconfig.tsbuildinfo +1 -1
  89. package/package.json +2 -2
@@ -15,9 +15,68 @@ import { keccakOf } from "../stream-sync/crypto-port.js";
15
15
  import { classifyControl, controlHashes, controlScope, deriveKeyCheck, parseScope, } from "@opendatalabs/personal-server-ts-stream-sync";
16
16
  import { RegistryRefusedError } from "../stream-sync/ports.js";
17
17
  import { commitFences } from "./delete-batch.js";
18
- import { purgeConnection } from "./purge.js";
18
+ import { blocked, PART_DONE, PART_PENDING, } from "./delete-status.js";
19
+ import { retireLegacyOf } from "./legacy-delete.js";
20
+ import { KEEP_TOMBSTONE_CONFLICT, purgeConnection } from "./purge.js";
19
21
  import { ConnectionLifetimeChanged, formatLifetime, holdsLifetime, parseLifetime, } from "./delete-lifetime.js";
20
22
  export { ConnectionLifetimeChanged, InvalidConnectionLifetime, } from "./delete-lifetime.js";
23
+ /**
24
+ * The storage part of a delete from one erasure report. `done` only on this
25
+ * device's own evidence that every object of the deleted lifetime is gone: a
26
+ * complete enumeration it made before erasing, and every delete acknowledged,
27
+ * with no body piece left. Every other path says what stands in the way, and
28
+ * a tombstone the report never mentions is not judged yet.
29
+ */
30
+ function storagePartOf(report, tombstones) {
31
+ if (report.unavailable)
32
+ return blocked("needs_another_device");
33
+ // A scan that could not list the deleted connections (`pending` with no
34
+ // connection to show for it) has judged nothing: it is not "all erased".
35
+ let part = report.pending ? PART_PENDING : PART_DONE;
36
+ const worse = (next) => {
37
+ if (rankOf(next) > rankOf(part))
38
+ part = next;
39
+ };
40
+ // A namespace a local connection holds (a reconnect, or another lifetime)
41
+ // shares its log scope with the deleted one: nothing of it is erased, and
42
+ // nothing shows it gone. The report lists these, and they are final until a
43
+ // newer delete of the namespace.
44
+ for (const ns of report.skipped)
45
+ if (tombstones.has(ns))
46
+ worse(blocked("re_added"));
47
+ // A namespace whose delete this device confirmed is either judged or listed
48
+ // as skipped. One the report names neither way is not judged yet.
49
+ const named = new Set([
50
+ ...report.connections.map((c) => c.ns),
51
+ ...report.skipped,
52
+ ]);
53
+ for (const ns of tombstones.keys())
54
+ if (!named.has(ns))
55
+ worse(PART_PENDING);
56
+ for (const { outcome } of report.connections)
57
+ worse(outcome.kind === "pending"
58
+ ? PART_PENDING
59
+ : outcome.kind === "stopped"
60
+ ? outcome.why === "rolled-back"
61
+ ? blocked("tombstone_rolled_back")
62
+ : outcome.why === "head-unreadable"
63
+ ? blocked("log_unreadable")
64
+ : // A reconnect replaced the lifetime: its objects share the
65
+ // log scope with the new one and are not deleted.
66
+ blocked("re_added")
67
+ : outcome.retained > 0
68
+ ? blocked("body_pieces_retained")
69
+ : outcome.witnessed
70
+ ? PART_DONE
71
+ : blocked("erased_elsewhere"));
72
+ return part;
73
+ }
74
+ const rankOf = (p) => p.state === "blocked" ? 2 : p.state === "pending" ? 1 : 0;
75
+ const KEEP_TOMBSTONE_SQL = `INSERT INTO delete_tombstones(connector, ns, version) VALUES (?, ?, ?)
76
+ ${KEEP_TOMBSTONE_CONFLICT}`;
77
+ const BOTH = { legacy: true, storage: true };
78
+ const NONE = { legacy: false, storage: false };
79
+ const isRolledBack = (o) => o.kind === "stopped" && o.why === "rolled-back";
21
80
  export class ConnectionStoppedError extends Error {
22
81
  connector;
23
82
  constructor(connector) {
@@ -94,10 +153,108 @@ export function createConnectionDeleter(originalDeps, options = {}) {
94
153
  const requests = new Set();
95
154
  /** Erasures running, by connector: one at a time per connector. */
96
155
  const erasures = new Map();
97
- /** Connectors whose erasure ended `pending`, until a later pass finishes it. */
98
- const erasing = new Set();
156
+ /**
157
+ * Connectors whose erasure is owed, with the stages a later pass must run:
158
+ * fresh news (a delete settled) owes both, an unfinished pass owes only the
159
+ * stage that can still make progress. What a part shows is a separate fact
160
+ * (`judged`): a stage that ended `blocked` is not owed again.
161
+ *
162
+ * A part that reads `pending` always has a pass owed behind it: here while
163
+ * the process runs, and after a restart in the start sweep, which reads the
164
+ * tombstone rows with no verdict (`done_at`).
165
+ */
166
+ const erasing = new Map();
167
+ const owe = (connector, which = BOTH) => {
168
+ const held = erasing.get(connector);
169
+ erasing.set(connector, {
170
+ legacy: which.legacy || !!held?.legacy,
171
+ storage: which.storage || !!held?.storage,
172
+ });
173
+ };
174
+ /** What the legacy stage keeps between this device's passes (`LegacyMemory`). */
175
+ const refusals = new Map();
176
+ const erasedSlots = new Map();
99
177
  /** The start sweep (deletes settled before this process) is still owed. */
100
- let sweepOwed = options.eraseLogs !== undefined;
178
+ const owesErasure = options.eraseLogs !== undefined || !!options.legacy;
179
+ let sweepOwed = owesErasure;
180
+ /**
181
+ * What the last pass here judged of each connector's delete. Dropped when a
182
+ * newer delete's tombstone is learned (`learnTombstone`): the pass that
183
+ * follows judges it again.
184
+ */
185
+ const judged = new Map();
186
+ /**
187
+ * The delete a connector's cached verdict belongs to: the control tombstone
188
+ * each namespace's delete confirmed, by registry version. A tombstone moves
189
+ * only forward, so a higher one is a newer delete. The stages judge against
190
+ * these tombstones (`LegacyMemory.tombstones`), and so does the cache: a
191
+ * verdict is kept only under the tombstones it was judged for. One notion of
192
+ * "this delete" drives both.
193
+ */
194
+ const tombstones = new Map();
195
+ /** A copy: a pass judges the tombstones it started with, whatever is learned meanwhile. */
196
+ const tombstonesOf = (connector) => new Map(tombstones.get(connector));
197
+ const deleteKey = (connector) => [...tombstonesOf(connector)]
198
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
199
+ .map(([ns, version]) => `${ns}@${version}`)
200
+ .join(",");
201
+ /**
202
+ * A delete confirmed this tombstone: a higher one than known is a newer
203
+ * delete, and answers true. The same one again is news of nothing.
204
+ */
205
+ function learnTombstone(connector, ns, version) {
206
+ const held = tombstones.get(connector) ?? new Map();
207
+ if ((held.get(ns) ?? 0) >= version)
208
+ return false;
209
+ held.set(ns, version);
210
+ tombstones.set(connector, held);
211
+ // What an earlier pass judged, and what the gateway refused, say nothing
212
+ // of a newer delete: this is the only place either is dropped.
213
+ judged.delete(connector);
214
+ refusals.delete(connector);
215
+ return true;
216
+ }
217
+ /**
218
+ * The tombstones the local database holds (`delete_tombstones`), learned
219
+ * once before the first pass: what a restart finds of the deletes this
220
+ * device confirmed. Written by the transactions that learn them (a fence
221
+ * landing, a purge), so a restart never has to read the control head to
222
+ * tell which delete it is erasing.
223
+ */
224
+ const loadTombstones = async () => {
225
+ const rows = await deps.db.query("SELECT connector, ns, version FROM delete_tombstones");
226
+ for (const row of rows)
227
+ learnTombstone(row.connector, row.ns, Number(row.version));
228
+ };
229
+ let hydration = null;
230
+ const hydrated = () => (hydration ??= loadTombstones().catch((error) => {
231
+ hydration = null;
232
+ throw error;
233
+ }));
234
+ /**
235
+ * The delete's three parts are all done: its verdict is final. It is kept
236
+ * with the delete's identity (`done_at` on the tombstone rows, at the
237
+ * versions this pass judged), so a restart reads it back and a newer
238
+ * delete's tombstone, written meanwhile, is left without one.
239
+ */
240
+ async function recordVerdict(connector, status) {
241
+ if (stop.signal.aborted ||
242
+ erasing.has(connector) ||
243
+ flights.has(connector) ||
244
+ ![status.fence, status.legacy, status.storage].every((part) => part.state === "done"))
245
+ return;
246
+ const held = tombstonesOf(connector);
247
+ if (held.size === 0)
248
+ return;
249
+ await deps.db.batch([...held].map(([ns, version]) => ({
250
+ sql: "UPDATE delete_tombstones SET done_at = CAST(strftime('%s','now') AS INTEGER) * 1000 WHERE connector=? AND ns=? AND version=? AND done_at IS NULL",
251
+ params: [connector, ns, version],
252
+ })));
253
+ }
254
+ /** The durable rows of a connector's delete: its identity and whether it finished. */
255
+ const rowsOf = (connector) => deps.db.query("SELECT ns, version, done_at FROM delete_tombstones WHERE connector=?", [connector]);
256
+ /** Every row says the delete finished: all three parts were done at these versions. */
257
+ const finishedIn = (rows) => rows.length > 0 && rows.every((row) => row.done_at !== null);
101
258
  /**
102
259
  * The control rows the plan listed, by delete id, then by scope. Only a
103
260
  * delete this process just planned has one; the landing takes it. Each
@@ -127,11 +284,17 @@ export function createConnectionDeleter(originalDeps, options = {}) {
127
284
  id: row.delete_id,
128
285
  };
129
286
  };
287
+ // Each fence the intent holds is a tombstone the delete confirmed: written
288
+ // in the transaction that records the fence, so the two never part.
130
289
  const save = (connector, intent) => deps.db.batch([
131
290
  {
132
291
  sql: "INSERT OR REPLACE INTO delete_intents(connector,delete_id,intent) VALUES (?,?,?)",
133
292
  params: [connector, intent.id, JSON.stringify(intent)],
134
293
  },
294
+ ...(intent.fences ?? []).map((fence) => ({
295
+ sql: KEEP_TOMBSTONE_SQL,
296
+ params: [connector, fence.ns, fence.version],
297
+ })),
135
298
  ]);
136
299
  const clear = (connector, id) => deps.db.batch([
137
300
  {
@@ -139,6 +302,90 @@ export function createConnectionDeleter(originalDeps, options = {}) {
139
302
  params: [connector, id],
140
303
  },
141
304
  ]);
305
+ /** The connector's control rows in a listing, each read as the control head it is. */
306
+ function* controlRowsOf(connector, entries, hashes) {
307
+ for (const entry of entries) {
308
+ const parsed = parseScope(entry.scope);
309
+ if (parsed?.kind !== "control" || parsed.connector !== connector)
310
+ continue;
311
+ yield {
312
+ entry,
313
+ ns: parsed.ns,
314
+ current: classifyControl(entry.read, hashes),
315
+ };
316
+ }
317
+ }
318
+ /**
319
+ * The one comparison between a delete's verdict and the newest tombstone
320
+ * this device can see. `ended` is what a registry listing shows of the
321
+ * connector: a tombstone above the one held for its namespace is a newer
322
+ * delete. It is written down (the same statement as a landed fence, which
323
+ * clears the connector's verdicts), learned, and owed to both stages. Every
324
+ * path that reads a verdict (a status, a request, an erasure pass, the
325
+ * start sweep) calls this first, so none can answer for a delete the
326
+ * registry has already moved past. A connector with no delete known here
327
+ * is not this device's to adopt: a sync of the control row does that, and
328
+ * names the tombstone. For a connector with a delete on record, a tombstone
329
+ * in any namespace counts, one this device holds no row or connection for
330
+ * too: the connector's delete is what the verdict speaks for, and the
331
+ * erasure pass judges every deleted namespace the registry lists.
332
+ */
333
+ async function adoptEnded(connector, ended, options = {}) {
334
+ if (ended.size === 0)
335
+ return false;
336
+ await hydrated();
337
+ const held = tombstones.get(connector);
338
+ if (!held)
339
+ return false;
340
+ const newer = [...ended].filter(([ns, version]) => version > (held.get(ns) ?? 0));
341
+ if (newer.length === 0)
342
+ return false;
343
+ await deps.db.batch([
344
+ ...newer.map(([ns, version]) => ({
345
+ sql: KEEP_TOMBSTONE_SQL,
346
+ params: [connector, ns, version],
347
+ })),
348
+ {
349
+ sql: "UPDATE delete_tombstones SET done_at = NULL WHERE connector=?",
350
+ params: [connector],
351
+ },
352
+ ]);
353
+ for (const [ns, version] of newer)
354
+ learnTombstone(connector, ns, version);
355
+ if (owesErasure && options.owe !== false)
356
+ owe(connector);
357
+ return true;
358
+ }
359
+ /**
360
+ * `adoptEnded` for connectors whose delete is known here, from one fresh
361
+ * listing. A registry that cannot be listed leaves what is known standing:
362
+ * the newest tombstone this device can see is the one it already holds.
363
+ */
364
+ async function refreshTombstones(connectors, options = {}) {
365
+ const newer = new Set();
366
+ try {
367
+ await hydrated();
368
+ const known = [...connectors].filter((c) => tombstones.has(c));
369
+ if (known.length === 0)
370
+ return newer;
371
+ const [hashes, entries] = await Promise.all([
372
+ hashesOf(),
373
+ deps.registry.listControlRows(),
374
+ ]);
375
+ for (const connector of known) {
376
+ const ended = new Map();
377
+ for (const { ns, current } of controlRowsOf(connector, entries, hashes))
378
+ if (current.kind === "deleted")
379
+ ended.set(ns, current.version);
380
+ if (await adoptEnded(connector, ended, options))
381
+ newer.add(connector);
382
+ }
383
+ }
384
+ catch (error) {
385
+ deps.logger.warn({ error: error instanceof Error ? error.message : String(error) }, "stream sync: the registry's newest delete tombstones could not be read");
386
+ }
387
+ return newer;
388
+ }
142
389
  /**
143
390
  * The pins, from one listing of the control rows. A listing is as fresh as a
144
391
  * read of the row, and taken after this call; the row may still move before
@@ -159,22 +406,21 @@ export function createConnectionDeleter(originalDeps, options = {}) {
159
406
  const listing = new Map();
160
407
  // The control rows already tombstoned, by namespace: the end of a lifetime.
161
408
  const ended = new Map();
162
- for (const entry of entries) {
163
- const parsed = parseScope(entry.scope);
164
- if (parsed?.kind !== "control" || parsed.connector !== connector)
165
- continue;
166
- const current = classifyControl(entry.read, hashes);
409
+ for (const { entry, ns, current } of controlRowsOf(connector, entries, hashes)) {
167
410
  listing.set(entry.scope, { ...entry.read });
168
411
  if (current.kind === "deleted")
169
- ended.set(parsed.ns, current.version);
412
+ ended.set(ns, current.version);
170
413
  // A control row of another key ends the same way: its tombstone is the
171
414
  // same for every key.
172
415
  if (current.kind === "active" || current.kind === "foreign")
173
416
  pins.push({
174
- ns: parsed.ns,
417
+ ns,
175
418
  version: current.kind === "active" ? current.generation : current.version,
176
419
  });
177
420
  }
421
+ // A listing is the newest word on the delete: a tombstone newer than the
422
+ // one held ends the verdict held, whoever asked.
423
+ await adoptEnded(connector, ended);
178
424
  return { intent: { id: deps.newOp(), pins }, listing, ended };
179
425
  }
180
426
  async function readConnectionLifetime(connector) {
@@ -210,7 +456,9 @@ export function createConnectionDeleter(originalDeps, options = {}) {
210
456
  const rows = await deps.db.query("SELECT ns FROM connections WHERE connector=?", [connector]);
211
457
  return rows.some((row) => !intent.pins.some((p) => p.ns === row.ns));
212
458
  }
213
- async function purgeLocal(connector, intent, held = new Set()) {
459
+ async function purgeLocal(connector, intent, held = new Set(),
460
+ /** The tombstones the registry listing showed, by namespace. */
461
+ ended = new Map()) {
214
462
  const connections = await deps.db.query("SELECT connection_id,ns,generation,control_version FROM connections WHERE connector=?", [connector]);
215
463
  for (const connection of connections) {
216
464
  const pin = intent.pins.find((p) => p.ns === connection.ns);
@@ -234,9 +482,24 @@ export function createConnectionDeleter(originalDeps, options = {}) {
234
482
  : deps.queue.run(id, kind, work),
235
483
  },
236
484
  };
237
- await purgeConnection(nested, connection.connection_id, {
238
- controlVersion: pin ? pin.version + 1 : connection.control_version,
239
- });
485
+ // The purge may run ahead of its fence. Only a tombstone the delete
486
+ // confirmed is the delete's identity: a fence that landed, or one the
487
+ // registry listing shows. A version this purge expects, or the 0 of
488
+ // a connection no row names, is not written to the ledger.
489
+ const landed = pin
490
+ ? (intent.fences ?? []).find((f) => f.ns === pin.ns)?.version
491
+ : undefined;
492
+ const listed = ended.get(connection.ns);
493
+ await purgeConnection(nested, connection.connection_id, landed !== undefined
494
+ ? { controlVersion: landed }
495
+ : listed !== undefined && !pin
496
+ ? { controlVersion: listed }
497
+ : {
498
+ controlVersion: pin
499
+ ? pin.version + 1
500
+ : connection.control_version,
501
+ confirmed: false,
502
+ });
240
503
  await deps.db.batch([
241
504
  {
242
505
  sql: "UPDATE run_streams SET decision='discarded',reason='control_deleted',replace=0 WHERE run_id IN (SELECT run_id FROM runs WHERE connection_id=?)",
@@ -347,6 +610,8 @@ export function createConnectionDeleter(originalDeps, options = {}) {
347
610
  { ns: pin.ns, version: pin.version + 1 },
348
611
  ],
349
612
  }));
613
+ // The tombstone this delete confirmed: it is this delete's identity.
614
+ const confirmed = (pin) => learnTombstone(connector, pin.ns, pin.version + 1);
350
615
  try {
351
616
  const unfenced = intent.pins.filter((p) => !fenced(p.ns));
352
617
  if (unfenced.length > 0) {
@@ -373,8 +638,10 @@ export function createConnectionDeleter(originalDeps, options = {}) {
373
638
  rows,
374
639
  });
375
640
  for (const [i, pin] of unfenced.entries())
376
- if (turns[i] === "committed")
641
+ if (turns[i] === "committed") {
377
642
  await recordFence(pin);
643
+ confirmed(pin);
644
+ }
378
645
  }
379
646
  // The per-row pass: each fence the request did not store.
380
647
  await settleAll(intent.pins
@@ -382,6 +649,7 @@ export function createConnectionDeleter(originalDeps, options = {}) {
382
649
  .map(async (pin) => {
383
650
  await landFence(connector, pin, hashes);
384
651
  await recordFence(pin);
652
+ confirmed(pin);
385
653
  }));
386
654
  fencesEnded(true);
387
655
  await saved;
@@ -400,32 +668,112 @@ export function createConnectionDeleter(originalDeps, options = {}) {
400
668
  }
401
669
  /**
402
670
  * The namespaces of `connector` whose delete has not settled here: a local
403
- * connection in them is not purged (a connection added again, or one the
404
- * purge has not reached, is another lifetime). `null` while a delete of the
405
- * connector is in flight: nothing of it is settled. One namespace's live
406
- * connection never holds back another's erasure: a delete that names a
407
- * lifetime leaves a local connection no pin names, by design.
671
+ * connection in them is not purged and is not one the delete ended (a
672
+ * connection added again, or one registered after the tombstone, is another
673
+ * lifetime). `null` while a delete of the connector is in flight: nothing of
674
+ * it is settled. One namespace's live connection never holds back another's
675
+ * erasure: a delete that names a lifetime leaves a local connection no pin
676
+ * names, by design.
677
+ *
678
+ * A connection still `active` at a generation the held tombstone ended is
679
+ * stale, not a re-add: its purge is only waiting for the next sync of the
680
+ * control row (a status read or the start sweep can learn the tombstone
681
+ * first). A reconnect registers a higher generation, and one that never
682
+ * registered has no generation to compare: both still hold the namespace.
408
683
  */
409
684
  async function unsettledNamespaces(connector) {
410
685
  const [intent] = await deps.db.query("SELECT 1 FROM delete_intents WHERE connector=?", [connector]);
411
686
  if (intent)
412
687
  return null;
413
- const live = await deps.db.query("SELECT DISTINCT ns FROM connections WHERE connector=? AND control_state<>'deleted'", [connector]);
414
- return new Set(live.map((row) => row.ns));
688
+ const live = await deps.db.query("SELECT ns, control_state, generation FROM connections WHERE connector=? AND control_state<>'deleted'", [connector]);
689
+ const held = tombstonesOf(connector);
690
+ return new Set(live
691
+ .filter((row) => !(row.control_state === "active" &&
692
+ Number(row.generation) <= (held.get(row.ns) ?? 0)))
693
+ .map((row) => row.ns));
415
694
  }
416
695
  /**
417
696
  * One erasure pass for `connector`; answers whether it is unfinished. The
418
697
  * caller has consumed the connector's queue entry: what is queued after
419
698
  * that is news from while the pass runs, and this does not touch it.
420
699
  */
421
- async function eraseSettled(connector) {
700
+ async function eraseSettled(connector, owed) {
422
701
  try {
702
+ // What this device confirmed of the delete, before a restart too.
703
+ await hydrated();
423
704
  if (stop.signal.aborted)
424
- return false;
705
+ return NONE;
706
+ }
707
+ catch (error) {
708
+ deps.logger.warn({
709
+ connector,
710
+ error: error instanceof Error ? error.message : String(error),
711
+ }, "stream sync: the confirmed delete tombstones could not be read");
712
+ return owed;
713
+ }
714
+ // The newest tombstone the registry shows, before anything is judged by
715
+ // the one held: a newer delete is judged whole by this pass.
716
+ if ((await refreshTombstones([connector], { owe: false })).size > 0)
717
+ owed = BOTH;
718
+ const held = tombstonesOf(connector);
719
+ const key = deleteKey(connector);
720
+ const judge = (part) => judgeFor(connector, key, part);
721
+ try {
722
+ // A delete whose verdict is final has nothing left to judge: the same
723
+ // tombstone read again (a sync cycle, a restart) changes nothing.
724
+ if (finishedIn(await rowsOf(connector)))
725
+ return NONE;
425
726
  const skipNamespaces = await unsettledNamespaces(connector);
426
727
  if (skipNamespaces === null)
427
- return false;
428
- return (await options.eraseLogs(connector, stop.signal, { skipNamespaces })).pending;
728
+ return NONE;
729
+ // The legacy copy first: it needs no log port, so a device that cannot
730
+ // erase storage still retires it. A stage that is not owed keeps what
731
+ // its last pass judged and sends nothing.
732
+ let left = NONE;
733
+ if (options.legacy && owed.legacy) {
734
+ const legacy = options.legacy();
735
+ if (!legacy) {
736
+ judge({ legacy: blocked("needs_another_device") });
737
+ }
738
+ else {
739
+ let refused = refusals.get(connector);
740
+ if (!refused)
741
+ refusals.set(connector, (refused = new Map()));
742
+ const outcome = await retireLegacyOf({
743
+ ...deps,
744
+ memory: {
745
+ refused,
746
+ erased: erasedSlots,
747
+ tombstones: held,
748
+ },
749
+ }, legacy, connector, stop.signal);
750
+ judge({
751
+ legacy: outcome.part,
752
+ ...(outcome.rolledBack && { rolledBack: true }),
753
+ });
754
+ // Retry is decided by the part as well as by the stage's own flag:
755
+ // a part that reads pending always has a pass queued behind it.
756
+ left = {
757
+ ...left,
758
+ legacy: outcome.pending || outcome.part.state === "pending",
759
+ };
760
+ }
761
+ }
762
+ if (!options.eraseLogs || !owed.storage)
763
+ return left;
764
+ const report = await options.eraseLogs(connector, stop.signal, {
765
+ skipNamespaces,
766
+ tombstones: held,
767
+ });
768
+ const storage = storagePartOf(report, held);
769
+ judge({ storage });
770
+ if (report.connections.some((c) => isRolledBack(c.outcome)))
771
+ judge({ rolledBack: true });
772
+ // The same report drives the part and the retry.
773
+ return {
774
+ ...left,
775
+ storage: report.pending || storage.state === "pending",
776
+ };
429
777
  }
430
778
  catch (error) {
431
779
  // The eraser reports a failure as pending; this is its own bug or a
@@ -434,9 +782,39 @@ export function createConnectionDeleter(originalDeps, options = {}) {
434
782
  connector,
435
783
  error: error instanceof Error ? error.message : String(error),
436
784
  }, "stream sync: connection log erasure failed");
437
- return true;
785
+ return owed;
438
786
  }
439
787
  }
788
+ /**
789
+ * The stages of the delete known now that no pass has given a verdict a
790
+ * later pass cannot change: not judged yet, still pending, or waiting for
791
+ * a device that can (`needs_another_device`).
792
+ */
793
+ function unfinishedStages(connector) {
794
+ const seen = judged.get(connector);
795
+ const open = (part) => part === undefined ||
796
+ part.state === "pending" ||
797
+ (part.state === "blocked" && part.reason === "needs_another_device");
798
+ return { legacy: open(seen?.legacy), storage: open(seen?.storage) };
799
+ }
800
+ /**
801
+ * Forget a storage verdict of `blocked(re_added)`: it says a local
802
+ * connection held a namespace, and one was purged since.
803
+ */
804
+ function releaseReAdded(connector) {
805
+ const seen = judged.get(connector);
806
+ const storage = seen?.storage;
807
+ if (storage?.state !== "blocked" || storage.reason !== "re_added")
808
+ return;
809
+ const { storage: _released, ...rest } = seen;
810
+ judged.set(connector, rest);
811
+ }
812
+ /** Keeps a verdict only if the delete it judged is still the connector's newest. */
813
+ function judgeFor(connector, key, part) {
814
+ if (key !== deleteKey(connector))
815
+ return;
816
+ judged.set(connector, { ...judged.get(connector), ...part });
817
+ }
440
818
  /**
441
819
  * One erasure at a time per connector. A caller while one runs queues the
442
820
  * connector again, since what it knows (a delete settled) may be newer than
@@ -445,29 +823,92 @@ export function createConnectionDeleter(originalDeps, options = {}) {
445
823
  * entry the pass itself leaves (`pending`) waits for the retry loop.
446
824
  */
447
825
  function eraseLogsOf(connector) {
448
- if (!options.eraseLogs)
826
+ if (!owesErasure)
449
827
  return Promise.resolve();
450
828
  const held = erasures.get(connector);
451
829
  if (held) {
452
- erasing.add(connector);
830
+ owe(connector);
453
831
  return held;
454
832
  }
455
833
  const run = (async () => {
456
834
  let again;
457
835
  do {
836
+ const owed = erasing.get(connector) ?? BOTH;
458
837
  erasing.delete(connector);
459
- const unfinished = await eraseSettled(connector);
838
+ let unfinished;
839
+ try {
840
+ unfinished = await eraseSettled(connector, owed);
841
+ }
842
+ catch (error) {
843
+ // The entry was taken when the pass started: a pass that threw has
844
+ // not finished it, so it is owed again.
845
+ owe(connector, owed);
846
+ throw error;
847
+ }
460
848
  again = erasing.has(connector) && !stop.signal.aborted;
461
- if (unfinished)
462
- erasing.add(connector);
849
+ if (unfinished.legacy || unfinished.storage)
850
+ owe(connector, unfinished);
463
851
  } while (again);
852
+ // Settled for good: the delete's tombstones are not needed any more.
853
+ try {
854
+ await recordVerdict(connector, await deleteStatus(connector));
855
+ }
856
+ catch (error) {
857
+ deps.logger.warn({
858
+ connector,
859
+ error: error instanceof Error ? error.message : String(error),
860
+ }, "stream sync: the settled delete's verdict could not be recorded");
861
+ }
464
862
  })().finally(() => {
465
863
  if (erasures.get(connector) === run)
466
864
  erasures.delete(connector);
865
+ // The run is over: its verdict is read and the connector is no longer in
866
+ // flight, so a retry that looks now finds any work left owed queued.
867
+ options.onRetryStateChange?.();
868
+ if (erasing.has(connector))
869
+ options.onUnfinished?.();
467
870
  });
468
871
  erasures.set(connector, run);
872
+ // Handled where it is made: a caller that drops the run (`void`) or reads
873
+ // it later must not leave a rejection unhandled. A caller that awaits the
874
+ // run still sees it reject.
875
+ run.catch(() => undefined);
469
876
  return run;
470
877
  }
878
+ /**
879
+ * The three parts of `connector`'s delete (`delete-status.ts`). While a
880
+ * delete is landing, or before a pass has judged a part, that part is
881
+ * `pending`: it is only `done` or `blocked` on a pass's word.
882
+ */
883
+ async function deleteStatus(connector) {
884
+ // A verdict speaks for the tombstone it was judged at: a newer one the
885
+ // registry shows ends it before it is read.
886
+ await refreshTombstones([connector]);
887
+ return deleteStatusSnapshot(connector);
888
+ }
889
+ async function deleteStatusSnapshot(connector) {
890
+ const [open] = await deps.db.query("SELECT 1 FROM delete_intents WHERE connector=?", [connector]);
891
+ if (open)
892
+ return {
893
+ fence: PART_PENDING,
894
+ legacy: PART_PENDING,
895
+ storage: PART_PENDING,
896
+ };
897
+ // A verdict that is final is read from the rows that hold it, so a
898
+ // restart, a reconnect or a sync cycle cannot turn it back into pending.
899
+ if (finishedIn(await rowsOf(connector)))
900
+ return { fence: PART_DONE, legacy: PART_DONE, storage: PART_DONE };
901
+ const seen = judged.get(connector);
902
+ // A host with no stage cannot do it: another device of the account must.
903
+ // A stage no pass has judged is not done: `done` is only ever a pass's
904
+ // word, from evidence it read.
905
+ const unjudged = (can) => !can ? blocked("needs_another_device") : PART_PENDING;
906
+ return {
907
+ fence: seen?.rolledBack ? blocked("tombstone_rolled_back") : PART_DONE,
908
+ legacy: seen?.legacy ?? unjudged(!!options.legacy),
909
+ storage: seen?.storage ?? unjudged(!!options.eraseLogs),
910
+ };
911
+ }
471
912
  function schedule(connector) {
472
913
  const held = flights.get(connector);
473
914
  if (held)
@@ -480,15 +921,24 @@ export function createConnectionDeleter(originalDeps, options = {}) {
480
921
  fencesEnded(false); // a landing that failed before its fence says "not fenced"
481
922
  if (flights.get(connector) === landing)
482
923
  flights.delete(connector);
924
+ options.onRetryStateChange?.();
483
925
  });
484
926
  const landing = { fenced, done };
485
927
  flights.set(connector, landing);
928
+ // Owed from the start, so a status read between the landing's end and
929
+ // the erasure's start does not call the connector settled.
930
+ if (owesErasure)
931
+ owe(connector);
486
932
  // A delete that settled is erased from storage, outside its own queue.
487
- void done.then(() => eraseLogsOf(connector), () => undefined);
933
+ void done.then(() => {
934
+ void eraseLogsOf(connector);
935
+ }, () => undefined);
488
936
  return landing;
489
937
  }
490
938
  async function resumeDelete(connector) {
491
- if (stop.signal.aborted || !(await readIntent(connector)))
939
+ if (stop.signal.aborted)
940
+ return null;
941
+ if (!(await readIntent(connector)))
492
942
  return null;
493
943
  if (stop.signal.aborted)
494
944
  return null;
@@ -500,6 +950,20 @@ export function createConnectionDeleter(originalDeps, options = {}) {
500
950
  return { connector, why: error instanceof Error ? error.name : "Error" };
501
951
  }
502
952
  }
953
+ /**
954
+ * Start every landing the intent rows owe and return their results without
955
+ * waiting for them: a landing stuck at the registry must not hold back what
956
+ * the caller does next. Each result has a handler from the moment it is
957
+ * made; a caller that reads it later still sees it reject.
958
+ */
959
+ async function startDeletes() {
960
+ const rows = await deps.db.query("SELECT connector FROM delete_intents ORDER BY connector");
961
+ return rows.map(({ connector }) => {
962
+ const result = resumeDelete(connector);
963
+ result.catch(() => undefined);
964
+ return result;
965
+ });
966
+ }
503
967
  async function requestConnectionDelete(connector, request = {}) {
504
968
  stop.signal.throwIfAborted();
505
969
  controlScope(connector, "");
@@ -531,7 +995,7 @@ export function createConnectionDeleter(originalDeps, options = {}) {
531
995
  if (open && (empty || samePlan(open, planned.intent)))
532
996
  return open;
533
997
  if (empty) {
534
- await purgeLocal(connector, planned.intent, held);
998
+ await purgeLocal(connector, planned.intent, held, planned.ended);
535
999
  await options.eraseLegacy?.(connector);
536
1000
  return null;
537
1001
  }
@@ -580,6 +1044,50 @@ export function createConnectionDeleter(originalDeps, options = {}) {
580
1044
  fenced: await withinBudget(landing.fenced, options.fenceWaitMs),
581
1045
  };
582
1046
  }
1047
+ /**
1048
+ * Start the owed erasures: first, once, every connector with a connection
1049
+ * deleted here (a delete settled before this process started, or adopted
1050
+ * from another device); then every connector whose erasure is queued. Only
1051
+ * the connectors queued and not in flight start, and only their runs are
1052
+ * returned: a pass in flight is never joined, since a caller that joined it
1053
+ * would stay pending as long as that connector's storage does, and would
1054
+ * hold back what is queued behind it. That pass takes what arrives while it
1055
+ * runs (`again`) and tells the host when it is over (`onRetryStateChange`).
1056
+ * A run that throws queues its connector again.
1057
+ */
1058
+ async function startErasures() {
1059
+ if (!owesErasure || stop.signal.aborted)
1060
+ return [];
1061
+ if (sweepOwed) {
1062
+ // Claimed before the reads: a purge that arrives while they run sets
1063
+ // it again, and a read that fails gives it back.
1064
+ sweepOwed = false;
1065
+ try {
1066
+ // A purge whose connector lookup failed wrote its tombstone all the
1067
+ // same: read the table again.
1068
+ await loadTombstones();
1069
+ // A final verdict is read against the registry too: another device
1070
+ // may have deleted again while this process was off.
1071
+ await refreshTombstones(tombstones.keys());
1072
+ const rows = await deps.db.query("SELECT DISTINCT connector FROM connections WHERE control_state='deleted' ORDER BY connector");
1073
+ for (const { connector } of rows)
1074
+ owe(connector);
1075
+ // A delete this device confirmed and has no final verdict for is
1076
+ // owed too, though a reconnect replaced its local connection: the
1077
+ // tombstone rows say it is unfinished, not the connection rows.
1078
+ const unfinished = await deps.db.query("SELECT DISTINCT connector FROM delete_tombstones WHERE done_at IS NULL ORDER BY connector");
1079
+ for (const { connector } of unfinished)
1080
+ owe(connector);
1081
+ }
1082
+ catch (error) {
1083
+ sweepOwed = true;
1084
+ throw error;
1085
+ }
1086
+ }
1087
+ return [...erasing.keys()]
1088
+ .filter((connector) => !erasures.has(connector))
1089
+ .map((connector) => eraseLogsOf(connector));
1090
+ }
583
1091
  return {
584
1092
  requestConnectionDelete(connector, lifetime) {
585
1093
  const request = requestConnectionDelete(connector, lifetime);
@@ -589,47 +1097,72 @@ export function createConnectionDeleter(originalDeps, options = {}) {
589
1097
  },
590
1098
  readConnectionLifetime,
591
1099
  async resumeDeletes() {
592
- const rows = await deps.db.query("SELECT connector FROM delete_intents ORDER BY connector");
593
- return (await Promise.all(rows.map(({ connector }) => resumeDelete(connector)))).filter((p) => p !== null);
1100
+ return (await Promise.all(await startDeletes())).filter((p) => p !== null);
594
1101
  },
595
1102
  resumeDelete,
596
- /** A connection of the connector was purged here: its erasure may be owed. */
597
- noteSettled(connector) {
598
- if (options.eraseLogs)
599
- erasing.add(connector);
1103
+ startDeletes,
1104
+ deleteStatus,
1105
+ deleteStatusSnapshot,
1106
+ /**
1107
+ * A connection of the connector was purged here: its erasure may be owed.
1108
+ * `tombstone` is the control tombstone that ended it (namespace and
1109
+ * registry version): the identity of the delete, which a delete of the
1110
+ * same connector later replaces. A purge that ran ahead of its fence has
1111
+ * none yet: it owes the stages with no verdict and learns nothing.
1112
+ */
1113
+ noteSettled(connector, tombstone) {
1114
+ // A higher tombstone is a newer delete: both stages judge it afresh and
1115
+ // the gateway is asked again. The same one again (a sync cycle reads the
1116
+ // deleted control row every time) is news of nothing: a final verdict
1117
+ // and a terminal refusal stand, and only a stage with none is owed.
1118
+ // A purge that ran ahead of its fence names no tombstone: nothing is
1119
+ // learned, and the stages with no final verdict are owed.
1120
+ const newer = tombstone
1121
+ ? learnTombstone(connector, tombstone.ns, tombstone.version)
1122
+ : false;
1123
+ if (!owesErasure)
1124
+ return;
1125
+ // A connection held a namespace back and is gone: what held it back is
1126
+ // no longer true, so the same tombstone is judged again. A connection
1127
+ // that still holds it (or another that does) holds it back again.
1128
+ if (!newer)
1129
+ releaseReAdded(connector);
1130
+ const owed = newer ? BOTH : unfinishedStages(connector);
1131
+ if (owed.legacy || owed.storage)
1132
+ owe(connector, owed);
600
1133
  },
601
1134
  /**
602
1135
  * A connection was purged and its connector is unknown: the sweep of
603
1136
  * every deleted connection is owed again.
604
1137
  */
605
1138
  noteSweepOwed() {
606
- if (options.eraseLogs)
1139
+ if (owesErasure)
607
1140
  sweepOwed = true;
608
1141
  },
609
1142
  /** Whether erasure work is owed: the start sweep, or an unfinished erasure. */
610
1143
  erasureOwed: () => sweepOwed || erasing.size > 0,
611
1144
  /**
612
- * Run the owed erasures: first, once, every connector with a connection
613
- * deleted here (a delete settled before this process started, or adopted
614
- * from another device); then every connector whose erasure is unfinished.
615
- * Answers true while one is still unfinished, so the caller retries.
1145
+ * Whether the retry loop has work to come back to: a delete not landed (its
1146
+ * intent row is still there: the one durable fact, read now, that a landing
1147
+ * clears when it ends, supersession included), an erasure queued or left
1148
+ * unfinished, or the start sweep. The in-memory parts are read after the
1149
+ * database read, so the answer is one fact at the moment it returns. An
1150
+ * erasure that runs with nothing more owed is not work for a tick.
1151
+ */
1152
+ async retryOwed() {
1153
+ const intents = await deps.db.query("SELECT 1 FROM delete_intents LIMIT 1");
1154
+ return intents.length > 0 || sweepOwed || erasing.size > 0;
1155
+ },
1156
+ startErasures,
1157
+ /**
1158
+ * Start the owed erasures and wait for the ones started. Answers true while
1159
+ * one is still queued, so the caller retries. The answer is a fact at the
1160
+ * moment it returns: a timer is never decided from it, only from
1161
+ * `retryOwed()` when the timer is decided.
616
1162
  */
617
1163
  async resumeErasures() {
618
- if (!options.eraseLogs || stop.signal.aborted)
619
- return false;
620
- if (sweepOwed) {
621
- const rows = await deps.db.query("SELECT DISTINCT connector FROM connections WHERE control_state='deleted' ORDER BY connector");
622
- for (const { connector } of rows)
623
- erasing.add(connector);
624
- // Only once the rows are queued: a query that failed leaves it owed.
625
- sweepOwed = false;
626
- }
627
- // A run in progress is waited for, not queued again: what it leaves
628
- // unfinished is in `erasing` when it ends, and so is what arrived
629
- // while it ran. Without this wait the loop would find the queue empty
630
- // (a running pass has taken its entry) and stop with that work owed.
631
- await Promise.all([...new Set([...erasing, ...erasures.keys()])].map((connector) => erasures.get(connector) ?? eraseLogsOf(connector)));
632
- return erasing.size > 0;
1164
+ await Promise.all(await startErasures());
1165
+ return [...erasing.keys()].some((connector) => !erasures.has(connector));
633
1166
  },
634
1167
  async close() {
635
1168
  stop.abort(new Error("sync closed"));