xchannel 1.3.0

mmap-backed IPC channels with regionized layout, alignment-safe headers, and file rolling.
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
692
693
# xchannel

**xchannel** is a tiny, zero-copy, mmap-backed IPC channel with automatic region and file rolling. It lets a single writer append messages to a persistent stream that multiple readers can replay from the beginning (**LateJoin**) or tail in real time (**Live**)—without a broker or background service.

## Features
* Shared‑memory / IPC logs without a broker.
* Constant-time tailing (readers only track a byte offset).
* Works on Linux and macOS (16 KiB) and typical 4 KiB page systems.
* **Zero‑copy access**: messages are written directly into a memory‑mapped
  region and read back without additional copying.
* **Rolling regions and files**: large channels are segmented into
  fixed‑size regions. When a region fills up the writer rolls over to
  the next region; when the end of a file is reached a new file with
  an incremented sequence number is created automatically.
* **Two reader modes**:
    * **LateJoin** – start from the beginning of the earliest existing
      channel file.
    * **Live** – join the channel at the current write position and only
      observe new messages.
* **MTU enforcement**: optional maximum message size to defend against
  unbounded memory usage or corrupted input.
* **Atomic state management**: the shared write position and message
  count are tracked using atomic variables with proper memory ordering
* **Very simple, low maintenance**: the system relies on a minimal set of concepts. 
 There are no background services, no complex synchronization mechanisms, and no external dependencies.
* **No back pressure**: readers cannot slow down the writer, retention is controlled by rolling policy rather than consumer speed.
* **Clear non-aliasing contract (single writer)**: readers never observe bytes 
  while they’re being written. This is a language-agnostic safety property (C/C++/Rust/..), 
  and fits Rust’s `&mut`/`&` guarantees naturally.

## Minimum example

```rust
use xchannel::{WriterBuilder, ReaderBuilder};

let region = xchannel::page_size();           // ensure page-aligned regions
let mut w = WriterBuilder::new("demo.xch")
    .region_size(region)
    .file_roll_size(10_000_000)
    .build()?;
            
// write a message
let payload = b"hello world";
if let Some(buf) = w.try_reserve(payload.len()) {
    buf.copy_from_slice(payload);
    w.commit(1, payload.len() as u32, timestamp)?;
}

// read it back
let mut r = ReaderBuilder::new("demo.xch")
    .late_join()
    .batch_limit(1000)
    .build()?;
if let Some(msg) = r.try_read() {
    let hdr = msg.header();
    println!("type={}, len={}", hdr.message_type, hdr.length);
    println!("payload={:?}", msg.payload());
}
```

## Batch read example

```rust
use xchannel::ReaderBuilder;

let mut r = ReaderBuilder::new("demo.xch").late_join().build()?;
if let Some(batch) = r.try_read_batch(None) {
    for idx in (0..batch.len()).rev() {
        let msg = batch.get(idx).unwrap();
        let hdr = msg.header();
        let payload = msg.payload();
        // payload is opaque bytes; parse as needed.
        println!("type={}, len={}, first={:?}", hdr.message_type, hdr.length, payload.get(0));
    }
}
```

---


----------

<!--
Goal: explain design ideas + show Rust examples
-->

# xchannel

## mmap-backed IPC channels for Rust

Zero-copy • Append-only • Multi-reader

---

# Why another channel?

Typical Rust channels:

* `std::sync::mpsc`
* `tokio::mpsc`
* `crossbeam`

These are great but they:

* work **inside one process**
* messages exist **only in memory**
* cannot **replay history**
* cannot easily **tail from another process**

---

# Motivation

Some systems need:

* **cross-process communication**
* **persistent message streams**
* **very low overhead**
* **simple debugging**

Typical examples:

* trading systems
* logging pipelines
* market data distribution
* real-time analytics

---

# Core idea

Instead of a queue:

**Use an append-only log stored in a memory-mapped file**

```
Writer ---> mmap file ---> Readers
```

Properties:

* writer **appends messages**
* readers **scan sequentially**
* messages remain **persistent**

Readers can start:

* from **beginning**
* from **current tail**

---

# Architecture overview

```
                                                  Writer
                                                  │ append messages
        ┌─────────────────────────────────────────────┐
        │ mmap file                                   │
        │                                             │
        │ msg1 msg2 msg3 msg4 msg5 msg6 msg7 msg8 ... │
        │                                             │
        └─────────────────────────────────────────────┘
            ▲                                ▲
            │                                │
        Reader A                         Reader B
        (LateJoin)                        (Live)
```

Key property:

Readers **never block the writer**.

---

# File structure

Channel files are divided into **regions**.

```
File
┌─────────────────────────────┐
│ Region 0                    │
│ ChannelHeader + messages    │
├─────────────────────────────┤
│ Region 1                    │
│ messages                    │
├─────────────────────────────┤
│ Region 2                    │
│ messages                    │
└─────────────────────────────┘
```

Regions provide:

* predictable memory layout
* simple boundary handling
* easier file rolling

---

# Record layout

Each record looks like:

```
[ MessageHeader ][ payload ][ padding ]
```

Header fields include:

* committed flag
* message type
* payload length
* timestamp

Readers check:

```
header.committed
```

---

# Record memory layout

```
┌──────────────────────────────┐
│ MessageHeader                │
│                              │
│ committed                    │
│ message_type                 │
│ payload_length               │
│ timestamp_ns                 │
└──────────────────────────────┘
┌──────────────────────────────┐
│ Payload bytes                │
│ user message                 │
└──────────────────────────────┘
┌──────────────────────────────┐
│ Padding (optional)           │
└──────────────────────────────┘
```

---

# Writer workflow

```
reserve → write payload → publish
```

Steps:

1. reserve memory
2. write payload
3. prepare next header
4. commit current message

The **commit flag is written last**.

---

# Publish protocol

Writer publishes a message in this order:

```
1. write payload(i)
2. prepare header(i+1)      // write-ahead header
3. commit header(i) = true  (Release)
```

Meaning:

* the **next header slot exists before publication**
* the message becomes visible **only after commit**

---

# Why prepare the next header first?

When a reader sees:

```
header(i).committed == true
```

then:

* payload(i) is fully written
* header(i+1) already exists

So the reader can continue scanning safely:

```
header(i) → payload(i) → header(i+1)
```

No global metadata required.

---

# Writer pipeline visualization

```
header(i) ready
            write payload(i)
            prepare header(i+1)
            commit header(i)
```

Key property:

The **commit flag is the only synchronization point**.

---

# Cache contention problem

Naive design:

```
writer updates global head pointer
readers poll the same pointer
```

Result:

```
CPU1 (writer)  <---->  CPU2 (reader)
      cache invalidations
```

This causes unnecessary **cache coherence traffic**.

---

# Commit flag solution

Each message has its **own commit flag**.

Readers check different cache lines as they scan.

```
msg1.header.committed
msg2.header.committed
msg3.header.committed
```

Benefits:

* minimal contention
* scalable readers
* avoids cache bouncing

---

# Rust example: writer

```rust
use xchannel::WriterBuilder;

fn main() -> std::io::Result<()> {
    let mut writer = WriterBuilder::new("demo.xch")
        .build()?;
    let payload = b"hello xchannel";
    let buf = writer.try_reserve(payload.len())?;
    buf.copy_from_slice(payload);
    writer.commit(1, payload.len() as u32, 0 )?;
    Ok(())
}
```

---

# Rust example: reader

```rust
use xchannel::ReaderBuilder;

fn main() -> std::io::Result<()> {

    let mut reader = ReaderBuilder::new("demo.xch")
        .late_join()
        .build()?;

    while let Some(msg) = reader.try_read() {

        let header = msg.header();
        let payload = msg.payload();

        println!(
            "type={} len={} payload={:?}",
            header.message_type,
            header.length,
            payload
        );
    }

    Ok(())
}
```

---

# Rust aliasing requirement

Rust enforces strict aliasing rules:

```
&mut T  → exclusive access
&T      → shared access
```

Simultaneous read/write would violate:

```
&mut [u8] vs &[u8]
```

This is especially important with **mmap memory**.

---

# The aliasing challenge

Writer and readers operate on the **same mapped memory**.

Naively this could allow:

```
writer writing payload
reader reading same payload
```

This would break Rust’s **non-aliasing contract**.

---

# xchannel solution

The algorithm guarantees:

**Writer and readers never access the same memory region simultaneously**

Except one field:

```
AtomicBool committed
```

---

# Access separation

Writer accesses:

```
payload(i)
header(i)
```

Readers access only:

```
payload(j)
header(j)
```

Where

```
j < committed_index
```

Meaning the message is already **published**.

---

# Publish ordering

Writer:

```
write payload
prepare next header
commit = true (Release)
```

Reader:

```
if committed.load(Acquire) {
    read payload
}
```

Guarantees:

* no partial reads
* correct memory ordering

---

# Why this satisfies Rust aliasing rules

After commit:

```
writer never touches payload again
```

Then readers access:

```
&[u8]
```

Timeline:

```
writer (&mut) → finished
reader (&) → begins
```

No overlapping access.

Rust’s **non-aliasing guarantee is preserved**.

---

# The only shared memory location

Both sides access only:

```
AtomicBool committed
```

Safe because:

* atomic operations
* Acquire / Release ordering
* tiny memory footprint

---

# Reader modes

### LateJoin

```
start from beginning
```

Useful for:

* replay
* debugging
* analytics

---

### Live

```
start from tail
```

Useful for:

* real-time consumers
* monitoring
* streaming pipelines

---

# Rolling files

Channels can run indefinitely.

Files roll when necessary:

```
demo.xch
demo.xch.1
demo.xch.2
```

Process:

1. writer writes **Roll marker**
2. creates next file
3. readers follow automatically

---

# Why mmap?

Benefits:

* zero-copy payload access
* OS page cache handles IO
* sequential reads are extremely fast
* minimal syscalls

Readers simply scan memory:

```
header → header → header
```

---

# Why this design fits Rust well

The design aligns with Rust principles:

Ownership transfer:

```
writer owns payload → commit → reader observes
```

Concurrency:

```
atomic publication
```

Memory layout:

```
simple + predictable
```

---

# Key design principles

xchannel relies on:

1. append-only log
2. commit-flag publication
3. write-ahead headers
4. sequential scanning
5. strict memory ownership transfer

Result:

```
safe + zero-copy + low latency + scalable
```

---

# When to use xchannel

Good fit:

* market data distribution
* logging pipelines
* inter-process messaging
* persistent event streams
* historical replay (simulation)


---

# Summary

xchannel provides:

* mmap-based IPC channels
* zero-copy message access
* append-only persistent log
* minimal contention design
* Rust-safe memory access model

---