election_machines 0.1.5-aarch64-linux → 0.5.2-aarch64-linux

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 29d4c01a2d680a88316cfa83313040d0aa84dd74d31962db1608e3bb4452dd9f
4
- data.tar.gz: a53d8af2a9b815fd87b10494d7335703d9547fe7dcac02c218d958f0cc2f27a6
3
+ metadata.gz: 205e52e6c2ef3a7f082d18bcec9c062f5d69563ec1126f1c1fbf45fa179b1c1c
4
+ data.tar.gz: 02a4e840d38d419696d7be8c79bc9ad8f17a4395ed490f02854bcb062fc6ad04
5
5
  SHA512:
6
- metadata.gz: 9a133ef6d2028797c68a192038472db83dcb48a17d8de70b3ae5adb6a7b94db9df71047e837c06d5d2fd8aebb58977280b524d16e09940baf769aacf73b0af84
7
- data.tar.gz: e8f46a38a50c59a21c0ec2eff28c4c45e9dbb9ff0696c1904f5dee183df96633ff14b80c8e848fa824085a6313e7a11a48d59386b67d5e94071583661a9a7617
6
+ metadata.gz: c61d0b9a319454cf34acd2991cd383546de770bfdf44f00a4dd156adea5af861463a76c3034b4d489a527d6135bb194b2422fcf30c0ea4e08536ca442d8caa95
7
+ data.tar.gz: c68695da8e2b753afb0be369e6d439da2c5fd4468326bba661447ad5b46a59482b23f31c5552d136550d81d50d72fb510167dbfafd80dc7f9277f3f7c526db75
data/CHANGELOG.md CHANGED
@@ -1,5 +1,70 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.2](https://github.com/seuros/election_machines/compare/election_machines/v0.5.1...election_machines/v0.5.2) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * fix wrapped classes at load so building a value runs no Ruby ([098786d](https://github.com/seuros/election_machines/commit/098786dd4a933eea2390ec28e489ac7599086e51))
9
+
10
+ ## [0.5.1](https://github.com/seuros/election_machines/compare/election_machines/v0.5.0...election_machines/v0.5.1) (2026-11-16)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * elect queries the live incumbent before acquiring ([c27843a](https://github.com/seuros/election_machines/commit/c27843a2259b44bd6f642ad6c717bd84bcbff813))
16
+
17
+ ## [0.5.0](https://github.com/seuros/election_machines/compare/election_machines/v0.4.1...election_machines/v0.5.0) (2026-11-14)
18
+
19
+
20
+ ### ⚠ BREAKING CHANGES
21
+
22
+ * read sibling tokens, leases and checkpoints with own_or_sibling and delegate lease refusal names
23
+
24
+ ### Features
25
+
26
+ * read sibling tokens, leases and checkpoints with own_or_sibling and delegate lease refusal names ([1b7c5a9](https://github.com/seuros/election_machines/commit/1b7c5a99ae0720478b984cc2693afd6b28c5a26a))
27
+
28
+ ## [0.4.1](https://github.com/seuros/election_machines/compare/election_machines/v0.4.0...election_machines/v0.4.1) (2026-11-14)
29
+
30
+
31
+ ### Bug Fixes
32
+
33
+ * **deps:** require matryona-machines >= 0.3 and build exact-field messages lazily ([2af60e9](https://github.com/seuros/election_machines/commit/2af60e9b11cd79bf3a387edce8e26a442d94b10e))
34
+
35
+ ## [0.4.0](https://github.com/seuros/election_machines/compare/election_machines/v0.3.0...election_machines/v0.4.0) (2026-11-14)
36
+
37
+
38
+ ### ⚠ BREAKING CHANGES
39
+
40
+ * adopt matryona-machines 0.2: shared instant, exact field reads, compiler-checked symbol tables
41
+
42
+ ### Features
43
+
44
+ * adopt matryona-machines 0.2: shared instant, exact field reads, compiler-checked symbol tables ([b7cbfd2](https://github.com/seuros/election_machines/commit/b7cbfd2adb6edd2a7c5dce7e57c501d7f29a8c2b))
45
+
46
+ ## [0.3.0](https://github.com/seuros/election_machines/compare/election_machines/v0.2.0...election_machines/v0.3.0) (2026-11-14)
47
+
48
+
49
+ ### ⚠ BREAKING CHANGES
50
+
51
+ * validate every value through the core, seal values, exact-class reads, clone-then-keep elect/heartbeat/resign
52
+
53
+ ### Features
54
+
55
+ * validate every value through the core, seal values, exact-class reads, clone-then-keep elect/heartbeat/resign ([43bbf42](https://github.com/seuros/election_machines/commit/43bbf42813a6cc4ca663764c6ee1186eeff626ec))
56
+
57
+ ## [0.2.0](https://github.com/seuros/election_machines/compare/election_machines/v0.1.5...election_machines/v0.2.0) (2026-11-13)
58
+
59
+
60
+ ### ⚠ BREAKING CHANGES
61
+
62
+ * converted to the fleet conventions. One exhaustive Refusal per crate, Result from every operation that can refuse, a refusal changes nothing, provable idempotent repeats are honoured, Ruby mirrors the core. No compatibility aliases. Requires lease-machines >= 0.4. Refusal is { NoCandidates, Lease(LeaseRefusal) }; elect returns Result<Leadership, Refusal>; Ruby answers values and symbols instead of string tuples.
63
+
64
+ ### Features
65
+
66
+ * carry the lease refusal whole, honour a live incumbent, scoped restorable elections and Integer-nanosecond Ruby values ([7c23feb](https://github.com/seuros/election_machines/commit/7c23feb24c50da07795646ae7b37f7f04072f318))
67
+
3
68
  ## [0.1.5](https://github.com/seuros/election_machines/compare/election_machines/v0.1.4...election_machines/v0.1.5) (2026-11-06)
4
69
 
5
70
 
data/README.md CHANGED
@@ -11,22 +11,30 @@ gem 'election_machines'
11
11
  ```
12
12
 
13
13
  ```ruby
14
+ SECOND = 1_000_000_000 # every instant and span is Integer nanoseconds
15
+ now = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond) }
16
+
14
17
  election = ElectionMachines::Election.new
15
18
 
16
19
  # Three workers report in. The lowest id takes the chair.
17
- status, leader, token, expires_at = election.elect([9, 2, 5], clock.now, 30.0)
18
- # => ["elected", 2, 1, 30.0]
20
+ elected = election.elect([9, 2, 5], now.call, 30 * SECOND)
21
+ # => Elected(lease: Lease(owner: 2, token: FencingToken(raw: 1), expires_at: ...))
22
+ token = elected.lease.token
19
23
 
20
24
  # The leader keeps the chair by heartbeating with its token.
21
- election.heartbeat(2, token, clock.now, 30.0)
22
- # => ["renewed", 2, 1, ...]
25
+ election.heartbeat(2, token, now.call, 30 * SECOND)
26
+ # => Lease(owner: 2, token: FencingToken(raw: 1), expires_at: ...)
23
27
 
24
28
  # Anyone else asking while the lease is live just learns who's in charge.
25
- election.elect([5], clock.now, 30.0)
26
- # => ["incumbent", 2, 1, ...]
29
+ election.elect([5], now.call, 30 * SECOND)
30
+ # => Incumbent(lease: Lease(owner: 2, ...))
31
+
32
+ # A call that isn't honoured answers a Symbol and changes nothing.
33
+ election.heartbeat(5, token, now.call, 30 * SECOND)
34
+ # => :wrong_owner
27
35
  ```
28
36
 
29
- Every call returns the same four-element shape: a status string, then the leader, token, and expiry, or three nils when there's nothing to report.
37
+ The Ruby API is the core's, name for name: `ElectionMachines::Election` is the core's `Election`, every `Data` value has the fields of the core type it mirrors, and arguments come in the core's order. An honoured call answers a value (`Elected`, `Incumbent`, `Lease`). A refused one answers a Symbol, never raises, and leaves the election exactly as it was.
30
38
 
31
39
  ## A Message to the Resistance
32
40
 
@@ -58,10 +66,10 @@ end
58
66
  ```mermaid
59
67
  stateDiagram-v2
60
68
  [*] --> vacant
61
- vacant --> held: elect, lowest candidate wins, token n
62
- held --> held: heartbeat by leader with token, renewed
63
- held --> held: elect by anyone before expiry, incumbent
64
- held --> vacant: resign by leader with token, released
69
+ vacant --> held: elect, lowest candidate wins, Elected under token n
70
+ held --> held: heartbeat by leader with token, Lease renewed
71
+ held --> held: elect by anyone before expiry, Incumbent
72
+ held --> vacant: resign by leader with token, Lease given up
65
73
  held --> held: lease lapses, next elect names a new leader with token n+1
66
74
  ```
67
75
 
@@ -74,70 +82,75 @@ sequenceDiagram
74
82
  participant B as Scheduler B (id 2)
75
83
 
76
84
  A->>E: elect([1, 2], t=0, ttl=30)
77
- E-->>A: elected, leader 1, token 1, expires 30
85
+ E-->>A: Elected, leader 1, token 1, expires 30
78
86
  Note over A: ticks the cron table, heartbeats every 10s
79
87
  A->>E: heartbeat(1, token 1, t=10, ttl=30)
80
- E-->>A: renewed, expires 40
88
+ E-->>A: Lease, expires 40
81
89
 
82
90
  Note over A: partitioned at t=12, silent
83
91
 
84
92
  B->>E: elect([2], t=20, ttl=30)
85
- E-->>B: incumbent, leader 1, token 1, expires 40
93
+ E-->>B: Incumbent, leader 1, token 1, expires 40
86
94
  Note over B: lease still live. B waits.
87
95
 
88
96
  B->>E: elect([2], t=45, ttl=30)
89
- E-->>B: elected, leader 2, token 2, expires 75
97
+ E-->>B: Elected, leader 2, token 2, expires 75
90
98
  Note over B: now ticks the cron table
91
99
 
92
100
  Note over A: partition heals at t=50
93
101
  A->>E: heartbeat(1, token 1, t=50, ttl=30)
94
- E-->>A: WrongOwner
102
+ E-->>A: :wrong_owner
95
103
  Note over A: stands down. One captain the whole time.
96
104
  ```
97
105
 
98
106
  ## How the Relay Works
99
107
 
108
+ The examples count in seconds to stay readable: `s = 1_000_000_000`, so `10 * s` is ten seconds of Integer nanoseconds.
109
+
100
110
  ### Elect
101
111
 
102
- Pass the ids of the workers that are present, the current time, and how long the lease should last. The lowest id wins. The token starts at 1 and only ever goes up.
112
+ Pass the ids of the workers that are present, the current time, and how long the lease should last. The lowest id wins. The list can be any length. The token's sequence starts at 1 and only ever goes up.
103
113
 
104
114
  ```ruby
105
115
  election = ElectionMachines::Election.new
106
116
 
107
- election.elect([9, 2, 5], 0, 10) # => ["elected", 2, 1, 10.0]
108
- election.lease # => [2, 1, 10.0]
117
+ elected = election.elect([9, 2, 5], 0, 10 * s)
118
+ elected.lease # => Lease(owner: 2, token: FencingToken(raw: 1), expires_at: 10 * s)
119
+ elected.incumbent? # => false
120
+ election.lease # => the same Lease
109
121
  ```
110
122
 
111
- Ask again while that lease is live and you get the incumbent, even if you offer a lower id. Sitting captains aren't unseated by a late arrival.
123
+ Ask again while that lease is live and you get the incumbent, even if you offer a lower id. Sitting captains aren't unseated by a late arrival. `Incumbent` is an honoured answer, not a refusal: there is a leader, here is its lease, and nothing changed.
112
124
 
113
125
  ```ruby
114
- election.elect([1], 1, 10) # => ["incumbent", 2, 1, 10.0]
126
+ election.elect([1], 1 * s, 10 * s) # => Incumbent(lease: Lease(owner: 2, ...))
115
127
  ```
116
128
 
117
- An empty roster is `no_candidates`.
129
+ An empty roster is the refusal `:no_candidates`, whatever the clock and whoever sits in the chair: nobody was nominated. To learn who leads without nominating anyone, read `election.lease`.
118
130
 
119
131
  ### Heartbeat
120
132
 
121
- The leader renews by presenting its id and token. The new expiry is counted from `now`.
133
+ The leader renews by presenting its id and token. The new expiry is counted from `now`, and it never moves backwards: a repeated or reordered heartbeat is honoured and loses no time.
122
134
 
123
135
  ```ruby
124
136
  election = ElectionMachines::Election.new
125
- election.elect([2], 0, 10)
137
+ token = election.elect([2], 0, 10 * s).lease.token
126
138
 
127
- election.heartbeat(2, 1, 3, 10) # => ["renewed", 2, 1, 13.0]
128
- election.heartbeat(1, 1, 4, 10) # => ["WrongOwner", nil, nil, nil]
139
+ election.heartbeat(2, token, 3 * s, 10 * s) # => Lease(owner: 2, token: ..., expires_at: 13 * s)
140
+ election.heartbeat(1, token, 4 * s, 10 * s) # => :wrong_owner
129
141
  ```
130
142
 
131
143
  A heartbeat from anyone but the leader is refused and changes nothing.
132
144
 
133
145
  ### Resign
134
146
 
135
- A leader steps down by presenting its token. The chair is vacant immediately, and the next election fills it.
147
+ A leader steps down by presenting its token, and is answered the lease it gave up. The chair is vacant immediately, and the next election fills it.
136
148
 
137
149
  ```ruby
138
- election.resign(2, 1, 5) # => ["released", nil, nil, nil]
139
- election.lease # => nil
140
- election.elect([7, 3], 6, 10) # => ["elected", 3, 2, 16.0]
150
+ election.resign(2, token, 5 * s) # => Lease(owner: 2, ...), the one given up
151
+ election.lease # => nil
152
+ election.resign(2, token, 5 * s) # => :no_lease, the election keeps no record of who resigned
153
+ election.elect([7, 3], 6 * s, 10 * s) # => Elected(lease: Lease(owner: 3, token: FencingToken(raw: 2), ...))
141
154
  ```
142
155
 
143
156
  Token 2. The old token is dead from here on.
@@ -148,51 +161,96 @@ Nothing happens at the moment of expiry. The chair is only re-filled when someon
148
161
 
149
162
  ```ruby
150
163
  election = ElectionMachines::Election.new
151
- election.elect([2], 0, 10)
164
+ old = election.elect([2], 0, 10 * s).lease.token
152
165
 
153
- election.heartbeat(2, 1, 11, 10) # => ["Expired", nil, nil, nil]
154
- election.lease # => [2, 1, 10.0]
166
+ election.heartbeat(2, old, 11 * s, 10 * s) # => :expired
167
+ election.lease # => Lease(owner: 2, ..., expires_at: 10 * s)
155
168
 
156
- election.elect([5], 12, 10) # => ["elected", 5, 2, 22.0]
157
- election.heartbeat(2, 1, 13, 10) # => ["WrongOwner", nil, nil, nil]
169
+ election.elect([5], 12 * s, 10 * s) # => Elected(lease: Lease(owner: 5, token: FencingToken(raw: 2), ...))
170
+ election.heartbeat(2, old, 13 * s, 10 * s) # => :wrong_owner
158
171
  ```
159
172
 
160
- The old leader's late heartbeat is rejected with `WrongOwner`. Its token is also stale, and `StaleToken` is what you'd see if it had the right id and the wrong token.
173
+ The old leader's late heartbeat is refused with `:wrong_owner`. Its token is also stale, and `:stale_token` is what you'd see if it had the right id and the wrong token.
161
174
 
162
175
  ### Time only moves forward
163
176
 
164
- You supply `now`. The election remembers the latest it has seen and refuses to go backwards.
177
+ You supply `now`. The election remembers the latest one it honoured and refuses to go backwards. A refused call never moves that watermark.
165
178
 
166
179
  ```ruby
167
180
  election = ElectionMachines::Election.new
168
- election.elect([2], 5, 10)
169
- election.elect([2], 0, 10) # => ["ClockRegressed", nil, nil, nil]
181
+ election.elect([2], 5 * s, 10 * s)
182
+ election.elect([2], 0, 10 * s) # => :clock_regressed
170
183
  ```
171
184
 
172
- Feed it a monotonic clock. Not the wall clock.
185
+ Feed it a monotonic clock, `Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)`. Not the wall clock. If your clock can step back and you would rather not refuse, `election.with_clock_policy(:clamp)` evaluates an earlier `now` at the watermark instead, so a backwards step can neither revive a lease nor shorten one.
186
+
187
+ ### Tokens and scopes
188
+
189
+ A `FencingToken` is plain data: `raw` is the election's scope in the top 16 bits above a sequence number counted from 1. `ElectionMachines::Election.new` is scope zero, so its tokens read 1, 2, 3. Two elections in one scope issue the same tokens, so give every election whose tokens could meet its own scope:
190
+
191
+ ```ruby
192
+ billing = ElectionMachines::Election.with_scope(1)
193
+ reports = ElectionMachines::Election.with_scope(2)
194
+
195
+ token = billing.elect([4], 0, 10 * s).lease.token
196
+ token.scope # => 1
197
+ reports.heartbeat(4, token, 1 * s, 10 * s) # => :unknown, not a token of this election
198
+ ```
199
+
200
+ Tokens of one scope are ordered, tokens of two scopes are not, so there is no `<`. Compare with `token.order(other)` (`-1`, `0`, `1`, or `nil` across scopes) and `token.newer_than?(other)`.
201
+
202
+ `FencingToken`, `Lease` and `Checkpoint` are the lease core's types, which the election core re-exports. Wherever a method takes one it reads it by its readers (`raw`; `owner`, `token`, `expires_at`; `scope`, `issued`, `lease`, `observed`), so the `lease_machines` gem's values of the same names fit as they are. This gem does not depend on that one. A bare Integer is not a token: it raises `TypeError`. What it keeps is always its own: a `Lease` built with the lease gem's token, a `Checkpoint`, `Elected` or `Incumbent` built with the lease gem's lease, holds this gem's `FencingToken` and `Lease`, so it is `==` to what the election answers.
173
203
 
174
204
  ## Checkpoints
175
205
 
176
- An election can hand you a `Checkpoint` and roll back to it, but only itself, and only to the most recent one.
206
+ A fresh election counts from 1 again, so it would hand out tokens the old one already issued. To survive a restart, write the checkpoint down before anyone acts on the decision that produced it, and build the next election from it.
177
207
 
178
208
  ```ruby
179
- election = ElectionMachines::Election.new
180
- election.elect([1], 0, 10)
209
+ election = ElectionMachines::Election.with_scope(7)
210
+ election.elect([1], 0, 10 * s)
181
211
  saved = election.checkpoint
212
+ # => Checkpoint(scope: 7, issued: 1, lease: Lease(owner: 1, ...), observed: 0)
182
213
 
183
- election.heartbeat(1, 1, 1, 10) # => ["renewed", 1, 1, 11.0]
184
- election.restore!(saved) # => ArgumentError, a transition happened since
214
+ # The process dies. Rebuild from the four stored fields.
215
+ saved = ElectionMachines::Checkpoint.from_parts(scope, issued, lease, observed)
216
+ election = ElectionMachines::Election.restored(7, saved, :reject)
217
+ election.elect([2], 10 * s, 10 * s).lease.token # => FencingToken(raw: (7 << 48) | 2), never 1 again
185
218
  ```
186
219
 
187
- Any successful transition, or any successful restore, invalidates every checkpoint taken before it. That rules out rewinding past a decision someone has already acted on. A checkpoint from one election can't be fed to another. This is for testing and in-process simulation, not for surviving a restart.
220
+ `restored(scope, checkpoint, clock_policy)` takes the scope and the clock policy explicitly: the scope is yours to pass, never read out of the checkpoint, and a checkpoint of another scope raises `RangeError`. A `Checkpoint` is plain data, so any election of that scope can be restored from it, and a refused call leaves an earlier checkpoint as current as it was. `Checkpoint.from_parts` raises `RangeError` when the fields contradict each other: a live lease must carry token number `issued` of `scope`.
221
+
222
+ One thing no value can check: restoring an older checkpoint than the newest one you committed reissues tokens. Persist first, expose second.
223
+
224
+ ## Every answer
225
+
226
+ | Method | Honoured | Refused (changes nothing) | Records the clock |
227
+ | --- | --- | --- | --- |
228
+ | `elect(candidates, now, ttl)` | `Elected(lease)` (new leader, new token), `Incumbent(lease)` (live leader stays, nothing changed) | `:no_candidates`, `:clock_regressed`, `:invalid_ttl`, `:exhausted` | `Elected`: yes, the new lease's expiry depends on `now`. `Incumbent`: no, nothing changes |
229
+ | `heartbeat(owner, token, now, ttl)` | `Lease` under the same token; a repeat is honoured | `:unknown`, `:clock_regressed`, `:no_lease`, `:wrong_owner`, `:stale_token`, `:expired`, `:invalid_ttl` | yes: honoured only while unexpired at `now`, a repeat included |
230
+ | `resign(owner, token, now)` | `Lease`, the one given up | `:unknown`, `:clock_regressed`, `:no_lease` (a repeat included), `:wrong_owner`, `:stale_token`, `:expired` | yes: honoured only while unexpired at `now` |
231
+ | `lease` | `Lease` or `nil` | | |
232
+ | `checkpoint` | `Checkpoint` | | |
233
+ | `scope`, `issued`, `clock_policy` | Integer, Integer, `:reject` or `:clamp` | | |
234
+ | `with_clock_policy(clock_policy)` | the election itself | | |
235
+ | `Election.new`, `Election.with_scope(scope)` | `Election` | | |
236
+ | `Election.restored(scope, checkpoint, clock_policy)` | `Election` | raises `RangeError` for a checkpoint of another scope | |
237
+
238
+ Under `:clamp` the instant recorded is the one the call was evaluated at, so the observed clock stays where it was.
239
+
240
+ `ElectionMachines::REFUSALS` lists exactly the nine symbols above, the ones an election can answer. `:no_candidates` is the election's own. The other eight are the lease core's refusals, which the election core carries whole (`Refusal::Lease(..)`) and answers under the lease core's own symbol, so `:wrong_owner` here is the `lease_machines` gem's `:wrong_owner`. The lease core's `:occupied` and `:held` never come back: a live leader is the honoured `Incumbent`. Its `:fenced` and `:out_of_phase` belong to the lease holder, which an election has none of.
188
241
 
189
242
  ## The Rules of the Relay
190
243
 
191
- - **Ids and tokens are Integers** in `0..2**64-1`. Up to 64 candidates per election. Floats and strings raise `TypeError`, out of range raises `RangeError`, a 65th candidate raises `ArgumentError`.
192
- - **Times are seconds** as Integer or Float, from a monotonic origin you choose. `ttl` must be positive. Negative, infinite, NaN, or absurdly large values raise `ArgumentError`.
193
- - **Rejections don't raise.** `WrongOwner`, `StaleToken`, `Expired`, `ClockRegressed`, and `no_candidates` all come back as a status with three nils. Only malformed input raises.
194
- - **Bad input never half-applies.** Arguments are checked before anything changes.
195
- - **Frozen means frozen.** `freeze` the election and `elect`, `heartbeat`, `resign`, and `restore!` raise `FrozenError`. `lease` still reads.
244
+ - **Owners are Integers** in `0..2**64-1`, in a list of any length. Floats, strings and nil raise `TypeError`, out of range raises `RangeError`.
245
+ - **Times are Integer nanoseconds**, from a monotonic origin you choose, for instants (`now`, `expires_at`, `observed`) and spans (`ttl`) alike. A Float raises `TypeError`, a negative or unrepresentable value raises `RangeError`. A zero `ttl`, or one that overflows, is the refusal `:invalid_ttl`.
246
+ - **Refusals don't raise.** Every one is a Symbol: `:no_candidates` for the core's `Refusal::NoCandidates`, and for `Refusal::Lease(reason)` the lease core's symbol for `reason`. There is no catch-all. Only malformed input raises: `TypeError` for the wrong type, `RangeError` for a value the core does not accept (a clock policy other than `:reject` or `:clamp` included). Nothing raises `ArgumentError` except Ruby itself, for the wrong number of arguments.
247
+ - **Values are valid or do not exist.** `FencingToken.new`, `Lease.new`, `Checkpoint.new`, `Elected.new` and `Incumbent.new` are checked by the core whoever calls them: `Lease.new('x', token, 0)` raises `TypeError`, `Lease.new(1, token, -1)` raises `RangeError`.
248
+ - **The binding never loses work.** Every argument is read and checked before the election is asked anything. Building the answer runs Ruby (`Elected.new`, `Incumbent.new`, `Lease.new`, `FencingToken.new`), so the election decides on a copy, the answer is built, and the copy is kept only if the election is still unfrozen (`FrozenError` otherwise) and unchanged (`RuntimeError` otherwise: something re-entered it while the answer was built). A call that raised changed nothing.
249
+ - **The binding is the authority on values.** `FencingToken`, `Lease`, `Checkpoint`, `Elected` and `Incumbent` are sealed (no `allocate`, no subclass), but Ruby binds a subclass constant before `inherited` raises, `Data#initialize` can be bound directly and `Marshal.load` skips `initialize`. So the native side reads one of this gem's values only when it is exactly that class (a subclass raises `TypeError`, whatever it holds) and checks every field again as the core's constructor does: a forged value raises `TypeError` or `RangeError` and never reaches the election.
250
+ - **A refusal changes nothing.** Not the lease, not the token count, not the observed clock, not the checkpoint you saved a moment ago.
251
+ - **Honoured repeats.** `Incumbent` and a repeated `heartbeat` are honoured. A repeated `resign` is `:no_lease`, because the election cannot prove who resigned.
252
+ - **Scopes are yours.** `with_scope(scope)` takes an Integer in `0..65_535`; a token of another scope is `:unknown` before anything is looked up.
253
+ - **Frozen means frozen.** `freeze` the election and `elect`, `heartbeat`, `resign`, and `with_clock_policy` raise `FrozenError`. The readers still read.
196
254
 
197
255
  ## What You Think You're Doing vs Reality
198
256
 
@@ -203,7 +261,7 @@ A partition looks identical to a crash from the outside. If your election promot
203
261
 
204
262
  ## What's Yours
205
263
 
206
- The election decides. It doesn't talk to the network, run timers, or store anything across a restart. Run it in one place, write its decisions down before anyone acts on them, and make the thing the leader controls check the token before every action. A token the resource has already seen beaten is a captain who has already been replaced.
264
+ The election decides. It doesn't talk to the network, run timers, or store anything: surviving a restart is `checkpoint` plus your storage. Run it in one place, write its decisions down before anyone acts on them, and make the thing the leader controls check the token before every action. A token the resource has already seen beaten is a captain who has already been replaced.
207
265
 
208
266
  ## License
209
267
 
@@ -1,5 +1,45 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.1](https://github.com/seuros/election_machines/compare/election-machines-v0.5.0...election-machines-v0.5.1) (2026-11-16)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * elect queries the live incumbent before acquiring ([c27843a](https://github.com/seuros/election_machines/commit/c27843a2259b44bd6f642ad6c717bd84bcbff813))
9
+
10
+ ## [0.5.0](https://github.com/seuros/election_machines/compare/election-machines-v0.4.0...election-machines-v0.5.0) (2026-11-14)
11
+
12
+
13
+ ### ⚠ BREAKING CHANGES
14
+
15
+ * adopt matryona-machines 0.2: shared instant, exact field reads, compiler-checked symbol tables
16
+
17
+ ### Features
18
+
19
+ * adopt matryona-machines 0.2: shared instant, exact field reads, compiler-checked symbol tables ([b7cbfd2](https://github.com/seuros/election_machines/commit/b7cbfd2adb6edd2a7c5dce7e57c501d7f29a8c2b))
20
+
21
+ ## [0.4.0](https://github.com/seuros/election_machines/compare/election-machines-v0.3.0...election-machines-v0.4.0) (2026-11-14)
22
+
23
+
24
+ ### ⚠ BREAKING CHANGES
25
+
26
+ * validate every value through the core, seal values, exact-class reads, clone-then-keep elect/heartbeat/resign
27
+
28
+ ### Features
29
+
30
+ * validate every value through the core, seal values, exact-class reads, clone-then-keep elect/heartbeat/resign ([43bbf42](https://github.com/seuros/election_machines/commit/43bbf42813a6cc4ca663764c6ee1186eeff626ec))
31
+
32
+ ## [0.3.0](https://github.com/seuros/election_machines/compare/election-machines-v0.2.2...election-machines-v0.3.0) (2026-11-13)
33
+
34
+
35
+ ### ⚠ BREAKING CHANGES
36
+
37
+ * converted to the fleet conventions. One exhaustive Refusal per crate, Result from every operation that can refuse, a refusal changes nothing, provable idempotent repeats are honoured, Ruby mirrors the core. No compatibility aliases. Requires lease-machines >= 0.4. Refusal is { NoCandidates, Lease(LeaseRefusal) }; elect returns Result<Leadership, Refusal>; Ruby answers values and symbols instead of string tuples.
38
+
39
+ ### Features
40
+
41
+ * carry the lease refusal whole, honour a live incumbent, scoped restorable elections and Integer-nanosecond Ruby values ([7c23feb](https://github.com/seuros/election_machines/commit/7c23feb24c50da07795646ae7b37f7f04072f318))
42
+
3
43
  ## [0.2.2](https://github.com/seuros/election_machines/compare/election-machines-v0.2.1...election-machines-v0.2.2) (2026-11-06)
4
44
 
5
45
 
@@ -11,7 +11,98 @@ list; this list is not a consensus membership configuration.
11
11
 
12
12
  All lease-machine persistence, fencing, authentication, and clock requirements
13
13
  apply. A fresh election instance is a fresh namespace, not failover recovery.
14
- Empty candidate lists make no authority transition. Heartbeats renew a lease;
15
- they are not an asynchronous failure detector. This policy is **not Raft,
16
- quorum voting, or partition-safe leader election without an external serialized
17
- durable authority**. Raft elections remain in `consensus-machines`.
14
+ Heartbeats renew a lease; they are not an asynchronous failure detector. This
15
+ policy is **not Raft, quorum voting, or partition-safe leader election without
16
+ an external serialized durable authority**. Raft elections remain in
17
+ `consensus-machines`.
18
+
19
+ ## Contract
20
+
21
+ - **One refusal type.** Every call that can refuse returns
22
+ `Result<_, Refusal>`, and a refusal changes nothing: no grant, no token, no
23
+ observed clock. `Refusal` has two variants: `NoCandidates`, the election's
24
+ own, and `Lease(LeaseRefusal)`, which carries the embedded
25
+ `LeaseAuthority`'s refusal whole. `LeaseRefusal` is `lease_machines::Refusal`,
26
+ re-exported; `Refusal: From<LeaseRefusal>`. `Lease(..)` displays as "the
27
+ lease authority refused" and its `Error::source` is the carried lease
28
+ refusal, so an error chain prints each reason once. The election copies none of the lease core's names, so it
29
+ has no variant it cannot answer. The table below lists which lease refusals
30
+ can arrive from each call; `Occupied`, `Held`, `Fenced` and `OutOfPhase`
31
+ arrive from none.
32
+ - **A live incumbent is honoured, not refused.** `elect` answers
33
+ `Ok(Leadership::Incumbent(lease))` with the lease in force, whoever the
34
+ candidates were, and changes nothing. `elect` asks the authority for the live
35
+ grant first (`LeaseAuthority::incumbent`, which checks the clock and the ttl
36
+ as `acquire` would) and acquires only when there is none, so the authority
37
+ never has a live grant to answer `Occupied` or `Held` for.
38
+ `Ok(Leadership::Elected(lease))` is a new leader under a new token.
39
+ - **An empty candidate list is a refusal**, `NoCandidates`, checked before the
40
+ clock and whatever the incumbent: nobody was nominated, so nothing was
41
+ honoured. Read the leader with `lease()`.
42
+ - **Repeats.** A repeated `heartbeat` is honoured and never shortens the
43
+ lease. A repeated `resign` is `Lease(NoLease)`: the election keeps no record of who
44
+ resigned what, so it cannot prove the claim.
45
+ - **Scopes.** The election issues no ids of its own: leadership tokens come
46
+ from the authority's sequence and carry its scope. `Election::with_scope`
47
+ picks it, `new()` is scope zero, and a token of another scope, or one never
48
+ issued, is `Lease(Unknown)` before any lookup. Tokens of two scopes have no order:
49
+ compare with `FencingToken::order` or `is_newer_than`.
50
+ - **Restarts.** A fresh election counts from one again. Persist `checkpoint()`
51
+ before exposing a decision and rebuild with
52
+ `Election::restored(scope, checkpoint, clock)`: the scope and the clock
53
+ policy are stated again, and a checkpoint of another scope is `None`.
54
+ Restoring an older checkpoint than the newest committed one reissues tokens;
55
+ no pure value can detect that.
56
+ - **Time** is `core::time::Duration` since an epoch the caller picks, for
57
+ `now`, `ttl` and `expires_at` alike. Under `ClockPolicy::Reject` an earlier
58
+ `now` is `Lease(ClockRegressed)`; under `Clamp` the call is evaluated at the latest
59
+ honoured observation.
60
+ - **Sibling types.** `OwnerId`, `FencingToken`, `Lease`, `Checkpoint` and
61
+ `ClockPolicy` are `lease-machines` types, re-exported here, and so is its
62
+ `Refusal`, as `LeaseRefusal`.
63
+
64
+ | Call | Honoured | Refused: own | Refused: `Lease(..)` carrying | Records `now` |
65
+ | --- | --- | --- | --- | --- |
66
+ | `elect(candidates, now, ttl)` | `Leadership::Elected(lease)`, `Leadership::Incumbent(lease)` | `NoCandidates` | `ClockRegressed`, `InvalidTtl`, `Exhausted` | `Elected`: yes, the new grant's expiry depends on it. `Incumbent`: no, nothing changes |
67
+ | `heartbeat(owner, token, now, ttl)` | `Lease` (same token) | | `Unknown`, `ClockRegressed`, `NoLease`, `WrongOwner`, `StaleToken`, `Expired`, `InvalidTtl` | yes: honoured only while unexpired at `now`, a replay included |
68
+ | `resign(owner, token, now)` | `Lease` (the one given up) | | `Unknown`, `ClockRegressed`, `NoLease`, `WrongOwner`, `StaleToken`, `Expired` | yes: honoured only while unexpired at `now` |
69
+ | `restored(scope, checkpoint, clock)` | `Some(Election)` | `None`: the checkpoint is of another scope | | |
70
+
71
+ Under `Clamp` the instant recorded is the one the call was evaluated at, so
72
+ the watermark stays where it was. A refusal records nothing.
73
+
74
+ ## Example
75
+
76
+ ```rust
77
+ use core::time::Duration;
78
+ use election_machines::{ClockPolicy, Election, Leadership, LeaseRefusal, OwnerId, Refusal};
79
+
80
+ fn main() -> Result<(), Box<dyn std::error::Error>> {
81
+ let seconds = Duration::from_secs;
82
+ let mut election = Election::with_scope(7);
83
+
84
+ let candidates = [OwnerId::new(9), OwnerId::new(2)];
85
+ let elected = election.elect(&candidates, seconds(0), seconds(30))?;
86
+ assert!(!elected.is_incumbent(), "nobody led before");
87
+ let lease = elected.lease();
88
+ assert_eq!((lease.owner(), lease.token().scope()), (OwnerId::new(2), 7));
89
+
90
+ // A live leader stays, whoever asks; nothing changes.
91
+ let asked = election.elect(&[OwnerId::new(1)], seconds(1), seconds(30))?;
92
+ assert_eq!(asked, Leadership::Incumbent(lease));
93
+
94
+ let renewed = election.heartbeat(lease.owner(), lease.token(), seconds(10), seconds(30))?;
95
+ assert_eq!(renewed.expires_at(), seconds(40));
96
+ let stranger = election.heartbeat(OwnerId::new(9), lease.token(), seconds(11), seconds(30));
97
+ assert_eq!(stranger, Err(Refusal::Lease(LeaseRefusal::WrongOwner)));
98
+
99
+ // Persist the checkpoint, then restore it under the same scope only.
100
+ let saved = election.checkpoint();
101
+ assert!(Election::restored(8, saved.clone(), ClockPolicy::Reject).is_none());
102
+ let mut restored = Election::restored(7, saved, ClockPolicy::Reject).ok_or("another scope")?;
103
+ restored.resign(lease.owner(), lease.token(), seconds(12))?;
104
+ let next = restored.elect(&candidates, seconds(12), seconds(30))?.lease();
105
+ assert!(next.token().is_newer_than(lease.token()));
106
+ Ok(())
107
+ }
108
+ ```
@@ -1,4 +1,4 @@
1
1
  # frozen_string_literal: true
2
2
  module ElectionMachines
3
- VERSION = '0.1.5'
3
+ VERSION = '0.5.2'
4
4
  end
@@ -1,3 +1,171 @@
1
1
  # frozen_string_literal: true
2
+
2
3
  require_relative 'election_machines/version'
4
+
5
+ # Every value mirrors the core type of the same name, field for field, and
6
+ # every method takes the core's arguments in the core's order. Every instant
7
+ # and span (`now`, `ttl`, `expires_at`, `observed`) is Integer nanoseconds.
8
+ # Owners are Integers: the core's `OwnerId` is the caller's number.
9
+ #
10
+ # FencingToken, Lease and Checkpoint are the lease core's types, which the
11
+ # election core re-exports. Wherever a method takes one it reads it by its
12
+ # readers, so the `lease_machines` gem's values of the same names fit as they
13
+ # are; this gem does not depend on that one.
14
+ #
15
+ # The native side is the authority on every value it reads: one of this gem's
16
+ # classes must be exactly that class (a subclass is a TypeError, whatever it
17
+ # holds), and every field is validated again through the core constructor, so
18
+ # a value forged past `initialize` (`Marshal.load`, a bound
19
+ # `Data#initialize`) raises TypeError or RangeError and never reaches the core.
20
+ module ElectionMachines
21
+
22
+ # A fencing token: the issuing election's scope in the top 16 bits of `raw`
23
+ # above a sequence number counted from 1. Plain data, so it survives a trip
24
+ # over the wire as `raw` and comes back with `from_raw`. A token built here
25
+ # proves nothing by itself: the election still answers :unknown to one it
26
+ # never issued.
27
+ #
28
+ # Tokens of one scope are ordered; tokens of two scopes are not, so there is
29
+ # no `<` or `<=>`. Compare with `order` and `newer_than?`.
30
+ FencingToken = Data.define(:raw) do
31
+ # The core's `FencingToken::from_raw`. RangeError when the sequence number
32
+ # is zero, which no election issues.
33
+ def self.from_raw(raw) = new(raw)
34
+
35
+ def initialize(raw:)
36
+ ElectionMachines.__send__(:native_raw, raw)
37
+ super
38
+ end
39
+
40
+ # The scope of the election that issued this token.
41
+ def scope = ElectionMachines.__send__(:native_token_scope, self)
42
+
43
+ # -1, 0 or 1 against a token of the same scope; nil across scopes.
44
+ def order(other) = ElectionMachines.__send__(:native_token_order, self, other)
45
+
46
+ # Whether this token is of `other`'s scope and strictly newer. False across
47
+ # scopes, so its negation does not mean "older or equal".
48
+ def newer_than?(other) = ElectionMachines.__send__(:native_token_newer, self, other)
49
+ end
50
+
51
+ # One leadership: who leads, under which token, until when. Built by hand
52
+ # it is held to the rule a granted one is: an Integer owner in 0..2**64-1,
53
+ # a token read by its `raw` reader and kept as this gem's FencingToken,
54
+ # Integer nanoseconds. TypeError for the wrong type, RangeError for a value
55
+ # outside that.
56
+ Lease = Data.define(:owner, :token, :expires_at) do
57
+ def initialize(owner:, token:, expires_at:)
58
+ super(owner:, token: ElectionMachines.__send__(:native_lease, owner, token, expires_at), expires_at:)
59
+ end
60
+ end
61
+
62
+ # Committed election state, the core's `Checkpoint`: persist the four fields
63
+ # before exposing a decision, rebuild with `from_parts`. RangeError when
64
+ # `issued` is beyond the scope's token space or `lease` is not the grant
65
+ # that history ends with (it must carry token number `issued` of `scope`).
66
+ #
67
+ # `lease` is read by its readers and kept as this gem's Lease.
68
+ Checkpoint = Data.define(:scope, :issued, :lease, :observed) do
69
+ # The core's `Checkpoint::from_parts`.
70
+ def self.from_parts(scope, issued, lease, observed) = new(scope, issued, lease, observed)
71
+
72
+ def initialize(scope:, issued:, lease:, observed:)
73
+ held = ElectionMachines.__send__(:native_checkpoint, scope, issued, lease, observed)
74
+ super(scope:, issued:, lease: held, observed:)
75
+ end
76
+ end
77
+
78
+ # The core's `Leadership::Elected`: the smallest candidate now leads under
79
+ # `lease`, which carries a new token. `lease` is read by its readers and
80
+ # kept as this gem's Lease, validated like one.
81
+ Elected = Data.define(:lease) do
82
+ def initialize(lease:) = super(lease: ElectionMachines.__send__(:native_held, lease))
83
+
84
+ def incumbent? = false
85
+ end
86
+
87
+ # The core's `Leadership::Incumbent`: a leader's unexpired `lease` is still
88
+ # in force. Honoured, and nothing changed. `lease` is read by its readers
89
+ # and kept as this gem's Lease, validated like one.
90
+ Incumbent = Data.define(:lease) do
91
+ def initialize(lease:) = super(lease: ElectionMachines.__send__(:native_held, lease))
92
+
93
+ def incumbent? = true
94
+ end
95
+
96
+ # Sealed: no subclass can skip the checks above by overriding `initialize`,
97
+ # and no bare `allocate` builds a value that never ran them. Ruby still
98
+ # binds a subclass constant before `inherited` raises; the native side
99
+ # refuses its instances.
100
+ [FencingToken, Lease, Checkpoint, Elected, Incumbent].each do |value|
101
+ value.singleton_class.undef_method(:allocate)
102
+ value.define_singleton_method(:inherited) { |_| raise TypeError, "#{value} cannot be subclassed" }
103
+ end
104
+ end
105
+
106
+ # Native is required: no algorithm fallback. It resolves the classes above
107
+ # once, here.
3
108
  require 'election_machines_native/election_machines_native'
109
+
110
+ module ElectionMachines
111
+ class << self
112
+ private :native_raw, :native_token_scope, :native_token_order, :native_token_newer, :native_lease,
113
+ :native_held, :native_checkpoint
114
+ end
115
+
116
+ # A lease as the native side answers it, `[owner, raw, expires_at]`.
117
+ def self.lease_of(row) = Lease.new(row[0], FencingToken.new(row[1]), row[2])
118
+ private_class_method :lease_of
119
+
120
+ # The core's `Election`: one resource, one token scope. `elect` answers
121
+ # Elected or Incumbent when honoured, `heartbeat` and `resign` a Lease, and
122
+ # each a refusal Symbol otherwise. A refusal changes nothing.
123
+ class Election
124
+ class << self
125
+ # A fresh token namespace in scope zero.
126
+ def new = with_scope(0)
127
+
128
+ # A fresh token namespace whose tokens carry `scope`, an Integer in
129
+ # 0..65_535. Give each election its own.
130
+ def with_scope(scope) = native_with_scope(scope)
131
+
132
+ # The newest committed checkpoint of `scope`, with the clock policy
133
+ # stated again. RangeError when the checkpoint is of another scope.
134
+ def restored(scope, checkpoint, clock_policy)
135
+ native_restored(scope, checkpoint, clock_policy)
136
+ end
137
+
138
+ private :native_with_scope, :native_restored
139
+ end
140
+
141
+ # :reject or :clamp. The core's builder consumes the election; here it
142
+ # changes this one and answers it.
143
+ def with_clock_policy(clock_policy)
144
+ native_with_clock_policy(clock_policy)
145
+ self
146
+ end
147
+
148
+ # The last leadership granted (it may have expired), nil after a resignation.
149
+ def lease
150
+ held = native_lease
151
+ held && ElectionMachines.__send__(:lease_of, held)
152
+ end
153
+
154
+ def checkpoint
155
+ scope, issued, held, observed = native_checkpoint
156
+ Checkpoint.new(scope, issued, held && ElectionMachines.__send__(:lease_of, held), observed)
157
+ end
158
+
159
+ # Every decision decides on a copy of the election, builds the answer
160
+ # (its `new` runs), then keeps the copy only if this election is still
161
+ # unfrozen (FrozenError) and unchanged (RuntimeError: a re-entrant call
162
+ # changed it). Either way, a raise means nothing was applied.
163
+ #
164
+ # `candidates` is an Array of owner Integers, of any length.
165
+ def elect(candidates, now, ttl) = native_elect(candidates, now, ttl)
166
+
167
+ def heartbeat(owner, token, now, ttl) = native_heartbeat(owner, token, now, ttl)
168
+
169
+ def resign(owner, token, now) = native_resign(owner, token, now)
170
+ end
171
+ end
@@ -1,15 +1,168 @@
1
1
  module ElectionMachines
2
2
  VERSION: String
3
- type outcome = [String, Integer?, Integer?, Float?]
4
- class Checkpoint
3
+ REFUSALS: Array[Symbol]
4
+ CLOCK_POLICIES: Array[Symbol]
5
+
6
+ # Integer nanoseconds on one monotonic clock, for instants (now, expires_at,
7
+ # observed) and spans (ttl) alike:
8
+ # Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond). A non-Integer
9
+ # raises TypeError; a negative value, or one past 2**64 seconds, RangeError.
10
+ type nanoseconds = Integer
11
+ # An Integer in 0..65_535; TypeError for a non-Integer, RangeError outside.
12
+ type scope = Integer
13
+ # An Integer in 0..2**64-1, the caller's own number for a candidate.
14
+ type owner = Integer
15
+ type clock_policy = :reject | :clamp
16
+ # Every symbol that means "this call was not honoured and changed nothing",
17
+ # and exactly REFUSALS: no catch-all, and none an election cannot answer.
18
+ # :no_candidates is the core's `Refusal::NoCandidates`. The rest are the
19
+ # core's `Refusal::Lease(reason)`, answered as the lease core's own symbol
20
+ # for `reason`. The lease core's :occupied and :held never arrive (a live
21
+ # leader is the honoured Incumbent), nor do :fenced and :out_of_phase (the
22
+ # lease holder's). Each method below lists exactly the ones it can answer.
23
+ type refusal = :no_candidates | :no_lease | :wrong_owner | :stale_token | :unknown | :expired
24
+ | :clock_regressed | :invalid_ttl | :exhausted
25
+ # What heartbeat and resign can answer for the owner, token and clock.
26
+ # :unknown is a token this election never issued, which includes every token
27
+ # of another scope; :stale_token is one it issued that is no longer in force.
28
+ type held_refusal = :unknown | :clock_regressed | :no_lease | :wrong_owner | :stale_token | :expired
29
+ # The core's `Leadership`: both are honoured, Incumbent changed nothing.
30
+ type leadership = Elected | Incumbent
31
+
32
+ # Anything read as a fencing token: this gem's FencingToken, or the
33
+ # `lease_machines` gem's. A bare Integer is not one (TypeError).
34
+ interface _FencingToken
35
+ def raw: () -> Integer
5
36
  end
37
+
38
+ # Anything read as a lease: this gem's Lease, or the `lease_machines` gem's.
39
+ interface _Lease
40
+ def owner: () -> owner
41
+ def token: () -> _FencingToken
42
+ def expires_at: () -> nanoseconds
43
+ end
44
+
45
+ # Anything read as a checkpoint: this gem's, or the `lease_machines` gem's.
46
+ interface _Checkpoint
47
+ def scope: () -> scope
48
+ def issued: () -> Integer
49
+ def lease: () -> _Lease?
50
+ def observed: () -> nanoseconds
51
+ end
52
+
53
+ class FencingToken < Data
54
+ # Scope in the top 16 bits above a sequence number counted from 1.
55
+ attr_reader raw: Integer
56
+ # TypeError for a non-Integer; RangeError outside 1..2**64-1 or when the
57
+ # sequence number is zero.
58
+ def self.new: (Integer raw) -> FencingToken
59
+ | (raw: Integer) -> FencingToken
60
+ def self.from_raw: (Integer raw) -> FencingToken
61
+ def scope: () -> scope
62
+ # nil across scopes: such tokens are not comparable.
63
+ def order: (_FencingToken other) -> (-1 | 0 | 1)?
64
+ # False across scopes.
65
+ def newer_than?: (_FencingToken other) -> bool
66
+ end
67
+
68
+ class Lease < Data
69
+ attr_reader owner: owner
70
+ attr_reader token: FencingToken
71
+ attr_reader expires_at: nanoseconds
72
+ # Validated like a granted one: TypeError for a non-Integer owner or
73
+ # instant or a token without `raw`, RangeError for an owner outside
74
+ # 0..2**64-1, a token `from_raw` rejects or an instant out of range.
75
+ # `token` is read by its readers and kept as this gem's FencingToken.
76
+ def self.new: (owner owner, _FencingToken token, nanoseconds expires_at) -> Lease
77
+ | (owner: owner, token: _FencingToken, expires_at: nanoseconds) -> Lease
78
+ end
79
+
80
+ class Checkpoint < Data
81
+ attr_reader scope: scope
82
+ # Tokens issued so far, resignations included; the next is `issued + 1`.
83
+ attr_reader issued: Integer
84
+ attr_reader lease: Lease?
85
+ attr_reader observed: nanoseconds
86
+ # RangeError when `issued` is past 2**48-1, or `lease` does not carry
87
+ # token number `issued` of `scope`. `lease` is read by its readers and
88
+ # kept as this gem's Lease.
89
+ def self.new: (scope scope, Integer issued, _Lease? lease, nanoseconds observed) -> Checkpoint
90
+ | (scope: scope, issued: Integer, lease: _Lease?, observed: nanoseconds) -> Checkpoint
91
+ def self.from_parts: (scope scope, Integer issued, _Lease? lease, nanoseconds observed) -> Checkpoint
92
+ end
93
+
94
+ class Elected < Data
95
+ attr_reader lease: Lease
96
+ # `lease` is read by its readers, validated like Lease.new and kept as
97
+ # this gem's Lease: TypeError without the readers, RangeError otherwise.
98
+ def self.new: (_Lease lease) -> Elected
99
+ | (lease: _Lease) -> Elected
100
+ def incumbent?: () -> false
101
+ end
102
+
103
+ class Incumbent < Data
104
+ attr_reader lease: Lease
105
+ # Read, validated and kept like Elected's.
106
+ def self.new: (_Lease lease) -> Incumbent
107
+ | (lease: _Lease) -> Incumbent
108
+ def incumbent?: () -> true
109
+ end
110
+
111
+ # The core's `Election`. Honoured answers come first in every return type,
112
+ # then the refusals that method can answer. A refusal changes nothing, the
113
+ # observed clock included. Every mutating call raises FrozenError on a
114
+ # frozen election.
6
115
  class Election
116
+ # A fresh token namespace in scope zero.
7
117
  def self.new: () -> Election
8
- def elect: (Array[Integer], Integer | Float, Integer | Float) -> outcome
9
- def heartbeat: (Integer, Integer, Integer | Float, Integer | Float) -> outcome
10
- def resign: (Integer, Integer, Integer | Float) -> outcome
118
+ # A fresh token namespace whose tokens carry `scope`.
119
+ def self.with_scope: (scope scope) -> Election
120
+ # RangeError when `checkpoint` is of another scope. TypeError unless
121
+ # `clock_policy` is a Symbol, RangeError unless :reject or :clamp.
122
+ def self.restored: (scope scope, _Checkpoint checkpoint, clock_policy clock_policy) -> Election
123
+ # Changes this election and answers it. TypeError for a non-Symbol,
124
+ # RangeError unless :reject or :clamp.
125
+ def with_clock_policy: (clock_policy clock_policy) -> self
126
+ def clock_policy: () -> clock_policy
127
+ def scope: () -> scope
128
+ def issued: () -> Integer
129
+ # The last leadership granted; it may have expired. nil after a resignation.
130
+ def lease: () -> Lease?
11
131
  def checkpoint: () -> Checkpoint
12
- def restore!: (Checkpoint) -> bool
13
- def lease: () -> [Integer, Integer, Float]?
132
+ # Elected: the smallest candidate, under a new token. Incumbent: a live
133
+ # leader stays, whoever the candidates were; nothing changed.
134
+ # :no_candidates for an empty Array, checked before the clock.
135
+ def elect: (Array[owner] candidates, nanoseconds now, nanoseconds ttl)
136
+ -> (leadership | :no_candidates | :clock_regressed | :invalid_ttl | :exhausted)
137
+ # The renewed Lease, under the same token. A repeat is honoured and never
138
+ # shortens the lease.
139
+ def heartbeat: (owner owner, _FencingToken token, nanoseconds now, nanoseconds ttl)
140
+ -> (Lease | held_refusal | :invalid_ttl)
141
+ # The Lease that was given up. A repeat is :no_lease.
142
+ def resign: (owner owner, _FencingToken token, nanoseconds now) -> (Lease | held_refusal)
143
+
144
+ private
145
+
146
+ type row = [Integer, Integer, Integer]
147
+ type saved = [Integer, Integer, row?, Integer]
148
+ private def self.native_with_scope: (Integer) -> Election
149
+ private def self.native_restored: (Integer, _Checkpoint, Symbol) -> Election
150
+ def native_with_clock_policy: (Symbol) -> nil
151
+ def native_lease: () -> row?
152
+ def native_checkpoint: () -> saved
153
+ def native_elect: (Array[Integer], Integer, Integer) -> (Elected | Incumbent | refusal)
154
+ def native_heartbeat: (Integer, _FencingToken, Integer, Integer) -> (Lease | refusal)
155
+ def native_resign: (Integer, _FencingToken, Integer) -> (Lease | refusal)
14
156
  end
157
+
158
+ private
159
+
160
+ private def self.native_raw: (Integer) -> nil
161
+ private def self.native_token_scope: (_FencingToken) -> Integer
162
+ private def self.native_token_order: (_FencingToken, _FencingToken) -> (-1 | 0 | 1)?
163
+ private def self.native_token_newer: (_FencingToken, _FencingToken) -> bool
164
+ private def self.native_lease: (owner, _FencingToken, nanoseconds) -> FencingToken
165
+ private def self.native_held: (_Lease) -> Lease
166
+ private def self.native_checkpoint: (scope, Integer, _Lease?, nanoseconds) -> Lease?
167
+ private def self.lease_of: ([Integer, Integer, Integer]) -> Lease
15
168
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: election_machines
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.5
4
+ version: 0.5.2
5
5
  platform: aarch64-linux
6
6
  authors:
7
7
  - Abdelkader Boudih
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-06 00:00:00.000000000 Z
11
+ date: 2026-11-16 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: A thin Rust bridge for deterministic nomination and lease renewal. No
14
14
  distributed election service.