1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Per-client durable inbox — the bus's delivery boundary (DOC-60 §7, #6462).
//!
//! Why: until #6462 every subscriber of one instance shared a single 64-slot
//! `tokio::sync::broadcast` ring. `broadcast` measures backlog across ALL
//! attached receivers and cannot send to a subset, so #6461 could keep the §9
//! log truthful only by refusing the publish — which made one client that
//! stops reading refuse every publish to that instance, healthy co-subscribers
//! included, for as long as it stayed attached. Owner ruling on #6462: bound
//! that. Giving each subscription its own buffer moves the delivery boundary
//! from the instance to the client, so a stalled client's backlog is its own
//! problem and costs the instance memory rather than its availability. What it
//! costs exactly is stated below — bounded in the availability sense that
//! matters, but neither zero nor always self-limiting.
//! What: [`ClientInbox`], one bounded queue per subscription; [`InboxSet`],
//! the per-instance fan-out that owns them; [`InboxSubscription`], the reader
//! handle that detaches on drop; and [`InboxMiss`], the §9 record that keeps a
//! loss from being a silent one.
//! Test: `bus::tests` — `a_wedged_client_does_not_refuse_publishes_for_a_healthy_co_subscriber`,
//! `eviction_is_recorded_per_client_in_the_durable_log`,
//! `concurrent_publishers_lose_nothing_without_a_record`,
//! `a_detached_subscription_stops_costing_the_instance`.
//!
//! ## Eviction policy, and the two points DOC-60 §7 does not settle
//!
//! §7 specifies a durable inbox and its replay-on-connect recovery. It does
//! not state a per-client buffer depth, nor which envelope loses when a live
//! client's buffer is full. Both are settled here in the direction that keeps
//! the §9 log answerable, which is §4's actual requirement:
//!
//! 1. **Depth is [`CLIENT_INBOX_CAPACITY`], per subscription.** It carries the
//! retired shared ring's depth forward unchanged, so an instance's worst
//! case grows with the number of attached clients rather than staying fixed
//! — which is the point: a wedged client can no longer spend anyone else's
//! budget.
//! 2. **The OLDEST unread envelope loses, and the loss is recorded.** #4271's
//! defect was never the eviction; it was the lie — the log said `delivered`
//! and nobody was told. Every eviction here writes an [`InboxMiss`] to
//! the §9 stream naming the displaced `message_id` and the subscription that
//! lost it, and the reader gets an [`InboxItem::Lagged`] at the point of
//! loss. Refusing the NEWEST envelope instead would leave a recovering
//! client reading stale traffic forever with no way to catch up, and would
//! put the refusal back on the publisher — the wedge #6462 exists to remove.
//!
//! Recovery is unchanged from #6461 and is what makes eviction survivable: the
//! §9 JSONL stream holds every envelope, so a client that sees a `lagged` frame
//! re-reads the log from its last known `message_id`. The frame names the log's
//! path and the subscription id, which is the key its [`InboxMiss`] records are
//! written under.
//!
//! ## What a permanently wedged client actually costs
//!
//! A client that stops reading and then goes away costs nothing:
//! [`InboxSubscription::drop`] detaches its inbox and frees what it never read.
//!
//! A client that stops reading and STAYS is the case #6462 was opened for, and
//! its cost is ongoing. When an SSE peer's TCP window fills, hyper stops
//! polling the response body but does not drop the future, so the subscription
//! is never dropped and `Drop` never runs. From then on the instance carries
//! that client's [`CLIENT_INBOX_CAPACITY`]-envelope buffer AND pays, on every
//! subsequent publish to that instance, one [`InboxMiss`] line in the durable
//! §9 stream plus one `warn!` — durable-log growth and log volume proportional
//! to publish rate, for as long as the wedged client stays attached. That is
//! deliberate: the alternative levers (a reaper, an idle timer, a cap on
//! subscriptions) are the policy call #6462's review promoted to the owner,
//! not decisions this change makes.
//!
//! **The operator's lever is deregistering the instance**
//! (`DELETE /api/v1/bus/instances/{instance_id}`), which closes every
//! subscription and stops the fan-out. The `warn!` names the instance and the
//! subscription on every miss, so a wedged client is identifiable from the
//! daemon log without a new diagnostic.
//!
//! What is gone either way is the AVAILABILITY cost: no publisher is refused
//! and no co-subscriber is slowed, however long the wedge lasts.
use VecDeque;
use Arc;
use Mutex;
use ;
use ;
use Notify;
use BusEnvelope;
/// How many envelopes ONE subscription buffers before it displaces its oldest.
///
/// Why: peer messages are low-volume by construction — DOC-60 §3 keeps
/// streaming token deltas on the existing per-crate buses — so a shallow
/// buffer is right, and it is what bounds a never-polling client's cost. This
/// is the depth the retired shared ring had, now applied per client so one
/// client's backlog is charged to that client.
///
/// Public because it is part of the delivery contract a subscriber reasons
/// about: fall this far behind and the next envelope displaces your oldest.
/// Test: `eviction_is_recorded_per_client_in_the_durable_log`.
pub const CLIENT_INBOX_CAPACITY: usize = 64;
/// The `record` discriminator on an [`InboxMiss`] line in the §9 stream.
///
/// Why: the durable stream now carries two record shapes. A reader that
/// deserializes every line as a [`BusEnvelope`] must be able to tell them apart
/// without guessing, and an envelope record has no `record` field at all — so
/// presence of this key IS the discriminator.
/// Test: `miss_records_are_distinguishable_from_envelopes`.
pub const INBOX_MISS_RECORD: &str = "inbox_miss";
/// What one read from an inbox yields.
///
/// Why: a subscriber needs to learn about a gap AT the gap, not after the
/// fact — that is the whole content of #4271's SSE half. Making the gap a
/// value in the same stream as the envelopes puts it in order by construction.
/// What: an envelope, or the count this subscription lost since its last read.
/// The envelope is boxed because it is an order of magnitude larger than the
/// counter and the enum would otherwise be sized by its rare variant.
/// Test: `a_stalled_subscriber_reads_its_lag_before_the_surviving_envelopes`.
/// One envelope one subscription will never read, with its §9 record's facts.
///
/// Why: the miss happens inside the fan-out, under the instance's lock, but the
/// durable write belongs to [`PeerBus::publish`](super::PeerBus::publish) —
/// which owns the logger and the ordering. Handing the facts out as a value
/// keeps the IO out of the guarded section without losing what was lost.
/// What: the lost envelope, the subscription that lost it, and why.
/// Test: `eviction_is_recorded_per_client_in_the_durable_log`.
/// The §9 record written when one client will never read an envelope.
///
/// Why: DOC-60 §4 forbids an outcome the sender and the operator cannot
/// distinguish, and #4271 is what that looks like when it is violated — a
/// `delivered` record for an envelope its recipient never saw. A miss is not a
/// delivery failure (co-subscribers may well have read it), so it is not a
/// second `delivery_state` on the envelope; it is a separate fact about one
/// subscription, and it is recorded as one.
/// What: the lost `message_id`, the subscription that lost it, and that
/// subscription's running loss count — enough to reconstruct exactly what any
/// one client did and did not see by replaying the stream.
///
/// Displacement is the only thing that produces one. A subscription closed by a
/// deregistration also loses envelopes, but never alongside a client that took
/// them: [`InboxSet`]'s terminal flag makes a set all-open or all-closed, so a
/// fan-out into a closed set accepts nothing, and `publish` records THAT
/// envelope `dropped` — which already says it reached no one. The record is
/// named for the fact (one client will not read this) rather than the mechanism,
/// so a second cause would not need a second shape.
/// Test: `eviction_is_recorded_per_client_in_the_durable_log`,
/// `miss_records_are_distinguishable_from_envelopes`.
/// The mutable half of one inbox.
/// One subscription's bounded, per-client buffer.
///
/// Why: see the module doc — this is what moves the delivery boundary off the
/// instance. Each inbox is written by publishers under [`InboxSet`]'s lock and
/// read by exactly one reader, the [`InboxSubscription`] that owns it.
/// What: a bounded [`VecDeque`] plus the lag counters, behind one mutex, with a
/// [`Notify`] the single reader parks on.
/// Test: `eviction_is_recorded_per_client_in_the_durable_log`,
/// `a_stalled_subscriber_reads_its_lag_before_the_surviving_envelopes`.
/// Every inbox attached to one instance, and the fan-out over them.
///
/// Why: the instance-level lock survives the move to per-client buffers, but
/// its job changes. It no longer gates delivery on the slowest reader — it
/// makes ONE publish's fan-out indivisible, so two concurrent publishers cannot
/// interleave and hand two clients the same two envelopes in opposite orders.
/// That is the ordering guarantee the retired broadcast ring gave for free and
/// that `two_subscribers_one_lagging_account_exactly` pins.
/// What: the attached inboxes, the set's own terminal flag, and the
/// subscription-id source. Attach, detach, close, and fan-out all take the same
/// lock; a reader takes only its own inbox's.
/// Test: `two_subscribers_one_lagging_account_exactly`,
/// `concurrent_publishers_lose_nothing_without_a_record`,
/// `a_subscription_attached_after_deregistration_ends_rather_than_parking`.
/// The fan-out lock's contents.
///
/// Why `closed` lives HERE rather than beside the inboxes as a separate atomic
/// (#6462 review): [`InboxSet::attach`] and [`InboxSet::close_all`] must not
/// interleave. `close_all` closes the inboxes present when it takes the lock;
/// an `attach` landing a moment later used to push a fresh OPEN inbox into a
/// set nothing would ever close again — its instance is already out of the
/// registry, so no publisher can reach it and no second deregister can fire.
/// The reader then parked forever and its SSE stream never ended, which the
/// retired `broadcast` did not do (the last `Sender` dropped and the stream
/// yielded `None`). Putting the flag under the same guard as the vector makes
/// the race unrepresentable rather than unlikely.
/// What: the attached inboxes plus whether this set has been terminated.
/// Test: `a_subscription_attached_after_deregistration_ends_rather_than_parking`.
/// What one fan-out actually did.
///
/// Why: the publisher must write a durable record stating what happened, and
/// the two outcomes carry different records and different answers to the
/// sender. Since #6462 a slow subscriber is no longer one of them: it cannot
/// refuse a publish, so the `Saturated` arm — and the `503` it produced — is
/// gone.
/// What: delivered to every attached inbox (naming whatever each displaced), or
/// nothing attached at all.
/// Test: `publish_without_subscriber_errors`,
/// `eviction_is_recorded_per_client_in_the_durable_log`.
/// What one inbox did with one envelope.
///
/// Why it is not `Option<MissedEnvelope>`: see [`ClientInbox::deliver`]. The
/// distinction between "took it" and "took nothing" is the one #6462's review
/// found missing, and an `Option` cannot carry it.
/// What: took it cleanly, took it by displacing its oldest, or refused it
/// because the subscription is closed. The displacement payload is boxed
/// because [`MissedEnvelope`] carries a whole envelope and the other two
/// variants carry nothing.
/// Test: `a_publish_racing_deregistration_is_not_recorded_delivered`.
/// One client's read handle on its inbox.
///
/// Why it owns the detach: a subscriber that goes away — an SSE body dropped
/// when the client disconnects — must stop being fanned out to and must stop
/// holding envelopes nobody will read. Tying that to `Drop` means no code path
/// can forget it, which is what keeps a disconnected client's cost at zero
/// rather than at [`CLIENT_INBOX_CAPACITY`] envelopes forever.
/// What: the inbox plus its set, with `recv`/`try_recv` over the former.
/// Exactly one of these exists per inbox, which is why the inbox's `Notify`
/// only ever needs to wake one reader.
/// Test: `a_detached_subscription_stops_costing_the_instance`,
/// `deregister_ends_a_subscription_after_it_drains`.