@optimystic/db-core 1.8.1 → 1.10.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 (127) hide show
  1. package/dist/src/cohort-topic/addressing.d.ts +46 -6
  2. package/dist/src/cohort-topic/addressing.d.ts.map +1 -1
  3. package/dist/src/cohort-topic/addressing.js +58 -18
  4. package/dist/src/cohort-topic/addressing.js.map +1 -1
  5. package/dist/src/cohort-topic/member-engine.d.ts +21 -1
  6. package/dist/src/cohort-topic/member-engine.d.ts.map +1 -1
  7. package/dist/src/cohort-topic/member-engine.js +39 -9
  8. package/dist/src/cohort-topic/member-engine.js.map +1 -1
  9. package/dist/src/cohort-topic/membership/publisher.js +1 -1
  10. package/dist/src/cohort-topic/membership/publisher.js.map +1 -1
  11. package/dist/src/cohort-topic/membership/source.d.ts +4 -0
  12. package/dist/src/cohort-topic/membership/source.d.ts.map +1 -1
  13. package/dist/src/cohort-topic/membership/source.js +4 -0
  14. package/dist/src/cohort-topic/membership/source.js.map +1 -1
  15. package/dist/src/cohort-topic/membership/verifier.d.ts +51 -9
  16. package/dist/src/cohort-topic/membership/verifier.d.ts.map +1 -1
  17. package/dist/src/cohort-topic/membership/verifier.js +138 -46
  18. package/dist/src/cohort-topic/membership/verifier.js.map +1 -1
  19. package/dist/src/cohort-topic/ports.d.ts +85 -14
  20. package/dist/src/cohort-topic/ports.d.ts.map +1 -1
  21. package/dist/src/cohort-topic/ports.js +1 -1
  22. package/dist/src/cohort-topic/ports.js.map +1 -1
  23. package/dist/src/cohort-topic/registration/renewal.d.ts +26 -5
  24. package/dist/src/cohort-topic/registration/renewal.d.ts.map +1 -1
  25. package/dist/src/cohort-topic/registration/renewal.js +71 -21
  26. package/dist/src/cohort-topic/registration/renewal.js.map +1 -1
  27. package/dist/src/cohort-topic/service.d.ts +34 -2
  28. package/dist/src/cohort-topic/service.d.ts.map +1 -1
  29. package/dist/src/cohort-topic/service.js +86 -28
  30. package/dist/src/cohort-topic/service.js.map +1 -1
  31. package/dist/src/cohort-topic/sig/payloads.d.ts +5 -1
  32. package/dist/src/cohort-topic/sig/payloads.d.ts.map +1 -1
  33. package/dist/src/cohort-topic/sig/payloads.js +6 -1
  34. package/dist/src/cohort-topic/sig/payloads.js.map +1 -1
  35. package/dist/src/cohort-topic/sig/threshold.d.ts +29 -4
  36. package/dist/src/cohort-topic/sig/threshold.d.ts.map +1 -1
  37. package/dist/src/cohort-topic/sig/threshold.js +39 -7
  38. package/dist/src/cohort-topic/sig/threshold.js.map +1 -1
  39. package/dist/src/cohort-topic/walk.d.ts +19 -4
  40. package/dist/src/cohort-topic/walk.d.ts.map +1 -1
  41. package/dist/src/cohort-topic/walk.js +29 -6
  42. package/dist/src/cohort-topic/walk.js.map +1 -1
  43. package/dist/src/cohort-topic/willingness.d.ts +17 -1
  44. package/dist/src/cohort-topic/willingness.d.ts.map +1 -1
  45. package/dist/src/cohort-topic/willingness.js +18 -3
  46. package/dist/src/cohort-topic/willingness.js.map +1 -1
  47. package/dist/src/cohort-topic/wire/index.d.ts +1 -1
  48. package/dist/src/cohort-topic/wire/index.d.ts.map +1 -1
  49. package/dist/src/cohort-topic/wire/index.js +1 -1
  50. package/dist/src/cohort-topic/wire/index.js.map +1 -1
  51. package/dist/src/cohort-topic/wire/payloads.d.ts +14 -0
  52. package/dist/src/cohort-topic/wire/payloads.d.ts.map +1 -1
  53. package/dist/src/cohort-topic/wire/payloads.js +20 -0
  54. package/dist/src/cohort-topic/wire/payloads.js.map +1 -1
  55. package/dist/src/cohort-topic/wire/primitives.d.ts +8 -0
  56. package/dist/src/cohort-topic/wire/primitives.d.ts.map +1 -1
  57. package/dist/src/cohort-topic/wire/primitives.js +24 -4
  58. package/dist/src/cohort-topic/wire/primitives.js.map +1 -1
  59. package/dist/src/cohort-topic/wire/types.d.ts +37 -0
  60. package/dist/src/cohort-topic/wire/types.d.ts.map +1 -1
  61. package/dist/src/cohort-topic/wire/validate.d.ts +9 -1
  62. package/dist/src/cohort-topic/wire/validate.d.ts.map +1 -1
  63. package/dist/src/cohort-topic/wire/validate.js +23 -4
  64. package/dist/src/cohort-topic/wire/validate.js.map +1 -1
  65. package/dist/src/collection/collection.d.ts +17 -0
  66. package/dist/src/collection/collection.d.ts.map +1 -1
  67. package/dist/src/collection/collection.js +19 -0
  68. package/dist/src/collection/collection.js.map +1 -1
  69. package/dist/src/reactivity/config.d.ts +9 -5
  70. package/dist/src/reactivity/config.d.ts.map +1 -1
  71. package/dist/src/reactivity/config.js +9 -4
  72. package/dist/src/reactivity/config.js.map +1 -1
  73. package/dist/src/reactivity/index.d.ts +4 -3
  74. package/dist/src/reactivity/index.d.ts.map +1 -1
  75. package/dist/src/reactivity/index.js +4 -3
  76. package/dist/src/reactivity/index.js.map +1 -1
  77. package/dist/src/reactivity/notification.d.ts +7 -0
  78. package/dist/src/reactivity/notification.d.ts.map +1 -1
  79. package/dist/src/reactivity/notification.js +1 -1
  80. package/dist/src/reactivity/notification.js.map +1 -1
  81. package/dist/src/reactivity/rotation.d.ts +73 -57
  82. package/dist/src/reactivity/rotation.d.ts.map +1 -1
  83. package/dist/src/reactivity/rotation.js +54 -54
  84. package/dist/src/reactivity/rotation.js.map +1 -1
  85. package/dist/src/reactivity/subscription.d.ts +12 -9
  86. package/dist/src/reactivity/subscription.d.ts.map +1 -1
  87. package/dist/src/reactivity/subscription.js +9 -6
  88. package/dist/src/reactivity/subscription.js.map +1 -1
  89. package/dist/src/reactivity/topic-anchor.d.ts +36 -31
  90. package/dist/src/reactivity/topic-anchor.d.ts.map +1 -1
  91. package/dist/src/reactivity/topic-anchor.js +41 -39
  92. package/dist/src/reactivity/topic-anchor.js.map +1 -1
  93. package/dist/src/reactivity/verify.d.ts +26 -9
  94. package/dist/src/reactivity/verify.d.ts.map +1 -1
  95. package/dist/src/reactivity/verify.js +26 -11
  96. package/dist/src/reactivity/verify.js.map +1 -1
  97. package/dist/src/reactivity/wire.d.ts +1 -1
  98. package/dist/src/reactivity/wire.d.ts.map +1 -1
  99. package/dist/src/transactor/change-notifier.d.ts +1 -1
  100. package/package.json +5 -5
  101. package/src/cohort-topic/addressing.ts +83 -23
  102. package/src/cohort-topic/member-engine.ts +77 -8
  103. package/src/cohort-topic/membership/publisher.ts +1 -1
  104. package/src/cohort-topic/membership/source.ts +4 -0
  105. package/src/cohort-topic/membership/verifier.ts +169 -51
  106. package/src/cohort-topic/ports.ts +87 -15
  107. package/src/cohort-topic/registration/renewal.ts +87 -24
  108. package/src/cohort-topic/service.ts +157 -35
  109. package/src/cohort-topic/sig/payloads.ts +7 -2
  110. package/src/cohort-topic/sig/threshold.ts +41 -7
  111. package/src/cohort-topic/walk.ts +46 -9
  112. package/src/cohort-topic/willingness.ts +34 -3
  113. package/src/cohort-topic/wire/index.ts +1 -0
  114. package/src/cohort-topic/wire/payloads.ts +21 -0
  115. package/src/cohort-topic/wire/primitives.ts +26 -4
  116. package/src/cohort-topic/wire/types.ts +37 -0
  117. package/src/cohort-topic/wire/validate.ts +26 -3
  118. package/src/collection/collection.ts +20 -0
  119. package/src/reactivity/config.ts +10 -5
  120. package/src/reactivity/index.ts +4 -3
  121. package/src/reactivity/notification.ts +8 -1
  122. package/src/reactivity/rotation.ts +86 -78
  123. package/src/reactivity/subscription.ts +12 -9
  124. package/src/reactivity/topic-anchor.ts +42 -45
  125. package/src/reactivity/verify.ts +36 -17
  126. package/src/reactivity/wire.ts +1 -1
  127. package/src/transactor/change-notifier.ts +1 -1
@@ -19,7 +19,9 @@
19
19
  * cold-start gate decides whether to instantiate, else `no_state` (walk steps toward the root).
20
20
  * 3. **Admission** — on `accepted`, assign the deterministic primary/backup slots, persist the
21
21
  * soft-state record, count the arrival, run the promotion trigger, and attach the topic-traffic
22
- * signal to the reply.
22
+ * signal to the reply. A decline that only reflects members not heard from yet — a cohort that has
23
+ * just started serving the topic — is held on the injected {@link QuorumWait} while they answer,
24
+ * then decided again, once.
23
25
  *
24
26
  * Every collaborator is injected, so the engine unit-tests without FRET or libp2p.
25
27
  */
@@ -62,6 +64,20 @@ export interface RegisterContext {
62
64
  readonly parentCoord?: Uint8Array;
63
65
  }
64
66
 
67
+ /**
68
+ * Holds a register whose cohort has not heard from enough of its members yet, so it can be admitted on the
69
+ * same request once they answer (§Cold-start instantiation). db-p2p's host implements it over the cohort
70
+ * gossip: it asks the members to gossip their willingness now and resolves as their frames merge.
71
+ */
72
+ export interface QuorumWait {
73
+ /**
74
+ * Resolve when `ready()` turns true or the wait's deadline passes, with the clock at which it settled.
75
+ * Resolves at once (with `now`) when no wait can be opened — the engine is closed, the members were
76
+ * asked too recently to be asked again, or too many registers are already waiting.
77
+ */
78
+ until(ready: () => boolean, now: number): Promise<number>;
79
+ }
80
+
65
81
  /** Current cohort snapshot — the FRET host fills this from the membership source. */
66
82
  export interface CohortSnapshotView {
67
83
  readonly members: readonly Uint8Array[];
@@ -93,6 +109,11 @@ export interface CohortMemberEngineDeps {
93
109
  readonly cohort: () => CohortSnapshotView;
94
110
  /** Whether a quorum of members is willing to serve `tier` (the cold-start gate input). */
95
111
  readonly quorumWilling: (tier: Tier) => boolean;
112
+ /**
113
+ * Where a register declined only for want of members' gossip (`awaitingMembers`) waits for it, once,
114
+ * before the decision is made again. Absent → such a register is declined at once.
115
+ */
116
+ readonly quorumWait?: QuorumWait;
96
117
  // --- anti-DoS guards (all optional; absent = that gate is skipped) ---
97
118
  readonly rateLimiter?: RegisterRateLimiter;
98
119
  /**
@@ -172,11 +193,7 @@ class StoreCohortMemberEngine implements CohortMemberEngine {
172
193
 
173
194
  // 2. Hot path: this cohort already serves the topic.
174
195
  if (this.serves(topicId)) {
175
- if (this.deps.promotion.isPromoted(topicId)) {
176
- // Promoted: bounce same-tier registrations onward (the cheap single-RPC redirect).
177
- return promotedRedirectReply(ctx.treeTier + 1, this.deps.traffic.snapshot(topicId));
178
- }
179
- return this.admitOrDecline(reg, topicId, participantId, tier, ctx, now);
196
+ return this.decideServed(reg, topicId, participantId, tier, ctx, now, true);
180
197
  }
181
198
 
182
199
  // 3. Cold path: instantiate only at a legitimate growth point with a willing quorum. `ctx.followOn`
@@ -192,7 +209,7 @@ class StoreCohortMemberEngine implements CohortMemberEngine {
192
209
  return this.unwillingCohort(reg, now);
193
210
  }
194
211
  this.deps.coldStart.instantiate(topicId, ctx.treeTier, ctx.parentCoord, tier);
195
- return this.admitOrDecline(reg, topicId, participantId, tier, ctx, now);
212
+ return this.admitOrDecline(reg, topicId, participantId, tier, ctx, now, true);
196
213
  }
197
214
 
198
215
  /**
@@ -284,7 +301,28 @@ class StoreCohortMemberEngine implements CohortMemberEngine {
284
301
 
285
302
  // --- admission ---
286
303
 
287
- /** Run the willingness check; on `accepted` persist the record and attach the traffic signal. */
304
+ /** The decision for a topic this cohort serves: a promoted topic redirects onward, any other runs admission. */
305
+ private async decideServed(
306
+ reg: RegisterV1,
307
+ topicId: Uint8Array,
308
+ participantId: Uint8Array,
309
+ tier: Tier,
310
+ ctx: RegisterContext,
311
+ now: number,
312
+ mayWait: boolean,
313
+ ): Promise<RegisterReplyV1> {
314
+ if (this.deps.promotion.isPromoted(topicId)) {
315
+ // Promoted: bounce same-tier registrations onward (the cheap single-RPC redirect).
316
+ return promotedRedirectReply(ctx.treeTier + 1, this.deps.traffic.snapshot(topicId));
317
+ }
318
+ return this.admitOrDecline(reg, topicId, participantId, tier, ctx, now, mayWait);
319
+ }
320
+
321
+ /**
322
+ * Run the willingness check; on `accepted` persist the record and attach the traffic signal. A quorum
323
+ * short only for want of members' gossip is waited for when `mayWait` — which the decision made after
324
+ * that wait never is, so one register waits at most once.
325
+ */
288
326
  private async admitOrDecline(
289
327
  reg: RegisterV1,
290
328
  topicId: Uint8Array,
@@ -292,6 +330,7 @@ class StoreCohortMemberEngine implements CohortMemberEngine {
292
330
  tier: Tier,
293
331
  ctx: RegisterContext,
294
332
  now: number,
333
+ mayWait: boolean,
295
334
  ): Promise<RegisterReplyV1> {
296
335
  const outcome = this.deps.willingness.evaluate(reg, this.deps.profile, now);
297
336
  switch (outcome.kind) {
@@ -299,6 +338,9 @@ class StoreCohortMemberEngine implements CohortMemberEngine {
299
338
  return { v: 1, result: "unwilling_member", candidateMembers: outcome.candidateMembers.map(bytesKey) };
300
339
  }
301
340
  case "unwilling_cohort": {
341
+ if (mayWait && outcome.awaitingMembers && this.deps.quorumWait !== undefined) {
342
+ return this.decideOnceMembersAnswer(this.deps.quorumWait, reg, topicId, participantId, tier, ctx, now);
343
+ }
302
344
  return { v: 1, result: "unwilling_cohort", retryAfterMs: outcome.retryAfterMs };
303
345
  }
304
346
  case "accepted": {
@@ -310,6 +352,33 @@ class StoreCohortMemberEngine implements CohortMemberEngine {
310
352
  }
311
353
  }
312
354
 
355
+ /**
356
+ * Hold `reg` until the members it is waiting on have gossiped (or the wait gives up), then decide again
357
+ * from the top of the served-topic path at the clock the wait settled at: the topic can have been
358
+ * promoted, or lost its forwarder to a topic-budget eviction, while the request was held.
359
+ */
360
+ private async decideOnceMembersAnswer(
361
+ wait: QuorumWait,
362
+ reg: RegisterV1,
363
+ topicId: Uint8Array,
364
+ participantId: Uint8Array,
365
+ tier: Tier,
366
+ ctx: RegisterContext,
367
+ now: number,
368
+ ): Promise<RegisterReplyV1> {
369
+ const settledAt = await wait.until(() => !this.awaitsMembers(reg, now), now);
370
+ if (!this.serves(topicId)) {
371
+ return this.unwillingCohort(reg, settledAt);
372
+ }
373
+ return this.decideServed(reg, topicId, participantId, tier, ctx, settledAt, false);
374
+ }
375
+
376
+ /** True while `reg` is still declined only for want of members' gossip. */
377
+ private awaitsMembers(reg: RegisterV1, now: number): boolean {
378
+ const outcome = this.deps.willingness.evaluate(reg, this.deps.profile, now);
379
+ return outcome.kind === "unwilling_cohort" && outcome.awaitingMembers;
380
+ }
381
+
313
382
  private async accept(
314
383
  reg: RegisterV1,
315
384
  topicId: Uint8Array,
@@ -150,7 +150,7 @@ class SigningMembershipCertPublisher implements MembershipCertPublisher {
150
150
  cert.rotationSig = bytesToB64url(rotation.rotationSig);
151
151
  cert.rotationSigners = rotation.rotationSigners.map(bytesToB64url);
152
152
  }
153
- this.deps.sink.publish(encodeCohortMessage(cert, this.deps.maxMessageBytes));
153
+ this.deps.sink.publish(snapshot.coord, encodeCohortMessage(cert, this.deps.maxMessageBytes));
154
154
  this.lastEpoch = bytesToB64url(snapshot.cohortEpoch);
155
155
  this.lastPublishedAt = now;
156
156
  return cert;
@@ -12,6 +12,10 @@
12
12
  *
13
13
  * Both back-ends present the same {@link IMembershipSource} surface; this router picks between them by
14
14
  * tier. db-p2p supplies the two concrete sources (tx-log reader and FRET cert source).
15
+ *
16
+ * The router picks a source and nothing more: the per-call lookup options a verifier passes to
17
+ * `current` / `fetch` (`{ rootPlaced: true }` for the root of a root-placed topic) go to the chosen
18
+ * source untouched, and it is that source which decides where a root-placed coord's cert is fetched from.
15
19
  */
16
20
 
17
21
  import type { IMembershipSource } from "../ports.js";
@@ -5,7 +5,10 @@
5
5
  * a threshold-signed message:
6
6
  *
7
7
  * 1. takes the message's `signers`, the cohort `coord` the signers should belong to, and the tier;
8
- * 2. looks up the cached `MembershipCertV1` for that coord (or pulls the source's `current`);
8
+ * 2. looks up the cached `MembershipCertV1` for that coord (or pulls the source's `current`); a
9
+ * fetched cert is considered only if its own `cohortCoord` names that coord — a cert for any other
10
+ * coord is treated as no cert, since the trust gate and the cache would otherwise be consulted for
11
+ * the coord the cert names rather than the one being verified;
9
12
  * 3. checks the signers are a `≥ minSigs` subset of the cert's members and the signature verifies;
10
13
  * 4. **on failure against a cached/stale cert, re-fetches the cert from any cohort member exactly
11
14
  * once and retries**; still failing → the message is untrusted.
@@ -14,7 +17,8 @@
14
17
  * is a `≥ minSigs` quorum over its own `members`) proves only internal well-formedness — *not* that the
15
18
  * attesting key set is the legitimate cohort for the coord. An adversary controlling `k − x` keys could
16
19
  * mint a self-consistent cert over a coord it does not own. So before a (re)fetched cert is believed,
17
- * {@link CachingMembershipVerifier.certIsTrusted} requires it to be self-consistent **AND** anchored by
20
+ * the gate ({@link CachingMembershipVerifier.directVerdict}, then
21
+ * {@link CachingMembershipVerifier.certIsTrusted}) requires it to be self-consistent **AND** anchored by
18
22
  * at least one of:
19
23
  *
20
24
  * - **Trust root** — `(coord, epoch, member-set)` is in the out-of-band-seeded {@link TrustRoot} set
@@ -33,23 +37,45 @@
33
37
  * behavior, so there is strictly no regression on coords no node can verify today (distant T2/T3, and
34
38
  * T0/T1 until the committed-index binding lands). Once a coord *does* hold a trusted cert, the chain
35
39
  * governs successors: an un-anchored cert for an already-trusted coord is rejected (no TOFU downgrade),
36
- * which is what gives the rotation chain its teeth. The FRET / tx-log direct-anchor bindings that close
37
- * the remaining TOFU gap are tracked in `cohort-topic-trust-anchor-fret-binding` and the backlog
38
- * `...-fret-stabilization-proof` / `...-txlog-committed-binding` tickets.
40
+ * which is what gives the rotation chain its teeth. Two direct-anchor bindings in db-p2p close parts of
41
+ * the gap: `FretTrustAnchor` judges a coord this node serves against its own ring view, and
42
+ * `CommitLogTrustAnchor` judges a reactivity root — a root-placed coord whose placement names its key —
43
+ * against the tail block's commit proof, fetched from the tail's storage group, so a distant subscriber
44
+ * is anchored too. What remains TOFU is a distant coord under neither (other T2/T3 coords a node does
45
+ * not serve, tracked in the backlog `...-fret-stabilization-proof`, and T0/T1 until
46
+ * `...-txlog-committed-binding`).
47
+ *
48
+ * **The gate waits only for the direct verdict.** `directAnchor` may return a promise (the commit-log
49
+ * anchor asks the network), so the gate is in two steps: {@link CachingMembershipVerifier.directVerdict}
50
+ * (self-consistency, trust roots, the direct anchor — nothing that reads per-coord state) is awaited by
51
+ * `loadFrom`, and {@link CachingMembershipVerifier.certIsTrusted} then decides synchronously. Everything
52
+ * that reads or writes the per-coord maps runs after that one `await`, in one synchronous turn with the
53
+ * cache write — see the comment at the `await`.
39
54
  *
40
55
  * **Deviation from the ticket sketch (documented):** `verifyMessage` takes the cohort `tier`. A coord
41
56
  * is an opaque hash, so the T0/T1-vs-T2/T3 source dispatch the same ticket mandates cannot be derived
42
57
  * from the coord alone; the caller already knows the tier (it computed the coord from the message's
43
58
  * claimed tier/topic). The `tier` is threaded into the gate so the direct anchor is consulted with the
44
59
  * same tier the router used (the binding is tier-scoped).
60
+ *
61
+ * **Root-placed coords (§Tier addressing → Root placement at a routing key).** Everything above says
62
+ * "`≥ minSigs`" for the node-wide threshold. The root of a root-placed topic is a different kind of
63
+ * cohort — the group responsible for a routing key, typically smaller than `minSigs` — so a caller that
64
+ * knows the coord is root-placed passes a {@link RootPlacement}, and the verifier then uses
65
+ * `ceil(members × quorumRatio)` of the cert being checked against for **every** threshold it applies at
66
+ * that coord: the cert's self-consistency, the rotation-chain quorum (over the predecessor's members),
67
+ * and the message itself. The ratio is the caller's own configuration, never read off a message or cert.
68
+ * The placement is also handed to the membership source and the direct anchor, which need it to find
69
+ * and judge the root group. A cached cert remembers the rule it was validated under, and a call under a
70
+ * different rule does not see it — see {@link CachingMembershipVerifier.heldUnder}.
45
71
  */
46
72
 
47
- import type { IMembershipTrustAnchor, RingCoord, TrustRoot } from "../ports.js";
73
+ import type { IMembershipTrustAnchor, MembershipLookupOptions, RingCoord, RootPlacement, TrustAnchorVerdict, TrustRoot } from "../ports.js";
48
74
  import { noAuthorityTrustAnchor } from "../ports.js";
49
75
  import { b64urlToBytes, bytesToB64url, decodeMembershipCertV1 } from "../wire/codec.js";
50
76
  import { CohortWireError } from "../wire/validate.js";
51
77
  import type { MembershipCertV1 } from "../wire/types.js";
52
- import { DEFAULT_MIN_SIGS, type CohortSigner } from "../sig/threshold.js";
78
+ import { DEFAULT_MIN_SIGS, rootPlacedMinSigs, type CohortSigner } from "../sig/threshold.js";
53
79
  import { membershipCertSigningPayload } from "../sig/payloads.js";
54
80
  import type { IMembershipSourceRouter } from "./source.js";
55
81
  import { LruMap } from "../../utility/lru-map.js";
@@ -67,8 +93,12 @@ export type VerifyResult = "verified" | "untrusted";
67
93
 
68
94
  /** Caches certs per coord and verifies threshold-signed messages with one stale-cert refetch. */
69
95
  export interface MembershipVerifier {
70
- /** Cache `cert` as the latest known membership for its coord. */
71
- cache(cert: MembershipCertV1): void;
96
+ /**
97
+ * Cache `cert` as the latest known membership for its coord. `placement` is the rule the cert was
98
+ * published under — pass it for a root-placed coord, so later calls carrying the same placement use
99
+ * the entry; omit it for every other coord.
100
+ */
101
+ cache(cert: MembershipCertV1, placement?: RootPlacement): void;
72
102
  /**
73
103
  * Drop everything cached for `cohortCoord` (base64url form, as on a cert's `cohortCoord`): the cached
74
104
  * cert — including a *trusted* self-published one, i.e. the trust lock — and any stale-gap strike
@@ -88,8 +118,11 @@ export interface MembershipVerifier {
88
118
  * Eventual refetch is *preserved*: a cold cache or a membership rotation still re-fetches once the
89
119
  * interval elapses (unlike outright suppression). Omit `opts` (the default, and every existing caller)
90
120
  * for the unbounded exactly-one-refetch behavior.
121
+ *
122
+ * `opts.placement` declares `expectedCoord` root-placed: the threshold is then
123
+ * `ceil(members × quorumRatio)` instead of the verifier's `minSigs` (see the module header).
91
124
  */
92
- verifyMessage(signers: readonly Uint8Array[], expectedCoord: RingCoord, tier: number, payload: Uint8Array, sig: Uint8Array, opts?: RefetchBound): Promise<VerifyResult>;
125
+ verifyMessage(signers: readonly Uint8Array[], expectedCoord: RingCoord, tier: number, payload: Uint8Array, sig: Uint8Array, opts?: VerifyMessageOptions): Promise<VerifyResult>;
93
126
  }
94
127
 
95
128
  /**
@@ -103,6 +136,16 @@ export interface RefetchBound {
103
136
  readonly now?: number;
104
137
  }
105
138
 
139
+ /** Per-call options of {@link MembershipVerifier.verifyMessage}: the refetch bound, plus the coord's placement. */
140
+ export interface VerifyMessageOptions extends RefetchBound {
141
+ /**
142
+ * Present when `expectedCoord` is the root of a root-placed topic. Its threshold is then
143
+ * `ceil(cert.members.length × quorumRatio)` — the formula a storage group's commit certificate uses —
144
+ * rather than the verifier's constructor `minSigs`. Build it with `createRootPlacement`.
145
+ */
146
+ readonly placement?: RootPlacement;
147
+ }
148
+
106
149
  export interface MembershipVerifierDeps {
107
150
  signer: CohortSigner;
108
151
  router: IMembershipSourceRouter;
@@ -154,6 +197,11 @@ interface CachedCert {
154
197
  cert: MembershipCertV1;
155
198
  /** True only when the cert passed via trust-root / direct-anchor / chain, or was self-published (`cache`). */
156
199
  trusted: boolean;
200
+ /**
201
+ * The threshold rule the cert was validated (or self-published) under: the root-placement quorum ratio,
202
+ * or `undefined` for the default `minSigs` rule. See {@link CachingMembershipVerifier.heldUnder}.
203
+ */
204
+ quorumRatio: number | undefined;
157
205
  }
158
206
 
159
207
  /** A {@link TrustRoot} pre-normalized to the cert's base64url form for cheap matching. */
@@ -200,10 +248,10 @@ class CachingMembershipVerifier implements MembershipVerifier {
200
248
  this.staleGapStrikes = new LruMap(maxCoords);
201
249
  }
202
250
 
203
- cache(cert: MembershipCertV1): void {
251
+ cache(cert: MembershipCertV1, placement?: RootPlacement): void {
204
252
  // The public cache feeds this node its OWN freshly-published cert — a node trusts a cert it itself
205
253
  // published, so it is marked trusted and may anchor the next rotation in the attestation chain.
206
- this.byCoord.set(cert.cohortCoord, { cert, trusted: true });
254
+ this.byCoord.set(cert.cohortCoord, { cert, trusted: true, quorumRatio: placement?.quorumRatio });
207
255
  }
208
256
 
209
257
  forget(cohortCoord: string): void {
@@ -224,17 +272,20 @@ class CachingMembershipVerifier implements MembershipVerifier {
224
272
  this.staleGapStrikes.delete(cohortCoord);
225
273
  }
226
274
 
227
- async verifyMessage(signers: readonly Uint8Array[], expectedCoord: RingCoord, tier: number, payload: Uint8Array, sig: Uint8Array, opts?: RefetchBound): Promise<VerifyResult> {
275
+ async verifyMessage(signers: readonly Uint8Array[], expectedCoord: RingCoord, tier: number, payload: Uint8Array, sig: Uint8Array, opts?: VerifyMessageOptions): Promise<VerifyResult> {
228
276
  const coordKey = bytesToB64url(expectedCoord);
229
277
  const source = this.deps.router.for(tier);
278
+ const placement = opts?.placement;
279
+ const lookup = lookupOptionsFor(placement);
230
280
 
231
281
  // Seed from the cheap cached view if we hold nothing yet. A cached cert already passed the gate when
232
- // it was loaded (or was self-published via `cache`), so it is used directly for message verification.
233
- let cert = this.byCoord.get(coordKey)?.cert;
282
+ // it was loaded (or was self-published via `cache`), so it is used directly for message verification
283
+ // — provided it passed under the rule this call applies (see `heldUnder`).
284
+ let cert = this.heldUnder(coordKey, placement)?.cert;
234
285
  if (cert === undefined) {
235
- cert = await this.loadFrom(source.current(expectedCoord), tier);
286
+ cert = await this.loadFrom(source.current(expectedCoord, lookup), coordKey, tier, placement);
236
287
  }
237
- if (cert !== undefined && this.messageVerifies(cert, signers, payload, sig)) {
288
+ if (cert !== undefined && this.messageVerifies(cert, signers, payload, sig, placement)) {
238
289
  this.staleGapStrikes.delete(coordKey); // a verify resets the consecutive stale-gap strike count
239
290
  return "verified";
240
291
  }
@@ -247,14 +298,31 @@ class CachingMembershipVerifier implements MembershipVerifier {
247
298
  if (!this.refetchAllowed(coordKey, opts)) {
248
299
  return "untrusted";
249
300
  }
250
- const refreshed = await this.loadFrom(source.fetch(expectedCoord), tier);
251
- if (refreshed !== undefined && this.messageVerifies(refreshed, signers, payload, sig)) {
301
+ const refreshed = await this.loadFrom(source.fetch(expectedCoord, lookup), coordKey, tier, placement);
302
+ if (refreshed !== undefined && this.messageVerifies(refreshed, signers, payload, sig, placement)) {
252
303
  this.staleGapStrikes.delete(coordKey); // a verify resets the consecutive stale-gap strike count
253
304
  return "verified";
254
305
  }
255
306
  return "untrusted";
256
307
  }
257
308
 
309
+ /**
310
+ * The cached entry for `coordKey`, **only if it was validated under the rule this call applies** — the
311
+ * same root-placement ratio, or both the default rule. An entry held under any other rule reads as
312
+ * absent, for every purpose: message verification, the attestation-chain predecessor, and the trust
313
+ * lock. So a cert that passed one threshold is never taken as having passed another, and the call
314
+ * re-validates from the source under its own rule instead.
315
+ */
316
+ private heldUnder(coordKey: string, placement: RootPlacement | undefined): CachedCert | undefined {
317
+ const held = this.byCoord.get(coordKey);
318
+ return held !== undefined && held.quorumRatio === placement?.quorumRatio ? held : undefined;
319
+ }
320
+
321
+ /** The signature threshold over `cert`'s members: `ceil(members × quorumRatio)` for a root-placed coord, else the node-wide `minSigs`. */
322
+ private minSigsFor(cert: MembershipCertV1, placement: RootPlacement | undefined): number {
323
+ return placement === undefined ? this.minSigs : rootPlacedMinSigs(cert.members.length, placement);
324
+ }
325
+
258
326
  /**
259
327
  * Whether a `source.fetch()` refetch is permitted for `coordKey` now. Unbounded (always `true`) unless
260
328
  * the caller supplies both `minRefetchIntervalMs` and `now`, in which case at most one refetch per coord
@@ -277,11 +345,14 @@ class CachingMembershipVerifier implements MembershipVerifier {
277
345
 
278
346
  /**
279
347
  * Decode an encoded cert, run it through the trust gate, cache it (with its trusted status), and return
280
- * it for message verification; `undefined` if absent, malformed, or rejected by the gate. A rejected
281
- * cert (failed self-consistency, a `"rejected"` direct anchor, or an un-anchored cert for an
282
- * already-trusted coord) is treated exactly like an absent cert, so the single refetch still fires.
348
+ * it for message verification; `undefined` if absent, malformed, for a coord other than `coordKey`, or
349
+ * rejected by the gate. A rejected cert (failed self-consistency, a `"rejected"` direct anchor, or an
350
+ * un-anchored cert for an already-trusted coord) is treated exactly like an absent cert, so the single
351
+ * refetch still fires. The coord check runs before the gate: the gate, the direct anchor and the cache
352
+ * are all keyed on the cert's own `cohortCoord`, so a self-consistent cert for an unrelated coord would
353
+ * otherwise pass as trust-on-first-use there and then verify a message for `coordKey`.
283
354
  */
284
- private async loadFrom(pending: Promise<Uint8Array | undefined>, tier: number): Promise<MembershipCertV1 | undefined> {
355
+ private async loadFrom(pending: Promise<Uint8Array | undefined>, coordKey: string, tier: number, placement: RootPlacement | undefined): Promise<MembershipCertV1 | undefined> {
285
356
  const encoded = await pending;
286
357
  if (encoded === undefined) {
287
358
  return undefined;
@@ -290,7 +361,17 @@ class CachingMembershipVerifier implements MembershipVerifier {
290
361
  let trust: CertTrust;
291
362
  try {
292
363
  cert = decodeMembershipCertV1(encoded, this.deps.maxMessageBytes);
293
- trust = this.certIsTrusted(cert, tier);
364
+ if (cert.cohortCoord !== coordKey) {
365
+ return undefined;
366
+ }
367
+ // The last `await` on the load path, and it has to be in this function. Two loads of one coord can
368
+ // be in flight across it, so everything that reads or writes `byCoord` / `staleGapStrikes` — the
369
+ // gate's chain, fallback and stale-gap recovery, then the `lockedUnderAnotherRule` read and the
370
+ // cache write below — runs after it in one synchronous turn. Awaiting an async gate here instead
371
+ // puts a microtask between the gate's reads and the write, and a second load's first-use check
372
+ // then misses the lock this load is about to write.
373
+ const direct = await this.directVerdict(cert, tier, placement);
374
+ trust = this.certIsTrusted(cert, direct, placement);
294
375
  } catch (err) {
295
376
  if (err instanceof CohortWireError) {
296
377
  return undefined; // a malformed cert (or non-base64url signer) is treated as no cert
@@ -300,37 +381,68 @@ class CachingMembershipVerifier implements MembershipVerifier {
300
381
  if (trust === "reject") {
301
382
  return undefined;
302
383
  }
384
+ if (this.lockedUnderAnotherRule(cert.cohortCoord, placement)) {
385
+ return cert; // usable for this call's message check, but it must not displace the lock
386
+ }
303
387
  // Only a `"trusted"` cert may anchor a successor in the attestation chain; a `"tofu"` cert is cached
304
388
  // for message verification but must never launder trust into a rotation.
305
- this.byCoord.set(cert.cohortCoord, { cert, trusted: trust === "trusted" });
389
+ this.byCoord.set(cert.cohortCoord, { cert, trusted: trust === "trusted", quorumRatio: placement?.quorumRatio });
306
390
  return cert;
307
391
  }
308
392
 
309
393
  /**
310
- * The trust gate (see the module header). A cert is accepted iff it is self-consistent **and** anchored
311
- * by a trust root, the direct anchor, or the attestation chain; otherwise it falls to the interim TOFU
312
- * fallback (first-use only). Returns whether the cert is a trusted anchor (`"trusted"`), an interim
313
- * TOFU acceptance (`"tofu"`), or rejected (`"reject"`).
394
+ * Whether the coord holds a **trusted** cert validated under a rule other than this call's. Such an entry
395
+ * is invisible to this call ({@link heldUnder}), so the trust gate ran as if the coord were cold and may
396
+ * have accepted the cert on first use. Caching that result would erase the trust lock through a side
397
+ * door — a call under one rule downgrading what another rule established — so it is used for the
398
+ * current message only.
399
+ *
400
+ * NOTE: a coord has one rule by construction (it follows from how the coord was derived), so two rules
401
+ * meeting at one coord is an anomaly, and the cost here — a source read on every call under the second
402
+ * rule — is not paid in normal operation. If it ever is, key the cache by `(coord, rule)` instead.
314
403
  */
315
- private certIsTrusted(cert: MembershipCertV1, tier: number): CertTrust {
316
- if (!this.certIsSelfConsistent(cert)) {
317
- return "reject"; // internal well-formedness is the precondition for any trust path
404
+ private lockedUnderAnotherRule(coordKey: string, placement: RootPlacement | undefined): boolean {
405
+ const held = this.byCoord.get(coordKey);
406
+ return held !== undefined && held.trusted && held.quorumRatio !== placement?.quorumRatio;
407
+ }
408
+
409
+ /**
410
+ * The first step of the trust gate: what can be said of a cert without reading per-coord state. A cert
411
+ * that is not self-consistent is `"rejected"` (internal well-formedness is the precondition for any trust
412
+ * path), one matching a configured genesis root is `"anchored"` (authoritative, checked before the direct
413
+ * anchor), and otherwise the direct anchor decides. This is the only step that may wait — the anchor may
414
+ * ask the network — which is why it reads none of the per-coord maps: self-consistency is pure and the
415
+ * trust roots are fixed at construction. Keep it that way.
416
+ */
417
+ private async directVerdict(cert: MembershipCertV1, tier: number, placement: RootPlacement | undefined): Promise<TrustAnchorVerdict> {
418
+ if (!this.certIsSelfConsistent(cert, placement)) {
419
+ return "rejected";
318
420
  }
319
421
  if (this.matchesTrustRoot(cert)) {
320
- return "trusted"; // a configured genesis root is authoritative, checked before the direct anchor
422
+ return "anchored";
321
423
  }
322
- const verdict = this.anchor.directAnchor(cert, tier);
323
- if (verdict === "anchored") {
424
+ return this.anchor.directAnchor(cert, tier, placement);
425
+ }
426
+
427
+ /**
428
+ * The trust gate (see the module header), given the cert's {@link directVerdict}. A cert is accepted iff
429
+ * it is self-consistent **and** anchored by a trust root, the direct anchor, or the attestation chain;
430
+ * otherwise it falls to the interim TOFU fallback (first-use only). Returns whether the cert is a trusted
431
+ * anchor (`"trusted"`), an interim TOFU acceptance (`"tofu"`), or rejected (`"reject"`). Synchronous on
432
+ * purpose: it reads the per-coord maps, and `loadFrom` runs it in the same turn as its cache write.
433
+ */
434
+ private certIsTrusted(cert: MembershipCertV1, direct: TrustAnchorVerdict, placement: RootPlacement | undefined): CertTrust {
435
+ if (direct === "anchored") {
324
436
  return "trusted";
325
437
  }
326
- if (verdict === "rejected") {
438
+ if (direct === "rejected") {
327
439
  return "reject"; // a contradicted binding is a forgery — fatal, overrides the TOFU fallback
328
440
  }
329
- // verdict === "unknown": no local authority for this coord. Try the attestation chain, else fall back.
330
- if (this.hasRotationAttestation(cert) && this.chainGrantsTrust(cert)) {
441
+ // direct === "unknown": no local authority for this coord. Try the attestation chain, else fall back.
442
+ if (this.hasRotationAttestation(cert) && this.chainGrantsTrust(cert, placement)) {
331
443
  return "trusted";
332
444
  }
333
- const fallback = this.fallbackTrust(cert);
445
+ const fallback = this.fallbackTrust(cert, placement);
334
446
  if (fallback !== "reject") {
335
447
  return fallback; // first-use TOFU (coord not locked): no stale lock to recover from
336
448
  }
@@ -338,7 +450,7 @@ class CachingMembershipVerifier implements MembershipVerifier {
338
450
  // did not chain-verify — the state that strands a former cohort member forever. Consult the stale-gap
339
451
  // recovery counter, which releases the lock only on a demonstrated chain gap (never a forged rotation
340
452
  // off the current predecessor). See {@link staleGapRecovery}.
341
- return this.staleGapRecovery(cert);
453
+ return this.staleGapRecovery(cert, placement);
342
454
  }
343
455
 
344
456
  /**
@@ -361,9 +473,9 @@ class CachingMembershipVerifier implements MembershipVerifier {
361
473
  * reach the source, so a {@link RefetchBound}-suppressed refetch observes no cert and recovery paces itself
362
474
  * with the (bounded) refetch rate — intended, do not "fix" that pacing.
363
475
  */
364
- private staleGapRecovery(cert: MembershipCertV1): CertTrust {
476
+ private staleGapRecovery(cert: MembershipCertV1, placement: RootPlacement | undefined): CertTrust {
365
477
  const coordKey = cert.cohortCoord;
366
- const locked = this.byCoord.get(coordKey);
478
+ const locked = this.heldUnder(coordKey, placement);
367
479
  // Recovery-eligible only on an explicit rotation gap: a full attestation whose prevEpoch is neither the
368
480
  // cert's own epoch (a self-referential rotation) nor the cached trusted epoch (a forgery off the current
369
481
  // predecessor — the case the lock exists to reject).
@@ -394,8 +506,8 @@ class CachingMembershipVerifier implements MembershipVerifier {
394
506
  * cert (a failed/absent rotation, including a forged rotation off a trusted predecessor) is **rejected**
395
507
  * — no silent TOFU downgrade — which is what gives the attestation chain its teeth.
396
508
  */
397
- private fallbackTrust(cert: MembershipCertV1): CertTrust {
398
- return this.byCoord.get(cert.cohortCoord)?.trusted ? "reject" : "tofu";
509
+ private fallbackTrust(cert: MembershipCertV1, placement: RootPlacement | undefined): CertTrust {
510
+ return this.heldUnder(cert.cohortCoord, placement)?.trusted ? "reject" : "tofu";
399
511
  }
400
512
 
401
513
  /** Whether a cert carries a full rotation attestation (all three fields; validated all-or-nothing on the wire). */
@@ -409,12 +521,12 @@ class CachingMembershipVerifier implements MembershipVerifier {
409
521
  * quorum over this cert's signing payload via `rotationSig`. A predecessor that only reached the cache via
410
522
  * TOFU (not trusted) must not anchor the successor — the trusted-cache invariant.
411
523
  */
412
- private chainGrantsTrust(cert: MembershipCertV1): boolean {
524
+ private chainGrantsTrust(cert: MembershipCertV1, placement: RootPlacement | undefined): boolean {
413
525
  const prevEpoch = cert.prevEpoch!;
414
526
  if (prevEpoch === cert.cohortEpoch) {
415
527
  return false; // a cert cannot rotate from itself
416
528
  }
417
- const predecessor = this.byCoord.get(cert.cohortCoord);
529
+ const predecessor = this.heldUnder(cert.cohortCoord, placement);
418
530
  if (predecessor === undefined || !predecessor.trusted || predecessor.cert.cohortEpoch !== prevEpoch) {
419
531
  return false;
420
532
  }
@@ -425,7 +537,8 @@ class CachingMembershipVerifier implements MembershipVerifier {
425
537
  b64urlToBytes(cert.rotationSig!),
426
538
  cert.rotationSigners!.map((s) => b64urlToBytes(s)),
427
539
  predecessor.cert,
428
- this.minSigs,
540
+ // The rotation is signed by the PREDECESSOR cohort, so the quorum is counted over its members.
541
+ this.minSigsFor(predecessor.cert, placement),
429
542
  );
430
543
  }
431
544
 
@@ -440,7 +553,7 @@ class CachingMembershipVerifier implements MembershipVerifier {
440
553
  }
441
554
 
442
555
  /** A cert is self-consistent only if its own threshold signature is a valid quorum of its members. */
443
- private certIsSelfConsistent(cert: MembershipCertV1): boolean {
556
+ private certIsSelfConsistent(cert: MembershipCertV1, placement: RootPlacement | undefined): boolean {
444
557
  // `signers` is validated only as a string array (not per-element base64url), so `b64urlToBytes`
445
558
  // below may throw `CohortWireError` on a malformed signer — `loadFrom`'s try/catch turns that
446
559
  // into "no cert" rather than letting it escape.
@@ -449,15 +562,20 @@ class CachingMembershipVerifier implements MembershipVerifier {
449
562
  b64urlToBytes(cert.thresholdSig),
450
563
  cert.signers.map((s) => b64urlToBytes(s)),
451
564
  cert,
452
- this.minSigs,
565
+ this.minSigsFor(cert, placement),
453
566
  );
454
567
  }
455
568
 
456
- private messageVerifies(cert: MembershipCertV1, signers: readonly Uint8Array[], payload: Uint8Array, sig: Uint8Array): boolean {
457
- return this.deps.signer.verifyThreshold(payload, sig, signers, cert, this.minSigs);
569
+ private messageVerifies(cert: MembershipCertV1, signers: readonly Uint8Array[], payload: Uint8Array, sig: Uint8Array, placement: RootPlacement | undefined): boolean {
570
+ return this.deps.signer.verifyThreshold(payload, sig, signers, cert, this.minSigsFor(cert, placement));
458
571
  }
459
572
  }
460
573
 
574
+ /** The membership-source options for a call: `{ rootPlaced: true }` under a placement, none otherwise. */
575
+ function lookupOptionsFor(placement: RootPlacement | undefined): MembershipLookupOptions | undefined {
576
+ return placement === undefined ? undefined : { rootPlaced: true };
577
+ }
578
+
461
579
  /** Pre-normalize a {@link TrustRoot} (raw bytes) to the cert's base64url form for cheap matching. */
462
580
  function normalizeTrustRoot(root: TrustRoot): NormalizedTrustRoot {
463
581
  return {