@serfab/cadre-core 0.13.0 → 1.1.0

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 (131) hide show
  1. package/README.md +20 -6
  2. package/dist/bootstrap-peer-store-file.js +2 -2
  3. package/dist/bootstrap-peer-store.d.ts +32 -12
  4. package/dist/bootstrap-peer-store.js +41 -15
  5. package/dist/bootstrap-peer-store.js.map +1 -1
  6. package/dist/cadre-node.d.ts +558 -80
  7. package/dist/cadre-node.js +1060 -170
  8. package/dist/cadre-node.js.map +1 -1
  9. package/dist/control-authorization.d.ts +2 -2
  10. package/dist/control-authorization.js +1 -0
  11. package/dist/control-authorization.js.map +1 -1
  12. package/dist/control-cohort.d.ts +13 -26
  13. package/dist/control-cohort.js +0 -26
  14. package/dist/control-cohort.js.map +1 -1
  15. package/dist/control-database.d.ts +299 -44
  16. package/dist/control-database.js +469 -69
  17. package/dist/control-database.js.map +1 -1
  18. package/dist/control-read-retry.d.ts +40 -11
  19. package/dist/control-read-retry.js +48 -15
  20. package/dist/control-read-retry.js.map +1 -1
  21. package/dist/control-retry.d.ts +58 -3
  22. package/dist/control-retry.js +58 -3
  23. package/dist/control-retry.js.map +1 -1
  24. package/dist/control-schema.d.ts +1 -1
  25. package/dist/control-schema.js +103 -19
  26. package/dist/control-schema.js.map +1 -1
  27. package/dist/control-write-retry.d.ts +80 -11
  28. package/dist/control-write-retry.js +176 -29
  29. package/dist/control-write-retry.js.map +1 -1
  30. package/dist/enrolled-machine-store.js +2 -2
  31. package/dist/index.d.ts +14 -7
  32. package/dist/index.js +33 -6
  33. package/dist/index.js.map +1 -1
  34. package/dist/node-local-snapshot.d.ts +15 -7
  35. package/dist/node-local-snapshot.js +23 -8
  36. package/dist/node-local-snapshot.js.map +1 -1
  37. package/dist/peer-dial.d.ts +143 -0
  38. package/dist/peer-dial.js +176 -0
  39. package/dist/peer-dial.js.map +1 -0
  40. package/dist/relay-addrs.d.ts +90 -52
  41. package/dist/relay-addrs.js +91 -59
  42. package/dist/relay-addrs.js.map +1 -1
  43. package/dist/relay-reservation.d.ts +71 -3
  44. package/dist/relay-reservation.js +116 -8
  45. package/dist/relay-reservation.js.map +1 -1
  46. package/dist/seed-bootstrap.d.ts +30 -1
  47. package/dist/seed-bootstrap.js +62 -17
  48. package/dist/seed-bootstrap.js.map +1 -1
  49. package/dist/storage-scope.d.ts +62 -0
  50. package/dist/storage-scope.js +75 -0
  51. package/dist/storage-scope.js.map +1 -0
  52. package/dist/strand-database.d.ts +34 -16
  53. package/dist/strand-database.js +38 -24
  54. package/dist/strand-database.js.map +1 -1
  55. package/dist/strand-first-sync-gate.d.ts +152 -0
  56. package/dist/strand-first-sync-gate.js +208 -0
  57. package/dist/strand-first-sync-gate.js.map +1 -0
  58. package/dist/strand-formation-manager.d.ts +87 -5
  59. package/dist/strand-formation-manager.js +109 -5
  60. package/dist/strand-formation-manager.js.map +1 -1
  61. package/dist/strand-formation-protocol.d.ts +21 -1
  62. package/dist/strand-formation-protocol.js +30 -0
  63. package/dist/strand-formation-protocol.js.map +1 -1
  64. package/dist/strand-instance-manager.d.ts +243 -6
  65. package/dist/strand-instance-manager.js +470 -37
  66. package/dist/strand-instance-manager.js.map +1 -1
  67. package/dist/strand-member-key.d.ts +20 -12
  68. package/dist/strand-member-key.js +20 -12
  69. package/dist/strand-member-key.js.map +1 -1
  70. package/dist/strand-member-registry.js +3 -0
  71. package/dist/strand-member-registry.js.map +1 -1
  72. package/dist/strand-membership-reconciler.d.ts +361 -0
  73. package/dist/strand-membership-reconciler.js +548 -0
  74. package/dist/strand-membership-reconciler.js.map +1 -0
  75. package/dist/strand-membership-writer.d.ts +131 -11
  76. package/dist/strand-membership-writer.js +396 -134
  77. package/dist/strand-membership-writer.js.map +1 -1
  78. package/dist/strand-network-config.d.ts +46 -14
  79. package/dist/strand-network-config.js +79 -23
  80. package/dist/strand-network-config.js.map +1 -1
  81. package/dist/strand-solicitation.d.ts +10 -1
  82. package/dist/strand-solicitation.js +5 -0
  83. package/dist/strand-solicitation.js.map +1 -1
  84. package/dist/strand-wake-protocol.d.ts +11 -7
  85. package/dist/strand-wake-protocol.js +20 -52
  86. package/dist/strand-wake-protocol.js.map +1 -1
  87. package/dist/strand-watcher.js +6 -0
  88. package/dist/strand-watcher.js.map +1 -1
  89. package/dist/timed-step.d.ts +12 -0
  90. package/dist/timed-step.js +28 -0
  91. package/dist/timed-step.js.map +1 -0
  92. package/dist/timeout-scheduler.d.ts +19 -0
  93. package/dist/timeout-scheduler.js +22 -0
  94. package/dist/timeout-scheduler.js.map +1 -0
  95. package/dist/types.d.ts +262 -30
  96. package/dist/types.js.map +1 -1
  97. package/package.json +8 -8
  98. package/src/bootstrap-peer-store-file.ts +2 -2
  99. package/src/bootstrap-peer-store.ts +69 -27
  100. package/src/cadre-node.ts +7301 -6353
  101. package/src/control-authorization.ts +2 -1
  102. package/src/control-cohort.ts +122 -130
  103. package/src/control-database.ts +537 -69
  104. package/src/control-read-retry.ts +202 -167
  105. package/src/control-retry.ts +297 -190
  106. package/src/control-schema.ts +103 -19
  107. package/src/control-write-retry.ts +533 -383
  108. package/src/enrolled-machine-store.ts +2 -2
  109. package/src/index.ts +83 -6
  110. package/src/node-local-snapshot.ts +25 -8
  111. package/src/peer-dial.ts +215 -0
  112. package/src/relay-addrs.ts +458 -436
  113. package/src/relay-reservation.ts +951 -828
  114. package/src/seed-bootstrap.ts +76 -18
  115. package/src/storage-scope.ts +78 -0
  116. package/src/strand-database.ts +50 -27
  117. package/src/strand-first-sync-gate.ts +258 -0
  118. package/src/strand-formation-manager.ts +140 -5
  119. package/src/strand-formation-protocol.ts +43 -1
  120. package/src/strand-instance-manager.ts +577 -37
  121. package/src/strand-member-key.ts +20 -12
  122. package/src/strand-member-registry.ts +3 -0
  123. package/src/strand-membership-reconciler.ts +680 -0
  124. package/src/strand-membership-writer.ts +527 -189
  125. package/src/strand-network-config.ts +102 -24
  126. package/src/strand-solicitation.ts +16 -1
  127. package/src/strand-wake-protocol.ts +21 -66
  128. package/src/strand-watcher.ts +6 -0
  129. package/src/timed-step.ts +28 -0
  130. package/src/timeout-scheduler.ts +28 -0
  131. package/src/types.ts +1789 -1554
@@ -9,7 +9,7 @@ import { canonicalDatetime } from './canonical-datetime.js';
9
9
  import { controlAuthorizationFields, CONTROL_TABLES } from './control-authorization.js';
10
10
  import { requireEd25519PublicKeyB64 } from './ed25519-key.js';
11
11
  import { retryControlWrite, SCHEMA_INIT_RETRY_POLICY } from './control-write-retry.js';
12
- import { retryControlRead } from './control-read-retry.js';
12
+ import { isCohortUnreachableRead, retryControlRead } from './control-read-retry.js';
13
13
  import { chainMessages } from './control-retry.js';
14
14
  const log = debug('sereus:cadre:control-db');
15
15
  const timing = debug('sereus:cadre:timing');
@@ -209,6 +209,7 @@ const GUARDED_KEY_COLUMN = {
209
209
  CadrePeer: 'PeerId',
210
210
  ValidationKey: 'Key',
211
211
  Strand: 'Id',
212
+ StrandPartyKey: 'Id',
212
213
  DeviceToken: 'PeerId',
213
214
  };
214
215
  /**
@@ -236,19 +237,43 @@ const STRAND_ID_CONFLICT = /UNIQUE constraint failed: Strand\.Id\b/i;
236
237
  * reword reddens there.
237
238
  */
238
239
  export function isStrandIdConflict(error) {
239
- if (!(error instanceof Error)) {
240
- return false;
241
- }
242
- return chainMessages(error).some(message => STRAND_ID_CONFLICT.test(message));
240
+ return errorChainMatches(error, STRAND_ID_CONFLICT);
241
+ }
242
+ /**
243
+ * The one `CadreControl.Revocation` row that retires nothing, filed once by an owner
244
+ * ({@link ControlDatabase.openRevocationLedger}) so the table is never a never-written
245
+ * block. The schema's table comment says why that matters and why the row can never read
246
+ * as a retirement; `RowIsGone` pins this exact triple.
247
+ */
248
+ export const REVOCATION_LEDGER_MARKER = {
249
+ tableName: 'Revocation',
250
+ rowKey: 'ledger',
251
+ stampId: 'opened',
252
+ };
253
+ /**
254
+ * The rejection a second insert of the ledger marker produces: the optimystic vtab's
255
+ * primary-key wording (see {@link STRAND_ID_CONFLICT}), naming both columns of
256
+ * `Revocation`'s composite key. Applied only to the marker's own insert, whose key
257
+ * ('Revocation', 'opened') no row but the marker can hold (`RowIsGone`), and `Revocation`
258
+ * has no other unique constraint.
259
+ */
260
+ const REVOCATION_LEDGER_CONFLICT = /UNIQUE constraint failed: Revocation\.TableName, Revocation\.StampId\b/i;
261
+ /** Did the ledger marker's insert fail because the marker is already filed? Text-matched, failing closed, like {@link isStrandIdConflict}. */
262
+ function isRevocationLedgerConflict(error) {
263
+ return errorChainMatches(error, REVOCATION_LEDGER_CONFLICT);
264
+ }
265
+ /** Whether any message in `error`'s cause chain matches `pattern`; false for a non-`Error`. */
266
+ function errorChainMatches(error, pattern) {
267
+ return error instanceof Error && chainMessages(error).some(message => pattern.test(message));
243
268
  }
244
269
  /**
245
270
  * Guarded tables a node may reap locally once their tombstone has committed — the
246
271
  * tables whose `AuthorizedDelete` carries the REAP branch (see the constraint comment on
247
- * `CadrePeer.AuthorizedDelete` in the schema). `Strand` is deliberately absent: its row
248
- * carries `MemberPrivateKey`, the party's own membership secret for that network, stored
249
- * nowhere else (tickets/backlog/debt-strand-tombstone-reap.md owns any future change).
250
- * `OwnerKey` has no production removal path and `MinOneOwner` makes an automated
251
- * owner-key reap a party-bricking hazard.
272
+ * `CadrePeer.AuthorizedDelete` in the schema). `Strand` and `StrandPartyKey` are
273
+ * deliberately absent: their rows carry `MemberPrivateKey` / `PrivateKey` — party
274
+ * secrets stored nowhere else (tickets/backlog/debt-strand-tombstone-reap.md owns any
275
+ * future change). `OwnerKey` has no production removal path and `MinOneOwner` makes an
276
+ * automated owner-key reap a party-bricking hazard.
252
277
  */
253
278
  export const REAPABLE_TABLES = ['CadrePeer', 'DeviceToken', 'ValidationKey'];
254
279
  /**
@@ -271,8 +296,16 @@ export class ControlDatabase {
271
296
  this.initialized = false;
272
297
  this.membershipListener = null;
273
298
  this.guardedDeleteListener = null;
299
+ this.controlWriteAbandonedListener = null;
274
300
  /** Tail of the local-write chain — see {@link withWriteLock}. */
275
301
  this.writeQueue = Promise.resolve();
302
+ /**
303
+ * Locked write bodies currently running (see {@link runWriteBody}); what
304
+ * {@link readRowsOnce} consults to route an unlocked read around a write that has
305
+ * started but not yet opened its transaction. At most 1 while every writer takes the
306
+ * lock — a count rather than a flag so it stays truthful if that ever stops holding.
307
+ */
308
+ this.runningWriteBodies = 0;
276
309
  /**
277
310
  * Pacing seams for {@link lockedWithRetry}. Production leaves this empty (real backoff,
278
311
  * real clock); specs inject a recorded `sleep` / fake `now` so no test waits out a real
@@ -355,8 +388,8 @@ export class ControlDatabase {
355
388
  // NOTE: this is where a slow launch is felt. Duration is (raw-storage operations
356
389
  // issued) × per-operation storage latency: ~1ms/op on an idle machine, but
357
390
  // 50-90ms/op on a loaded disk or a phone's flash under launch contention. A cold
358
- // start now reaches the backend 172 times (8 tables + 1 index, 21 distinct blocks
359
- // — dominated by its 130 genuine writes), a warm restart 52, because cadre-core
391
+ // start now reaches the backend 45 times (9 tables + 1 index, 20 distinct blocks
392
+ // — dominated by its genuine writes), a warm restart 13, because cadre-core
360
393
  // wraps every embedder storage in `@optimystic/db-p2p`'s write-through cache
361
394
  // (@serfab/quereus-plugin-sereus's cached-storage.ts). Uncached the same start issued ~2000 operations — the
362
395
  // upstream re-read amplification measured in
@@ -469,11 +502,33 @@ export class ControlDatabase {
469
502
  * opted in, `control-write-degraded-cohort-member` could no longer observe a sibling
470
503
  * publishing its own `CadrePeer` row and failed at suite setup on two runs out of two.
471
504
  *
472
- * `getAutocommit()` reports the whole `Database` rather than this call (the same
473
- * property {@link assertCommitBoundary} leans on), which is exactly what is wanted:
474
- * false means some writer's transaction is open, which is the only situation where a
475
- * read would have blocked. The check races that writer harmlessly in both directions
476
- * — losing it either reads normally (today's behaviour) or reads committed state.
505
+ * "A write is in flight" is {@link writeInFlight}, and it needs TWO signals because a
506
+ * write is invisible to `getAutocommit()` for part of its life. `Database.exec` takes
507
+ * the exec mutex first; the implicit transaction — the moment `getAutocommit()` turns
508
+ * false — opens only after the write has acquired the mutex, planned the statement,
509
+ * and awaited `begin()` on every connection. While the write WAITS for the mutex (a
510
+ * serialized read holds it, say) it still reports autocommit, so a read routed on
511
+ * `getAutocommit()` alone queued behind the write and answered only after its whole
512
+ * commit — tens of seconds against a slow cohort member, which is what timed out the
513
+ * degraded-cohort scenario's `isMember` read (verified against the engine directly;
514
+ * `complete/control-read-queues-behind-a-write-waiting-for-the-database`). So an
515
+ * UNLOCKED read also takes the committed path while any locked write body is running
516
+ * ({@link runningWriteBodies}), which covers that queued window and everything else a
517
+ * body does before its transaction opens. A read issued INSIDE a locked body
518
+ * (`underWriteLock`) must not: that body is the one being counted, and its guard reads
519
+ * need the refreshing path — so it keeps the transaction-only test.
520
+ *
521
+ * Both signals are sampled synchronously just before `eval`, which claims its place
522
+ * on the mutex in that same tick, so the only race left is a body starting or ending
523
+ * in between: a body that starts after the sample queues its statements BEHIND this
524
+ * read, and one that ended before it has nothing left to queue behind.
525
+ *
526
+ * Residual gaps, both of which still queue a read behind a write:
527
+ * - an EXPLICIT transaction ({@link inTransaction}) disqualifies the committed path in
528
+ * Quereus itself, so a read overlapping such a body's `COMMIT` falls back to the
529
+ * serialized path and waits for it;
530
+ * - a writer that bypasses {@link withWriteLock} is not counted (in this repo only
531
+ * `reference-app-web`'s deliberately-rejected diagnostics insert does).
477
532
  *
478
533
  * What a committed read gives up is observing a write that has not finished
479
534
  * committing, and that is safe for every caller here: an AWAITED write is committed by
@@ -481,15 +536,23 @@ export class ControlDatabase {
481
536
  * open explicit transaction and stays serialized, so it still sees its own
482
537
  * transaction's rows. A read after an UNAWAITED write on this database would be wrong
483
538
  * — no such caller exists, and {@link withWriteLock} is what keeps it that way.
539
+ *
540
+ * NOTE: counting whole bodies widens the stale (non-refreshing) window from "a
541
+ * transaction is open" to "a locked body is running", which adds a body's pre-transaction
542
+ * work and its post-commit tail (a `CadrePeer` write's membership-listener read). The
543
+ * slow part of a write against a degraded cohort is its commit, already inside the old
544
+ * window, so the added time is short; if a poller for replicated rows ever starves
545
+ * behind back-to-back local writes, narrow the count to the span from a body's first
546
+ * statement to its transaction opening.
484
547
  */
485
- async readRowsOnce(sql, params) {
548
+ async readRowsOnce(sql, params, underWriteLock) {
486
549
  let iterator;
487
- if (this.db.getAutocommit()) {
488
- iterator = this.db.eval(sql, params);
550
+ if (this.writeInFlight(underWriteLock)) {
551
+ log('read-eval: a write is in flight (%s), asking for a committed read: %s', this.db.getAutocommit() ? 'locked body running, no transaction open yet' : 'transaction open', sql);
552
+ iterator = this.db.eval(sql, params, { readConcurrency: 'committed' });
489
553
  }
490
554
  else {
491
- log('read-eval: a write is in flight, asking for a committed read: %s', sql);
492
- iterator = this.db.eval(sql, params, { readConcurrency: 'committed' });
555
+ iterator = this.db.eval(sql, params);
493
556
  }
494
557
  const rows = [];
495
558
  for await (const row of iterator) {
@@ -497,6 +560,19 @@ export class ControlDatabase {
497
560
  }
498
561
  return rows;
499
562
  }
563
+ /**
564
+ * Whether a control read should ask for a committed read — see {@link readRowsOnce}.
565
+ * `getAutocommit()` reports the whole `Database` (the property
566
+ * {@link assertCommitBoundary} leans on), so false means some writer's transaction is
567
+ * open. An unlocked read also counts a running locked body that has not opened its
568
+ * transaction yet; a read inside such a body does not, since it is that body.
569
+ */
570
+ writeInFlight(underWriteLock) {
571
+ if (!this.db.getAutocommit()) {
572
+ return true;
573
+ }
574
+ return !underWriteLock && this.runningWriteBodies > 0;
575
+ }
500
576
  /**
501
577
  * {@link readRowsOnce} plus the bounded transient-failure retry
502
578
  * ({@link retryControlRead}) — the funnel every UNLOCKED control read goes through, so a
@@ -512,8 +588,8 @@ export class ControlDatabase {
512
588
  * primary-key lookup or a `count(1)`); nothing streams.
513
589
  *
514
590
  * Each ATTEMPT is a fresh {@link readRowsOnce} call, so the committed-read opt-in
515
- * (`getAutocommit()`) is re-evaluated per attempt — a write can finish between attempts
516
- * and change the right answer.
591
+ * ({@link writeInFlight}) is re-evaluated per attempt — a write can finish between
592
+ * attempts and change the right answer.
517
593
  *
518
594
  * The retry's budget ({@link CONTROL_READ_RETRY_BUDGET_MS}, 1.5 s) is deliberately far
519
595
  * under the write funnel's: the tightest caller deadline over a control read is the
@@ -541,12 +617,19 @@ export class ControlDatabase {
541
617
  * under-lock callback seam is ever added, audit its read graph the same way.
542
618
  */
543
619
  readRows(sql, params, label, retry = true) {
620
+ // `retry: false` marks the reads that may run inside a locked write body, which is
621
+ // also what readRowsOnce's committed-read routing must know (see writeInFlight).
622
+ // NOTE: the membership-gate refresh passes it on EVERY trigger, including the
623
+ // unlocked ones (start, reconcile, seed-applied), so those keep the transaction-only
624
+ // routing and can still queue behind a write waiting for the exec mutex (as before this
625
+ // routing existed). Tolerable while its awaiting callers (reconcile, applySeed) carry no
626
+ // tight deadline; if one ever does, pass the locked/unlocked distinction through instead.
544
627
  if (!retry) {
545
- return this.readRowsOnce(sql, params);
628
+ return this.readRowsOnce(sql, params, true);
546
629
  }
547
630
  // The label lands LAST so the call site's name survives the spec-injected pacing —
548
631
  // it changes log attribution only, never behaviour (same layering as lockedWithRetry).
549
- return retryControlRead(() => this.readRowsOnce(sql, params), { ...this.controlReadRetryPacing, label });
632
+ return retryControlRead(() => this.readRowsOnce(sql, params, false), { ...this.controlReadRetryPacing, label });
550
633
  }
551
634
  /**
552
635
  * Query all strands from the control database
@@ -664,10 +747,12 @@ export class ControlDatabase {
664
747
  * {@link queryRevokedStamps} rather than inlining the SQL, so tests can interpose on
665
748
  * that seam to model the replicated live-row-plus-tombstone merge state.
666
749
  *
667
- * NOTE: runs a second query (the retired-stamp set) per call, and this sits on the
668
- * membership-gate refresh path; control tables are a handful of rows today, so this
669
- * is cheap — if they ever grow, fold the exclusion into one statement or cache the
670
- * retired-stamp set.
750
+ * NOTE: runs a second query (the retired-stamp set) per call, on the membership-gate
751
+ * refresh path. Its cost is storage consults, not rows (see {@link queryRevokedStamps}):
752
+ * while `Revocation` has never been written every call consults the cohort about it, and
753
+ * the ledger marker ({@link openRevocationLedger}) is what makes it a held block. Folding
754
+ * the exclusion into one statement would not help (it reads the same block), and caching
755
+ * the set would hide a tombstone arriving by replication.
671
756
  *
672
757
  * NOTE: this filter is HAND-MIRRORED by the gate suites' fake control databases
673
758
  * (`test/membership-gate-helpers.ts` and `test/cadre-node-authorized-surface.spec.ts`),
@@ -776,6 +861,24 @@ export class ControlDatabase {
776
861
  queryStrandStampId(strandId) {
777
862
  return this.queryStampId('Strand', strandId);
778
863
  }
864
+ /** `StrandPartyKey` stamp nonce — bound into {@link deleteStrandPartyKey}'s remove digest. */
865
+ queryStrandPartyKeyStampId(strandId) {
866
+ return this.queryStampId('StrandPartyKey', strandId);
867
+ }
868
+ /**
869
+ * Read THIS party's own strand membership private key (base64 protobuf; decode with
870
+ * `strandMemberKeyPair`) for one strand, or null when no `StrandPartyKey` row exists.
871
+ * The identity source the closed-strand founder bootstrap derives its `Member.Key` /
872
+ * `Manager.MemberKey` from — deliberately NOT `Strand.MemberPrivateKey`, the
873
+ * strand-wide read secret every joining party receives.
874
+ */
875
+ async queryStrandPartyKey(strandId) {
876
+ this.ensureInitialized();
877
+ for (const row of await this.readRows('select PrivateKey from CadreControl.StrandPartyKey where Id = ?', [strandId], 'strand-party-key')) {
878
+ return row.PrivateKey ?? null;
879
+ }
880
+ return null;
881
+ }
779
882
  /** `ValidationKey` stamp nonce — bound into {@link deleteValidationKey}'s remove digest. */
780
883
  queryValidationKeyStampId(key) {
781
884
  return this.queryStampId('ValidationKey', key);
@@ -792,9 +895,18 @@ export class ControlDatabase {
792
895
  * ({@link queryCadrePeers}, {@link queryPeerRecord},
793
896
  * {@link CadreNode.resolveDeviceToken}) drop any row whose stamp appears here.
794
897
  *
795
- * NOTE: re-reads the whole retired set on every call, and the caller runs per inbound
796
- * gate request while the table only ever grows. Cheap today (a cadre removes peers
797
- * rarely); if removals ever become routine, cache the set and invalidate it on write.
898
+ * NOTE: the per-call cost that matters is the storage layer's, not the row count. While
899
+ * `Revocation` has never been written, this node does not hold its block, and Optimystic
900
+ * consults a block's cohort on every read of a block it does not hold: 1 consult per
901
+ * call (measured), each a round trip to every other member on a multi-machine party. The
902
+ * ledger marker ({@link openRevocationLedger}) ends that — a held block is re-consulted
903
+ * at most once per read-repair window (10 s). Do not cache the set instead: a cache
904
+ * cannot see a tombstone arriving by replication, so it would delay a revocation. The
905
+ * row count only grows (append-only) but stays small while removals are rare; revisit if
906
+ * removals become routine and the scan itself shows up in a profile.
907
+ *
908
+ * An isolated node that has never received the `Revocation` block reads it as holding no
909
+ * revocations instead of throwing — see {@link readRevokedStampRows}.
798
910
  *
799
911
  * `retry: false` is forwarded by {@link queryCadrePeers} for the one caller that reads
800
912
  * under the write lock — see that method's note.
@@ -802,23 +914,76 @@ export class ControlDatabase {
802
914
  async queryRevokedStamps(tableName, retry = true) {
803
915
  this.ensureInitialized();
804
916
  const stamps = new Set();
805
- for (const row of await this.readRows('select StampId from CadreControl.Revocation where TableName = ?', [tableName], 'revoked-stamps', retry)) {
917
+ for (const row of await this.readRevokedStampRows(tableName, retry)) {
806
918
  stamps.add(row.StampId);
807
919
  }
808
920
  return stamps;
809
921
  }
922
+ /**
923
+ * The `Revocation` scan behind {@link queryRevokedStamps}, answering NO ROWS when the read
924
+ * fails `cohort-unreachable` ({@link isCohortUnreachableRead}): this node does not hold
925
+ * the block and could ask no other cohort member about it. Every other failure rethrows.
926
+ * The retry in {@link readRows} runs first, so a node whose connectivity returns within
927
+ * the read budget still gets the real answer.
928
+ *
929
+ * Without this, a machine cut off from every other machine in its party before it ever
930
+ * received the block — the block does not exist anywhere until the owner files the
931
+ * ledger marker ({@link openRevocationLedger}) on a connected reconcile pass — cannot
932
+ * answer ANY membership, peer-record or device-token lookup, although it holds those
933
+ * rows locally.
934
+ *
935
+ * NOTE: accepted tradeoff — `cohort-unreachable` on THIS read, and only this read, is
936
+ * treated as "no revocations known". It adds no fail-open that does not already exist:
937
+ * an isolated node holding a stale `Revocation` block is served it silently (the consult
938
+ * reaches nobody, so no doubt is raised), and a revocation authored elsewhere is invisible
939
+ * to it either way until connectivity returns. The other reasons still throw:
940
+ * `peers-unreachable` means part of the cohort answered, and `claimed-elsewhere` /
941
+ * `unmaterializable` mean the block exists, so an empty answer could admit a revoked
942
+ * member. Do not move this into {@link readRows}: an empty answer is known-safe only for
943
+ * a table whose empty state is its never-written state; decide any other table in its
944
+ * own reader. Revisit if optimystic starts reporting a held-but-stale block distinctly
945
+ * (the equivalence above then breaks), or if revocation enforcement must fail closed
946
+ * under partition.
947
+ *
948
+ * NOTE: an isolated node pays the whole read retry (up to
949
+ * `CONTROL_READ_RETRY_BUDGET_MS`, plus the slow attempt that exhausted it) before this
950
+ * answers, and {@link queryPeerRecord} then issues its row scan on top. If an isolated
951
+ * node's lookups are seen exceeding the admission gate's 2 s deadline
952
+ * (`ADMISSION_DECISION_TIMEOUT_MS`), skip the retry for this read when the first attempt
953
+ * fails `cohort-unreachable`.
954
+ */
955
+ async readRevokedStampRows(tableName, retry) {
956
+ try {
957
+ return await this.readRows('select StampId from CadreControl.Revocation where TableName = ?', [tableName], 'revoked-stamps', retry);
958
+ }
959
+ catch (error) {
960
+ if (!isCohortUnreachableRead(error)) {
961
+ throw error;
962
+ }
963
+ log('revoked-stamps(%s): no cohort member reachable and the Revocation block is not held here; reading as no revocations known: %s', tableName, error);
964
+ return [];
965
+ }
966
+ }
810
967
  /**
811
968
  * Every locally-held `CadreControl.Revocation` tombstone — identity triple plus its
812
969
  * `ReissuedAt` counter. Consumed by the cohort-growth re-issue sweep, which
813
970
  * enumerates what this node holds before {@link reissueRevocations} re-broadcasts
814
- * it. Plain scan with no `where`, so the composite-primary-key point-lookup hazard
815
- * (see the statement comment in {@link reissueRevocations}) does not arise. Unlocked,
816
- * like every other read.
971
+ * it, and by the reap sweep ({@link reapRevokedRows}). Plain scan with no `where`, so
972
+ * the composite-primary-key point-lookup hazard (see the statement comment in
973
+ * {@link reissueRevocations}) does not arise. Unlocked, like every other read.
974
+ *
975
+ * Skips the ledger marker ({@link REVOCATION_LEDGER_MARKER}): it retires nothing, so
976
+ * neither sweep may reap or re-sign it, and skipping it keeps `RevocationRow.tableName`
977
+ * a {@link RevocableTable}. Filtered on `TableName` alone, in TypeScript: `RowIsGone`
978
+ * admits no other row under `'Revocation'`.
817
979
  */
818
980
  async queryRevocations() {
819
981
  this.ensureInitialized();
820
982
  const rows = [];
821
983
  for (const row of await this.readRows('select TableName, RowKey, StampId, ReissuedAt from CadreControl.Revocation', undefined, 'revocations')) {
984
+ if (row.TableName === REVOCATION_LEDGER_MARKER.tableName) {
985
+ continue;
986
+ }
822
987
  rows.push({
823
988
  tableName: row.TableName,
824
989
  rowKey: row.RowKey,
@@ -1024,11 +1189,126 @@ export class ControlDatabase {
1024
1189
  * The remove digest binds only (Id, StampId) — not Type/MemberPrivateKey — so this
1025
1190
  * works identically for open and closed strands.
1026
1191
  *
1192
+ * When the strand has a `StrandPartyKey` row (this party's own membership identity for
1193
+ * the strand — minted at publish for closed strands), it is deleted IN THE SAME
1194
+ * transaction, with its own `'remove'`-tagged signature and its own `Revocation`
1195
+ * tombstone, so a re-published strand always mints fresh identity and no crash window
1196
+ * can orphan the key row. The party-key delete happens ONLY alongside an actual strand
1197
+ * row delete: a `StrandPartyKey` row with no local `Strand` row is a JOINER's identity
1198
+ * (the joiner never holds the strand row) and is not this method's to destroy — that
1199
+ * is {@link deleteStrandPartyKey}'s.
1200
+ *
1027
1201
  * A no-op (no throw, no tombstone) when the row does not exist — `false` then, `true`
1028
1202
  * when a row was actually removed.
1029
1203
  */
1030
1204
  deleteStrand(strandId, ownerKey, signMessage) {
1031
- return this.lockedWithRetry(() => this.deleteGuardedRow('Strand', strandId, ownerKey, signMessage), {}, 'strand-delete');
1205
+ return this.lockedWithRetry(() => this.deleteStrandAndPartyKey(strandId, ownerKey, signMessage), {}, 'strand-delete');
1206
+ }
1207
+ /**
1208
+ * The locked body of {@link deleteStrand}: the `Strand` delete + tombstone, plus — when
1209
+ * one exists — the strand's `StrandPartyKey` delete + tombstone, all in ONE
1210
+ * transaction. A two-table sibling of {@link deleteGuardedRow} (see that method for the
1211
+ * per-clause security rationale: stamp read inside the locked body, `'remove'`-tagged
1212
+ * digests, mandatory same-transaction tombstones); kept separate rather than
1213
+ * generalizing the shared body because no other guarded table has a companion row.
1214
+ *
1215
+ * NOTE: that duplication is a drift risk, not a correctness one — a future tightening of
1216
+ * {@link deleteGuardedRow}'s discipline (an extra precondition, a different digest shape)
1217
+ * will NOT reach this body. Grep for both when you change either; if a second guarded
1218
+ * table ever gains a companion row, generalize instead of copying this a third time.
1219
+ *
1220
+ * Not wrapped in {@link withWriteLock} — the caller holds the (non-re-entrant) lock.
1221
+ */
1222
+ async deleteStrandAndPartyKey(strandId, ownerKey, signMessage) {
1223
+ this.ensureInitialized();
1224
+ // retry: false — these reads run inside the locked write body (see queryStampId's NOTE).
1225
+ const strandStamp = await this.queryStampId('Strand', strandId, false);
1226
+ if (strandStamp === null) {
1227
+ log('delete Strand: no row for %s (already absent)', strandId);
1228
+ return false;
1229
+ }
1230
+ const partyKeyStamp = await this.queryStampId('StrandPartyKey', strandId, false);
1231
+ const strandSignature = signMessage(buildAuthorizationMessage('CadreControl.Strand', 'remove', [strandId, strandStamp]));
1232
+ const strandRevocationSignature = signMessage(buildAuthorizationMessage('CadreControl.Revocation', 'remove', ['Strand', strandId, strandStamp]));
1233
+ const partyKeySignature = partyKeyStamp === null ? null : signMessage(buildAuthorizationMessage('CadreControl.StrandPartyKey', 'remove', [strandId, partyKeyStamp]));
1234
+ const partyKeyRevocationSignature = partyKeyStamp === null ? null : signMessage(buildAuthorizationMessage('CadreControl.Revocation', 'remove', ['StrandPartyKey', strandId, partyKeyStamp]));
1235
+ await this.inTransaction('delete Strand', async () => {
1236
+ await this.db.exec(`
1237
+ delete from CadreControl.Strand
1238
+ with context OwnerKey = ?, Signature = ?
1239
+ where Id = ?
1240
+ `, [ownerKey, strandSignature, strandId]);
1241
+ await this.db.exec(`
1242
+ insert into CadreControl.Revocation (TableName, RowKey, StampId, ReissuedAt)
1243
+ with context OwnerKey = ?, Signature = ?
1244
+ values ('Strand', ?, ?, 0)
1245
+ `, [ownerKey, strandRevocationSignature, strandId, strandStamp]);
1246
+ if (partyKeyStamp !== null) {
1247
+ await this.db.exec(`
1248
+ delete from CadreControl.StrandPartyKey
1249
+ with context OwnerKey = ?, Signature = ?
1250
+ where Id = ?
1251
+ `, [ownerKey, partyKeySignature, strandId]);
1252
+ await this.db.exec(`
1253
+ insert into CadreControl.Revocation (TableName, RowKey, StampId, ReissuedAt)
1254
+ with context OwnerKey = ?, Signature = ?
1255
+ values ('StrandPartyKey', ?, ?, 0)
1256
+ `, [ownerKey, partyKeyRevocationSignature, strandId, partyKeyStamp]);
1257
+ }
1258
+ });
1259
+ log('Strand deleted: %s (stamp retired%s)', strandId, partyKeyStamp === null ? '' : '; party key deleted, stamp retired');
1260
+ this.notifyGuardedDelete({ tableName: 'Strand', rowKey: strandId, stampId: strandStamp });
1261
+ if (partyKeyStamp !== null) {
1262
+ this.notifyGuardedDelete({ tableName: 'StrandPartyKey', rowKey: strandId, stampId: partyKeyStamp });
1263
+ }
1264
+ return true;
1265
+ }
1266
+ /**
1267
+ * Insert this party's own strand membership identity key (`StrandPartyKey` row) using
1268
+ * an owner signature.
1269
+ *
1270
+ * Mirrors {@link insertStrand}: the owner signs the canonical row-bound authorization
1271
+ * message over (Id, PrivateKey, StampId) — binding the key material means a captured
1272
+ * approval can only ever reproduce the exact key it approved — and the StampId is
1273
+ * persisted as a unique column for single-use anti-replay.
1274
+ *
1275
+ * @param strandId - The strand this key is the party's identity for.
1276
+ * @param privateKey - The party's ed25519 strand member private key, base64 protobuf
1277
+ * (same encoding as `Strand.MemberPrivateKey`; mint with `generateStrandMemberKey`).
1278
+ * @param ownerKey - Public key of the authorizing owner.
1279
+ * @param signMessage - Function that ed25519-signs the raw message bytes (no pre-hash)
1280
+ * with the owner's private key, returning a base64url signature.
1281
+ */
1282
+ async insertStrandPartyKey(strandId, privateKey, ownerKey, signMessage) {
1283
+ this.ensureInitialized();
1284
+ log('Inserting strand party key for strand: %s', strandId);
1285
+ const peerId = this.config.libp2pNode.peerId.toString();
1286
+ const stampId = generateStampId(peerId);
1287
+ // Field order MUST match the schema's StrandPartyKey `AuthorizedInsert` verify:
1288
+ // Id, PrivateKey, StampId.
1289
+ const message = buildAuthorizationMessage('CadreControl.StrandPartyKey', 'add', [strandId, privateKey, stampId]);
1290
+ const signature = signMessage(message);
1291
+ await this.execWrite(`
1292
+ insert into CadreControl.StrandPartyKey (Id, PrivateKey, StampId)
1293
+ with context OwnerKey = ?, Signature = ?
1294
+ values (?, ?, ?)
1295
+ `, [ownerKey, signature, strandId, privateKey, stampId], 'strand-party-key-insert');
1296
+ log('Strand party key inserted for strand: %s', strandId);
1297
+ }
1298
+ /**
1299
+ * Owner-signed removal of one `StrandPartyKey` row — the party's own membership
1300
+ * identity for that strand, stored nowhere else, so this is as destructive as
1301
+ * {@link deleteStrand} on a closed strand. {@link deleteStrand} already removes the
1302
+ * founder's row alongside the `Strand` row in one transaction; this standalone form
1303
+ * exists for a party-key row with NO local `Strand` row (a joiner's identity — the
1304
+ * shape the formation tickets build on).
1305
+ *
1306
+ * Mirrors {@link deleteValidationKey}: `'remove'`-tagged digest over (Id, StampId),
1307
+ * `Revocation` tombstone in the same transaction. A no-op (no throw, no tombstone)
1308
+ * when the row does not exist — `false` then, `true` when a row was actually removed.
1309
+ */
1310
+ deleteStrandPartyKey(strandId, ownerKey, signMessage) {
1311
+ return this.lockedWithRetry(() => this.deleteGuardedRow('StrandPartyKey', strandId, ownerKey, signMessage), {}, 'strand-party-key-delete');
1032
1312
  }
1033
1313
  /**
1034
1314
  * Insert a validation key into the control database using an owner signature.
@@ -1309,16 +1589,26 @@ export class ControlDatabase {
1309
1589
  `, [ownerKey, revocationSignature, table, keyValue, stampId]);
1310
1590
  });
1311
1591
  log('%s deleted: %s (stamp retired)', table, keyValue);
1312
- if (this.guardedDeleteListener) {
1313
- try {
1314
- this.guardedDeleteListener({ tableName: table, rowKey: keyValue, stampId });
1315
- }
1316
- catch (error) {
1317
- log('guarded-delete listener threw (committed delete unaffected): %o', error);
1318
- }
1319
- }
1592
+ this.notifyGuardedDelete({ tableName: table, rowKey: keyValue, stampId });
1320
1593
  return true;
1321
1594
  }
1595
+ /**
1596
+ * Fire the guarded-delete listener for one committed tombstone, swallowing (and
1597
+ * logging) a listener throw — a committed delete never fails because bookkeeping did.
1598
+ * Shared by {@link deleteGuardedRow} and {@link deleteStrandAndPartyKey} (which files
1599
+ * up to two tombstones per transaction).
1600
+ */
1601
+ notifyGuardedDelete(revocation) {
1602
+ if (!this.guardedDeleteListener) {
1603
+ return;
1604
+ }
1605
+ try {
1606
+ this.guardedDeleteListener(revocation);
1607
+ }
1608
+ catch (error) {
1609
+ log('guarded-delete listener threw (committed delete unaffected): %o', error);
1610
+ }
1611
+ }
1322
1612
  /**
1323
1613
  * Delete one guarded row that an ALREADY-COMMITTED `Revocation` tombstone retires —
1324
1614
  * the local catch-up for a node that converged on a removal's tombstone while still
@@ -1427,8 +1717,9 @@ export class ControlDatabase {
1427
1717
  *
1428
1718
  * Two rows are deliberately left alone:
1429
1719
  *
1430
- * - **Tables outside {@link REAPABLE_TABLES}** (`Strand`, `OwnerKey`) — no reap branch
1431
- * exists on their `AuthorizedDelete`, so the delete would throw rather than no-op.
1720
+ * - **Tables outside {@link REAPABLE_TABLES}** (`Strand`, `StrandPartyKey`, `OwnerKey`)
1721
+ * — no reap branch exists on their `AuthorizedDelete`, so the delete would throw
1722
+ * rather than no-op.
1432
1723
  * - **This node's OWN `CadrePeer` / `DeviceToken` row** (`selfPeerId`). Reaping it would
1433
1724
  * fight this node's own re-registration: `registerSelf` / `retouchSelfDeviceToken` run
1434
1725
  * on the heartbeat and the growth drain, and after a self-reap their insert-if-absent
@@ -1448,8 +1739,11 @@ export class ControlDatabase {
1448
1739
  * skip-self rule is exercisable without one.
1449
1740
  *
1450
1741
  * NOTE: cost is O(tombstones), not O(live rows) — one {@link queryRevocations} scan plus
1451
- * one {@link queryStampId} point lookup per tombstone, and the empty-table early return
1452
- * makes the common case (a party that has never revoked anyone) a single scan per pass.
1742
+ * one {@link queryStampId} point lookup per tombstone, and the empty early return makes
1743
+ * the common case (a party that has never revoked anyone; {@link queryRevocations} skips
1744
+ * the ledger marker) a single scan per pass. That scan consults the cohort on every pass
1745
+ * only while `Revocation` has never been written; the ledger marker
1746
+ * ({@link openRevocationLedger}), filed by the same connected pass, makes it a held block.
1453
1747
  * But `Revocation` is append-only and unbounded, so this is O(all tombstones ever) point
1454
1748
  * lookups on every reconcile tick. Fine while revocations stay rare for a cadre-sized
1455
1749
  * party; if the table ever grows, persist a node-local high-water mark of what has
@@ -1556,6 +1850,74 @@ export class ControlDatabase {
1556
1850
  return executed;
1557
1851
  }, {}, 'revocation-reissue');
1558
1852
  }
1853
+ /**
1854
+ * Owner-signed filing of the singleton `Revocation` ledger marker
1855
+ * ({@link REVOCATION_LEDGER_MARKER}), the one row in that table that retires nothing.
1856
+ *
1857
+ * Why it exists: while `Revocation` has never been written, this node does not hold its
1858
+ * block, and Optimystic consults a block's cohort on EVERY read of a block it does not
1859
+ * hold — and every membership lookup, and every guarded insert's `NotRevoked` check,
1860
+ * reads this table. Once any row exists the block is held and re-checked at most once per
1861
+ * read-repair window, like every other populated table. The schema's table comment says
1862
+ * why the row can never read as a retirement.
1863
+ *
1864
+ * Insert-if-absent, shaped like {@link reissueRevocations}: the signature is minted
1865
+ * OUTSIDE the locked body so a retried attempt re-presents the same one, and the guard
1866
+ * runs INSIDE it so it sees a concurrent local writer's committed row. The guard scans
1867
+ * the `'Revocation'` rows and compares the stamp in TypeScript rather than seeking the
1868
+ * full composite primary key, which is served as a point lookup that can miss an existing
1869
+ * row on a networked database (tickets/backlog/debt-composite-pk-point-lookup-unreliable-untracked).
1870
+ *
1871
+ * Two owners filing at once: the loser either sees the marker in its guard or is refused
1872
+ * on the primary key, and both answer `'already-open'`.
1873
+ *
1874
+ * The caller decides WHEN. A marker committed while the node is alone is local-only and
1875
+ * can fork the collection, so {@link CadreNode} files it only while connected; this
1876
+ * method does not look at connectivity.
1877
+ *
1878
+ * @param ownerKey - owner public key for the write context (`Revocation.Authorized`).
1879
+ * @param signMessage - ed25519-signs the raw message bytes (no pre-hash) with that owner's
1880
+ * private key, returning a base64url signature.
1881
+ * @returns `'opened'` when this call filed the marker, `'already-open'` when it was
1882
+ * already there.
1883
+ */
1884
+ async openRevocationLedger(ownerKey, signMessage) {
1885
+ this.ensureInitialized();
1886
+ const { tableName, rowKey, stampId } = REVOCATION_LEDGER_MARKER;
1887
+ const signature = signMessage(buildAuthorizationMessage('CadreControl.Revocation', 'remove', [tableName, rowKey, stampId]));
1888
+ try {
1889
+ return await this.lockedWithRetry(async () => {
1890
+ if (await this.revocationLedgerFiled()) {
1891
+ return 'already-open';
1892
+ }
1893
+ // Bare `exec`: already inside the write lock, which is NOT re-entrant.
1894
+ await this.db.exec(`
1895
+ insert into CadreControl.Revocation (TableName, RowKey, StampId)
1896
+ with context OwnerKey = ?, Signature = ?
1897
+ values (?, ?, ?)
1898
+ `, [ownerKey, signature, tableName, rowKey, stampId]);
1899
+ log('Revocation ledger marker filed');
1900
+ return 'opened';
1901
+ }, {}, 'revocation-ledger-open');
1902
+ }
1903
+ catch (error) {
1904
+ if (!isRevocationLedgerConflict(error)) {
1905
+ throw error;
1906
+ }
1907
+ log('Revocation ledger marker already filed (refused on the primary key, most likely by another owner filing first): %s', error);
1908
+ return 'already-open';
1909
+ }
1910
+ }
1911
+ /**
1912
+ * Whether the ledger marker is present locally: a scan of the `'Revocation'` rows with the
1913
+ * stamp compared in TypeScript (see {@link openRevocationLedger} for why not a seek).
1914
+ * Called only inside the locked write body, so never retried (see queryStampId's NOTE).
1915
+ */
1916
+ async revocationLedgerFiled() {
1917
+ const { tableName, stampId } = REVOCATION_LEDGER_MARKER;
1918
+ const rows = await this.readRows('select StampId from CadreControl.Revocation where TableName = ?', [tableName], 'revocation-ledger', false);
1919
+ return rows.some(row => row.StampId === stampId);
1920
+ }
1559
1921
  /**
1560
1922
  * Run `body` between `beginTransaction` and `commit`, rolling back on failure.
1561
1923
  *
@@ -1616,6 +1978,19 @@ export class ControlDatabase {
1616
1978
  setGuardedDeleteListener(listener) {
1617
1979
  this.guardedDeleteListener = listener;
1618
1980
  }
1981
+ /**
1982
+ * Wire (or clear, with null) the single listener notified when {@link lockedWithRetry}
1983
+ * ABANDONS a control write. Same ownership contract as
1984
+ * {@link setMembershipChangeListener}: one CadreNode, wired in `start()` and cleared on
1985
+ * teardown, and a second call replaces the first rather than fanning out.
1986
+ *
1987
+ * Covers every write that reaches the funnel, foreground and background alike. A
1988
+ * foreground caller also sees the rethrown error; a background one often does not, which
1989
+ * is the whole reason this exists.
1990
+ */
1991
+ setControlWriteAbandonedListener(listener) {
1992
+ this.controlWriteAbandonedListener = listener;
1993
+ }
1619
1994
  /**
1620
1995
  * Run a `CadrePeer` row mutation and notify the membership listener once it has
1621
1996
  * COMMITTED.
@@ -1700,10 +2075,26 @@ export class ControlDatabase {
1700
2075
  async withWriteLock(fn) {
1701
2076
  // Chain behind the current tail regardless of how it settled, then park a
1702
2077
  // swallowed copy as the new tail so one failed write never poisons the queue.
1703
- const run = this.writeQueue.then(fn, fn);
2078
+ const body = () => this.runWriteBody(fn);
2079
+ const run = this.writeQueue.then(body, body);
1704
2080
  this.writeQueue = run.then(() => undefined, () => undefined);
1705
2081
  return run;
1706
2082
  }
2083
+ /**
2084
+ * Run one locked body, counted in {@link runningWriteBodies} from the moment it takes
2085
+ * the lock until it settles — so an unlocked read routes around it even while its
2086
+ * first statement is still waiting for the database's exec mutex, before
2087
+ * `getAutocommit()` can show it (see {@link readRowsOnce}).
2088
+ */
2089
+ async runWriteBody(fn) {
2090
+ this.runningWriteBodies++;
2091
+ try {
2092
+ return await fn();
2093
+ }
2094
+ finally {
2095
+ this.runningWriteBodies--;
2096
+ }
2097
+ }
1707
2098
  /**
1708
2099
  * {@link withWriteLock} plus the bounded transient-failure retry
1709
2100
  * ({@link retryControlWrite}) — the wrapper the whole public write surface goes
@@ -1727,12 +2118,24 @@ export class ControlDatabase {
1727
2118
  * `label` names the operation in this loop's debug lines and nothing else
1728
2119
  * ({@link ControlWriteRetryOptions.label}). Every call site in this class supplies one:
1729
2120
  * several writes retry CONCURRENTLY in a real party, so an unlabelled line cannot be
1730
- * attributed to a write — keep new call sites labelled.
2121
+ * attributed to a write — keep new call sites labelled. It is also the only thing that
2122
+ * attributes an abandonment reported through {@link setControlWriteAbandonedListener}.
2123
+ *
2124
+ * The abandonment observer lands LAST, after both the policy and the spec-injected
2125
+ * pacing, so this class's single listener is the one seam for it — a caller that
2126
+ * smuggled its own in through `policy` would be displaced here rather than fanning out.
1731
2127
  */
1732
2128
  lockedWithRetry(fn, policy = {}, label) {
1733
2129
  // The label lands LAST so a call site's own name survives both the policy and the
1734
2130
  // spec-injected pacing; it changes log attribution only, never behaviour.
1735
- return retryControlWrite(() => this.withWriteLock(fn), { ...policy, ...this.controlWriteRetryPacing, ...(label !== undefined ? { label } : {}) });
2131
+ return retryControlWrite(() => this.withWriteLock(fn), {
2132
+ ...policy,
2133
+ ...this.controlWriteRetryPacing,
2134
+ ...(label !== undefined ? { label } : {}),
2135
+ // Read through the field, not captured: a listener wired (or cleared) while a write
2136
+ // is already in backoff still governs that write's abandonment.
2137
+ onAbandon: (abandonment) => this.controlWriteAbandonedListener?.(abandonment)
2138
+ });
1736
2139
  }
1737
2140
  /**
1738
2141
  * One-statement local write, serialized by {@link withWriteLock} and retried on a
@@ -2096,22 +2499,19 @@ export class ControlDatabase {
2096
2499
  /**
2097
2500
  * Count `FormationUsage` rows recorded against a token (uses consumed so far).
2098
2501
  *
2099
- * This count IS the seat cap (`enforceFormationUseCap`), so an under-report admits a seat
2100
- * the invitation never paid for. It is served by a table SCAN, deliberately: a bare
2101
- * equality on a non-key column is a shape the optimystic vtab declines to claim, so the
2102
- * engine applies the filter itself over a full read of the table.
2103
- *
2104
- * NOTE: it was briefly an index seek, and that is what the scan is protecting against.
2105
- * `formation-unique-token-redesign` took `Token` out of the primary key and declared
2106
- * `FormationUsageByToken` purely to spare this scan, recording as a tripwire that an
2107
- * under-reporting descent would admit an unpaid-for seat — "a failure mode a scan could
2108
- * not produce". The tripwire fired. Across machines a secondary-index descent returns only
2109
- * the rows the READING machine wrote, so this count under-reported without bound on a
2110
- * multi-machine party and the cap over-admitted. The index was removed 2026-08-25; the
2111
- * measurement is recorded in the block comment at the `FormationUsage` declaration in
2112
- * `schemas/control.qsql`, and the engine defect in
2113
- * `blocked/secondary-index-seek-blind-to-sibling-rows`. Do NOT re-declare the index to
2114
- * speed this up while that ticket is open.
2502
+ * Served by a seek through the `FormationUsageByToken` index rather than a full scan of
2503
+ * the table, which is append-only and grows for the life of the party.
2504
+ *
2505
+ * NOTE: this count IS the seat cap (`enforceFormationUseCap`), so an under-report admits a
2506
+ * seat the invitation never paid for — and reading it through a secondary index makes the
2507
+ * cap depend on that index converging across machines. It did not, from 2026-08-04 to
2508
+ * 2026-08-25: a descent on a second machine returned only the rows that machine had
2509
+ * written, and the index was removed until the engine was fixed upstream (re-measured
2510
+ * 2026-09-17, `complete/restore-formation-usage-token-index`). The live guard is the
2511
+ * integration-tests scenario `strand-formation-concurrent-redemption`, which asserts both
2512
+ * machines' views of a raced redemption. If it fails on BOTH views again, index
2513
+ * convergence has regressed — fix the engine or take this read off the index, and do not
2514
+ * weaken that scenario's assertions to get a green run.
2115
2515
  *
2116
2516
  * `retry: false` is passed only by {@link assertSeatRemains}, which runs INSIDE a
2117
2517
  * locked write body — same per-call opt-out, and for the same reason, as