rogue_machines 0.1.2-aarch64-linux → 0.5.0-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: 5a40cc23e90281458a91d0cfca796618c09b54db623428c916b132da5636d81b
4
- data.tar.gz: 9746bbf5fcb6acf0583f82281dc609bcc9bf8e96dc345060ae640c111c747fee
3
+ metadata.gz: 18efde9a3711a446f7c2b9998d546b44f2878728fc3d90c65fdc525470a3040b
4
+ data.tar.gz: 964ceb96b8f1cf3fcb0d8c6c526ed73bf9168b4dd3da554f87b17b947300736f
5
5
  SHA512:
6
- metadata.gz: d54102acb662a217620f50bb0220a2f37bdc70918abb2b7242e1a058cb29cf931bfde686e5a843ba9198de5923063e036947d6dd8f9baa0d6fa7260eb946b7c1
7
- data.tar.gz: e45a49e8798fcc29bc1d08cac22c654577ac363f0fe386273ff9a43bc62b15e6ae8ee5b376006365bfce25d2f147bacbd9ce211c59331fa09e8c561cfae3db0e
6
+ metadata.gz: edd1850ef03c962b5e582cc23c92617db44380a9e784236fee022ea6ed8115cd6642480b6184a1af47aa348067d9eae122f3a5fa37a5f7ddf8911d6a5ff48ccc
7
+ data.tar.gz: c76085e0beb2878a13114e9ea5eed454e730040ee6029c91b65bfc2fd75b7f84d4a8ffc827a7f36c5801dd03440279a83d0f82c88aabf947b5a448475ca651e9
data/CHANGELOG.md CHANGED
@@ -1,5 +1,69 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.5.0](https://github.com/seuros/rogue_machines/compare/rogue_machines/v0.4.0...rogue_machines/v0.5.0) (2026-11-16)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * carry the runtime's garbled substitute in Replaced and Disarmed
9
+
10
+ ### Features
11
+
12
+ * carry the runtime's garbled substitute in Replaced and Disarmed ([acece66](https://github.com/seuros/rogue_machines/commit/acece668aa14809616fc90c3eb7f2c9665325dad))
13
+
14
+
15
+ ### Bug Fixes
16
+
17
+ * fix wrapped classes at load so building a value runs no Ruby ([39982ca](https://github.com/seuros/rogue_machines/commit/39982cace4de937ec30e83b9da15be38b0ed46b3))
18
+
19
+ ## [0.4.0](https://github.com/seuros/rogue_machines/compare/rogue_machines/v0.3.1...rogue_machines/v0.4.0) (2026-11-14)
20
+
21
+
22
+ ### ⚠ BREAKING CHANGES
23
+
24
+ * adopt matryona 0.4 symbol_or_fields for faults, naming what was received
25
+
26
+ ### Features
27
+
28
+ * adopt matryona 0.4 symbol_or_fields for faults, naming what was received ([29d07fe](https://github.com/seuros/rogue_machines/commit/29d07fe671cf3f00c8ff284f3a03dcaab0f0176e))
29
+
30
+ ## [0.3.1](https://github.com/seuros/rogue_machines/compare/rogue_machines/v0.3.0...rogue_machines/v0.3.1) (2026-11-14)
31
+
32
+
33
+ ### Bug Fixes
34
+
35
+ * **deps:** require matryona-machines >= 0.3 ([b92985b](https://github.com/seuros/rogue_machines/commit/b92985b2ee76787772e6d6c1e5deeffa1a039d89))
36
+
37
+ ## [0.3.0](https://github.com/seuros/rogue_machines/compare/rogue_machines/v0.2.0...rogue_machines/v0.3.0) (2026-11-14)
38
+
39
+
40
+ ### ⚠ BREAKING CHANGES
41
+
42
+ * adopt matryona-machines 0.2: struct-only field reads, caret rb-sys, missing_docs
43
+
44
+ ### Features
45
+
46
+ * adopt matryona-machines 0.2: struct-only field reads, caret rb-sys, missing_docs ([af562d6](https://github.com/seuros/rogue_machines/commit/af562d60cde84679fc6b8bce9eedb4af3559a0b4))
47
+
48
+ ## [0.2.0](https://github.com/seuros/rogue_machines/compare/rogue_machines/v0.1.3...rogue_machines/v0.2.0) (2026-11-14)
49
+
50
+
51
+ ### ⚠ BREAKING CHANGES
52
+
53
+ * mirror the core Rogue with sealed validated values, garbled replacement answers Replaced, runtime hands out a frozen copy
54
+
55
+ ### Features
56
+
57
+ * mirror the core Rogue with sealed validated values, garbled replacement answers Replaced, runtime hands out a frozen copy ([e805ae4](https://github.com/seuros/rogue_machines/commit/e805ae4792f25f5aeaa24b165192c14b80362067))
58
+
59
+ ## [0.1.3](https://github.com/seuros/rogue_machines/compare/rogue_machines/v0.1.2...rogue_machines/v0.1.3) (2026-11-06)
60
+
61
+
62
+ ### Bug Fixes
63
+
64
+ * extract arg_error and range error helpers in ffi ([ee6ccf4](https://github.com/seuros/rogue_machines/commit/ee6ccf4ef0caef9f5ef7b4496ee0ccdb633ddc1e))
65
+ * keep test modules out of the packaged crate ([425cf81](https://github.com/seuros/rogue_machines/commit/425cf81b4e94ea2abd8de21ec74426c71338c11c))
66
+
3
67
  ## [0.1.2](https://github.com/seuros/rogue_machines/compare/rogue_machines/v0.1.1...rogue_machines/v0.1.2) (2026-11-01)
4
68
 
5
69
 
data/README.md CHANGED
@@ -26,7 +26,9 @@ Requires **Ruby 4.0+** and a Rust toolchain, or a platform gem.
26
26
  ```ruby
27
27
  require 'rogue_machines'
28
28
 
29
- RogueMachines.arm(:payments, fault: :raise, share: 0.01, expires_in: 300)
29
+ MINUTE = 60 * 1_000_000_000 # Integer nanoseconds, like every time in this gem
30
+
31
+ RogueMachines.arm(:payments, fault: :raise, share: 0.01, expires_in: 5 * MINUTE)
30
32
 
31
33
  RogueMachines.run(:payments) do
32
34
  Payments.charge(order)
@@ -50,8 +52,8 @@ RogueMachines.run(:payments) { Payments.charge(order) } # the real call
50
52
  ```
51
53
 
52
54
  It allocates nothing: zero objects per call for a Symbol, a String or a frozen
53
- String name. The overhead is about 160 ns, most of it the name check rather
54
- than the native read. That is why this ships as a runtime dependency rather
55
+ String name. The overhead is a couple of hundred nanoseconds, most of it the
56
+ name check rather than the native read. That is why this ships as a runtime dependency rather
55
57
  than a test-only one. The interlock sits on every call to every protected
56
58
  dependency, so it has to be cheap enough to leave in.
57
59
 
@@ -62,12 +64,12 @@ file. Arming is an explicit call naming a target and a share of traffic.
62
64
 
63
65
  ## ⏱️ Every Experiment Self-Destructs
64
66
 
65
- `expires_in:` is **required**. There is no way to arm an experiment that
66
- outlives the officer who armed it, and no constructor in the Rust core that
67
- takes a fault without a reading it expires at.
67
+ `expires_in:` is **required**, in Integer nanoseconds. There is no way to arm
68
+ an experiment that outlives the officer who armed it, and no constructor in the
69
+ Rust core that takes a fault without an instant it expires at.
68
70
 
69
71
  ```ruby
70
- RogueMachines.arm(:payments, fault: :raise, share: 1.0, expires_in: 60)
72
+ RogueMachines.arm(:payments, fault: :raise, share: 1.0, expires_in: MINUTE)
71
73
  RogueMachines.armed # => [:payments]
72
74
 
73
75
  # sixty seconds later, with nobody touching anything
@@ -75,10 +77,11 @@ RogueMachines.armed # => []
75
77
  RogueMachines.armed? # => false
76
78
  ```
77
79
 
78
- An expiry is **observed, not scheduled**: nothing retires an experiment until
79
- something takes a reading. The first `run`, `armed` or `armed?` at or after the
80
- expiry retires it, and once retired a clock that steps backwards cannot bring
81
- it back.
80
+ An expiry is **judged, not scheduled**. An expired experiment injects nothing
81
+ from its expiry on, but the core only empties its slot when told to sweep. The
82
+ runtime sweeps under its lock whenever `run`, `armed`, `armed?` or `arm` takes
83
+ a reading, and once swept a clock that steps backwards cannot bring the
84
+ experiment back.
82
85
 
83
86
  An experiment lasts at most twenty-four hours. Past that it is configuration,
84
87
  not an experiment, and it must be armed again deliberately.
@@ -89,13 +92,14 @@ not an experiment, and it must be armed again deliberately.
89
92
 
90
93
  ```ruby
91
94
  # Fail.
92
- RogueMachines.arm(:payments, fault: :raise, share: 0.01, expires_in: 300)
95
+ RogueMachines.arm(:payments, fault: :raise, share: 0.01, expires_in: 5 * MINUTE)
93
96
 
94
- # Be slow, then make the real call.
95
- RogueMachines.arm(:search, fault: :delay, delay: 2, share: 0.5, expires_in: 300)
97
+ # Be slow (two seconds, in nanoseconds), then make the real call.
98
+ RogueMachines.arm(:search, fault: RogueMachines::Delay.new(2_000_000_000), share: 0.5,
99
+ expires_in: 5 * MINUTE)
96
100
 
97
101
  # Succeed, with a substitute.
98
- RogueMachines.arm(:catalogue, fault: :garble, garbled: [], share: 0.1, expires_in: 300)
102
+ RogueMachines.arm(:catalogue, fault: :garble, garbled: [], share: 0.1, expires_in: 5 * MINUTE)
99
103
  ```
100
104
 
101
105
  A `:raise` raises `RogueMachines::Injected`. A `:garble` returns `garbled:`
@@ -103,7 +107,7 @@ without running the block, which defaults to `nil` so a forgotten substitute
103
107
  cannot quietly return the real value.
104
108
 
105
109
  **There is no weapon that holds a caller forever.** A dependency that times out
106
- is a `:delay` longer than the caller's own budget, which leaves the caller's
110
+ is a `Delay` longer than the caller's own budget, which leaves the caller's
107
111
  timeout in charge of when it gives up. The delay is spent against the ambient
108
112
  `deadline_machines` budget, so a stall inside a deadline trips that deadline
109
113
  instead of sleeping past it. Because a deadline is opt-in per call site, a
@@ -114,8 +118,8 @@ it bounds what a mistyped argument can do to a caller that has none.
114
118
 
115
119
  ## 🎲 Targeting
116
120
 
117
- `share:` is a fraction of calls between 0 and 1, and the draw deciding each
118
- call comes from `RogueMachines.random`. Replace it to replay an exact run:
121
+ `share:` is a fraction of calls between 0 and 1 (or a `Fraction` of
122
+ millionths), and the draw deciding each call comes from `RogueMachines.random`. Replace it to replay an exact run:
119
123
 
120
124
  ```ruby
121
125
  RogueMachines.random = Random.new(1234)
@@ -136,8 +140,8 @@ expire an experiment without sleeping:
136
140
 
137
141
  ```ruby
138
142
  RogueMachines.clock = DeadlineMachines::TestClock.new
139
- RogueMachines.arm(:payments, fault: :raise, share: 1.0, expires_in: 60)
140
- RogueMachines.clock.advance(60)
143
+ RogueMachines.arm(:payments, fault: :raise, share: 1.0, expires_in: MINUTE)
144
+ RogueMachines.clock.now_ns += MINUTE
141
145
  RogueMachines.armed? # => false
142
146
  ```
143
147
 
@@ -148,15 +152,15 @@ rather than tripping it.
148
152
  everything first, because every armed expiry was computed against the outgoing
149
153
  clock and an expiry is only meaningful against the clock it came from.
150
154
 
151
- It is safe to do under load. A reading is taken before any lock, so that a
152
- caller's clock never runs inside one, which means a call can be part way
153
- through when the clock is replaced. Each reading therefore carries the
154
- generation it belongs to, and a call arriving with a superseded one is refused
155
- rather than acted on: arming raises and nothing is armed, a decision makes the
156
- real call, and a query reports nothing. A clock being replaced faster than a
157
- reading can be taken is answered the same way rather than retried forever, and
158
- a clock returning something that is not a non-negative Integer of nanoseconds
159
- raises an error naming the clock.
155
+ It is safe to do under load. A reading is taken before the runtime's lock, so
156
+ that a caller's clock never runs inside it, which means a call can be part way
157
+ through when the clock is replaced. Once the lock is held, the call checks that
158
+ the clock it read is still the one installed; if not, the reading is not acted
159
+ on and is taken again, up to `READINGS` times. After that, arming raises
160
+ `RogueMachines::Error` and nothing is armed, a decision makes the real call,
161
+ and a query reports nothing. A clock returning something that is not an Integer
162
+ raises `TypeError` naming the clock, and a negative reading `RangeError`.
163
+ `disarm` and `disarm_all` take no reading at all.
160
164
 
161
165
  Replacing `DeadlineMachines.clock` underneath is reflected, since the
162
166
  delegation is not memoised, but it cannot disarm anything. A clock whose epoch
@@ -169,7 +173,9 @@ experiment is measured from slightly before it is armed. With a real monotonic
169
173
  clock that is microseconds. Nothing infers that a reading came from a
170
174
  different clock: with several threads taking their own readings, a reading
171
175
  older than the arming is ordinary interleaving, and treating it as evidence of
172
- a clock change retires experiments that were just armed.
176
+ a clock change retires experiments that were just armed. For the same reason a
177
+ reading held across a backwards step of the *same* clock sweeps against
178
+ expiries it predates; replace clocks through `RogueMachines.clock=`.
173
179
 
174
180
  ---
175
181
 
@@ -178,9 +184,114 @@ a clock change retires experiments that were just armed.
178
184
  There is no pure-Ruby fallback and no switch to turn one on. `require
179
185
  'rogue_machines'` loads the extension and fails if it is not there. The gem is
180
186
  a binding to the `rogue-machines` crate in `ext/rogue_machines_native/core`,
181
- which has zero dependencies and builds `no_std` for wasm and for a
182
- microcontroller. The binding asks for its `std` feature, so the crate as this
183
- gem consumes it is not `no_std`.
187
+ which has zero dependencies, no features, and is plain `no_std`: the crate the
188
+ gem consumes is the one that builds for wasm and for a microcontroller.
189
+
190
+ ---
191
+
192
+ ## 🪞 The Core, Mirrored
193
+
194
+ Under the runtime sits a plain mirror of the core: `RogueMachines::Rogue` and
195
+ the Data values `Slot`, `Fraction`, `Draw`, `Delay`, `Experiment`, `Inject`,
196
+ `Replaced` and `Disarmed`, positional like the Rust constructors, with Integer
197
+ nanoseconds and symbols for unit variants (`:raise`, `:garble`, `:pass`,
198
+ `:armed`, `:already_armed`, `:not_armed`).
199
+
200
+ ```ruby
201
+ include RogueMachines
202
+
203
+ rogue = Rogue.new
204
+ slot = Slot.new(0)
205
+ experiment = Experiment.new(:raise, Fraction::ALL, 100)
206
+
207
+ rogue.arm(slot, experiment) # => :armed
208
+ rogue.arm(slot, experiment) # => :already_armed
209
+ rogue.decide(slot, 99, Draw.new(0)) # => #<data Inject fault=:raise>
210
+ rogue.decide(slot, 100, Draw.new(0)) # => :pass
211
+ rogue.any_armed? # => true: expired, still held
212
+ rogue.sweep(100) # => 1
213
+ rogue.disarm(slot) # => :not_armed
214
+ ```
215
+
216
+ Every Data value validates through the core when it is built, by the gem or by
217
+ hand: `TypeError` for the wrong type, `RangeError` for a value the core's
218
+ constructor rejects (`Slot.new(32)`, `Fraction.new(1_000_001)`,
219
+ `Draw.new(1_000_000)`, `Delay.new(-1)`, `Experiment.new(:nope, ...)`).
220
+ The value classes, and `Rogue`, are sealed: subclassing one raises
221
+ `TypeError` and `allocate` is undefined. Sealing stops accidents, not
222
+ reflection (a named subclass's constant is bound before `inherited` raises,
223
+ and `Marshal.load` skips `initialize`), so the binding is the authority: every
224
+ value it reads must be an instance of exactly the gem's class (`TypeError`
225
+ otherwise, a subclass included) and is rebuilt through the core's constructors
226
+ (`RangeError` for a forged one), before the core sees it.
227
+
228
+ ## 📜 Contract
229
+
230
+ - **Refusals.** The core has none: a `Slot` is the caller's own number, not an
231
+ issued id, and every slot can always be armed. The runtime has one,
232
+ `RogueMachines.arm` answering `:full` when every slot holds a live
233
+ experiment under another name; it changes nothing and never raises.
234
+ - **Answers say what held before.** Arming answers `:armed`, a `Replaced`
235
+ holding the experiment it displaced (expired or not) and, from the runtime,
236
+ the `garbled:` substitute that went with it (`nil` for none; the core mirror
237
+ `Rogue` keeps no substitutes, so its `Replaced` always holds `nil`), or
238
+ `:already_armed`;
239
+ disarming answers a `Disarmed` holding what was there and, from the
240
+ runtime, the substitute it removed (`nil` for none, always `nil` from
241
+ `Rogue`), or `:not_armed`.
242
+ - **Honoured repeats.** Re-arming a slot with the identical experiment and
243
+ disarming an empty slot are provable from the slot itself, so they are
244
+ honoured and change nothing. In the runtime a `:garble` substitute is part
245
+ of what is armed: `RogueMachines.arm` answers `:already_armed` only when the
246
+ stored substitute is equal (`==`) too; a differing one replaces it and
247
+ answers a `Replaced` holding the experiment and the old substitute, as a
248
+ differing experiment does.
249
+ - **Queries are pure.** In the core and in `Rogue`, every query judges expiry
250
+ against the instant it is given and changes nothing; only `sweep` empties
251
+ expired slots. The runtime's `armed`, `armed?`, `run` and `arm` sweep on
252
+ purpose, under the lock, with a reading against the installed clock.
253
+ - **Time** is Integer nanoseconds in and out: `expires_at`, `Delay#duration`,
254
+ every `now`, `expires_in:`. Non-Integer is `TypeError`; negative or past
255
+ `2**64 - 1` is `RangeError`.
256
+ - **Scopes and restarts.** Nothing is issued, so there is no scope. A fresh
257
+ process starts disarmed.
258
+ - **Exceptions.** Malformed input raises `TypeError` or `RangeError` before
259
+ anything changes. `Injected` is the fault itself; `Error` is a clock replaced
260
+ faster than it can be read.
261
+ - **Never loses work.** `Rogue#arm` and `#disarm` answer with values built by
262
+ Ruby, so each decides on a copy and keeps it only once the answer exists: a
263
+ raise while building it (a redefined `new`) applies nothing, freezing the
264
+ Rogue meanwhile raises `FrozenError` and changing it `RuntimeError`, with the
265
+ outer call not applied. No call holds the Rogue while Ruby code runs, so a
266
+ re-entrant call is an ordinary one, never a `fatal`.
267
+ - **The runtime's Rogue is not yours.** `RogueMachines.rogue` answers a frozen
268
+ copy taken under the lock: changing the runtime's own Rogue behind the names
269
+ would leave a name on an empty slot that the next arm hands to another name.
270
+ `Rogue#dup` is an unfrozen copy to experiment on.
271
+
272
+ ## Every answer
273
+
274
+ No answer records the clock: the core keeps none.
275
+
276
+ | Call | Honoured | Refused |
277
+ |:--|:--|:--|
278
+ | `Rogue#arm(slot, experiment)` | `:armed`, `Replaced`, `:already_armed` (unchanged) | never |
279
+ | `Rogue#disarm(slot)` | `Disarmed`, `:not_armed` (unchanged) | never |
280
+ | `Rogue#disarm_all` | slots emptied; `0` is unchanged | never |
281
+ | `Rogue#sweep(now)` | slots emptied because expired; `0` is unchanged | never |
282
+ | `Rogue#any_armed?` / `armed_count` | held slots, expired or not | query |
283
+ | `Rogue#live_count(now)` | slots live at `now` | query |
284
+ | `Rogue#vacant` | the lowest empty `Slot`, or `nil` | query |
285
+ | `Rogue#experiment(slot)` | what it holds, or `nil` | query |
286
+ | `Rogue#active(slot, now)` | what it holds if live at `now`, or `nil` | query |
287
+ | `Rogue#decide(slot, now, draw)` | `Inject`, `:pass` | query |
288
+ | `Rogue#dup` / `clone` | a copy holding the same experiments | query |
289
+ | `RogueMachines.rogue` | a frozen copy of the runtime's Rogue | query |
290
+ | `RogueMachines.arm(name, ...)` | `:armed`, `Replaced` (also for a new `garbled:`), `:already_armed` (unchanged) | `:full` (unchanged) |
291
+ | `RogueMachines.disarm(name)` | `Disarmed`, `:not_armed` (unchanged) | never |
292
+ | `RogueMachines.disarm_all` | experiments emptied; `0` is unchanged | never |
293
+ | `RogueMachines.armed` / `armed?` | names live now | never |
294
+ | `RogueMachines.run(name) { }` | the block's value, the substitute, or raises `Injected` | never |
184
295
 
185
296
  ---
186
297
 
@@ -188,11 +299,11 @@ gem consumes it is not `no_std`.
188
299
 
189
300
  - **No breaker, limiter, retry or budget.** It trips those. `breaker_machines`,
190
301
  `throttle_machines`, `chrono_machines` and `shed_machines` own them.
191
- - **No clock of its own.** Every reading is nanoseconds the caller passes in,
192
- which is why the core builds for bare metal.
302
+ - **No clock of its own.** Every instant is a `Duration` the caller passes in
303
+ (Integer nanoseconds in Ruby), which is why the core builds for bare metal.
193
304
  - **No randomness of its own.** The draw is the caller's.
194
305
  - **No capacity beyond 32 experiments**, because the armed set is one 32-bit
195
- word and the interlock on the hot path is a single load of it.
306
+ word and the interlock on the hot path is a single read of it.
196
307
 
197
308
  ---
198
309
 
@@ -0,0 +1,312 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RogueMachines
4
+ # Longest an experiment may run for, in nanoseconds. An experiment is
5
+ # something a person is waiting on, so a day is already generous; past that
6
+ # it is configuration, and it must be re-armed deliberately.
7
+ LONGEST_EXPERIMENT = 24 * 60 * 60 * 1_000_000_000
8
+
9
+ # Longest a single delay may wait, in nanoseconds. Bounds how long a stall
10
+ # can hold a caller that has no deadline of its own.
11
+ LONGEST_DELAY = 5 * 60 * 1_000_000_000
12
+
13
+ # Attempts at a reading taken against the clock still installed once the
14
+ # lock is held, before giving up on a clock replaced faster than that.
15
+ READINGS = 100
16
+
17
+ # The process-wide runtime: one Rogue, the names standing for its slots, and
18
+ # the substitutes the :garble experiments return. Every store is touched only
19
+ # under @lock; `run` reads the Rogue's gate outside it.
20
+ #
21
+ # Invariant: every Slot in @slots holds an experiment in @rogue (expired or
22
+ # not), and @substitutes has keys only from @slots.
23
+ @rogue = Rogue.new
24
+ @slots = {}
25
+ @substitutes = {}
26
+ @lock = Mutex.new
27
+
28
+ class << self
29
+ attr_writer :random
30
+
31
+ # Monotonic Integer nanoseconds. Delegates to deadline_machines rather
32
+ # than memoising it, so replacing that gem's clock moves every expiry
33
+ # with it.
34
+ def clock
35
+ @clock || DeadlineMachines.clock
36
+ end
37
+
38
+ # Installing a clock disarms everything first: every armed expiry was
39
+ # computed against the outgoing clock, and is not an expiry against
40
+ # another one. A reading already taken against the outgoing clock is not
41
+ # acted on: every call that uses a reading checks, under the lock, that
42
+ # the clock it read is still the one installed.
43
+ def clock=(clock)
44
+ @lock.synchronize do
45
+ Thread.handle_interrupt(Object => :never) do
46
+ @clock = clock
47
+ @rogue.disarm_all
48
+ @slots = {}
49
+ @substitutes = {}
50
+ end
51
+ end
52
+ end
53
+
54
+ def random
55
+ @random ||= Random.new
56
+ end
57
+
58
+ # A frozen copy of the runtime's Rogue, taken under the lock, for
59
+ # reading. Not the Rogue itself: disarming that behind the names would
60
+ # leave a name on an empty slot, which the next arm hands to a second
61
+ # name.
62
+ def rogue
63
+ @lock.synchronize { @rogue.dup.freeze }
64
+ end
65
+
66
+ # Arms an experiment under `name`, replacing any already there.
67
+ #
68
+ # RogueMachines.arm(:payments, fault: :raise, share: 0.01, expires_in: 300 * 10**9)
69
+ # RogueMachines.arm(:slow, fault: RogueMachines::Delay.new(2 * 10**9), share: 1, expires_in: 60 * 10**9)
70
+ # RogueMachines.arm(:lies, fault: :garble, garbled: [], share: 0.5, expires_in: 60 * 10**9)
71
+ #
72
+ # `expires_in` is Integer nanoseconds from now and required, so no
73
+ # experiment outlives the person who armed it. Answers what the core's
74
+ # `arm` answered for the slot (:armed, a Replaced, :already_armed), or
75
+ # :full, with nothing changed, when every slot holds a live experiment.
76
+ def arm(name, fault:, share:, expires_in:, garbled: nil)
77
+ key = named(name)
78
+ fraction = fraction_of(share)
79
+ checked_fault(fault)
80
+ span = span_of(expires_in)
81
+ payload = fault == :garble ? garbled : nil
82
+ found = locked_reading { |now| arm_at(key, Experiment.new(fault, fraction, now + span), payload, now) }
83
+ raise Error, "the clock was replaced #{READINGS} times while arming; nothing is armed" unless found
84
+
85
+ found.first
86
+ end
87
+
88
+ # What `name`'s slot held (a Disarmed, expired or not, carrying the
89
+ # substitute it removed), or :not_armed. Takes no reading.
90
+ def disarm(name)
91
+ key = named(name)
92
+ @lock.synchronize do
93
+ Thread.handle_interrupt(Object => :never) do
94
+ slot = @slots.delete(key)
95
+ next :not_armed unless slot
96
+
97
+ removed = @substitutes.delete(key)
98
+ disarmed(@rogue.disarm(slot), removed)
99
+ end
100
+ end
101
+ end
102
+
103
+ # How many experiments were held, expired or not.
104
+ def disarm_all
105
+ @lock.synchronize do
106
+ Thread.handle_interrupt(Object => :never) do
107
+ @slots = {}
108
+ @substitutes = {}
109
+ @rogue.disarm_all
110
+ end
111
+ end
112
+ end
113
+
114
+ # With no name, whether anything at all is live now.
115
+ def armed?(name = nil)
116
+ key = name.nil? ? nil : named(name).to_sym
117
+ names = armed
118
+ key.nil? ? names.any? : names.include?(key)
119
+ end
120
+
121
+ # The experiments live now. Retires the expired ones first, which
122
+ # releases their slots and substitutes; once retired, a clock stepping
123
+ # back cannot revive them.
124
+ def armed
125
+ found = locked_reading do |now|
126
+ retire(now)
127
+ @slots.keys.map(&:to_sym)
128
+ end
129
+ found ? found.first : []
130
+ end
131
+
132
+ # Runs the block, or the fault armed under `name` instead. Makes the real
133
+ # call when the clock was replaced faster than a reading could be taken.
134
+ def run(name)
135
+ legible(name)
136
+ return yield unless @rogue.any_armed?
137
+
138
+ key = named(name)
139
+ drawn = Draw.new(random.rand(PER_MILLION))
140
+ found = locked_reading { |now| decide_at(key, now, drawn) }
141
+ return yield unless found
142
+
143
+ decision, payload = found.first
144
+ return yield if decision == :pass
145
+
146
+ perform(name, decision.fault, payload) { yield }
147
+ end
148
+
149
+ private
150
+
151
+ # Arms under the lock. The room check changes nothing, so :full leaves
152
+ # every store as it was; only then are expired experiments retired.
153
+ #
154
+ # The substitute is part of what is armed: the core's :already_armed
155
+ # stands only when the stored one is equal too. A differing one is a
156
+ # replacement, answered as the core answers a differing experiment. Every
157
+ # Replaced carries the substitute it displaced.
158
+ def arm_at(key, experiment, payload, now)
159
+ return :full unless @slots.key?(key) || @rogue.vacant || @rogue.live_count(now) < @rogue.armed_count
160
+
161
+ Thread.handle_interrupt(Object => :never) do
162
+ retire(now)
163
+ slot = @slots[key] || @rogue.vacant
164
+ # Everything that runs caller code (the substitute's `==`, the answer
165
+ # values' `new`) runs before a store changes; the Rogue's own `arm`
166
+ # applies nothing when it raises.
167
+ previous = @substitutes[key]
168
+ same_payload = previous == payload
169
+ answer = @rogue.arm(slot, experiment)
170
+ @slots[key] = slot
171
+ payload.nil? ? @substitutes.delete(key) : @substitutes[key] = payload
172
+ replaced(answer, experiment, previous, same_payload)
173
+ end
174
+ end
175
+
176
+ # The runtime's answer for the core's disarming `answer`: a Disarmed
177
+ # holding the substitute it removed.
178
+ def disarmed(answer, removed)
179
+ case answer
180
+ when Disarmed then Disarmed.new(answer.experiment, removed)
181
+ else answer
182
+ end
183
+ end
184
+
185
+ # The runtime's answer for the core's `answer`: a Replaced holding the
186
+ # substitute it displaced, and :already_armed only for an equal one.
187
+ def replaced(answer, experiment, previous, same_payload)
188
+ case answer
189
+ when Replaced then Replaced.new(answer.experiment, previous)
190
+ when :already_armed then same_payload ? answer : Replaced.new(experiment, previous)
191
+ else answer
192
+ end
193
+ end
194
+
195
+ # The decision and the payload, read together under the lock. Retires
196
+ # anything expired first, which restores the disarmed fast path.
197
+ def decide_at(key, now, drawn)
198
+ retire(now) if @rogue.live_count(now) < @rogue.armed_count
199
+ slot = @slots[key]
200
+ decision = slot ? @rogue.decide(slot, now, drawn) : :pass
201
+ [decision, decision == :pass ? nil : @substitutes[key]]
202
+ end
203
+
204
+ # Empties the slots of experiments expired by `now` and drops their names
205
+ # and substitutes. Called only under the lock with a reading against the
206
+ # installed clock.
207
+ def retire(now)
208
+ Thread.handle_interrupt(Object => :never) do
209
+ next if @rogue.sweep(now).zero?
210
+
211
+ @slots.select! { |_, slot| @rogue.experiment(slot) }
212
+ @substitutes.select! { |key, _| @slots.key?(key) }
213
+ end
214
+ end
215
+
216
+ # `[block's answer]` for a reading taken outside the lock against the
217
+ # clock still installed once it is held, or nil after READINGS attempts.
218
+ # The caller's clock never runs inside the lock.
219
+ def locked_reading
220
+ READINGS.times do
221
+ source = clock
222
+ now = source.now_ns
223
+ checked_reading(source, now)
224
+ found = @lock.synchronize { [yield(now)] if clock.equal?(source) }
225
+ return found if found
226
+ end
227
+ nil
228
+ end
229
+
230
+ def checked_reading(source, now)
231
+ unless now.is_a?(Integer)
232
+ raise TypeError, "#{source.class} returned #{now.inspect}; a reading is an Integer of nanoseconds"
233
+ end
234
+ raise RangeError, "#{source.class} returned #{now}; a reading is not negative" if now.negative?
235
+ end
236
+
237
+ # Rejects a name the runtime cannot key on, without converting it, so a
238
+ # call site answers the same way whether or not anything is armed and the
239
+ # disarmed `run` allocates nothing.
240
+ def legible(name)
241
+ text = case name
242
+ when Symbol then name.name
243
+ when String then name
244
+ else raise TypeError, "an experiment name is a Symbol or a String, got #{name.class}"
245
+ end
246
+ raise RangeError, 'an experiment needs a name' if text.empty?
247
+ return if text.ascii_only? || (text.encoding == Encoding::UTF_8 && text.valid_encoding?)
248
+
249
+ raise RangeError, 'an experiment name is ASCII or valid UTF-8'
250
+ end
251
+
252
+ # The checked name as a frozen String key. Not `to_s`: a String subclass
253
+ # can override it, which armed one name and reported another.
254
+ def named(name)
255
+ legible(name)
256
+ name.is_a?(Symbol) ? name.name : -String.new(name)
257
+ end
258
+
259
+ # A Fraction as given, or a Numeric share of a whole rounded to
260
+ # millionths. A share too small to express is refused rather than armed
261
+ # as nothing.
262
+ def fraction_of(share)
263
+ return share if share.is_a?(Fraction)
264
+ unless share.is_a?(Numeric) && share.real?
265
+ raise TypeError, "share is a Fraction or a real Numeric, got #{share.class}"
266
+ end
267
+
268
+ raise RangeError, "share is between 0 and 1, got #{share}" unless share.finite? && share.between?(0, 1)
269
+
270
+ millionths = (share * PER_MILLION).round
271
+ raise RangeError, "share of #{share} is below one millionth" if millionths.zero? && share.positive?
272
+
273
+ Fraction.new(millionths)
274
+ end
275
+
276
+ # The fault is read natively, as Experiment.new reads it, never through
277
+ # `Delay#duration` or `===`; only LONGEST_DELAY, this runtime's own bound,
278
+ # is checked here, on the duration that was read.
279
+ def checked_fault(fault)
280
+ delay = RogueMachines.__send__(:__delay_of, fault)
281
+ return if delay.nil? || delay.between?(1, LONGEST_DELAY)
282
+
283
+ raise RangeError, "a delay is 1..#{LONGEST_DELAY} nanoseconds, got #{delay}"
284
+ end
285
+
286
+ def span_of(expires_in)
287
+ raise TypeError, 'expires_in is an Integer of nanoseconds' unless expires_in.is_a?(Integer)
288
+ return expires_in if expires_in.between?(1, LONGEST_EXPERIMENT)
289
+
290
+ raise RangeError, "expires_in is 1..#{LONGEST_EXPERIMENT} nanoseconds, got #{expires_in}"
291
+ end
292
+
293
+ def perform(name, fault, payload)
294
+ case fault
295
+ when :raise then raise Injected, "#{name} is armed to raise"
296
+ when :garble then payload
297
+ when Delay
298
+ stall(fault.duration)
299
+ yield
300
+ end
301
+ end
302
+
303
+ # Spends the delay against the caller's deadline rather than past it, so a
304
+ # slow dependency trips the timeout that was already there.
305
+ def stall(delay_ns)
306
+ DeadlineMachines.check!
307
+ delay_ns = DeadlineMachines.clamp_sleep(delay_ns)
308
+ sleep(delay_ns.fdiv(1_000_000_000)) if delay_ns.positive?
309
+ DeadlineMachines.check!
310
+ end
311
+ end
312
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RogueMachines
4
- VERSION = '0.1.2'
4
+ VERSION = '0.5.0'
5
5
  end