causal_machines 0.6.1
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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +84 -0
- data/Cargo.lock +307 -0
- data/Cargo.toml +27 -0
- data/LICENSE.txt +21 -0
- data/README.md +288 -0
- data/ext/causal_machines_native/core/CHANGELOG.md +59 -0
- data/ext/causal_machines_native/core/Cargo.toml +17 -0
- data/ext/causal_machines_native/core/README.md +118 -0
- data/ext/causal_machines_native/core/src/lib.rs +53 -0
- data/ext/causal_machines_native/core/src/tracker.rs +626 -0
- data/ext/causal_machines_native/core/src/vector.rs +200 -0
- data/ext/causal_machines_native/extconf.rb +2 -0
- data/ext/causal_machines_native/ffi/Cargo.toml +21 -0
- data/ext/causal_machines_native/ffi/extconf.rb +14 -0
- data/ext/causal_machines_native/ffi/src/classes.rs +43 -0
- data/ext/causal_machines_native/ffi/src/init.rs +56 -0
- data/ext/causal_machines_native/ffi/src/lib.rs +247 -0
- data/ext/causal_machines_native/ffi/src/values.rs +108 -0
- data/ext/causal_machines_native/ffi/src/vectors.rs +152 -0
- data/lib/causal_machines/version.rb +5 -0
- data/lib/causal_machines.rb +93 -0
- data/sig/causal_machines.rbs +148 -0
- metadata +89 -0
data/README.md
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
# CausalMachines
|
|
2
|
+
|
|
3
|
+
> The answer does not get to arrive before the question. ðŸ§
|
|
4
|
+
|
|
5
|
+
A causal-order tracker for Ruby. Every message travels with a stamp: a version vector saying what its sender had already seen. Before you act on a message, you show the tracker its stamp. The tracker tells you whether everything it depends on has been delivered here, exactly what is still missing if not, or that you already had it. Messages that arrive early wait as stamps, not payloads, and come back out the moment their dependencies land.
|
|
6
|
+
|
|
7
|
+
## Quick Start
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
gem 'causal_machines'
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ruby
|
|
14
|
+
members = CausalMachines::Membership.new([1, 2, 3])
|
|
15
|
+
tracker = CausalMachines::Causal.new(members, 3, 0) # members, me, generation
|
|
16
|
+
|
|
17
|
+
def on_message(tracker, stamp, payload, buffer)
|
|
18
|
+
case tracker.receive(stamp)
|
|
19
|
+
when :delivered then apply(payload)
|
|
20
|
+
when :held then buffer[[stamp.sender, stamp.clock]] = payload
|
|
21
|
+
when :duplicate, :already_held then return # seen before, nothing changed
|
|
22
|
+
else raise "tracker refused #{stamp}" # every other symbol is a refusal
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
while (released = tracker.release) # a Deliver or an Obsolete
|
|
26
|
+
ready = released.stamp
|
|
27
|
+
payload = buffer.delete([ready.sender, ready.clock])
|
|
28
|
+
apply(payload) if released.is_a?(CausalMachines::Deliver)
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
stamp = tracker.stamp # for a message you are about to send
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
One tracker per replica. Replica ids, generations and counters are Integers; clocks are `VersionVector` values and the member list a `Membership`. The tracker keeps stamps. The payloads stay with you.
|
|
36
|
+
|
|
37
|
+
## A Message to the Resistance
|
|
38
|
+
|
|
39
|
+
So you built a chat room on three servers. Alice asks "who broke the build?" on server one. Bob, on server two, sees it and answers "you did." Server three hears from Bob first, because networks are like that, and shows Carol an accusation with no question attached.
|
|
40
|
+
|
|
41
|
+
You know the usual fixes. Sort by wall-clock timestamp, and discover that server two's clock runs four seconds ahead, so Bob now answers questions before they are asked on every screen. Switch to a Lamport counter, and get one neat total order that still cannot tell you whether Bob had *seen* Alice's message or just happened to draw a bigger number. A single number can order events. It cannot say which ones were waiting on which.
|
|
42
|
+
|
|
43
|
+
What you need is a partial order: this happened after that, and those two never knew about each other. A version vector is the smallest thing that carries it. One counter per replica, compared entry by entry. The piece you would otherwise rebuild is the delivery rule on top: a message is ready when it is its sender's next one and everything the sender had seen is already here. That rule, the list of what is missing when it fails, and a bounded waiting room for the early arrivals, is this gem.
|
|
44
|
+
|
|
45
|
+
## Chapter 1: Stardate 2026.316, the AMS Fidge
|
|
46
|
+
|
|
47
|
+
> **AMS Fidge**, NCC-4231, *Fidge*-class causality cutter.
|
|
48
|
+
> A reply does not clear customs before the hail it answers.
|
|
49
|
+
|
|
50
|
+
The cutter does not carry cargo and does not chase anyone. It sits on the shipping lane and reads manifests. Every dispatch lists what its sender had on board when it left. The cutter compares that list against its own log and says one of three things: cleared, already logged, or waiting on these specific dispatches from those specific ships.
|
|
51
|
+
|
|
52
|
+
On a bridge somewhere, a cadet volunteers:
|
|
53
|
+
|
|
54
|
+
```ruby
|
|
55
|
+
def on_message(message)
|
|
56
|
+
@inbox << message
|
|
57
|
+
@inbox.sort_by!(&:sent_at).each { |m| show(m) }
|
|
58
|
+
end
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
"That," says the cutter's navigator, "orders the fleet by whose chronometer is the most wrong."
|
|
62
|
+
|
|
63
|
+
## The Flight Plan
|
|
64
|
+
|
|
65
|
+
Each stamp the tracker is shown ends up in one of these states:
|
|
66
|
+
|
|
67
|
+
```mermaid
|
|
68
|
+
stateDiagram-v2
|
|
69
|
+
[*] --> unseen
|
|
70
|
+
unseen --> delivered: receive, dependencies delivered
|
|
71
|
+
unseen --> held: receive, dependencies missing
|
|
72
|
+
unseen --> unseen: receive refused, hold table full, returns :full
|
|
73
|
+
held --> delivered: release, returns Deliver(stamp)
|
|
74
|
+
held --> dropped: release after absorb, returns Obsolete(stamp)
|
|
75
|
+
held --> unseen: forget
|
|
76
|
+
delivered --> delivered: receive again, returns :duplicate
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
And the afternoon Bob's answer overtook Alice's question:
|
|
80
|
+
|
|
81
|
+
```mermaid
|
|
82
|
+
sequenceDiagram
|
|
83
|
+
participant A as Alice (1)
|
|
84
|
+
participant B as Bob (2)
|
|
85
|
+
participant C as Carol (3)
|
|
86
|
+
|
|
87
|
+
A->>B: question [1,0,0]
|
|
88
|
+
Note over B: :delivered
|
|
89
|
+
B->>C: answer [1,1,0]
|
|
90
|
+
Note over C: :held, missing replica 1 counter 1
|
|
91
|
+
A->>C: question [1,0,0]
|
|
92
|
+
Note over C: :delivered
|
|
93
|
+
Note over C: release gives Deliver(answer)
|
|
94
|
+
A->>C: question [1,0,0] (retry)
|
|
95
|
+
Note over C: :duplicate
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## How the Tracker Works
|
|
99
|
+
|
|
100
|
+
### Stamp
|
|
101
|
+
|
|
102
|
+
```ruby
|
|
103
|
+
members = CausalMachines::Membership.new([1, 2, 3])
|
|
104
|
+
alice = CausalMachines::Causal.new(members, 1, 0)
|
|
105
|
+
bob = CausalMachines::Causal.new(members, 2, 0)
|
|
106
|
+
carol = CausalMachines::Causal.new(members, 3, 0)
|
|
107
|
+
|
|
108
|
+
question = alice.stamp
|
|
109
|
+
# => #<data CausalMachines::Stamp generation=0, sender=1,
|
|
110
|
+
# clock=#<data CausalMachines::VersionVector counters=[1, 0, 0, 0, 0, 0, 0, 0]>>
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`stamp` numbers your next message and hands back what to send with it. The clock has one counter per membership slot, in the order you listed the members; like the core's `VersionVector<8>`, it always holds `CausalMachines::MEMBERS` counters, the slots past your members at zero. Your own message counts as delivered to you from that moment. At counter `2**64 - 1` it answers `:exhausted` instead.
|
|
114
|
+
|
|
115
|
+
### Receive
|
|
116
|
+
|
|
117
|
+
```ruby
|
|
118
|
+
bob.receive(question) # => :delivered
|
|
119
|
+
answer = bob.stamp # clock counters [1, 1, 0, ...]: Bob had seen Alice's first
|
|
120
|
+
|
|
121
|
+
carol.receive(answer) # => :held, the question is not here yet
|
|
122
|
+
carol.receive(answer) # => :already_held
|
|
123
|
+
carol.receive(question) # => :delivered
|
|
124
|
+
carol.receive(question) # => :duplicate
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
`:delivered` means act on it now. `:held` means keep the payload somewhere; the tracker kept the stamp. `:already_held` and `:duplicate` are repeats: the tracker already has what you showed it, so the call is honoured and nothing changes. Anything else `receive` answers is a refusal. `check(stamp)` gives the same verdict (`:deliverable`, `:duplicate`, `:missing`) without changing anything, and the same refusals short of `:full`.
|
|
128
|
+
|
|
129
|
+
### Release
|
|
130
|
+
|
|
131
|
+
```ruby
|
|
132
|
+
carol.release # => #<data CausalMachines::Deliver stamp=answer>
|
|
133
|
+
carol.release # => nil
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
After any delivery, call `release` until it returns `nil`. `nil` means nothing is ready; `release` never refuses. Each call hands back the core's `Release`: a `Deliver(stamp)` for one held stamp whose dependencies have arrived, which now counts as delivered, or an `Obsolete(stamp)` (see Absorb below). One delivery can unblock a chain, so loop.
|
|
137
|
+
|
|
138
|
+
### Missing
|
|
139
|
+
|
|
140
|
+
```ruby
|
|
141
|
+
node = CausalMachines::Causal.new(CausalMachines::Membership.new([1, 2, 3]), 3, 0)
|
|
142
|
+
wanted = CausalMachines::Stamp.new(0, 2, CausalMachines::VersionVector.new([3, 4, 2]))
|
|
143
|
+
|
|
144
|
+
page = node.missing(wanted, 0, 2)
|
|
145
|
+
# page.gaps => [Gap(replica=1, from=1, through=3), Gap(replica=2, from=1, through=3)]
|
|
146
|
+
# page.next => 2
|
|
147
|
+
node.missing(wanted, page.next, 2)
|
|
148
|
+
# => Page(gaps=[Gap(replica=3, from=1, through=2)], next=nil)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
`missing(stamp, cursor, limit)` lists what stands between you and that message: per replica, the inclusive run of counters not delivered here. It answers a `Page`. Start at cursor 0, take at most `limit` gaps a call (up to `CausalMachines::MEMBERS`), and pass `page.next` back until it is `nil`. A cursor is a member slot; one past the last member was never handed out, so it is refused with `:unknown_member` (after the stamp itself is judged). These are the ranges to ask your peers for.
|
|
152
|
+
|
|
153
|
+
### Absorb
|
|
154
|
+
|
|
155
|
+
```ruby
|
|
156
|
+
vv = ->(*counters) { CausalMachines::VersionVector.new(counters) }
|
|
157
|
+
node = CausalMachines::Causal.new(CausalMachines::Membership.new([1, 2, 3]), 3, 0)
|
|
158
|
+
late = CausalMachines::Stamp.new(0, 1, vv[2, 0, 0])
|
|
159
|
+
node.receive(late) # => :held
|
|
160
|
+
|
|
161
|
+
node.absorb(0, vv[4, 0, 0]) # => :absorbed, a snapshot already covers 1..4 from replica 1
|
|
162
|
+
node.absorb(0, vv[3, 0, 0]) # => :already_covered, nothing new, nothing changed
|
|
163
|
+
node.clock # => VersionVector counters [4, 0, 0, ...]
|
|
164
|
+
node.release # => #<data CausalMachines::Obsolete stamp=late>
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
When you install state that already reflects a clock, `absorb` folds that clock into yours by taking the larger counter in every position, and answers `:absorbed`. When your clock already covers it, the call is an honoured repeat: `:already_covered`, nothing changed. A clock counting a slot outside the membership is refused with `:malformed`. Held stamps it covers come out of `release` as `Obsolete(stamp)`: drop their payloads, do not apply them.
|
|
168
|
+
|
|
169
|
+
### Vectors and memberships
|
|
170
|
+
|
|
171
|
+
```ruby
|
|
172
|
+
vv = ->(*counters) { CausalMachines::VersionVector.new(counters) }
|
|
173
|
+
vv[1, 2].compare(vv[1, 3]) # => :before
|
|
174
|
+
vv[2, 1].compare(vv[1, 2]) # => :concurrent
|
|
175
|
+
vv[1, 3].dominates?(vv[1, 2]) # => true
|
|
176
|
+
vv[2, 1].concurrent?(vv[1, 2]) # => true
|
|
177
|
+
vv[5, 0].merged(vv[2, 9]) # => VersionVector counters [5, 9, 0, ...]
|
|
178
|
+
vv[5, 0].get(0) # => 5
|
|
179
|
+
vv[5, 0].increment(1) # => VersionVector counters [5, 1, 0, ...]
|
|
180
|
+
vv[2**64 - 1].increment(0) # => :exhausted
|
|
181
|
+
vv[1].increment(8) # => :unknown_member
|
|
182
|
+
CausalMachines::VersionVector.new # => all zeros, the core's VersionVector::new
|
|
183
|
+
|
|
184
|
+
members = CausalMachines::Membership.new([10, 20, 30])
|
|
185
|
+
members.slot(20) # => 1
|
|
186
|
+
members.replica(2) # => 30
|
|
187
|
+
members.len # => 3
|
|
188
|
+
members.admits?(vv[0, 0, 0, 1]) # => false, counts a slot outside the members
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
`VersionVector` and `Membership` mirror the core types. `VersionVector.new(counters)` is the core's `from_counters`: up to `MEMBERS` counters, the rest zero. A vector is a value, so `increment` answers a new vector (the core's new counter is its `get(slot)`) or a refusal symbol, and `merged` answers the merge. `compare` answers `:equal`, `:before`, `:after` or `:concurrent`. `Membership.new(ids)` is `Membership::from_slice`: distinct ids, at most `MEMBERS`.
|
|
192
|
+
|
|
193
|
+
### Capacity
|
|
194
|
+
|
|
195
|
+
The tracker holds 64 early stamps and up to 8 members. Past that, `receive` refuses a stamp that would have to wait with `:full`:
|
|
196
|
+
|
|
197
|
+
```ruby
|
|
198
|
+
node = CausalMachines::Causal.new(CausalMachines::Membership.new([1, 2, 3]), 3, 0)
|
|
199
|
+
from_one = ->(n) { CausalMachines::Stamp.new(0, 1, CausalMachines::VersionVector.new([n])) }
|
|
200
|
+
CausalMachines::CAPACITY # => 64
|
|
201
|
+
CausalMachines::MEMBERS # => 8
|
|
202
|
+
(2..65).each { |n| node.receive(from_one[n]) }
|
|
203
|
+
node.receive(from_one[66]) # => :full
|
|
204
|
+
|
|
205
|
+
node.forget(1, 65) # => :forgotten
|
|
206
|
+
node.forget(1, 65) # => :not_held, nothing changed
|
|
207
|
+
node.receive(from_one[66]) # => :held
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
A held stamp is never evicted to make room. `forget(sender, counter)` drops one you have decided to stop waiting for; the sender will have to send it again. It answers `:forgotten` when it dropped one and `:not_held` when none was held. Both are honoured: asking to forget a stamp that isn't held is a repeat that changes nothing. A sender outside the membership is refused with `:unknown_member`.
|
|
211
|
+
|
|
212
|
+
### Conflict
|
|
213
|
+
|
|
214
|
+
```ruby
|
|
215
|
+
vv = ->(*counters) { CausalMachines::VersionVector.new(counters) }
|
|
216
|
+
node = CausalMachines::Causal.new(CausalMachines::Membership.new([1, 2, 3]), 3, 0)
|
|
217
|
+
waiting = CausalMachines::Stamp.new(0, 1, vv[2, 1, 0])
|
|
218
|
+
node.receive(waiting) # => :held
|
|
219
|
+
node.receive(CausalMachines::Stamp.new(0, 1, vv[1, 0, 0])) # => :delivered
|
|
220
|
+
|
|
221
|
+
other = CausalMachines::Stamp.new(0, 1, vv[2, 0, 0]) # same sender, same counter, another clock
|
|
222
|
+
node.check(other) # => :conflict
|
|
223
|
+
node.receive(other) # => :conflict, though nothing it depends on is missing
|
|
224
|
+
node.held # => 1, the held stamp is still there
|
|
225
|
+
node.forget(1, 2) # => :forgotten, you have chosen
|
|
226
|
+
node.receive(other) # => :delivered
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
Two stamps with the same sender and counter but different clocks cannot both be that sender's message, and the tracker has no way to know which one is. So it refuses the newcomer with `:conflict` whatever it would otherwise have been, ready to deliver, waiting, or already covered, and it never drops or replaces the held stamp to make the answer simpler. `check` and `missing` refuse the same way. The held stamp leaves only through `release`, or through `forget` when you decide the other one is right.
|
|
230
|
+
|
|
231
|
+
### Generations
|
|
232
|
+
|
|
233
|
+
```ruby
|
|
234
|
+
vv = ->(*counters) { CausalMachines::VersionVector.new(counters) }
|
|
235
|
+
node = CausalMachines::Causal.new(CausalMachines::Membership.new([1, 2, 3]), 3, 5)
|
|
236
|
+
node.receive(CausalMachines::Stamp.new(4, 1, vv[1, 0, 0])) # => :stale_generation
|
|
237
|
+
node.receive(CausalMachines::Stamp.new(6, 1, vv[1, 0, 0])) # => :future_generation
|
|
238
|
+
node.receive(CausalMachines::Stamp.new(5, 9, vv[1, 0, 0])) # => :unknown_member
|
|
239
|
+
node.receive(CausalMachines::Stamp.new(5, 1, vv[0, 1, 0])) # => :malformed, sender entry 0
|
|
240
|
+
node.receive(CausalMachines::Stamp.new(5, 1, vv[1, 0, 0, 1])) # => :malformed, outside the members
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
### What each call can answer
|
|
244
|
+
|
|
245
|
+
| Call | Honoured | Refusals |
|
|
246
|
+
| --- | --- | --- |
|
|
247
|
+
| `stamp` | a `Stamp` | `:exhausted` |
|
|
248
|
+
| `check` | `:deliverable`, `:duplicate`, `:missing` | `:conflict`, `:stale_generation`, `:future_generation`, `:unknown_member`, `:malformed` |
|
|
249
|
+
| `receive` | `:delivered`, `:held`, `:already_held`, `:duplicate` | `:conflict`, `:full`, `:stale_generation`, `:future_generation`, `:unknown_member`, `:malformed` |
|
|
250
|
+
| `release` | `Deliver(stamp)`, `Obsolete(stamp)`, `nil` | none |
|
|
251
|
+
| `forget` | `:forgotten`, `:not_held` | `:unknown_member` |
|
|
252
|
+
| `missing` | a `Page` (`gaps`, `next`) | `:conflict`, `:stale_generation`, `:future_generation`, `:unknown_member` (sender, or a cursor past the last member), `:malformed` |
|
|
253
|
+
| `absorb` | `:absorbed`, `:already_covered` | `:stale_generation`, `:future_generation`, `:malformed` |
|
|
254
|
+
| `VersionVector#increment` | a new `VersionVector` | `:unknown_member`, `:exhausted` |
|
|
255
|
+
|
|
256
|
+
Each refusal is the snake_case of one core `Refusal` variant. There is no catch-all symbol. No answer records a clock: the tracker takes no time at all, so the clock rule (an answer records `now` exactly when it depends on it) has nothing to apply to. There are no scoped ids either: replica ids, generations and counters are the caller's, not issued by the tracker.
|
|
257
|
+
|
|
258
|
+
Membership is fixed for the life of a tracker. Vectors from a different set of replicas mean nothing here, so the member list carries a generation number and stamps from any other generation are refused. Changing the membership means agreeing on a new generation somewhere else and building new trackers.
|
|
259
|
+
|
|
260
|
+
## The Rules of the Cutter
|
|
261
|
+
|
|
262
|
+
- **Ids, generations and counters are Integers** in `0..2**64-1`. Floats, nil, and strings raise `TypeError`. Out of range raises `RangeError`.
|
|
263
|
+
- **Values are valid or do not exist.** `VersionVector`, `Membership`, `Stamp`, `Gap`, `Page`, `Deliver` and `Obsolete` validate when built, by hand or by the tracker, through the core: a wrong type (an Array where a `VersionVector` belongs, say) raises `TypeError`, a value the core would not build raises `RangeError` (more than `MEMBERS` counters or members, duplicate members, a `Gap` from 0 or running backwards, a `Page` no listing answers: a cursor past the last slot, or more gaps than slots before its cursor). Every value class is final: subclassing one raises `TypeError` and `allocate` is gone, so nothing skips that check.
|
|
264
|
+
- **The binding trusts no value it reads.** Sealing stops accidents, not reflection: a named subclass's constant is bound before `inherited` raises, and `Marshal.load` skips `initialize`. So every value passed in must be an instance of exactly the gem's class (a subclass raises `TypeError`), and its fields are rebuilt through the core's constructors (a forged field raises `RangeError`). A forged value never reaches the core.
|
|
265
|
+
- **The binding never loses work.** Every conversion happens before the core is called, and the classes are resolved once, at load. Building an answer runs Ruby code (`new`), so `stamp` and `release` decide on a copy, build the answer, and keep the copy only if the tracker is still unfrozen and unchanged: if building raises, nothing is applied (no counter spent, no stamp taken from the hold table); if it freezes the tracker, `FrozenError`; if it re-enters and changes the tracker, `RuntimeError`, and the outer call is not applied.
|
|
266
|
+
- **Members are distinct and include you.** Duplicate members raise `RangeError` from `Membership.new`; a local id outside the membership, or a restored clock counting a slot outside it, raises `RangeError` from `Causal.new`/`Causal.restore`.
|
|
267
|
+
- **Refusals don't raise.** `:full`, `:conflict`, `:stale_generation`, `:future_generation`, `:unknown_member`, `:malformed` and `:exhausted` are answers. A refused call changes nothing. `:duplicate`, `:already_held`, `:not_held` and `:already_covered` are not refusals: the call was honoured and there was nothing left to do.
|
|
268
|
+
- **No work is lost to an exception.** Every argument is checked and every class looked up before the tracker changes; `release` cannot hand a stamp out of the hold table and then raise.
|
|
269
|
+
- **Mutating calls never answer a boolean.** Every answer is a value or a symbol, so no refusal can pass for `true` in an `if`. Only the predicates `dominates?`, `concurrent?`, `admits?` and `empty?` answer `true` or `false`.
|
|
270
|
+
- **One stamp per sender and counter.** A second stamp with the same sender and counter but a different clock is a `:conflict` while the first is held, even when the second could be delivered on the spot. The held one is never dropped for it.
|
|
271
|
+
- **Frozen means frozen.** `freeze` the tracker and `stamp`, `receive`, `release`, `forget` and `absorb` raise `FrozenError`. `check` and `missing` still answer.
|
|
272
|
+
|
|
273
|
+
## What You Think You're Doing vs Reality
|
|
274
|
+
|
|
275
|
+
### You Think: "I'll sort by timestamp, then process."
|
|
276
|
+
### Reality: A timestamp orders messages. It does not know which ones had met.
|
|
277
|
+
|
|
278
|
+
Two messages with timestamps 5 and 6 might be a question and its answer, or two strangers typing at once. A sort treats both cases the same, and gets the first one wrong whenever a clock drifts or a packet is slow. The stamp carries what the sender had actually seen, so the tracker can hold the answer for exactly the question it needs and let unrelated messages through without waiting.
|
|
279
|
+
|
|
280
|
+
## What's Yours
|
|
281
|
+
|
|
282
|
+
The tracker lives in your process and forgets everything when the process does. Persist `clock` and rebuild with `Causal.restore` if a restart must not reuse counters or redeliver. Payloads, the buffer that holds them while their stamp waits, the network, retransmission of the gaps `missing` reports, and any agreement on who the members are: all yours. Pre-1.0: breaking changes land in minor versions. It is the rulebook for causal order, not a broadcast runtime.
|
|
283
|
+
|
|
284
|
+
## License
|
|
285
|
+
|
|
286
|
+
MIT License. See [LICENSE.txt](LICENSE.txt) for details.
|
|
287
|
+
|
|
288
|
+
**Remember: the network will deliver the answer first. The question is whether you show it.**
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.7.0](https://github.com/seuros/causal_machines/compare/causal-machines-v0.6.0...causal-machines-v0.7.0) (2026-11-16)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### âš BREAKING CHANGES
|
|
7
|
+
|
|
8
|
+
* make Stamp fields private and rename Page::written to gaps
|
|
9
|
+
|
|
10
|
+
### Features
|
|
11
|
+
|
|
12
|
+
* make Stamp fields private and rename Page::written to gaps ([72e7251](https://github.com/seuros/causal_machines/commit/72e72511df535122c04c82b59293b7fbb7634063))
|
|
13
|
+
|
|
14
|
+
## [0.6.0](https://github.com/seuros/causal_machines/compare/causal-machines-v0.5.0...causal-machines-v0.6.0) (2026-11-14)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
### âš BREAKING CHANGES
|
|
18
|
+
|
|
19
|
+
* adopt matryona-machines 0.2: exact readers, symbols! tables, struct-only field reads
|
|
20
|
+
|
|
21
|
+
### Features
|
|
22
|
+
|
|
23
|
+
* adopt matryona-machines 0.2: exact readers, symbols! tables, struct-only field reads ([929e75f](https://github.com/seuros/causal_machines/commit/929e75f291a4e87ee25226b0c6e05e99f284339d))
|
|
24
|
+
|
|
25
|
+
## [0.5.0](https://github.com/seuros/causal_machines/compare/causal-machines-v0.4.0...causal-machines-v0.5.0) (2026-11-14)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
### âš BREAKING CHANGES
|
|
29
|
+
|
|
30
|
+
* validate Page and Gap in the core, refuse unissued missing cursors, seal values, clone-then-keep stamp/release
|
|
31
|
+
|
|
32
|
+
### Features
|
|
33
|
+
|
|
34
|
+
* validate Page and Gap in the core, refuse unissued missing cursors, seal values, clone-then-keep stamp/release ([87b24f6](https://github.com/seuros/causal_machines/commit/87b24f6c6c4c295e142fdafa01de7ab5e2dee17b))
|
|
35
|
+
|
|
36
|
+
## [0.4.0](https://github.com/seuros/causal_machines/compare/causal-machines-v0.3.0...causal-machines-v0.4.0) (2026-11-13)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
### âš BREAKING CHANGES
|
|
40
|
+
|
|
41
|
+
* see CONVENTIONS: one exhaustive Refusal per crate, Result from every mutator, honoured idempotent repeats, Ruby mirrors the core. No compatibility aliases. check and missing can answer Conflict; the Ruby class is Causal; release answers Deliver or Obsolete values.
|
|
42
|
+
|
|
43
|
+
### Features
|
|
44
|
+
|
|
45
|
+
* check conflicts on every receive path, Conflict and Full are refusals, forget answers Forgetting ([b2867a8](https://github.com/seuros/causal_machines/commit/b2867a83677cdc2180e9b771ce36eb4ed78624a9))
|
|
46
|
+
|
|
47
|
+
## [0.3.0](https://github.com/seuros/causal_machines/compare/causal-machines-v0.2.0...causal-machines-v0.3.0) (2026-11-13)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
### Features
|
|
51
|
+
|
|
52
|
+
* implement Default for Gap ([5aa1b2c](https://github.com/seuros/causal_machines/commit/5aa1b2c5029d9d45da2f1f8ca3fdfd19a659b8f7))
|
|
53
|
+
|
|
54
|
+
## [0.2.0](https://github.com/seuros/causal_machines/compare/causal-machines-v0.1.0...causal-machines-v0.2.0) (2026-11-12)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
### Features
|
|
58
|
+
|
|
59
|
+
* initial extraction ([cc9d39b](https://github.com/seuros/causal_machines/commit/cc9d39b5451f58f4762377dfa5dee280be0cbd9f))
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "causal-machines"
|
|
3
|
+
version = "0.7.0"
|
|
4
|
+
edition.workspace = true
|
|
5
|
+
rust-version.workspace = true
|
|
6
|
+
license.workspace = true
|
|
7
|
+
description = "Fixed-membership version vectors and bounded causal-delivery readiness"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
exclude = ["src/tests/", "src/**/tests.rs", "tests/"]
|
|
10
|
+
keywords = ["version-vector", "vector-clock", "causal", "replication", "no-std"]
|
|
11
|
+
categories = ["no-std", "algorithms"]
|
|
12
|
+
|
|
13
|
+
[dev-dependencies]
|
|
14
|
+
matryona-machines = { workspace = true, features = ["testing"] }
|
|
15
|
+
|
|
16
|
+
[lints]
|
|
17
|
+
workspace = true
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# causal-machines
|
|
2
|
+
|
|
3
|
+
> **AMS Fidge**, NCC-4231, *Fidge*-class causality cutter.
|
|
4
|
+
|
|
5
|
+
Engine-room flight manual: decide whether a dispatch may be opened yet, from
|
|
6
|
+
the vector it was stamped with.
|
|
7
|
+
|
|
8
|
+
Allocation-free `no_std` version vectors over a fixed membership, plus the
|
|
9
|
+
causal-delivery readiness check built on them. `VersionVector<N>` compares as a
|
|
10
|
+
partial order (`Equal`, `Before`, `After`, `Concurrent`), answers dominance and
|
|
11
|
+
concurrency, and merges by pointwise maximum. `Membership<N>` binds up to `N`
|
|
12
|
+
distinct replica ids to slots once; a different set of replicas is a different
|
|
13
|
+
membership generation.
|
|
14
|
+
|
|
15
|
+
`Causal<N, P>` is one replica's delivery state: the delivered clock and `P` hold
|
|
16
|
+
slots for the stamps of messages that arrived ahead of their dependencies. A
|
|
17
|
+
stamp is `Deliverable` when it is the sender's next message and everything the
|
|
18
|
+
sender had delivered is delivered here; `Duplicate` when the delivered clock
|
|
19
|
+
already covers it; otherwise `Missing`. `receive` delivers or parks, `release`
|
|
20
|
+
hands back parked stamps one at a time as their dependencies arrive (`None`
|
|
21
|
+
means nothing is ready), `forget` drops a parked stamp and says whether there
|
|
22
|
+
was one (`Forgetting::Forgotten` or `Forgetting::NotHeld`), and
|
|
23
|
+
`missing` lists the undelivered runs per replica into a caller buffer, resumable
|
|
24
|
+
by cursor. A cursor is a membership slot: 0 or a `Page::next` the tracker
|
|
25
|
+
handed out. One past the last slot was never issued and is refused with
|
|
26
|
+
`UnknownMember`, after the stamp itself is judged. It writes the first
|
|
27
|
+
`Page::gaps` entries of `out` and leaves the rest untouched (a refusal
|
|
28
|
+
writes none); build the buffer as `[Gap::default(); K]`. The default is a
|
|
29
|
+
placeholder the core never emits, because counters start at 1. A `Page`'s
|
|
30
|
+
fields are private: `Page::new::<N>(gaps, next)` rebuilds one and answers
|
|
31
|
+
`None` for a page `missing` could not have answered (more gaps than slots, a
|
|
32
|
+
cursor past the slots, or more gaps than slots before the cursor).
|
|
33
|
+
|
|
34
|
+
`Refusal` is the only refusal type, and no public enum is `#[non_exhaustive]`:
|
|
35
|
+
a new variant is a breaking change every caller matches on. A refused call was not honoured and leaves
|
|
36
|
+
the whole value untouched; `Causal` is `PartialEq`, so comparing against a
|
|
37
|
+
clone proves it. A stamp from another membership generation is refused with
|
|
38
|
+
`StaleGeneration` or `FutureGeneration`, an unknown sender with
|
|
39
|
+
`UnknownMember`, a clock counting outside the membership (or a zero sender
|
|
40
|
+
entry) with `Malformed`, and a counter at `u64::MAX` with `Exhausted`. A stamp
|
|
41
|
+
that must wait is refused with `Full` when no hold slot is free.
|
|
42
|
+
|
|
43
|
+
A stamp is refused with `Conflict` when a different stamp with the same sender
|
|
44
|
+
and counter is parked, on every path: whether the incoming stamp would have
|
|
45
|
+
been delivered, parked, or called a duplicate. Two stamps numbered alike with
|
|
46
|
+
different clocks cannot both be the sender's message, and the tracker cannot
|
|
47
|
+
tell which is, so it never drops or replaces the parked one for the other.
|
|
48
|
+
`check` and `missing` refuse the same way, so `check` answers what `receive`
|
|
49
|
+
would do. Parked stamps leave the hold table three ways only: handed back by
|
|
50
|
+
`release` (`Deliver` or `Obsolete`), dropped by name with `forget`, which is
|
|
51
|
+
how a caller resolves a conflict in favour of the refused stamp, or delivered
|
|
52
|
+
by `receive` when the identical stamp arrives again and is now ready. `absorb`
|
|
53
|
+
never touches the hold table.
|
|
54
|
+
|
|
55
|
+
`absorb` answers `Absorbing::Absorbed` when the clock advanced the delivered
|
|
56
|
+
clock and `Absorbing::AlreadyCovered` when the delivered clock already
|
|
57
|
+
dominated it: an idempotent repeat, provable from the delivered clock alone,
|
|
58
|
+
that changes nothing.
|
|
59
|
+
|
|
60
|
+
| Operation | Honoured | Refusals |
|
|
61
|
+
| --- | --- | --- |
|
|
62
|
+
| `stamp() -> Result<Stamp, Refusal>` | the stamp | `Exhausted` |
|
|
63
|
+
| `check(&stamp) -> Result<Readiness, Refusal>` | `Deliverable`, `Duplicate`, `Missing` | `StaleGeneration`, `FutureGeneration`, `UnknownMember`, `Malformed`, `Conflict` |
|
|
64
|
+
| `receive(&stamp) -> Result<Receipt, Refusal>` | `Delivered`, `Held`, `AlreadyHeld`, `Duplicate` | as `check`, plus `Full` |
|
|
65
|
+
| `release() -> Option<Release>` | a release, or `None` when nothing is ready | none |
|
|
66
|
+
| `forget(sender, counter) -> Result<Forgetting, Refusal>` | `Forgotten`, `NotHeld` | `UnknownMember` |
|
|
67
|
+
| `missing(&stamp, cursor, out) -> Result<Page, Refusal>` | the page | as `check`, then `UnknownMember` for a cursor past the last membership slot |
|
|
68
|
+
| `absorb(generation, &clock) -> Result<Absorbing, Refusal>` | `Absorbed`, `AlreadyCovered` | `StaleGeneration`, `FutureGeneration`, `Malformed` |
|
|
69
|
+
| `VersionVector::increment(slot) -> Result<u64, Refusal>` | the new counter | `UnknownMember`, `Exhausted` |
|
|
70
|
+
|
|
71
|
+
`Receipt::AlreadyHeld`, `Receipt::Duplicate`, `Forgetting::NotHeld` and
|
|
72
|
+
`Absorbing::AlreadyCovered` are idempotent repeats: what the caller asked for
|
|
73
|
+
already holds, so the call is honoured and changes nothing. In Ruby every
|
|
74
|
+
honoured outcome is the snake-case symbol of its variant.
|
|
75
|
+
|
|
76
|
+
No operation takes or records a clock: the core has no notion of time, so no
|
|
77
|
+
answer depends on `now`. It issues no ids either: replicas, generations and
|
|
78
|
+
counters are the caller's.
|
|
79
|
+
|
|
80
|
+
The values validate where they are built. `Membership::from_slice` refuses
|
|
81
|
+
duplicates and more than `N` ids, `Gap::new` refuses a run starting at 0 or
|
|
82
|
+
ending before it starts (its fields are private, read through `replica()`,
|
|
83
|
+
`from()` and `through()`, so no `Gap` skips that check), and `Stamp::new` and
|
|
84
|
+
`VersionVector::from_counters` accept every input; the receiving tracker judges
|
|
85
|
+
a stamp. A `Stamp` reads its parts through `generation()`, `sender()` and
|
|
86
|
+
`clock()`. In release builds no operation panics: an arm the invariants rule
|
|
87
|
+
out (a membership slot past `N`) is a `debug_assert!` that answers the most
|
|
88
|
+
conservative result with nothing changed.
|
|
89
|
+
|
|
90
|
+
This is a policy core. It stores stamps, never payloads. It has no transport, no
|
|
91
|
+
retransmission, no persistence, no clock and no membership change protocol. The
|
|
92
|
+
caller keys its own payload buffer by `(sender, counter)`, asks peers for the
|
|
93
|
+
gaps `missing` reports, and persists the delivered clock if a restart must not
|
|
94
|
+
reissue counters (`Causal::restore`).
|
|
95
|
+
|
|
96
|
+
```rust
|
|
97
|
+
use causal_machines::{Causal, Gap, Membership, Receipt, Release};
|
|
98
|
+
|
|
99
|
+
let members = Membership::<3>::from_slice(&[1, 2, 3]).expect("distinct ids");
|
|
100
|
+
let mut alice = Causal::<3, 4>::new(members, 1, 0).expect("member");
|
|
101
|
+
let mut bob = Causal::<3, 4>::new(members, 2, 0).expect("member");
|
|
102
|
+
let mut carol = Causal::<3, 4>::new(members, 3, 0).expect("member");
|
|
103
|
+
|
|
104
|
+
let question = alice.stamp().expect("counter has room");
|
|
105
|
+
assert_eq!(bob.receive(&question), Ok(Receipt::Delivered));
|
|
106
|
+
let answer = bob.stamp().expect("counter has room");
|
|
107
|
+
|
|
108
|
+
// The answer overtakes the question on the way to Carol.
|
|
109
|
+
assert_eq!(carol.receive(&answer), Ok(Receipt::Held));
|
|
110
|
+
let mut gaps = [Gap::default(); 3];
|
|
111
|
+
let page = carol.missing(&answer, 0, &mut gaps).expect("well formed");
|
|
112
|
+
assert_eq!((page.gaps(), page.next()), (1, None));
|
|
113
|
+
assert_eq!(Some(gaps[0]), Gap::new(1, 1, 1));
|
|
114
|
+
|
|
115
|
+
assert_eq!(carol.receive(&question), Ok(Receipt::Delivered));
|
|
116
|
+
assert_eq!(carol.release(), Some(Release::Deliver(answer)));
|
|
117
|
+
assert_eq!(carol.release(), None);
|
|
118
|
+
```
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
#![no_std]
|
|
2
|
+
#![cfg_attr(not(test), deny(clippy::indexing_slicing))]
|
|
3
|
+
#![doc = include_str!("../README.md")]
|
|
4
|
+
|
|
5
|
+
mod tracker;
|
|
6
|
+
mod vector;
|
|
7
|
+
|
|
8
|
+
pub use tracker::{Absorbing, Causal, Forgetting, Gap, Page, Readiness, Receipt, Release, Stamp};
|
|
9
|
+
pub use vector::{Causality, Membership, VersionVector};
|
|
10
|
+
|
|
11
|
+
/// Which replica an event came from.
|
|
12
|
+
pub type ReplicaId = u64;
|
|
13
|
+
|
|
14
|
+
/// Why a call was not honoured. A refused call leaves every state untouched.
|
|
15
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
16
|
+
pub enum Refusal {
|
|
17
|
+
/// The replica or slot is not part of the fixed membership.
|
|
18
|
+
UnknownMember,
|
|
19
|
+
/// The stamp was issued under an older membership generation.
|
|
20
|
+
StaleGeneration,
|
|
21
|
+
/// The stamp was issued under a membership generation not yet adopted here.
|
|
22
|
+
FutureGeneration,
|
|
23
|
+
/// The clock counts a slot outside the membership, or a stamp's sender
|
|
24
|
+
/// entry is zero.
|
|
25
|
+
Malformed,
|
|
26
|
+
/// The counter is at `u64::MAX`; no further event can be numbered.
|
|
27
|
+
Exhausted,
|
|
28
|
+
/// A parked stamp from the same sender with the same counter carries a
|
|
29
|
+
/// different clock. Answered whatever the readiness of either stamp:
|
|
30
|
+
/// deliverable, missing dependencies or already covered.
|
|
31
|
+
Conflict,
|
|
32
|
+
/// Dependencies are missing and every hold slot is taken.
|
|
33
|
+
Full,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
impl core::fmt::Display for Refusal {
|
|
37
|
+
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
|
38
|
+
f.write_str(match self {
|
|
39
|
+
Self::UnknownMember => "unknown member",
|
|
40
|
+
Self::StaleGeneration => "stale membership generation",
|
|
41
|
+
Self::FutureGeneration => "future membership generation",
|
|
42
|
+
Self::Malformed => "malformed clock",
|
|
43
|
+
Self::Exhausted => "counter exhausted",
|
|
44
|
+
Self::Conflict => "conflicting stamp already held",
|
|
45
|
+
Self::Full => "hold table full",
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
impl core::error::Error for Refusal {}
|
|
51
|
+
|
|
52
|
+
#[cfg(test)]
|
|
53
|
+
mod tests;
|