election_machines 0.1.5 → 0.5.2

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.
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
 
@@ -1,15 +1,17 @@
1
1
  [package]
2
2
  name = "election-machines"
3
- version = "0.2.2"
3
+ version = "0.5.1"
4
4
  edition.workspace = true
5
5
  rust-version.workspace = true
6
6
  license.workspace = true
7
7
  description = "Lease-backed deterministic owner nomination"
8
8
  readme = "README.md"
9
- exclude = ["src/**/tests.rs", "tests/"]
9
+ exclude = ["src/**/tests.rs", "src/tests/", "tests/"]
10
10
  keywords = ["leader-election", "lease", "fencing", "no-std"]
11
11
  categories = ["no-std", "algorithms"]
12
12
  [dependencies]
13
13
  lease-machines.workspace = true
14
+ [dev-dependencies]
15
+ matryona-machines = { workspace = true, features = ["testing"] }
14
16
  [lints]
15
17
  workspace = true
@@ -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
+ ```