orbit-link 0.6.8

Named reusable duplex sessions between members of an Orbit fleet.
Documentation
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! Producer-owned claims. Kernel holds are acquired only by segment lifecycle
//! code. Admission and helping use bounded atomic operations on this table.

use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering, fence};

use super::{Error, Inbox, Result};

pub(super) const FREE: u64 = 0;
pub(super) const RESERVED: u64 = 1;
pub(super) const COMMITTED: u64 = 2;
pub(super) const CANCELLED: u64 = 3;
pub(super) const WRITING: u32 = 1;
pub(super) const REFERENCED: u32 = 2;

#[cfg(test)]
pub(super) fn checkpoint(phase: &str) {
    if std::env::var("ORBIT_LINK_CRASH_PHASE").as_deref() == Ok(phase) {
        // The isolated child owns this process; no atexit/Drop may run.
        #[cfg(unix)]
        unsafe {
            libc::raise(libc::SIGKILL);
        }
        std::process::abort();
    }
}

#[repr(C, align(64))]
struct Owner {
    generation: AtomicU64,
    pid: AtomicU32,
    active: AtomicU32,
    /// Nonzero while this registration waits for a reader to free one of its
    /// records. The reader that frees one clears it and rings the producer's
    /// bell; nobody rings while it is zero.
    waiting: AtomicU32,
    _padding: [u8; 44],
}

#[repr(C, align(64))]
struct Record {
    seq: AtomicU64,
    position: AtomicU64,
    incarnation: AtomicU64,
    generation: AtomicU64,
    lane: AtomicU32,
    flags: AtomicU32,
    _padding: [u8; 24],
}

const _: () = assert!(size_of::<Owner>() == 64);
const _: () = assert!(size_of::<Record>() == 64);

pub(super) const fn registry_bytes(
    lanes: usize,
    capacity: usize,
) -> usize {
    // A lane holder and a lane-less publisher each have a registration budget.
    2 * lanes * (size_of::<Owner>() + capacity * size_of::<Record>())
}

pub(super) struct Producer {
    index: usize,
    generation: u64,
    /// Process-local: the record after the one this producer took last.
    /// Records free in roughly FIFO order, so the scan starts here rather
    /// than passing every busy record from the start of the range.
    next: AtomicUsize,
    // Dropped with the Inbox, after all borrowed write operations have ended.
    #[cfg(unix)]
    _hold: orbit_core::shm::LaneHold,
}

#[derive(Clone, Copy)]
pub(super) struct Intent {
    pub(super) position: u64,
    pub(super) incarnation: u64,
    generation: u64,
    pub(super) lane: usize,
}

impl Record {
    fn snapshot(&self) -> Option<Intent> {
        let before = self.seq.load(Ordering::Acquire);
        if before & 1 != 0 {
            return None;
        }
        let intent = Intent {
            position: self.position.load(Ordering::Relaxed),
            incarnation: self.incarnation.load(Ordering::Relaxed),
            generation: self.generation.load(Ordering::Relaxed),
            lane: self.lane.load(Ordering::Relaxed) as usize,
        };
        fence(Ordering::Acquire);
        (before == self.seq.load(Ordering::Relaxed)).then_some(intent)
    }
}

pub(crate) struct Reservation<'a> {
    inbox: &'a Inbox,
    record: usize,
    pub(super) position: u64,
    pub(super) epoch: u64,
    lane: usize,
    pub(super) committed: bool,
}

impl Reservation<'_> {
    pub(super) fn claim(
        &self,
        state: u64,
    ) -> u64 {
        ((self.record as u64 + 1) << 2) | state
    }
}

impl Drop for Reservation<'_> {
    fn drop(&mut self) {
        if !self.committed {
            // A valid reservation is never rolled back into FREE. Unwinding
            // cancels it; the reader will skip its admitted position.
            let slot = self.inbox.slot_header(self.lane, self.position);
            let _ = slot.claim.compare_exchange(
                self.claim(RESERVED),
                self.claim(CANCELLED),
                Ordering::AcqRel,
                Ordering::Acquire,
            );
            self.inbox.wake(self.lane, self.inbox.lane_header(self.lane));
        }
        self.inbox
            .record(self.record)
            .flags
            .fetch_and(!WRITING, Ordering::Release);
    }
}

impl Inbox {
    fn registry_base(&self) -> *mut u8 {
        unsafe {
            self.base.add(
                self.geometry.segment_bytes(self.lanes)
                    - registry_bytes(self.lanes, self.geometry.capacity)
                    - crate::admission::bytes(
                        self.lanes,
                        self.geometry.capacity,
                    ),
            )
        }
    }

    fn producer_owner(
        &self,
        index: usize,
    ) -> &Owner {
        unsafe { &*self.registry_base().cast::<Owner>().add(index) }
    }

    fn record(
        &self,
        index: usize,
    ) -> &Record {
        unsafe {
            &*self
                .registry_base()
                .add(2 * self.lanes * size_of::<Owner>())
                .cast::<Record>()
                .add(index)
        }
    }

    fn record_index(
        &self,
        claim: u64,
    ) -> Result<usize> {
        let index = (claim >> 2)
            .checked_sub(1)
            .ok_or(Error::Malformed("inbox claim has no producer"))?
            as usize;
        if index >= 2 * self.lanes * self.geometry.capacity {
            return Err(Error::Malformed(
                "inbox claim producer is outside registry",
            ));
        }
        Ok(index)
    }

    pub(super) fn intent_for_claim(
        &self,
        claim: u64,
    ) -> Result<Intent> {
        self.record(self.record_index(claim)?)
            .snapshot()
            .ok_or(Error::Malformed("referenced inbox intent is unstable"))
    }

    /// Bind a mapping to one producer registration under its cold-path hold.
    #[cfg(unix)]
    pub(crate) fn register_producer(
        &mut self,
        mut hold: impl FnMut(usize) -> Result<Option<orbit_core::shm::LaneHold>>,
    ) -> Result<()> {
        let pid = orbit_core::process::ProcessOwner::current()?.pid();
        for index in 0..2 * self.lanes {
            let Some(held) = hold(index)? else {
                continue;
            };
            self.recover_owner(index)?;
            if !self.owner_idle(index) {
                continue;
            }
            let owner = self.producer_owner(index);
            let generation =
                owner.generation.load(Ordering::Acquire).checked_add(1).ok_or(
                    Error::Malformed("inbox producer generation exhausted"),
                )?;
            owner.generation.store(generation, Ordering::Relaxed);
            owner.pid.store(pid, Ordering::Relaxed);
            // A previous holder may have died waiting.
            owner.waiting.store(0, Ordering::Relaxed);
            owner.active.store(1, Ordering::Release);
            self.producer = Some(Producer {
                index,
                generation,
                next: AtomicUsize::new(0),
                _hold: held,
            });
            return Ok(());
        }
        Err(Error::InboxFull)
    }

    fn owner_idle(
        &self,
        owner: usize,
    ) -> bool {
        let start = owner * self.geometry.capacity;
        (start..start + self.geometry.capacity)
            .all(|index| self.record(index).flags.load(Ordering::Acquire) == 0)
    }

    /// Cold path only. The caller holds this exact registration's kernel
    /// ownership guard continuously through recovery and any following reuse.
    pub(crate) fn recover_owner(
        &self,
        owner_index: usize,
    ) -> Result<()> {
        let owner = self.producer_owner(owner_index);
        if owner.active.fetch_or(0, Ordering::AcqRel) == 0 {
            return Ok(());
        }
        let generation = owner.generation.load(Ordering::Acquire);
        let start = owner_index * self.geometry.capacity;
        for index in start..start + self.geometry.capacity {
            let record = self.record(index);
            // A no-op RMW observes the current modification, not an old zero
            // from before the dead writer published its intent. Cold path.
            let flags = record.flags.fetch_or(0, Ordering::AcqRel);
            if flags == 0 {
                continue;
            }
            if flags & REFERENCED == 0 {
                record.flags.store(0, Ordering::Release);
                continue;
            }
            let Some(intent) = record.snapshot() else {
                return Err(Error::Malformed(
                    "dead referenced producer intent is unstable",
                ));
            };
            if intent.generation != generation || intent.lane >= self.lanes {
                return Err(Error::Malformed(
                    "dead producer intent identity mismatch",
                ));
            }
            let slot = self.slot_header(intent.lane, intent.position);
            let reserved = ((index as u64 + 1) << 2) | RESERVED;
            let turn = slot.seq.load(Ordering::Acquire);
            let claim = slot.claim.fetch_or(0, Ordering::AcqRel);
            if claim >> 2 != reserved >> 2 {
                // FREE is the reference-release boundary. Consumers never
                // mutate this producer record after publishing FREE.
                record.flags.store(0, Ordering::Release);
                continue;
            }
            if turn == intent.position {
                let _ = slot.claim.compare_exchange(
                    reserved,
                    reserved ^ RESERVED ^ CANCELLED,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                );
                #[cfg(test)]
                checkpoint("recovery-cancelled");
                self.help_claim(intent.lane, intent.position)?;
                #[cfg(test)]
                checkpoint("recovery-admitted");
                // Also repeat the wake for COMMITTED-before-wake crashes. Do
                // not retire this registration while retained claims remain.
                self.wake(intent.lane, self.lane_header(intent.lane));
                #[cfg(test)]
                checkpoint("recovery-woken");
            } else if claim == reserved {
                // Death after a tentative wrong-turn claim but before its
                // validation/rollback. No helper could have admitted it.
                if slot
                    .claim
                    .compare_exchange(
                        reserved,
                        FREE,
                        Ordering::Release,
                        Ordering::Relaxed,
                    )
                    .is_ok()
                {
                    record.flags.store(0, Ordering::Release);
                    continue;
                }
            }
            record.flags.fetch_and(!WRITING, Ordering::Release);
        }
        if self.owner_idle(owner_index) {
            owner.active.store(0, Ordering::Release);
        }
        Ok(())
    }

    #[cfg(unix)]
    pub(crate) fn recover_producers(
        &self,
        pid: Option<u32>,
        mut hold: impl FnMut(usize) -> Result<Option<orbit_core::shm::LaneHold>>,
    ) -> Result<()> {
        for index in 0..2 * self.lanes {
            let owner = self.producer_owner(index);
            if owner.active.fetch_or(0, Ordering::AcqRel) == 0
                || pid
                    .is_some_and(|pid| owner.pid.load(Ordering::Acquire) != pid)
            {
                continue;
            }
            let generation = owner.generation.load(Ordering::Acquire);
            let Some(_guard) = hold(index)? else {
                continue;
            };
            // Revalidate after taking the guard, not before and unlocked.
            if owner.generation.load(Ordering::Acquire) == generation {
                self.recover_owner(index)?;
            }
        }
        Ok(())
    }

    pub(crate) fn reserve_frame(
        &self,
        lane_index: usize,
    ) -> Result<Reservation<'_>> {
        // A claim race is not capacity exhaustion. Help the winner and try
        // the next turn, at most one lane-capacity worth of attempts. This
        // bounds our own work even if other producers continuously advance;
        // it never waits for a live writer to publish its payload.
        for _ in 0..self.geometry.capacity {
            match self.try_reserve_frame(lane_index) {
                Ok(Some(reservation)) => return Ok(reservation),
                Ok(None) => {}
                Err(error) => return Err(error),
            }
        }
        Err(Error::InboxContended)
    }

    fn try_reserve_frame(
        &self,
        lane_index: usize,
    ) -> Result<Option<Reservation<'_>>> {
        let lane = self.lane_header(lane_index);
        if lane.consumers.load(Ordering::Acquire) == 0 {
            return Err(Error::InboxFull);
        }
        let read = lane.read.load(Ordering::Acquire);
        let position = lane.reserve.load(Ordering::Acquire);
        let capacity = self.geometry.capacity as u64;
        if position.wrapping_sub(read) >= capacity {
            return Err(Error::InboxFull);
        }
        position
            .checked_add(capacity)
            .ok_or(Error::Malformed("inbox position exhausted"))?;
        let slot = self.slot_header(lane_index, position);
        if slot.claim.load(Ordering::Acquire) != FREE {
            self.help_claim(lane_index, position)?;
            return self.retry_after_progress(lane, position);
        }
        let (owner_index, generation) = self
            .producer
            .as_ref()
            .map(|p| (p.index, p.generation))
            .unwrap_or((0, 0));
        let start = owner_index * self.geometry.capacity;
        let records = self.geometry.capacity;
        let hint = self
            .producer
            .as_ref()
            .map_or(0, |p| p.next.load(Ordering::Relaxed) % records);
        let Some(index) = (hint..records)
            .chain(0..hint)
            .map(|offset| start + offset)
            .find(|index| self.take_record(*index))
        else {
            // The lane has room; this producer's frames elsewhere have not
            // been read yet. A reader that frees one can wake it.
            return Err(Error::ProducerBusy);
        };
        if let Some(producer) = &self.producer {
            producer.next.store(index - start + 1, Ordering::Relaxed);
        }
        let record = self.record(index);
        let before = record.seq.load(Ordering::Relaxed);
        let odd = before | 1;
        let Some(even) = odd.checked_add(1) else {
            record.flags.store(0, Ordering::Release);
            return Err(Error::Malformed("inbox intent sequence exhausted"));
        };
        record.seq.store(odd, Ordering::Relaxed);
        #[cfg(test)]
        checkpoint("intent-odd");
        fence(Ordering::Release);
        record.position.store(position, Ordering::Relaxed);
        let epoch = lane.epoch.load(Ordering::Acquire);
        record.incarnation.store(epoch, Ordering::Relaxed);
        record.generation.store(generation, Ordering::Relaxed);
        record.lane.store(lane_index as u32, Ordering::Relaxed);
        record.seq.store(even, Ordering::Release);
        #[cfg(test)]
        checkpoint("intent-published");
        record.flags.store(WRITING | REFERENCED, Ordering::Release);
        #[cfg(test)]
        checkpoint("before-claim");
        let reserved = ((index as u64 + 1) << 2) | RESERVED;
        if slot
            .claim
            .compare_exchange(
                FREE,
                reserved,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .is_err()
        {
            record.flags.store(0, Ordering::Release);
            self.help_claim(lane_index, position)?;
            return self.retry_after_progress(lane, position);
        }
        if slot.seq.load(Ordering::Acquire) != position {
            // Tentative claim for the wrong full turn: it was never valid.
            let _ = slot.claim.compare_exchange(
                reserved,
                FREE,
                Ordering::Release,
                Ordering::Relaxed,
            );
            record.flags.store(0, Ordering::Release);
            return self.retry_after_progress(lane, position);
        }
        #[cfg(test)]
        checkpoint("claimed");
        let _ = lane.reserve.compare_exchange(
            position,
            position + 1,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
        #[cfg(test)]
        checkpoint("admitted");
        Ok(Some(Reservation {
            inbox: self,
            record: index,
            position,
            epoch,
            lane: lane_index,
            committed: false,
        }))
    }

    fn retry_after_progress(
        &self,
        lane: &super::LaneHeader,
        position: u64,
    ) -> Result<Option<Reservation<'_>>> {
        // A failed attempt may follow an advanced cursor, never poll the
        // same live claim waiting for its owner to make progress.
        if lane.reserve.load(Ordering::Acquire) > position {
            Ok(None)
        } else {
            Err(Error::InboxContended)
        }
    }

    fn take_record(
        &self,
        index: usize,
    ) -> bool {
        let record = self.record(index);
        let flags = record.flags.load(Ordering::Acquire);
        if flags & WRITING != 0
            || record
                .flags
                .compare_exchange(
                    flags,
                    flags | WRITING,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                )
                .is_err()
        {
            return false;
        }
        if flags & REFERENCED != 0 {
            // Acquiring the previous writer's Release prevents observing a
            // FREE from before that writer's claim. The physical slot releases
            // the reference; no cross-owner reader RMW touches this record.
            let released = record.snapshot().is_some_and(|intent| {
                intent.lane < self.lanes
                    && self
                        .slot_header(intent.lane, intent.position)
                        .claim
                        .load(Ordering::Acquire)
                        >> 2
                        != index as u64 + 1
            });
            if !released {
                record.flags.fetch_and(!WRITING, Ordering::Release);
                return false;
            }
            record.flags.store(WRITING, Ordering::Relaxed);
        }
        true
    }

    fn help_claim(
        &self,
        lane_index: usize,
        position: u64,
    ) -> Result<()> {
        let slot = self.slot_header(lane_index, position);
        let claim = slot.claim.load(Ordering::Acquire);
        if !matches!(claim & 3, RESERVED | CANCELLED | COMMITTED) {
            return Ok(());
        }
        let index = self.record_index(claim)?;
        let Some(intent) = self.record(index).snapshot() else {
            return Ok(());
        };
        self.help_snapshot(lane_index, position, claim, intent)
    }

    fn help_snapshot(
        &self,
        lane_index: usize,
        position: u64,
        claim: u64,
        intent: Intent,
    ) -> Result<()> {
        let index = self.record_index(claim)?;
        let slot = self.slot_header(lane_index, position);
        let turn = slot.seq.load(Ordering::Acquire);
        if intent.position != position
            || turn != position
            || intent.lane != lane_index
            || (self.producer.is_some()
                && self
                    .producer_owner(index / self.geometry.capacity)
                    .generation
                    .load(Ordering::Acquire)
                    != intent.generation)
            || slot.claim.load(Ordering::Acquire) != claim
        {
            return Ok(());
        }
        // In particular CANCELLED never admits the next turn merely because
        // its reader has published a new turn before clearing the old claim.
        let _ = self.lane_header(lane_index).reserve.compare_exchange(
            position,
            position + 1,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
        Ok(())
    }

    pub(super) fn consume_frame(
        &self,
        lane_index: usize,
        position: u64,
        claim: u64,
    ) -> Result<()> {
        let next = position
            .checked_add(self.geometry.capacity as u64)
            .ok_or(Error::Malformed("inbox position exhausted"))?;
        let index = self.record_index(claim)?;
        let slot = self.slot_header(lane_index, position);
        slot.seq.store(next, Ordering::Release);
        #[cfg(test)]
        checkpoint("reader-turn");
        slot.claim.store(FREE, Ordering::Release);
        #[cfg(test)]
        checkpoint("reader-free");
        self.lane_header(lane_index)
            .read
            .store(position + 1, Ordering::Release);
        #[cfg(test)]
        checkpoint("reader-head");
        // FREE released the producer's record. Pairs with the fence in
        // `wait_for_record`: either that producer sees FREE, or this reader
        // sees it waiting. The same fence pairs the read cursor update with
        // the inbox-space arm and recheck.
        fence(Ordering::SeqCst);
        self.release_waiter(index / self.geometry.capacity);
        self.inbox_space_changed(lane_index);
        Ok(())
    }

    /// Ring a producer that waits for a record, on the transition only.
    fn release_waiter(
        &self,
        owner_index: usize,
    ) {
        let owner = self.producer_owner(owner_index);
        if owner.waiting.load(Ordering::Relaxed) == 0
            || owner.waiting.swap(0, Ordering::AcqRel) == 0
        {
            return;
        }
        // A failed send needs nothing more: a full socket queue already holds
        // a wake, and an unbound name belongs to a producer that is gone.
        #[cfg(unix)]
        if let Some(bell) = &self.bell {
            let _ = bell.ring(crate::bell::Doorbell::Producer(owner_index));
        }
    }

    /// This mapping's producer registration, if it publishes into SHM.
    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn producer_index(&self) -> Option<usize> {
        self.producer.as_ref().map(|producer| producer.index)
    }

    /// Ask to be rung when a reader frees one of this producer's records.
    /// Returns false when one is already free and nothing was armed: write
    /// again instead of waiting.
    #[cfg(all(unix, feature = "tokio"))]
    pub(crate) fn wait_for_record(&self) -> Result<bool> {
        let index = self
            .producer_index()
            .ok_or(Error::Malformed("this inbox mapping has no producer"))?;
        let owner = self.producer_owner(index);
        owner.waiting.store(1, Ordering::Relaxed);
        fence(Ordering::SeqCst);
        let start = index * self.geometry.capacity;
        // A free record leaves the word set: another task of this producer
        // may be waiting on it, and a later ring is only a recheck.
        Ok(!(start..start + self.geometry.capacity)
            .any(|record| self.record_free(record)))
    }

    /// Whether `take_record` could take this record now, without taking it.
    #[cfg(all(unix, feature = "tokio"))]
    fn record_free(
        &self,
        index: usize,
    ) -> bool {
        let record = self.record(index);
        let flags = record.flags.load(Ordering::Acquire);
        if flags & WRITING != 0 {
            return false;
        }
        flags & REFERENCED == 0
            || record.snapshot().is_some_and(|intent| {
                intent.lane < self.lanes
                    && self
                        .slot_header(intent.lane, intent.position)
                        .claim
                        .load(Ordering::Acquire)
                        >> 2
                        != index as u64 + 1
            })
    }
}

#[cfg(all(test, unix))]
#[path = "../../tests/unit/claims.rs"]
mod tests;