runner.bend

bend-kit-runner@0.10.0.1 · 1,785 lines · 0 definitions

1# Durable job runner: a journaled scheduler queue, bounded by a resources pool, with retry and a breaker per target. Source: https://github.com/paymog/bend-kit/tree/main/runner
2import Base
3import bend-kit-bytes@0.3.2.0/bytes.bend as Bytes
4import bend-kit-journal@0.2.0.0/journal.bend as J
5import bend-kit-scheduler@0.3.0.0/queue.bend as Q
6import bend-kit-resources@0.1.0.0/resources.bend as Res
7import bend-kit-retry@0.2.0.0/retry.bend as Retry
8import bend-kit-time@0.2.0.0/time.bend as Time
9import bend-kit-collections@0.1.3.0/heap.bend as H
10import bend-kit-collections@0.1.3.0/omap.bend as O
11import bend-kit-collections@0.1.3.0/hmap.bend as M
12import bend-kit-files@0.2.0.0/files.bend as Files
13
14# Why retry gave up on a ticket: its budget was spent, its deadline passed, its failure must not repeat,
15# or another try would repeat its failure.
16type Why is Data:
17  WhySpent{}
18  WhyLate{}
19  WhyUnsafe{}
20  WhyFailed{}
21
22# A ticket that retry gave up on, with its payload, and when it gave up (wall-clock ms).
23# It stays until Revive, Cancel, or Purge takes it.
24type Dead<-A: Data> is Data:
25  Dead{ticket: Q.Ticket<A>, why: Why, at: Nat}
26
27# One durable transition. Each one is one journal record, appended before the state changes.
28# Select: the queue's select at now. Replay runs it at the same now, so it takes the same ticket.
29# Requeue: the attempt failed; it counts one failure. Defer: the breaker held the ticket back; no attempt ran.
30# Abandon: retry gave up at at; the running ticket becomes dead. Revive: a dead ticket is pending again at deadline, with a new budget.
31# Purge: the dead tickets abandoned before before are dropped. PurgeAll: every dead ticket is dropped.
32# Break: the breaker of target changed to state.
33type Op<-A: Data> is Data:
34  Enqueue{deadline: Nat, payload: A}
35  Select{now: Nat}
36  Complete{id: Nat}
37  Cancel{id: Nat}
38  Requeue{id: Nat, deadline: Nat}
39  Defer{id: Nat, deadline: Nat}
40  Abandon{id: Nat, why: Why, at: Nat}
41  Revive{id: Nat, deadline: Nat}
42  Purge{before: Nat}
43  PurgeAll{}
44  Break{target: String, state: Retry.State}
45
46# The failed attempts of a ticket, and its first deadline, from which the policy deadline counts.
47type Try is Data:
48  Try{fails: Nat, start: Nat}
49
50# A Try for each ticket that is not yet complete, cancelled, or dead, by ticket id.
51def Tries() -> Data:
52  O.OMap<Nat, Try>
53
54# The breaker state of each target that has one, by target. An absent target is closed with no failures.
55def Breakers() -> Data:
56  Map<&2, Retry.State>
57
58def dead.hash(i: Nat) -> U32:
59  U32.from_nat(i)
60
61# The dead tickets, by ticket id.
62def Graves(-A: Data) -> Data:
63  M.HMap<Nat, Dead<A>>
64
65# The durable state: the queue, the tries, the dead tickets, and the breakers.
66type State<-A: Data> is Data:
67  State{queue: Q.State<A>, tries: Tries(), dead: Graves(A), breakers: Breakers()}
68
69def new(-A: Data) -> State<A>:
70  State{Q.new(A), O.OMap.new(Nat, Try), M.HMap.new(Nat, Dead<A>), Map.new(&2, Retry.State)}
71
72def queue(-A: Data, s: State<A>) -> Q.State<A>:
73  State{q, ts, ds, bs} = s
74  q
75
76def tries(-A: Data, s: State<A>) -> Tries():
77  State{q, ts, ds, bs} = s
78  ts
79
80# The dead tickets, by id. A Revive of one makes it pending again; a Cancel or a Purge drops it.
81def dead(-A: Data, s: State<A>) -> Graves(A):
82  State{q, ts, ds, bs} = s
83  ds
84
85def breakers(-A: Data, s: State<A>) -> Breakers():
86  State{q, ts, ds, bs} = s
87  bs
88
89# ---- dead tickets
90
91def dead.get(~A: Data, ds: Graves(A), +i: Nat) -> Maybe<&2, Dead<A>>:
92  M.HMap.get(~Nat, ~Dead<A>, ~dead.hash, ~Nat.is_eq, ds, i)
93
94def dead.drop(~A: Data, ds: Graves(A), +i: Nat) -> Graves(A):
95  M.HMap.del(~Nat, ~Dead<A>, ~dead.hash, ~Nat.is_eq, ds, i)
96
97def dead.bury(~A: Data, m: Maybe<&2, Q.Ticket<A>>, ds: Graves(A), w: Why, +at: Nat) -> Graves(A):
98  match m:
99    case None{}:
100      ds
101    case Some{Q.Ticket{+i, d, x}}:
102      M.HMap.put(~Nat, ~Dead<A>, ~dead.hash, ~Nat.is_eq, ds, i, Dead{Q.Ticket{i, d, x}, w, at})
103
104def dead.list.entries(-A: Data, es: List<&2, M.Entry<Nat, Dead<A>>>, acc: List<&2, Dead<A>>) -> List<&2, Dead<A>>:
105  match es:
106    case Nil{}:
107      acc
108    case Con{M.Entry{k, d}, rest}:
109      dead.list.entries(A, rest, Con{d, acc})
110
111def dead.list.go(-A: Data, ds: Graves(A), acc: List<&2, Dead<A>>) -> List<&2, Dead<A>>:
112  match ds:
113    case M.HNil{}:
114      acc
115    case M.HLeaf{h, es}:
116      dead.list.entries(A, es, acc)
117    case M.HBranch{lo, hi}:
118      dead.list.go(A, lo, dead.list.go(A, hi, acc))
119
120# The dead tickets, in no set order.
121def dead.list(-A: Data, ds: Graves(A)) -> List<&2, Dead<A>>:
122  dead.list.go(A, ds, Nil{})
123
124def dead.old.keep(-A: Data, old: Bool, +i: Nat, rest: List<&2, Nat>) -> List<&2, Nat>:
125  match old:
126    case True{}:
127      Con{i, rest}
128    case False{}:
129      rest
130
131# The ids of the dead tickets abandoned before t.
132def dead.old(-A: Data, ds: List<&2, Dead<A>>, +t: Nat) -> List<&2, Nat>:
133  match ds:
134    case Nil{}:
135      Nil{}
136    case Con{Dead{Q.Ticket{i, d, x}, w, +at}, rest}:
137      dead.old.keep(A, Nat.is_lt(at, t), i, dead.old(A, rest, t))
138
139def dead.drops(~A: Data, ks: List<&2, Nat>, ds: Graves(A)) -> Graves(A):
140  match ks:
141    case Nil{}:
142      ds
143    case Con{k, rest}:
144      dead.drops(~A, rest, dead.drop(~A, ds, k))
145
146# The dead tickets without those abandoned before t. It walks every dead ticket once.
147def dead.purge(~A: Data, +ds: Graves(A), +t: Nat) -> Graves(A):
148  dead.drops(~A, dead.old(A, dead.list(A, ds), t), ds)
149
150# ---- tries
151
152def tries.drop(ts: Tries(), +i: Nat) -> Tries():
153  O.OMap.del(~Nat, ~Try, ~Nat.cmp, ts, i)
154
155def tries.get(ts: Tries(), +i: Nat) -> Maybe<&2, Try>:
156  O.OMap.get(~Nat, ~Try, ~Nat.cmp, ts, i)
157
158def tries.bump.got(m: Maybe<&2, Try>, ts: Tries(), +i: Nat) -> Tries():
159  match m:
160    case None{}:
161      ts
162    case Some{Try{f, st}}:
163      O.OMap.put(~Nat, ~Try, ~Nat.cmp, ts, i, Try{1n+f, st})
164
165def tries.bump(+ts: Tries(), +i: Nat) -> Tries():
166  tries.bump.got(tries.get(ts, i), ts, i)
167
168# ---- breakers
169
170def brk.got(r: Breakers() & Retry.State) -> Retry.State:
171  (m, b) = r
172  b
173
174# The breaker state of target key.
175def brk.get(-A: Data, s: State<A>, key: String) -> Retry.State:
176  brk.got(Map.get(Retry.State, Retry.CircuitClosed{Nil{}}, breakers(A, s), key))
177
178def brk.state(br: Retry.Breaker, old: Retry.State) -> Retry.State:
179  match br:
180    case Retry.BreakerOff{}:
181      old
182    case Retry.BreakerOn{c, st}:
183      st
184
185def brk.nats(a: List<&2, Nat>, b: List<&2, Nat>) -> Bool:
186  match a b:
187    case Nil{} Nil{}:
188      True{}
189    case Con{+x, xs} Con{+y, ys}:
190      Bool.and(Nat.is_eq(x, y), brk.nats(xs, ys))
191    case p q:
192      False{}
193
194def brk.same(a: Retry.State, b: Retry.State) -> Bool:
195  match a b:
196    case Retry.CircuitClosed{xs} Retry.CircuitClosed{ys}:
197      brk.nats(xs, ys)
198    case Retry.CircuitOpen{+x} Retry.CircuitOpen{+y}:
199      Nat.is_eq(x, y)
200    case Retry.CircuitHalf{+x} Retry.CircuitHalf{+y}:
201      Nat.is_eq(x, y)
202    case p q:
203      False{}
204
205def calm.state(b: Retry.State) -> Retry.State:
206  match b:
207    case Retry.CircuitClosed{fs}:
208      Retry.CircuitClosed{fs}
209    case Retry.CircuitOpen{u}:
210      Retry.CircuitOpen{u}
211    case Retry.CircuitHalf{k}:
212      Retry.CircuitHalf{0n}
213
214def calm.map(m: Breakers()) -> Breakers():
215  match m:
216    case MTip{}:
217      MTip{}
218    case MLeaf{k, v}:
219      MLeaf{k, calm.state(v)}
220    case MNode{p, lo, hi}:
221      MNode{p, calm.map(lo), calm.map(hi)}
222
223# The probes of a half-open breaker died with the process that ran them, so open counts none in flight.
224def calm(-A: Data, s: State<A>) -> State<A>:
225  State{q, ts, ds, bs} = s
226  State{q, ts, ds, calm.map(bs)}
227
228# ---- the transition
229
230def step.enqueued(-A: Data, r: Q.State<A> & Nat, ts: Tries(), ds: Graves(A), bs: Breakers(), d: Nat) -> State<A>:
231  (q, i) = r
232  State{q, O.OMap.put(~Nat, ~Try, ~Nat.cmp, ts, i, Try{0n, d}), ds, bs}
233
234def step.selected(-A: Data, r: Q.State<A> & Maybe<&2, Q.Ticket<A>>, ts: Tries(), ds: Graves(A), bs: Breakers()) -> State<A>:
235  (q, t) = r
236  State{q, ts, ds, bs}
237
238def step.requeued(-A: Data, r: Q.State<A> & Bool, ts: Tries(), ds: Graves(A), bs: Breakers()) -> State<A>:
239  (q, b) = r
240  State{q, ts, ds, bs}
241
242# Complete takes the ticket from the running list only: O(running), not O(pending).
243def step.completed(-A: Data, r: Q.State<A> & Maybe<&2, Q.Ticket<A>>, ts: Tries(), ds: Graves(A), bs: Breakers()) -> State<A>:
244  (q, t) = r
245  State{q, ts, ds, bs}
246
247# Abandon takes the ticket from the running list, as Complete does, and keeps it with its payload.
248def step.abandoned(~A: Data, r: Q.State<A> & Maybe<&2, Q.Ticket<A>>, ts: Tries(), ds: Graves(A), bs: Breakers(), w: Why, +at: Nat) -> State<A>:
249  (q, t) = r
250  State{q, ts, dead.bury(~A, t, ds, w, at), bs}
251
252# The revived ticket keeps its payload and takes id i, the key it was dead under.
253def step.revived(~A: Data, m: Maybe<&2, Dead<A>>, +i: Nat, n: Nat, h: H.Heap<Q.Ticket<A>>, r: List<&2, Q.Ticket<A>>, ts: Tries(), ds: Graves(A), bs: Breakers(), +d: Nat) -> State<A>:
254  match m:
255    case None{}:
256      State{Q.State{n, h, r}, ts, ds, bs}
257    case Some{Dead{Q.Ticket{k, old, x}, w, at}}:
258      State{Q.State{n, H.Heap.push(~Q.Ticket<A>, ~(a => b => Q.le(A, a, b)), Q.Ticket{i, d, x}, h), r}, O.OMap.put(~Nat, ~Try, ~Nat.cmp, ts, i, Try{0n, d}), ds, bs}
259
260# The state after op. Live and replay both run it, so they agree.
261def step(~A: Data, s: State<A>, op: Op<A>) -> State<A>:
262  match s op:
263    case State{q, ts, ds, bs} Enqueue{+d, x}:
264      step.enqueued(A, Q.enqueue(~A, d, x, q), ts, ds, bs, d)
265    case State{q, ts, ds, bs} Select{now}:
266      step.selected(A, Q.select(~A, now, q), ts, ds, bs)
267    case State{q, ts, ds, bs} Complete{+i}:
268      step.completed(A, Q.complete(A, i, q), tries.drop(ts, i), ds, bs)
269    case State{q, ts, ds, bs} Cancel{+i}:
270      State{Q.cancel(~A, i, q), tries.drop(ts, i), dead.drop(~A, ds, i), bs}
271    case State{q, ts, ds, bs} Requeue{+i, d}:
272      step.requeued(A, Q.requeue(~A, i, d, q), tries.bump(ts, i), ds, bs)
273    case State{q, ts, ds, bs} Defer{i, d}:
274      step.requeued(A, Q.requeue(~A, i, d, q), ts, ds, bs)
275    case State{q, ts, ds, bs} Abandon{+i, w, at}:
276      step.abandoned(~A, Q.complete(A, i, q), tries.drop(ts, i), ds, bs, w, at)
277    case State{Q.State{n, h, r}, ts, +ds, bs} Revive{+i, d}:
278      step.revived(~A, dead.get(~A, ds, i), i, n, h, r, ts, dead.drop(~A, ds, i), bs, d)
279    case State{q, ts, ds, bs} Purge{t}:
280      State{q, ts, dead.purge(~A, ds, t), bs}
281    case State{q, ts, ds, bs} PurgeAll{}:
282      State{q, ts, M.HMap.new(Nat, Dead<A>), bs}
283    case State{q, ts, ds, bs} Break{k, b}:
284      State{q, ts, ds, Map.set(&2, Retry.State, bs, k, b)}
285
286def apply.op(~A: Data, m: Maybe<&2, Op<A>>, s: State<A>) -> Maybe<&2, State<A>>:
287  match m:
288    case None{}:
289      None{}
290    case Some{op}:
291      Some{step(~A, s, op)}
292
293# Folds one record into the replayed state. A record that does not decode ends the replay with None.
294def apply(~A: Data, ~R: Type, ~dec: R -> Maybe<&2, Op<A>>, acc: Maybe<&2, State<A>>, r: R) -> Maybe<&2, State<A>>:
295  match acc:
296    case None{}:
297      None{}
298    case Some{s}:
299      apply.op(~A, dec(r), s)
300
301# A journal record. Compaction writes one Snap of the whole state; every other record is one op.
302type Rec<-A: Data> is Data:
303  Snap{state: State<A>}
304  Do{op: Op<A>}
305
306def load.rec(~A: Data, m: Maybe<&2, Rec<A>>, s: State<A>) -> Maybe<&2, State<A>>:
307  match m:
308    case None{}:
309      None{}
310    case Some{Snap{t}}:
311      Some{t}
312    case Some{Do{op}}:
313      Some{step(~A, s, op)}
314
315# Folds one record into the replayed state: a Snap replaces it, and an op steps it, as apply does.
316# A record that does not decode ends the replay with None.
317def load(~A: Data, ~R: Type, ~dec: R -> Maybe<&2, Rec<A>>, acc: Maybe<&2, State<A>>, r: R) -> Maybe<&2, State<A>>:
318  match acc:
319    case None{}:
320      None{}
321    case Some{s}:
322      load.rec(~A, dec(r), s)
323
324# ---- pool
325
326# Picked: a due ticket and one unit of the pool for it. Idle: no due ticket, or no free unit; the pool is unchanged.
327type Pick<-A: Data> is Type:
328  Picked{pool: Res.Pool, ticket: Q.Ticket<A>, grant: Res.Grant}
329  Idle{pool: Res.Pool}
330
331def pick.took(-A: Data, r: Res.Reserve, t: Q.Ticket<A>) -> Pick<A>:
332  match r:
333    case Res.Took{p, g}:
334      Picked{p, t, g}
335    case Res.Refused{p}:
336      Idle{p}
337
338def pick.due(-A: Data, m: Maybe<&2, Q.Ticket<A>>, p: Res.Pool) -> Pick<A>:
339  match m:
340    case None{}:
341      Idle{p}
342    case Some{t}:
343      pick.took(A, Res.reserve(p, 1n), t)
344
345def pick.sel(-A: Data, r: Q.State<A> & Maybe<&2, Q.Ticket<A>>, p: Res.Pool) -> Pick<A>:
346  (q, m) = r
347  pick.due(A, m, p)
348
349# The ticket that Select{now} takes, with one unit of p, when there is a ticket due and a unit free.
350def pick(~A: Data, p: Res.Pool, s: State<A>, now: Nat) -> Pick<A>:
351  State{q, ts, ds, bs} = s
352  pick.sel(A, Q.select(~A, now, q), p)
353
354# ---- retry
355
356# The budget left for ticket i: the policy's attempts less its failures, until its start plus the policy deadline.
357def budget.of(+attempts: Nat, t: Maybe<&2, Try>, d: Maybe<&2, Nat>) -> Retry.Budget:
358  match t d:
359    case None{} m:
360      Retry.Budget{attempts, None{}}
361    case Some{Try{f, st}} None{}:
362      Retry.Budget{Nat.sub(attempts, f), None{}}
363    case Some{Try{f, +st}} Some{ms}:
364      Retry.Budget{Nat.sub(attempts, f), Some{Nat.add(st, ms)}}
365
366def budget(p: Retry.Policy, t: Maybe<&2, Try>) -> Retry.Budget:
367  Retry.Policy{a, base, cap, d} = p
368  budget.of(a, t, d)
369
370# The failures so far: the index of the next retry.
371def fails(t: Maybe<&2, Try>) -> Nat:
372  match t:
373    case None{}:
374      0n
375    case Some{Try{f, st}}:
376      f
377
378# Why retry stopped a transient failure: no attempt is left, or the next wait would reach the deadline.
379def gave(b: Retry.Budget) -> Why:
380  Retry.Budget{left, d} = b
381  match left:
382    case 0n:
383      WhySpent{}
384    case 1n+k:
385      WhyLate{}
386
387# A settled attempt completes its ticket; retry gave up at now on any other.
388def stopped(-A: Data, o: Retry.Outcome, b: Retry.Budget, +id: Nat, +now: Nat) -> Op<A>:
389  match o:
390    case Retry.Settled{}:
391      Complete{id}
392    case Retry.Failed{}:
393      Abandon{id, WhyFailed{}, now}
394    case Retry.Unsafe{}:
395      Abandon{id, WhyUnsafe{}, now}
396    case Retry.Transient{w}:
397      Abandon{id, gave(b), now}
398
399def after.plan(-A: Data, pl: Retry.Plan, o: Retry.Outcome, b: Retry.Budget, +id: Nat, +now: Nat) -> Op<A>:
400  match pl:
401    case Retry.PlanStop{}:
402      stopped(A, o, b, id, now)
403    case Retry.PlanWait{w}:
404      Requeue{id, Nat.add(now, w)}
405
406# The record after an attempt of ticket id ends at now with o: requeue at now plus retry's wait,
407# complete when o is settled, or abandon when retry gave up.
408def after(-A: Data, +o: Retry.Outcome, p: Retry.Policy, +b: Retry.Budget, +id: Nat, +n: Nat, +now: Nat, +r: Nat) -> Op<A>:
409  after.plan(A, Retry.plan(o, p, b, n, now, r), o, b, id, now)
410
411# When an open breaker lets attempts start again.
412def until(br: Retry.Breaker, +now: Nat) -> Nat:
413  match br:
414    case Retry.BreakerOn{c, Retry.CircuitOpen{u}}:
415      u
416    case Retry.BreakerOn{c, Retry.CircuitClosed{fs}}:
417      Nat.add(now, Retry.Circuit.cooldown(c))
418    case Retry.BreakerOn{c, Retry.CircuitHalf{k}}:
419      Nat.add(now, Retry.Circuit.cooldown(c))
420    case Retry.BreakerOff{}:
421      now
422
423# The record for a ticket that admit refused: Defer to when the breaker may admit, or Abandon when its budget is spent or late.
424def held(-A: Data, why: Retry.Deny, br: Retry.Breaker, +id: Nat, +now: Nat) -> Op<A>:
425  match why:
426    case Retry.DenyOpen{}:
427      Defer{id, until(br, now)}
428    case Retry.DenyLate{}:
429      Abandon{id, WhyLate{}, now}
430    case Retry.DenySpent{}:
431      Abandon{id, WhySpent{}, now}
432
433# ---- the record codec: a u32le tag, then u64le fields; an Enqueue then holds the payload.
434# An Abandon is tag 8, then id, why.code, and at. A Purge is tag 11 and before; a PurgeAll is tag 12.
435# A Break is tag 10, then its target and its breaker state.
436
437def why.code(w: Why) -> Nat:
438  match w:
439    case WhySpent{}:
440      0n
441    case WhyLate{}:
442      1n
443    case WhyUnsafe{}:
444      2n
445    case WhyFailed{}:
446      3n
447
448def W() -> Nat:
449  Nat.mul(65536n, 65536n)
450
451# Nat fields hold values under 2^64.
452def put.u64(b: Bytes.Bytes, +at: U32, +n: Nat) -> Bytes.Bytes:
453  Bytes.set.u32le(Bytes.set.u32le(b, at, U32.from_nat(Nat.mod(n, W()))), (at + 4 : U32), U32.from_nat(Nat.div(n, W())))
454
455def head(+tag: U32, +a: Nat, +c: Nat) -> Bytes.Bytes:
456  put.u64(put.u64(Bytes.set.u32le(Bytes.new(20), 0, tag), 4, a), 12, c)
457
458def snap.u32(out: Bytes.Bytes, +v: U32) -> Bytes.Bytes:
459  Bytes.append(out, Bytes.set.u32le(Bytes.new(4), 0, v))
460
461def snap.u64(out: Bytes.Bytes, +n: Nat) -> Bytes.Bytes:
462  Bytes.append(out, put.u64(Bytes.new(8), 0, n))
463
464def snap.chars(s: String, out: Bytes.Bytes) -> Bytes.Bytes:
465  match s:
466    case SNil{}:
467      out
468    case SCon{Chr{c}, t}:
469      snap.chars(t, snap.u32(out, c))
470
471# A target is a u32 count of chars, then each char as a u32.
472def snap.key(out: Bytes.Bytes, +k: String) -> Bytes.Bytes:
473  snap.chars(k, snap.u32(out, Bytes.count(k, 0)))
474
475def snap.nats(xs: List<&2, Nat>, out: Bytes.Bytes) -> Bytes.Bytes:
476  match xs:
477    case Nil{}:
478      out
479    case Con{x, rest}:
480      snap.nats(rest, snap.u64(out, x))
481
482# A breaker state is a u32 kind. 0 is closed: a u32 count, then each failure as a u64. 1 is open: until. 2 is half-open: busy.
483def snap.brk(out: Bytes.Bytes, b: Retry.State) -> Bytes.Bytes:
484  match b:
485    case Retry.CircuitClosed{+fs}:
486      snap.nats(fs, snap.u32(snap.u32(out, 0), U32.from_nat(List.length(&2, Nat, fs))))
487    case Retry.CircuitOpen{u}:
488      snap.u64(snap.u32(out, 1), u)
489    case Retry.CircuitHalf{k}:
490      snap.u64(snap.u32(out, 2), k)
491
492def encode(~A: Data, ~penc: A -> Bytes.Bytes, op: Op<A>) -> Bytes.Bytes:
493  match op:
494    case Enqueue{+d, x}:
495      Bytes.append(put.u64(Bytes.set.u32le(Bytes.new(12), 0, 1), 4, d), penc(x))
496    case Select{+now}:
497      head(2, now, 0n)
498    case Complete{+i}:
499      head(3, i, 0n)
500    case Cancel{+i}:
501      head(4, i, 0n)
502    case Requeue{+i, +d}:
503      head(5, i, d)
504    case Defer{+i, +d}:
505      head(6, i, d)
506    case Abandon{+i, w, +at}:
507      Bytes.append(head(8, i, why.code(w)), put.u64(Bytes.new(8), 0, at))
508    case Revive{+i, +d}:
509      head(9, i, d)
510    case Purge{+t}:
511      head(11, t, 0n)
512    case PurgeAll{}:
513      head(12, 0n, 0n)
514    case Break{k, b}:
515      snap.brk(snap.key(snap.u32(Bytes.new(0), 10), k), b)
516
517def get.field(m: Maybe<&2, U32>) -> U32:
518  match m:
519    case None{}:
520      0
521    case Some{x}:
522      x
523
524def get.u32(r: Bytes.Bytes & Maybe<&2, U32>) -> Bytes.Bytes & U32:
525  (b, m) = r
526  (b, get.field(m))
527
528def get.hi(+lo: U32, r: Bytes.Bytes & Maybe<&2, U32>) -> Bytes.Bytes & Nat:
529  (b, m) = r
530  (b, Nat.add(U32.to_nat(lo), Nat.mul(U32.to_nat(get.field(m)), W())))
531
532def get.lo(+at: U32, r: Bytes.Bytes & Maybe<&2, U32>) -> Bytes.Bytes & Nat:
533  (b, m) = r
534  +lo = get.field(m)
535  get.hi(lo, Bytes.get.u32le(b, (at + 4 : U32)))
536
537def get.u64(b: Bytes.Bytes, +at: U32) -> Bytes.Bytes & Nat:
538  get.lo(at, Bytes.get.u32le(b, at))
539
540# ---- the snapshot codec: tag 7 and the next id, then the heap, the running list, the tries, the dead tickets, and the breakers.
541# A u32 flag starts each tree node and list cell (1) and marks each end (0), so decode rebuilds the same shape.
542# A ticket is its u64 id and deadline, then a u32 length and the payload.
543# The dead tickets are a trie: each node is a u32 kind, 0 empty, 1 a bucket, or 2 a branch, then its lo and hi nodes.
544# A bucket is its u32 hash, then a list of entries: the u64 key, the ticket, a u32 why.code, and the u64 abandon time.
545# A breaker is its target, then its state, as in a Break record.
546
547def snap.payload(out: Bytes.Bytes, p: Bytes.Bytes) -> Bytes.Bytes:
548  Bytes.Bytes{+len, buf} = p
549  Bytes.append(snap.u32(out, len), Bytes.Bytes{len, buf})
550
551def snap.ticket(~A: Data, ~penc: A -> Bytes.Bytes, out: Bytes.Bytes, t: Q.Ticket<A>) -> Bytes.Bytes:
552  Q.Ticket{+i, +d, x} = t
553  snap.payload(snap.u64(snap.u64(out, i), d), penc(x))
554
555def snap.heap(~A: Data, ~penc: A -> Bytes.Bytes, h: H.Heap<Q.Ticket<A>>, out: Bytes.Bytes) -> Bytes.Bytes:
556  match h:
557    case H.HLeaf{}:
558      snap.u32(out, 0)
559    case H.HNode{+n, t, l, r}:
560      snap.heap(~A, ~penc, r, snap.heap(~A, ~penc, l, snap.ticket(~A, ~penc, snap.u64(snap.u32(out, 1), n), t)))
561
562def snap.run(~A: Data, ~penc: A -> Bytes.Bytes, xs: List<&2, Q.Ticket<A>>, out: Bytes.Bytes) -> Bytes.Bytes:
563  match xs:
564    case Nil{}:
565      snap.u32(out, 0)
566    case Con{t, rest}:
567      snap.run(~A, ~penc, rest, snap.ticket(~A, ~penc, snap.u32(out, 1), t))
568
569def snap.tries(ts: Tries(), out: Bytes.Bytes) -> Bytes.Bytes:
570  match ts:
571    case O.OTip{}:
572      snap.u32(out, 0)
573    case O.OBin{+n, +k, Try{+f, +st}, lo, hi}:
574      snap.tries(hi, snap.tries(lo, snap.u64(snap.u64(snap.u64(snap.u32(snap.u32(out, 1), n), k), f), st)))
575
576def snap.entries(~A: Data, ~penc: A -> Bytes.Bytes, es: List<&2, M.Entry<Nat, Dead<A>>>, out: Bytes.Bytes) -> Bytes.Bytes:
577  match es:
578    case Nil{}:
579      snap.u32(out, 0)
580    case Con{M.Entry{k, Dead{t, w, at}}, rest}:
581      snap.entries(~A, ~penc, rest, snap.u64(snap.u32(snap.ticket(~A, ~penc, snap.u64(snap.u32(out, 1), k), t), U32.from_nat(why.code(w))), at))
582
583def snap.graves(~A: Data, ~penc: A -> Bytes.Bytes, ds: Graves(A), out: Bytes.Bytes) -> Bytes.Bytes:
584  match ds:
585    case M.HNil{}:
586      snap.u32(out, 0)
587    case M.HLeaf{h, es}:
588      snap.entries(~A, ~penc, es, snap.u32(snap.u32(out, 1), h))
589    case M.HBranch{lo, hi}:
590      snap.graves(~A, ~penc, hi, snap.graves(~A, ~penc, lo, snap.u32(out, 2)))
591
592def snap.brks(xs: List<&2, Sigma<&2, &2, String, _ => Retry.State>>, out: Bytes.Bytes) -> Bytes.Bytes:
593  match xs:
594    case Nil{}:
595      snap.u32(out, 0)
596    case Con{(k, b), rest}:
597      snap.brks(rest, snap.brk(snap.key(snap.u32(out, 1), k), b))
598
599# The Snap record of s.
600def encode.snap(~A: Data, ~penc: A -> Bytes.Bytes, s: State<A>) -> Bytes.Bytes:
601  State{Q.State{+n, h, run}, ts, ds, bs} = s
602  snap.brks(Map.to_list(&2, Retry.State, bs),
603    snap.graves(~A, ~penc, ds, snap.tries(ts, snap.run(~A, ~penc, run, snap.heap(~A, ~penc, h, snap.u64(snap.u32(Bytes.new(0), 7), n))))))
604
605def encode.rec(~A: Data, ~penc: A -> Bytes.Bytes, r: Rec<A>) -> Bytes.Bytes:
606  match r:
607    case Snap{s}:
608      encode.snap(~A, ~penc, s)
609    case Do{op}:
610      encode(~A, ~penc, op)
611
612# A snapshot reader: the record, and the offset of the next field.
613type Rd is Type:
614  Rd{b: Bytes.Bytes, at: U32}
615
616# One step of the snapshot decoder. None: a field runs past the record or does not decode.
617def Dec(-T: Type) -> Type:
618  Rd -> Maybe<&1, Rd & T>
619
620def Dec.next(-A: Type, -B: Type, m: Maybe<&1, Rd & A>, f: A -> Dec(B)) -> Maybe<&1, Rd & B>:
621  match m:
622    case None{}:
623      None{}
624    case Some{(r, x)}:
625      f(x)(r)
626
627def Dec.bind(-A: Type, -B: Type, m: Dec(A), f: A -> Dec(B)) -> Dec(B):
628  r => Dec.next(A, B, m(r), f)
629
630def Dec.pure(-A: Type, x: A) -> Dec(A):
631  r => Some{(r, x)}
632
633def Dec.fail(-A: Type) -> Dec(A):
634  r => None{}
635
636def rd.u32.of(m: Maybe<&2, U32>, b: Bytes.Bytes, +at: U32) -> Maybe<&1, Rd & U32>:
637  match m:
638    case None{}:
639      None{}
640    case Some{x}:
641      Some{(Rd{b, (at + 4 : U32)}, x)}
642
643def rd.u32.got(+at: U32, r: Bytes.Bytes & Maybe<&2, U32>) -> Maybe<&1, Rd & U32>:
644  (b, m) = r
645  rd.u32.of(m, b, at)
646
647def rd.u32.at(r: Rd) -> Maybe<&1, Rd & U32>:
648  Rd{b, +at} = r
649  rd.u32.got(at, Bytes.get.u32le(b, at))
650
651def rd.u32() -> Dec(U32):
652  r => rd.u32.at(r)
653
654def rd.u64.of(+lo: U32, +hi: U32) -> Nat:
655  Nat.add(U32.to_nat(lo), Nat.mul(U32.to_nat(hi), W()))
656
657def rd.u64() -> Dec(Nat):
658  do Dec<Nat>:
659    lo : U32 <- rd.u32()
660    hi : U32 <- rd.u32()
661    return rd.u64.of(lo, hi)
662
663def rd.cut.got(+at: U32, +n: U32, r: Bytes.Bytes & Bytes.Bytes) -> Maybe<&1, Rd & Bytes.Bytes>:
664  (b, p) = r
665  Some{(Rd{b, (at + n : U32)}, p)}
666
667def rd.cut.if(ok: Bool, b: Bytes.Bytes, +at: U32, +n: U32) -> Maybe<&1, Rd & Bytes.Bytes>:
668  match ok:
669    case False{}:
670      None{}
671    case True{}:
672      rd.cut.got(at, n, Bytes.slice(b, at, n))
673
674def rd.cut.at(+n: U32, r: Rd) -> Maybe<&1, Rd & Bytes.Bytes>:
675  Rd{Bytes.Bytes{+len, buf}, +at} = r
676  rd.cut.if(Bytes.fits(len, at, n), Bytes.Bytes{len, buf}, at, n)
677
678# The next n octets.
679def rd.cut(+n: U32) -> Dec(Bytes.Bytes):
680  r => rd.cut.at(n, r)
681
682def rd.flag.of(+m: U32) -> Dec(Bool):
683  Bool.pick(Dec(Bool), U32.is_eq(m, 0), Dec.pure(Bool, False{}), Bool.pick(Dec(Bool), U32.is_eq(m, 1), Dec.pure(Bool, True{}), Dec.fail(Bool)))
684
685# A u32 flag: 1 is True, 0 is False, and any other value fails.
686def rd.flag() -> Dec(Bool):
687  Dec.bind(U32, Bool, rd.u32(), m => rd.flag.of(m))
688
689def rd.payload(-A: Data, +i: Nat, +d: Nat, m: Maybe<&2, A>) -> Dec(Q.Ticket<A>):
690  match m:
691    case None{}:
692      Dec.fail(Q.Ticket<A>)
693    case Some{x}:
694      Dec.pure(Q.Ticket<A>, Q.Ticket{i, d, x})
695
696def rd.ticket(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>) -> Dec(Q.Ticket<A>):
697  do Dec<Q.Ticket<A>>:
698    i : Nat <- rd.u64()
699    d : Nat <- rd.u64()
700    n : U32 <- rd.u32()
701    p : Bytes.Bytes <- rd.cut(n)
702    rd.payload(A, i, d, pdec(p))
703
704# Each rd.* tree reader takes the flag already read. fuel bounds the depth: every node holds at least one 4-octet flag.
705def rd.heap(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, +fuel: Nat, node: Bool) -> Dec(H.Heap<Q.Ticket<A>>):
706  match fuel node:
707    case 0n b:
708      Dec.fail(H.Heap<Q.Ticket<A>>)
709    case 1n+f False{}:
710      Dec.pure(H.Heap<Q.Ticket<A>>, H.HLeaf{})
711    case 1n+f True{}:
712      do Dec<H.Heap<Q.Ticket<A>>>:
713        n : Nat <- rd.u64()
714        t : Q.Ticket<A> <- rd.ticket(~A, ~pdec)
715        lf : Bool <- rd.flag()
716        l : H.Heap<Q.Ticket<A>> <- rd.heap(~A, ~pdec, f, lf)
717        rf : Bool <- rd.flag()
718        r : H.Heap<Q.Ticket<A>> <- rd.heap(~A, ~pdec, f, rf)
719        return H.HNode{n, t, l, r}
720
721def rd.run(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, +fuel: Nat, more: Bool) -> Dec(List<&2, Q.Ticket<A>>):
722  match fuel more:
723    case 0n b:
724      Dec.fail(List<&2, Q.Ticket<A>>)
725    case 1n+f False{}:
726      Dec.pure(List<&2, Q.Ticket<A>>, Nil{})
727    case 1n+f True{}:
728      do Dec<List<&2, Q.Ticket<A>>>:
729        t : Q.Ticket<A> <- rd.ticket(~A, ~pdec)
730        m : Bool <- rd.flag()
731        rest : List<&2, Q.Ticket<A>> <- rd.run(~A, ~pdec, f, m)
732        return Con{t, rest}
733
734def rd.tries(+fuel: Nat, node: Bool) -> Dec(O.OMap<Nat, Try>):
735  match fuel node:
736    case 0n b:
737      Dec.fail(O.OMap<Nat, Try>)
738    case 1n+f False{}:
739      Dec.pure(O.OMap<Nat, Try>, O.OTip{})
740    case 1n+f True{}:
741      do Dec<O.OMap<Nat, Try>>:
742        n : U32 <- rd.u32()
743        k : Nat <- rd.u64()
744        fails : Nat <- rd.u64()
745        st : Nat <- rd.u64()
746        lf : Bool <- rd.flag()
747        lo : O.OMap<Nat, Try> <- rd.tries(f, lf)
748        hf : Bool <- rd.flag()
749        hi : O.OMap<Nat, Try> <- rd.tries(f, hf)
750        return O.OBin{n, k, Try{fails, st}, lo, hi}
751
752def rd.why(+c: U32) -> Dec(Why):
753  Bool.pick(Dec(Why), U32.is_eq(c, 0), Dec.pure(Why, WhySpent{}),
754  Bool.pick(Dec(Why), U32.is_eq(c, 1), Dec.pure(Why, WhyLate{}),
755  Bool.pick(Dec(Why), U32.is_eq(c, 2), Dec.pure(Why, WhyUnsafe{}),
756  Bool.pick(Dec(Why), U32.is_eq(c, 3), Dec.pure(Why, WhyFailed{}), Dec.fail(Why)))))
757
758def rd.entries(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, +fuel: Nat, more: Bool) -> Dec(List<&2, M.Entry<Nat, Dead<A>>>):
759  match fuel more:
760    case 0n b:
761      Dec.fail(List<&2, M.Entry<Nat, Dead<A>>>)
762    case 1n+f False{}:
763      Dec.pure(List<&2, M.Entry<Nat, Dead<A>>>, Nil{})
764    case 1n+f True{}:
765      do Dec<List<&2, M.Entry<Nat, Dead<A>>>>:
766        k : Nat <- rd.u64()
767        t : Q.Ticket<A> <- rd.ticket(~A, ~pdec)
768        c : U32 <- rd.u32()
769        w : Why <- rd.why(c)
770        at : Nat <- rd.u64()
771        m : Bool <- rd.flag()
772        rest : List<&2, M.Entry<Nat, Dead<A>>> <- rd.entries(~A, ~pdec, f, m)
773        return Con{M.Entry{k, Dead{t, w, at}}, rest}
774
775# A trie node whose kind is already read: nil is kind 0, leaf kind 1, and branch kind 2. Any other kind fails.
776def rd.graves(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, +fuel: Nat, nil: Bool, leaf: Bool, branch: Bool) -> Dec(Graves(A)):
777  match fuel nil leaf branch:
778    case 0n a b c:
779      Dec.fail(Graves(A))
780    case 1n+f True{} b c:
781      Dec.pure(Graves(A), M.HNil{})
782    case 1n+f False{} True{} c:
783      do Dec<Graves(A)>:
784        h : U32 <- rd.u32()
785        m : Bool <- rd.flag()
786        es : List<&2, M.Entry<Nat, Dead<A>>> <- rd.entries(~A, ~pdec, f, m)
787        return M.HLeaf{h, es}
788    case 1n+f False{} False{} True{}:
789      do Dec<Graves(A)>:
790        +lk : U32 <- rd.u32()
791        lo : Graves(A) <- rd.graves(~A, ~pdec, f, U32.is_eq(lk, 0), U32.is_eq(lk, 1), U32.is_eq(lk, 2))
792        +hk : U32 <- rd.u32()
793        hi : Graves(A) <- rd.graves(~A, ~pdec, f, U32.is_eq(hk, 0), U32.is_eq(hk, 1), U32.is_eq(hk, 2))
794        return M.HBranch{lo, hi}
795    case 1n+f False{} False{} False{}:
796      Dec.fail(Graves(A))
797
798# Each rd.* sequence reader takes the count or flag already read. fuel bounds its length: every item holds at least 4 octets.
799def rd.chars(+fuel: Nat, end: Bool, +n: U32) -> Dec(String):
800  match fuel end:
801    case 0n b:
802      Dec.fail(String)
803    case 1n+f True{}:
804      Dec.pure(String, SNil{})
805    case 1n+f False{}:
806      +k = (n - 1 : U32)
807      do Dec<String>:
808        c : U32 <- rd.u32()
809        rest : String <- rd.chars(f, U32.is_eq(k, 0), k)
810        return SCon{Chr{c}, rest}
811
812def rd.key(+fuel: Nat) -> Dec(String):
813  do Dec<String>:
814    +n : U32 <- rd.u32()
815    rd.chars(fuel, U32.is_eq(n, 0), n)
816
817def rd.nats(+fuel: Nat, end: Bool, +n: U32) -> Dec(List<&2, Nat>):
818  match fuel end:
819    case 0n b:
820      Dec.fail(List<&2, Nat>)
821    case 1n+f True{}:
822      Dec.pure(List<&2, Nat>, Nil{})
823    case 1n+f False{}:
824      +k = (n - 1 : U32)
825      do Dec<List<&2, Nat>>:
826        x : Nat <- rd.u64()
827        rest : List<&2, Nat> <- rd.nats(f, U32.is_eq(k, 0), k)
828        return Con{x, rest}
829
830def rd.closed(+fuel: Nat) -> Dec(Retry.State):
831  do Dec<Retry.State>:
832    +n : U32 <- rd.u32()
833    fs : List<&2, Nat> <- rd.nats(fuel, U32.is_eq(n, 0), n)
834    return Retry.CircuitClosed{fs}
835
836def rd.brk.of(+fuel: Nat, +kind: U32) -> Dec(Retry.State):
837  Bool.pick(Dec(Retry.State), U32.is_eq(kind, 0), rd.closed(fuel),
838  Bool.pick(Dec(Retry.State), U32.is_eq(kind, 1), Dec.bind(Nat, Retry.State, rd.u64(), u => Dec.pure(Retry.State, Retry.CircuitOpen{u})),
839  Bool.pick(Dec(Retry.State), U32.is_eq(kind, 2), Dec.bind(Nat, Retry.State, rd.u64(), k => Dec.pure(Retry.State, Retry.CircuitHalf{k})), Dec.fail(Retry.State))))
840
841def rd.brk(+fuel: Nat) -> Dec(Retry.State):
842  Dec.bind(U32, Retry.State, rd.u32(), k => rd.brk.of(fuel, k))
843
844def rd.break(-A: Data, +fuel: Nat) -> Dec(Op<A>):
845  do Dec<Op<A>>:
846    k : String <- rd.key(fuel)
847    b : Retry.State <- rd.brk(fuel)
848    return Break{k, b}
849
850def rd.brks(+fuel: Nat, more: Bool, acc: Map<&2, Retry.State>) -> Dec(Map<&2, Retry.State>):
851  match fuel more:
852    case 0n b:
853      Dec.fail(Map<&2, Retry.State>)
854    case 1n+f False{}:
855      Dec.pure(Map<&2, Retry.State>, acc)
856    case 1n+f True{}:
857      do Dec<Map<&2, Retry.State>>:
858        k : String <- rd.key(f)
859        b : Retry.State <- rd.brk(f)
860        m : Bool <- rd.flag()
861        rd.brks(f, m, Map.set(&2, Retry.State, acc, k, b))
862
863def rd.state(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, +fuel: Nat) -> Dec(State<A>):
864  do Dec<State<A>>:
865    n : Nat <- rd.u64()
866    hf : Bool <- rd.flag()
867    h : H.Heap<Q.Ticket<A>> <- rd.heap(~A, ~pdec, fuel, hf)
868    rf : Bool <- rd.flag()
869    run : List<&2, Q.Ticket<A>> <- rd.run(~A, ~pdec, fuel, rf)
870    tf : Bool <- rd.flag()
871    ts : O.OMap<Nat, Try> <- rd.tries(fuel, tf)
872    +dk : U32 <- rd.u32()
873    ds : Graves(A) <- rd.graves(~A, ~pdec, fuel, U32.is_eq(dk, 0), U32.is_eq(dk, 1), U32.is_eq(dk, 2))
874    bf : Bool <- rd.flag()
875    bs : Map<&2, Retry.State> <- rd.brks(fuel, bf, Map.new(&2, Retry.State))
876    return State{Q.State{n, h, run}, ts, ds, bs}
877
878# The value read, when the reader ended at len, the record's end.
879def rd.done(-T: Data, +len: U32, m: Maybe<&1, Rd & T>) -> Maybe<&2, T>:
880  match m:
881    case None{}:
882      None{}
883    case Some{(Rd{b, +at}, +x)}:
884      Bool.pick(Maybe<&2, T>, U32.is_eq(at, len), Some{x}, None{})
885
886# The Abandon of ticket a at e whose why.code is c, or None for any other code.
887def decode.abandon(-A: Data, +a: Nat, +c: Nat, +e: Nat) -> Maybe<&2, Op<A>>:
888  Bool.pick(Maybe<&2, Op<A>>, Nat.is_eq(c, 0n), Some{Abandon{a, WhySpent{}, e}},
889  Bool.pick(Maybe<&2, Op<A>>, Nat.is_eq(c, 1n), Some{Abandon{a, WhyLate{}, e}},
890  Bool.pick(Maybe<&2, Op<A>>, Nat.is_eq(c, 2n), Some{Abandon{a, WhyUnsafe{}, e}},
891  Bool.pick(Maybe<&2, Op<A>>, Nat.is_eq(c, 3n), Some{Abandon{a, WhyFailed{}, e}}, None{}))))
892
893def decode.small(-A: Data, ok: Bool, +tag: U32, +a: Nat, +c: Nat) -> Maybe<&2, Op<A>>:
894  match ok:
895    case False{}:
896      None{}
897    case True{}:
898      Bool.pick(Maybe<&2, Op<A>>, U32.is_eq(tag, 2), Some{Select{a}},
899      Bool.pick(Maybe<&2, Op<A>>, U32.is_eq(tag, 3), Some{Complete{a}},
900      Bool.pick(Maybe<&2, Op<A>>, U32.is_eq(tag, 4), Some{Cancel{a}},
901      Bool.pick(Maybe<&2, Op<A>>, U32.is_eq(tag, 5), Some{Requeue{a, c}},
902      Bool.pick(Maybe<&2, Op<A>>, U32.is_eq(tag, 6), Some{Defer{a, c}},
903      Bool.pick(Maybe<&2, Op<A>>, U32.is_eq(tag, 9), Some{Revive{a, c}},
904      Bool.pick(Maybe<&2, Op<A>>, U32.is_eq(tag, 11), Some{Purge{a}},
905      Bool.pick(Maybe<&2, Op<A>>, U32.is_eq(tag, 12), Some{PurgeAll{}}, None{}))))))))
906
907def decode.long(-A: Data, ok: Bool, +a: Nat, +c: Nat, r: Bytes.Bytes & Nat) -> Maybe<&2, Op<A>>:
908  match ok:
909    case False{}:
910      None{}
911    case True{}:
912      (b, +e) = r
913      decode.abandon(A, a, c, e)
914
915def decode.payload(-A: Data, m: Maybe<&2, A>, +d: Nat) -> Maybe<&2, Op<A>>:
916  match m:
917    case None{}:
918      None{}
919    case Some{x}:
920      Some{Enqueue{d, x}}
921
922def decode.c.if(-A: Data, abandon: Bool, +tag: U32, +len: U32, +a: Nat, +c: Nat, b: Bytes.Bytes) -> Maybe<&2, Op<A>>:
923  match abandon:
924    case True{}:
925      decode.long(A, U32.is_eq(len, 28), a, c, get.u64(b, 20))
926    case False{}:
927      decode.small(A, U32.is_eq(len, 20), tag, a, c)
928
929# An Abandon is 28 octets; every other op without a payload is 20.
930def decode.c(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, +tag: U32, +len: U32, +a: Nat, r: Bytes.Bytes & Nat) -> Maybe<&2, Op<A>>:
931  (b, +c) = r
932  decode.c.if(A, U32.is_eq(tag, 8), tag, len, a, c, b)
933
934def decode.kind(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, enq: Bool, +tag: U32, +len: U32, +a: Nat, b: Bytes.Bytes) -> Maybe<&2, Op<A>>:
935  match enq:
936    case True{}:
937      decode.payload(A, pdec(Bytes.snd(Bytes.slice(b, 12, (len - 12 : U32)))), a)
938    case False{}:
939      decode.c(~A, ~pdec, tag, len, a, get.u64(b, 12))
940
941def decode.a(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, +tag: U32, +len: U32, r: Bytes.Bytes & Nat) -> Maybe<&2, Op<A>>:
942  (b, +a) = r
943  decode.kind(~A, ~pdec, U32.is_eq(tag, 1), tag, len, a, b)
944
945def decode.tag.if(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, brk: Bool, +tag: U32, +len: U32, b: Bytes.Bytes) -> Maybe<&2, Op<A>>:
946  match brk:
947    case True{}:
948      rd.done(Op<A>, len, rd.break(A, U32.to_nat((len / 4 + 1 : U32)))(Rd{b, 4}))
949    case False{}:
950      decode.a(~A, ~pdec, tag, len, get.u64(b, 4))
951
952def decode.tag(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, +len: U32, r: Bytes.Bytes & U32) -> Maybe<&2, Op<A>>:
953  (b, +tag) = r
954  decode.tag.if(~A, ~pdec, U32.is_eq(tag, 10), tag, len, b)
955
956def decode.len(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, ok: Bool, +len: U32, b: Bytes.Bytes) -> Maybe<&2, Op<A>>:
957  match ok:
958    case False{}:
959      None{}
960    case True{}:
961      decode.tag(~A, ~pdec, len, get.u32(Bytes.get.u32le(b, 0)))
962
963# The op of a record, or None when it is not one that encode writes.
964def decode(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, b: Bytes.Bytes) -> Maybe<&2, Op<A>>:
965  Bytes.Bytes{+len, buf} = b
966  decode.len(~A, ~pdec, U32.is_ge(len, 12), len, Bytes.Bytes{len, buf})
967
968# The state of a Snap record whose tag is already checked. The decoder must end at the record's end.
969def decode.snap(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, b: Bytes.Bytes) -> Maybe<&2, State<A>>:
970  Bytes.Bytes{+len, buf} = b
971  rd.done(State<A>, len, rd.state(~A, ~pdec, U32.to_nat((len / 4 + 1 : U32)))(Rd{Bytes.Bytes{len, buf}, 4}))
972
973def decode.snapped(-A: Data, m: Maybe<&2, State<A>>) -> Maybe<&2, Rec<A>>:
974  match m:
975    case None{}:
976      None{}
977    case Some{s}:
978      Some{Snap{s}}
979
980def decode.did(-A: Data, m: Maybe<&2, Op<A>>) -> Maybe<&2, Rec<A>>:
981  match m:
982    case None{}:
983      None{}
984    case Some{op}:
985      Some{Do{op}}
986
987def decode.rec.if(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, snap: Bool, b: Bytes.Bytes) -> Maybe<&2, Rec<A>>:
988  match snap:
989    case True{}:
990      decode.snapped(A, decode.snap(~A, ~pdec, b))
991    case False{}:
992      decode.did(A, decode(~A, ~pdec, b))
993
994def decode.rec.tag(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, r: Bytes.Bytes & U32) -> Maybe<&2, Rec<A>>:
995  (b, +tag) = r
996  decode.rec.if(~A, ~pdec, U32.is_eq(tag, 7), b)
997
998# The Rec of a journal record, or None when it is neither a Snap nor an op that encode.rec writes.
999def decode.rec(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, b: Bytes.Bytes) -> Maybe<&2, Rec<A>>:
1000  decode.rec.tag(~A, ~pdec, get.u32(Bytes.get.u32le(b, 0)))
1001
1002# ---- the runner
1003
1004# policy: retry's policy for each ticket. circuit: the breaker of each target. idle: ms that drain waits when no attempt started.
1005# compact: tick compacts the journal once records past this many octets were appended since open or the last compaction; 0 never.
1006type Config is Data:
1007  Config{policy: Retry.Policy, circuit: Retry.Circuit, idle: U32, compact: U32}
1008
1009# The journal, its path, its file cap, and its length at open or at the last compaction.
1010type Log is Type:
1011  Log{journal: J.Journal, path: String, limit: U32, base: U32}
1012
1013# An attempt that runs: its unit of the pool, the budget that admit left, and its target.
1014type Flight<-A: Data> is Type:
1015  Flight{ticket: Q.Ticket<A>, grant: Res.Grant, budget: Retry.Budget, target: String}
1016
1017def Out(-X: Type) -> Type:
1018  Result<&1, &1, U32 & String, X>
1019
1020# A message to the fiber that owns the runner. Ended: an attempt finished. Add and Drop: another fiber asks for an enqueue or a cancel.
1021type Msg<-A: Data> is Type:
1022  Ended{id: Nat, outcome: Retry.Outcome}
1023  Add{deadline: Nat, payload: A, reply: Chan(Out(Nat))}
1024  Drop{id: Nat, reply: Chan(Out(Unit))}
1025
1026# An open runner. Replaying its journal gives its state; its pool bounds the attempts that run at once.
1027# Each attempt sends its outcome, and each other fiber its ask, on inbox. flights are the attempts that run.
1028type Runner<-A: Data> is Type:
1029  Runner{log: Log, state: State<A>, pool: Res.Pool, config: Config, inbox: Chan(Msg<A>), flights: List<&1, Flight<A>>}
1030
1031# The runner, the claim fuel left, and the first error.
1032def Claimed(-A: Data) -> Type:
1033  Runner<A> & Nat & Out(Unit)
1034
1035def Ran(-A: Data) -> Type:
1036  Runner<A> & Out(Unit)
1037
1038# Wall-clock ms since the Unix epoch. Deadlines must keep their meaning across a restart.
1039def clock() -> IO(Nat):
1040  do IO<Nat>:
1041    t : Time.Instant <- Time.now()
1042    return Time.Duration.to_ms_nat(Time.Instant.since_epoch(t))
1043
1044def first(a: Out(Unit), b: Out(Unit)) -> Out(Unit):
1045  match a:
1046    case Fail{e}:
1047      Fail{e}
1048    case Done{u}:
1049      b
1050
1051def log.appended(+path: String, +limit: U32, +base: U32, x: J.Journal & Out(Unit)) -> Log & Out(Unit):
1052  (j, o) = x
1053  (Log{j, path, limit, base}, o)
1054
1055def log.append(l: Log, p: Bytes.Bytes) -> IO(Log & Out(Unit)):
1056  Log{j, +path, +limit, +base} = l
1057  do IO<Log & Out(Unit)>:
1058    x : J.Journal & Out(Unit) <- J.append(j, p)
1059    return log.appended(path, limit, base, x)
1060
1061def log.close(l: Log) -> IO(Unit):
1062  Log{j, path, limit, base} = l
1063  J.close(j)
1064
1065# The journal reads with limit as its record cap, so that a snapshot fits; appends keep max.
1066def log.of(j: J.Journal, +max: U32, path: String, +limit: U32) -> Log:
1067  J.Journal{file, cap, +end, ok} = j
1068  Log{J.Journal{file, max, end, ok}, path, limit, end}
1069
1070def commit.done(~A: Data, x: Log & Out(Unit), s: State<A>, +op: Op<A>, p: Res.Pool, c: Config, ib: Chan(Msg<A>), fs: List<&1, Flight<A>>) -> Ran(A):
1071  match x:
1072    case (j, Done{u}):
1073      (Runner{j, step(~A, s, op), p, c, ib, fs}, Done{u})
1074    case (j, Fail{e}):
1075      (Runner{j, s, p, c, ib, fs}, Fail{e})
1076
1077# Appends op, and applies it once the append is durable. After a failed append the state is as it was,
1078# and the journal refuses every later append until the runner is reopened.
1079def commit(~A: Data, ~penc: A -> Bytes.Bytes, r: Runner<A>, +op: Op<A>) -> IO(Ran(A)):
1080  Runner{j, s, p, c, ib, fs} = r
1081  do IO<Ran(A)>:
1082    x : Log & Out(Unit) <- log.append(j, encode(~A, ~penc, op))
1083    return commit.done(~A, x, s, op, p, c, ib, fs)
1084
1085def enqueue.done(-A: Data, +id: Nat, y: Ran(A)) -> Runner<A> & Out(Nat):
1086  match y:
1087    case (r, Done{u}):
1088      (r, Done{id})
1089    case (r, Fail{e}):
1090      (r, Fail{e})
1091
1092# Adds a job that is due at deadline (wall-clock ms) and answers its ticket id once the record is durable.
1093def enqueue(~A: Data, ~penc: A -> Bytes.Bytes, r: Runner<A>, +deadline: Nat, x: A) -> IO(Runner<A> & Out(Nat)):
1094  Runner{j, +s, p, c, ib, fs} = r
1095  do IO<Runner<A> & Out(Nat)>:
1096    y : Ran(A) <- commit(~A, ~penc, Runner{j, s, p, c, ib, fs}, Enqueue{deadline, x})
1097    return enqueue.done(A, Q.next_id(A, queue(A, s)), y)
1098
1099# Cancels ticket id. A running attempt finishes, but its ticket is never selected again. A dead ticket is dropped.
1100def cancel(~A: Data, ~penc: A -> Bytes.Bytes, r: Runner<A>, +id: Nat) -> IO(Ran(A)):
1101  commit(~A, ~penc, r, Cancel{id})
1102
1103# Makes dead ticket id pending again at deadline (wall-clock ms), with its payload and a new retry budget.
1104# A ticket that is not dead does not change.
1105def revive(~A: Data, ~penc: A -> Bytes.Bytes, r: Runner<A>, +id: Nat, +deadline: Nat) -> IO(Ran(A)):
1106  commit(~A, ~penc, r, Revive{id, deadline})
1107
1108# Drops, as one record, the dead tickets that retry gave up on before `before` (wall-clock ms).
1109def purge(~A: Data, ~penc: A -> Bytes.Bytes, r: Runner<A>, +before: Nat) -> IO(Ran(A)):
1110  commit(~A, ~penc, r, Purge{before})
1111
1112# Drops every dead ticket, as one record.
1113def purge.all(~A: Data, ~penc: A -> Bytes.Bytes, r: Runner<A>) -> IO(Ran(A)):
1114  commit(~A, ~penc, r, PurgeAll{})
1115
1116# ---- asks from other fibers
1117
1118# The runner back, and its inbox. Another fiber passes the inbox to ask.enqueue and ask.cancel.
1119def inbox(-A: Data, r: Runner<A>) -> Runner<A> & Chan(Msg<A>):
1120  Runner{j, s, p, c, +ib, fs} = r
1121  (Runner{j, s, p, c, ib, fs}, ib)
1122
1123def ask.answer(-X: Type, m: Maybe<&1, Out(X)>) -> Out(X):
1124  match m:
1125    case None{}:
1126      Fail{(32, "runner: the runner closed before it answered")}
1127    case Some{o}:
1128      o
1129
1130def ask.sent(-A: Data, -X: Type, x: Result<&1, &1, Msg<A>, Unit>, +rep: Chan(Out(X))) -> IO(Out(X)):
1131  match x:
1132    case Fail{m}:
1133      IO.pure(Out(X), Fail{(32, "runner: the inbox is closed")})
1134    case Done{u}:
1135      do IO<Out(X)>:
1136        a : Maybe<&1, Out(X)> <- Chan.recv(Out(X), rep)
1137        return ask.answer(X, a)
1138
1139# Sends m, built with a new reply channel, on the inbox and waits for the reply.
1140def ask(-A: Data, -X: Type, +ib: Chan(Msg<A>), m: Chan(Out(X)) -> Msg<A>) -> IO(Out(X)):
1141  do IO<Out(X)>:
1142    +rep : Chan(Out(X)) <- Chan.new(Out(X), 1)
1143    x : Result<&1, &1, Msg<A>, Unit> <- Chan.send(Msg<A>, ib, m(rep))
1144    ask.sent(A, X, x, rep)
1145
1146# From another fiber: adds a job due at deadline, and answers its ticket id once the record is durable.
1147# The answer comes when the fiber that owns the runner reads the inbox, in tick or drain.
1148def ask.enqueue(-A: Data, +ib: Chan(Msg<A>), +deadline: Nat, x: A) -> IO(Out(Nat)):
1149  ask(A, Nat, ib, rep => Add{deadline, x, rep})
1150
1151# From another fiber: cancels ticket id, as cancel does. The answer comes when the owner reads the inbox.
1152def ask.cancel(-A: Data, +ib: Chan(Msg<A>), +id: Nat) -> IO(Out(Unit)):
1153  ask(A, Unit, ib, rep => Drop{id, rep})
1154
1155# ---- one round
1156
1157# A grant of this runner's pool always fits it, so Kept does not happen.
1158def release.got(-A: Data, x: Res.Release, j: Log, s: State<A>, c: Config, ib: Chan(Msg<A>), fs: List<&1, Flight<A>>) -> Runner<A>:
1159  match x:
1160    case Res.Released{p}:
1161      Runner{j, s, p, c, ib, fs}
1162    case Res.Kept{p, g}:
1163      Runner{j, s, p, c, ib, fs}
1164
1165def release(-A: Data, r: Runner<A>, g: Res.Grant) -> Runner<A>:
1166  Runner{j, s, p, c, ib, fs} = r
1167  release.got(A, Res.release(p, g), j, s, c, ib, fs)
1168
1169def claim.held(-A: Data, y: Ran(A), g: Res.Grant, next: Runner<A> -> IO(Claimed(A))) -> IO(Claimed(A)):
1170  match y:
1171    case (r, Fail{e}):
1172      IO.pure(Claimed(A), (release(A, r, g), 0n, Fail{e}))
1173    case (r, Done{u}):
1174      next(release(A, r, g))
1175
1176def claim.tag(-A: Data, +id: Nat, o: Retry.Outcome) -> IO(Msg<A>):
1177  IO.pure(Msg<A>, Ended{id, o})
1178
1179def trip.if(~A: Data, ~penc: A -> Bytes.Bytes, same: Bool, r: Runner<A>, +key: String, st: Retry.State) -> IO(Ran(A)):
1180  match same:
1181    case True{}:
1182      IO.pure(Ran(A), (r, Done{Unit{}}))
1183    case False{}:
1184      commit(~A, ~penc, r, Break{key, st})
1185
1186# Appends a Break when the target's breaker left old, so that a reopen restores it.
1187def trip(~A: Data, ~penc: A -> Bytes.Bytes, r: Runner<A>, +key: String, +old: Retry.State, br: Retry.Breaker) -> IO(Ran(A)):
1188  +st = brk.state(br, old)
1189  trip.if(~A, ~penc, brk.same(old, st), r, key, st)
1190
1191def claim.go(~A: Data, ~penc: A -> Bytes.Bytes, ~work: A -> IO(Retry.Outcome), +now: Nat, gate: Retry.Gate, +br: Retry.Breaker, b: Retry.Budget, +key: String,
1192    r: Runner<A>, +id: Nat, d: Nat, +x: A, g: Res.Grant, next: Runner<A> -> IO(Claimed(A))) -> IO(Claimed(A)):
1193  match gate:
1194    case Retry.GateGo{}:
1195      Runner{j, s, p, c, +ib, fs} = r
1196      do IO<Claimed(A)>:
1197        u : Chan(Msg<A>) <- IO.fork.go(Msg<A>, IO.bind(Retry.Outcome, Msg<A>, work(x), o => claim.tag(A, id, o)), ib)
1198        next(Runner{j, s, p, c, ib, Con{Flight{Q.Ticket{id, d, x}, g, b, key}, fs}})
1199    case Retry.GateNo{why}:
1200      do IO<Claimed(A)>:
1201        y : Ran(A) <- commit(~A, ~penc, r, held(A, why, br, id, now))
1202        claim.held(A, y, g, next)
1203
1204def claim.tripped(~A: Data, ~penc: A -> Bytes.Bytes, ~work: A -> IO(Retry.Outcome), +now: Nat, y: Ran(A), gate: Retry.Gate, +br: Retry.Breaker, b: Retry.Budget, +key: String,
1205    +id: Nat, d: Nat, +x: A, g: Res.Grant, next: Runner<A> -> IO(Claimed(A))) -> IO(Claimed(A)):
1206  match y:
1207    case (r, Fail{e}):
1208      IO.pure(Claimed(A), (release(A, r, g), 0n, Fail{e}))
1209    case (r, Done{u}):
1210      claim.go(~A, ~penc, ~work, now, gate, br, b, key, r, id, d, x, g, next)
1211
1212# A change to the breaker is durable before the attempt starts.
1213def claim.gate(~A: Data, ~penc: A -> Bytes.Bytes, ~work: A -> IO(Retry.Outcome), +now: Nat, a: Retry.Breaker & Retry.Budget & Retry.Gate, +key: String, +old: Retry.State,
1214    r: Runner<A>, +id: Nat, d: Nat, +x: A, g: Res.Grant, next: Runner<A> -> IO(Claimed(A))) -> IO(Claimed(A)):
1215  (+br, b, gate) = a
1216  do IO<Claimed(A)>:
1217    y : Ran(A) <- trip(~A, ~penc, r, key, old, br)
1218    claim.tripped(~A, ~penc, ~work, now, y, gate, br, b, key, id, d, x, g, next)
1219
1220# The selected ticket asks its target's breaker and its own budget for an attempt.
1221def claim.admit(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), +now: Nat, r: Runner<A>, t: Q.Ticket<A>, g: Res.Grant,
1222    next: Runner<A> -> IO(Claimed(A))) -> IO(Claimed(A)):
1223  Runner{j, +s, p, +c, ib, fs} = r
1224  Config{pol, circ, idle, every} = c
1225  Q.Ticket{+id, d, +x} = t
1226  +key = target(x)
1227  +old = brk.get(A, s, key)
1228  claim.gate(~A, ~penc, ~work, now, Retry.admit(Retry.BreakerOn{circ, old}, budget(pol, tries.get(tries(A, s), id)), now), key, old,
1229    Runner{j, s, p, c, ib, fs}, id, d, x, g, next)
1230
1231def claim.selected(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), +now: Nat, y: Ran(A),
1232    t: Q.Ticket<A>, g: Res.Grant, next: Runner<A> -> IO(Claimed(A))) -> IO(Claimed(A)):
1233  match y:
1234    case (r, Fail{e}):
1235      IO.pure(Claimed(A), (release(A, r, g), 0n, Fail{e}))
1236    case (r, Done{u}):
1237      claim.admit(~A, ~penc, ~target, ~work, now, r, t, g, next)
1238
1239def claim.pick(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), +left: Nat, +now: Nat, k: Pick<A>, j: Log, s: State<A>,
1240    c: Config, ib: Chan(Msg<A>), fs: List<&1, Flight<A>>, next: Runner<A> -> IO(Claimed(A))) -> IO(Claimed(A)):
1241  match k:
1242    case Idle{p}:
1243      IO.pure(Claimed(A), (Runner{j, s, p, c, ib, fs}, Nat.add(1n, left), Done{Unit{}}))
1244    case Picked{p, t, g}:
1245      do IO<Claimed(A)>:
1246        y : Ran(A) <- commit(~A, ~penc, Runner{j, s, p, c, ib, fs}, Select{now})
1247        claim.selected(~A, ~penc, ~target, ~work, now, y, t, g, next)
1248
1249# Starts an attempt for each due ticket while the pool has a free unit; each attempt sends its outcome on the inbox.
1250# fuel bounds the tickets taken, and the fuel left comes back.
1251def claim(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), fuel: Nat, +now: Nat, r: Runner<A>) -> IO(Claimed(A)):
1252  match fuel:
1253    case 0n:
1254      IO.pure(Claimed(A), (r, 0n, Done{Unit{}}))
1255    case 1n+n:
1256      Runner{j, +s, p, c, ib, fs} = r
1257      +m = n
1258      claim.pick(~A, ~penc, ~target, ~work, m, now, pick(~A, p, s, now), j, s, c, ib, fs, (r2 => claim(~A, ~penc, ~target, ~work, m, now, r2)))
1259
1260def settle.done(-A: Data, y: Ran(A), g: Res.Grant, err: Out(Unit), next: Runner<A> -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1261  (r, res) = y
1262  next(release(A, r, g), first(err, res))
1263
1264def settle.br(~A: Data, ~penc: A -> Bytes.Bytes, +op: Op<A>, y: Ran(A), g: Res.Grant, err: Out(Unit),
1265    next: Runner<A> -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1266  match y:
1267    case (r, Fail{e}):
1268      next(release(A, r, g), first(err, Fail{e}))
1269    case (r, Done{u}):
1270      do IO<Runner<A> & Out(Bool)>:
1271        z : Ran(A) <- commit(~A, ~penc, r, op)
1272        settle.done(A, z, g, err, next)
1273
1274# Tells the target's breaker, appends the outcome's op, and returns the attempt's unit to the pool.
1275# The op of a cancelled ticket changes no state: the queue no longer holds it.
1276def settle.op(~A: Data, ~penc: A -> Bytes.Bytes, +o: Retry.Outcome, b: Retry.Budget, +id: Nat, +key: String, +now: Nat, +rnd: Nat, r: Runner<A>, g: Res.Grant,
1277    err: Out(Unit), next: Runner<A> -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1278  Runner{j, +s, p, +c, ib, fs} = r
1279  Config{pol, circ, idle, every} = c
1280  +old = brk.get(A, s, key)
1281  do IO<Runner<A> & Out(Bool)>:
1282    y : Ran(A) <- trip(~A, ~penc, Runner{j, s, p, c, ib, fs}, key, old, Retry.Breaker.done(Retry.BreakerOn{circ, old}, now, Retry.failed(o)))
1283    settle.br(~A, ~penc, after(A, o, pol, b, id, fails(tries.get(tries(A, s), id)), now, rnd), y, g, err, next)
1284
1285def random(r: Out(U32)) -> Nat:
1286  match r:
1287    case Done{x}:
1288      U32.to_nat(x)
1289    case Fail{e}:
1290      0n
1291
1292def take.keep(-A: Data, m: Maybe<&1, Flight<A>>, xs: List<&1, Flight<A>>) -> List<&1, Flight<A>>:
1293  match m:
1294    case None{}:
1295      xs
1296    case Some{f}:
1297      Con{f, xs}
1298
1299def take.at(-A: Data, eq: Bool, f: Flight<A>, r: Maybe<&1, Flight<A>> & List<&1, Flight<A>>) -> Maybe<&1, Flight<A>> & List<&1, Flight<A>>:
1300  match eq:
1301    case True{}:
1302      (m, xs) = r
1303      (Some{f}, take.keep(A, m, xs))
1304    case False{}:
1305      (m, xs) = r
1306      (m, Con{f, xs})
1307
1308# The flight of ticket id, and the other flights.
1309def take(-A: Data, fs: List<&1, Flight<A>>, +id: Nat) -> Maybe<&1, Flight<A>> & List<&1, Flight<A>>:
1310  match fs:
1311    case Nil{}:
1312      (None{}, Nil{})
1313    case Con{Flight{Q.Ticket{+i, d, x}, g, b, k}, rest}:
1314      take.at(A, Nat.is_eq(i, id), Flight{Q.Ticket{i, d, x}, g, b, k}, take(A, rest, id))
1315
1316def settle.flight(~A: Data, ~penc: A -> Bytes.Bytes, mf: Maybe<&1, Flight<A>>, +o: Retry.Outcome, +now: Nat, +rnd: Nat, r: Runner<A>, err: Out(Unit),
1317    next: Runner<A> -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1318  match mf:
1319    case None{}:
1320      next(r, err)
1321    case Some{Flight{Q.Ticket{id, d, x}, g, b, key}}:
1322      settle.op(~A, ~penc, o, b, id, key, now, rnd, r, g, err, next)
1323
1324def settle.take(~A: Data, ~penc: A -> Bytes.Bytes, t: Maybe<&1, Flight<A>> & List<&1, Flight<A>>, +o: Retry.Outcome, +now: Nat, +rnd: Nat,
1325    j: Log, s: State<A>, p: Res.Pool, c: Config, ib: Chan(Msg<A>), err: Out(Unit),
1326    next: Runner<A> -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1327  (mf, fs) = t
1328  settle.flight(~A, ~penc, mf, o, now, rnd, Runner{j, s, p, c, ib, fs}, err, next)
1329
1330# Settles the flight of ticket id with outcome o.
1331def settle(~A: Data, ~penc: A -> Bytes.Bytes, +id: Nat, +o: Retry.Outcome, +now: Nat, +rnd: Nat, r: Runner<A>, err: Out(Unit),
1332    next: Runner<A> -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1333  Runner{j, s, p, c, ib, fs} = r
1334  settle.take(~A, ~penc, take(A, fs, id), o, now, rnd, j, s, p, c, ib, err, next)
1335
1336# Sends the failure to the asker, and keeps it as the round's error.
1337def asked.failed(-A: Data, -X: Type, +rep: Chan(Out(X)), r: Runner<A>, +c: U32, +m: String, err: Out(Unit),
1338    next: Runner<A> -> Nat -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1339  do IO<Runner<A> & Out(Bool)>:
1340    x : Result<&1, &1, Out(X), Unit> <- Chan.send(Out(X), rep, Fail{(c, m)})
1341    next(r, 0n, first(err, Fail{(c, m)}))
1342
1343def asked.fail(-A: Data, -X: Type, +rep: Chan(Out(X)), r: Runner<A>, e: U32 & String, err: Out(Unit),
1344    next: Runner<A> -> Nat -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1345  (c, m) = e
1346  asked.failed(A, X, rep, r, c, m, err, next)
1347
1348def added(-A: Data, +rep: Chan(Out(Nat)), y: Runner<A> & Out(Nat), err: Out(Unit),
1349    next: Runner<A> -> Nat -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1350  match y:
1351    case (r, Done{+i}):
1352      do IO<Runner<A> & Out(Bool)>:
1353        x : Result<&1, &1, Out(Nat), Unit> <- Chan.send(Out(Nat), rep, Done{i})
1354        next(r, 1n, err)
1355    case (r, Fail{e}):
1356      asked.fail(A, Nat, rep, r, e, err, next)
1357
1358def dropped(-A: Data, +rep: Chan(Out(Unit)), y: Ran(A), err: Out(Unit),
1359    next: Runner<A> -> Nat -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1360  match y:
1361    case (r, Done{u}):
1362      do IO<Runner<A> & Out(Bool)>:
1363        x : Result<&1, &1, Out(Unit), Unit> <- Chan.send(Out(Unit), rep, Done{Unit{}})
1364        next(r, 0n, err)
1365    case (r, Fail{e}):
1366      asked.fail(A, Unit, rep, r, e, err, next)
1367
1368# Settles an ended attempt, or appends an ask's op and answers it. next gets the claim fuel the message adds: 1 for an enqueue.
1369def handle(~A: Data, ~penc: A -> Bytes.Bytes, m: Msg<A>, +now: Nat, +rnd: Nat, r: Runner<A>, err: Out(Unit),
1370    next: Runner<A> -> Nat -> Out(Unit) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1371  match m:
1372    case Ended{+id, +o}:
1373      settle(~A, ~penc, id, o, now, rnd, r, err, (r2 => e2 => next(r2, 0n, e2)))
1374    case Add{+d, x, +rep}:
1375      IO.bind(Runner<A> & Out(Nat), Runner<A> & Out(Bool), enqueue(~A, ~penc, r, d, x), y => added(A, rep, y, err, next))
1376    case Drop{+i, +rep}:
1377      IO.bind(Ran(A), Runner<A> & Out(Bool), cancel(~A, ~penc, r, i), y => dropped(A, rep, y, err, next))
1378
1379def merged(-A: Data, e: Out(Unit), k: Claimed(A)) -> Claimed(A):
1380  (r, n, err) = k
1381  (r, n, first(e, err))
1382
1383def empty.heap(-A: Data, h: H.Heap<Q.Ticket<A>>) -> Bool:
1384  match h:
1385    case H.HLeaf{}:
1386      True{}
1387    case H.HNode{n, t, l, r}:
1388      False{}
1389
1390def empty.list(-A: Data, xs: List<&2, Q.Ticket<A>>) -> Bool:
1391  match xs:
1392    case Nil{}:
1393      True{}
1394    case Con{t, rest}:
1395      False{}
1396
1397# No ticket is pending or running. Dead tickets wait for a Revive, so they do not count.
1398def idle(-A: Data, s: State<A>) -> Bool:
1399  State{Q.State{n, h, run}, ts, ds, bs} = s
1400  Bool.and(empty.heap(A, h), empty.list(A, run))
1401
1402def pending(-A: Data, s: State<A>) -> Nat:
1403  State{Q.State{n, h, run}, ts, ds, bs} = s
1404  H.Heap.size(Q.Ticket<A>, h)
1405
1406# The flights back, and whether none runs.
1407def flights.none(-A: Data, fs: List<&1, Flight<A>>) -> List<&1, Flight<A>> & Bool:
1408  match fs:
1409    case Nil{}:
1410      (Nil{}, True{})
1411    case Con{f, rest}:
1412      (Con{f, rest}, False{})
1413
1414# ---- compaction
1415
1416# Kept: compaction failed before the rename, and the old journal stands.
1417# Lost: the rename happened, but the new journal did not open. Moved: the journal at path is the snapshot.
1418type Swap is Type:
1419  Kept{err: U32 & String}
1420  Lost{err: U32 & String}
1421  Moved{journal: J.Journal}
1422
1423def swap.reopened(x: Out(J.Journal & Unit)) -> Swap:
1424  match x:
1425    case Fail{e}:
1426      Lost{e}
1427    case Done{(j, u)}:
1428      Moved{j}
1429
1430# The reopen fsyncs the directory, so the rename is durable before the next append.
1431def swap.renamed(+path: String, +limit: U32, x: Out(Unit)) -> IO(Swap):
1432  match x:
1433    case Fail{e}:
1434      IO.pure(Swap, Kept{e})
1435    case Done{u}:
1436      do IO<Swap>:
1437        y : Out(J.Journal & Unit) <- J.open(~Unit, ~(a => b => a), path, limit, limit, Unit{})
1438        return swap.reopened(y)
1439
1440def swap.written(+path: String, +tmp: String, +limit: U32, x: J.Journal & Out(Unit)) -> IO(Swap):
1441  match x:
1442    case (t, Fail{e}):
1443      do IO<Swap>:
1444        J.close(t)
1445        return Kept{e}
1446    case (t, Done{u}):
1447      do IO<Swap>:
1448        J.close(t)
1449        y : Out(Unit) <- Files.rename(tmp, path)
1450        swap.renamed(path, limit, y)
1451
1452def swap.opened(+path: String, +tmp: String, +limit: U32, x: Out(J.Journal & Unit), snap: Bytes.Bytes) -> IO(Swap):
1453  match x:
1454    case Fail{e}:
1455      IO.pure(Swap, Kept{e})
1456    case Done{(t, u)}:
1457      do IO<Swap>:
1458        y : J.Journal & Out(Unit) <- J.append(t, snap)
1459        swap.written(path, tmp, limit, y)
1460
1461# Writes snap as the only record of path.compact, fsyncs it, and renames it over path.
1462def swap(+path: String, +limit: U32, snap: Bytes.Bytes) -> IO(Swap):
1463  +tmp = path ++ ".compact"
1464  do IO<Swap>:
1465    gone : Out(Unit) <- Files.remove(tmp)
1466    x : Out(J.Journal & Unit) <- J.open(~Unit, ~(a => b => a), tmp, limit, limit, Unit{})
1467    swap.opened(path, tmp, limit, x, snap)
1468
1469def log.stop(j: J.Journal) -> J.Journal:
1470  J.Journal{file, max, end, ok} = j
1471  J.Journal{file, max, end, False{}}
1472
1473def compact.moved(x: Swap, j: J.Journal, +max: U32, path: String, +limit: U32, +base: U32) -> IO(Log & Out(Unit)):
1474  match x:
1475    case Kept{e}:
1476      IO.pure(Log & Out(Unit), (Log{j, path, limit, base}, Fail{e}))
1477    case Lost{e}:
1478      IO.pure(Log & Out(Unit), (Log{log.stop(j), path, limit, base}, Fail{e}))
1479    case Moved{k}:
1480      do IO<Log & Out(Unit)>:
1481        J.close(j)
1482        return (log.of(k, max, path, limit), Done{Unit{}})
1483
1484def compact.if(~A: Data, ~penc: A -> Bytes.Bytes, ok: Bool, j: J.Journal, +max: U32, +path: String, +limit: U32, +base: U32, s: State<A>) -> IO(Log & Out(Unit)):
1485  match ok:
1486    case False{}:
1487      IO.pure(Log & Out(Unit), (Log{j, path, limit, base}, Fail{(5, "runner: an append failed; reopen the runner")}))
1488    case True{}:
1489      do IO<Log & Out(Unit)>:
1490        x : Swap <- swap(path, limit, encode.snap(~A, ~penc, s))
1491        compact.moved(x, j, max, path, limit, base)
1492
1493def compact.done(-A: Data, x: Log & Out(Unit), s: State<A>, p: Res.Pool, c: Config, ib: Chan(Msg<A>), fs: List<&1, Flight<A>>) -> Ran(A):
1494  (l, o) = x
1495  (Runner{l, s, p, c, ib, fs}, o)
1496
1497# Writes the state as one Snap record into a new journal, fsyncs it, and renames it over the old one.
1498# A crash leaves one of the two journals, and both replay to this state. After a failure the old
1499# journal stands; when the failure came after the rename, appends stop until the runner is reopened.
1500def compact(~A: Data, ~penc: A -> Bytes.Bytes, r: Runner<A>) -> IO(Ran(A)):
1501  Runner{Log{j, path, limit, base}, +s, p, c, ib, fs} = r
1502  J.Journal{file, +max, end, +ok} = j
1503  do IO<Ran(A)>:
1504    x : Log & Out(Unit) <- compact.if(~A, ~penc, ok, J.Journal{file, max, end, ok}, max, path, limit, base, s)
1505    return compact.done(A, x, s, p, c, ib, fs)
1506
1507def tick.ran(e: Out(Unit), b: Bool) -> Out(Bool):
1508  match e:
1509    case Fail{x}:
1510      Fail{x}
1511    case Done{u}:
1512      Done{b}
1513
1514def tick.compacted(-A: Data, +b: Bool, y: Ran(A)) -> Runner<A> & Out(Bool):
1515  (r, e) = y
1516  (r, tick.ran(e, b))
1517
1518def tick.due(~A: Data, ~penc: A -> Bytes.Bytes, due: Bool, +b: Bool, r: Runner<A>) -> IO(Runner<A> & Out(Bool)):
1519  match due:
1520    case False{}:
1521      IO.pure(Runner<A> & Out(Bool), (r, Done{b}))
1522    case True{}:
1523      do IO<Runner<A> & Out(Bool)>:
1524        y : Ran(A) <- compact(~A, ~penc, r)
1525        return tick.compacted(A, b, y)
1526
1527def tick.size(~A: Data, ~penc: A -> Bytes.Bytes, r: Runner<A>, +b: Bool) -> IO(Runner<A> & Out(Bool)):
1528  Runner{Log{J.Journal{file, max, +end, ok}, path, limit, +base}, s, p, +c, ib, fs} = r
1529  Config{pol, circ, idle, +every} = c
1530  tick.due(~A, ~penc, Bool.and(Bool.not(U32.is_eq(every, 0)), U32.is_gt((end - base : U32), every)), b,
1531    Runner{Log{J.Journal{file, max, end, ok}, path, limit, base}, s, p, c, ib, fs})
1532
1533# Compacts once the journal grew past Config.compact octets since open or the last compaction.
1534def tick.grown(~A: Data, ~penc: A -> Bytes.Bytes, t: Runner<A> & Out(Bool)) -> IO(Runner<A> & Out(Bool)):
1535  match t:
1536    case (r, Fail{e}):
1537      IO.pure(Runner<A> & Out(Bool), (r, Fail{e}))
1538    case (r, Done{b}):
1539      tick.size(~A, ~penc, r, b)
1540
1541def tick.polled(-A: Data, x: Poll<&1, &1, Maybe<&1, Msg<A>>, Unit>) -> Maybe<&1, Msg<A>>:
1542  match x:
1543    case Ready{m}:
1544      m
1545    case Wait{u}:
1546      None{}
1547
1548def tick.wait(-A: Data, t: List<&1, Flight<A>> & Bool, j: Log, s: State<A>, p: Res.Pool, c: Config, +ib: Chan(Msg<A>)) ->
1549    IO(Runner<A> & Maybe<&1, Msg<A>>):
1550  (fs, none) = t
1551  match none:
1552    case False{}:
1553      do IO<Runner<A> & Maybe<&1, Msg<A>>>:
1554        m : Maybe<&1, Msg<A>> <- Chan.recv(Msg<A>, ib)
1555        return (Runner{j, s, p, c, ib, fs}, m)
1556    case True{}:
1557      do IO<Runner<A> & Maybe<&1, Msg<A>>>:
1558        x : Poll<&1, &1, Maybe<&1, Msg<A>>, Unit> <- Chan.try_recv(Msg<A>, ib, 0)
1559        return (Runner{j, s, p, c, ib, fs}, tick.polled(A, x))
1560
1561# The next message. While an attempt runs, it waits for one; when none runs, it takes one only when the inbox holds one.
1562def tick.next(-A: Data, r: Runner<A>) -> IO(Runner<A> & Maybe<&1, Msg<A>>):
1563  Runner{j, s, p, c, ib, fs} = r
1564  tick.wait(A, flights.none(A, fs), j, s, p, c, ib)
1565
1566# Handles the message, then claims due tickets into free units with the claim fuel left. None ends the round.
1567def tick.got(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), x: Runner<A> & Maybe<&1, Msg<A>>, +ran: Bool, +left: Nat,
1568    err: Out(Unit), next: Claimed(A) -> IO(Runner<A> & Out(Bool))) -> IO(Runner<A> & Out(Bool)):
1569  (r, m) = x
1570  match m:
1571    case None{}:
1572      IO.pure(Runner<A> & Out(Bool), (r, tick.ran(err, ran)))
1573    case Some{msg}:
1574      do IO<Runner<A> & Out(Bool)>:
1575        +now : Nat <- clock()
1576        rnd : Out(U32) <- IO.random_u32()
1577        handle(~A, ~penc, msg, now, random(rnd), r, err, (r2 => more => e2 =>
1578          IO.bind(Claimed(A), Runner<A> & Out(Bool), claim(~A, ~penc, ~target, ~work, Nat.add(left, more), now, r2), k2 => next(merged(A, e2, k2)))))
1579
1580# Handles messages until no attempt runs and the inbox is empty. fuel bounds the messages; attempts that still run
1581# when it ends stay in the runner, and the next tick settles them.
1582def tick.run(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), fuel: Nat, +ran: Bool, k: Claimed(A)) ->
1583    IO(Runner<A> & Out(Bool)):
1584  match fuel:
1585    case 0n:
1586      (r, left, err) = k
1587      IO.pure(Runner<A> & Out(Bool), (r, tick.ran(err, ran)))
1588    case 1n+n:
1589      (r, +left, err) = k
1590      do IO<Runner<A> & Out(Bool)>:
1591        x : Runner<A> & Maybe<&1, Msg<A>> <- tick.next(A, r)
1592        tick.got(~A, ~penc, ~target, ~work, x, ran, left, err, (k2 => tick.run(~A, ~penc, ~target, ~work, n, True{}, k2)))
1593
1594# Fuel for each pending ticket, each attempt that may already run, and the last look at the inbox.
1595def tick.at(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), +now: Nat, r: Runner<A>) -> IO(Runner<A> & Out(Bool)):
1596  Runner{j, +s, +p, c, ib, fs} = r
1597  +fuel = Nat.add(2n, Nat.add(pending(A, s), Res.capacity(p)))
1598  do IO<Runner<A> & Out(Bool)>:
1599    k : Claimed(A) <- claim(~A, ~penc, ~target, ~work, fuel, now, Runner{j, s, p, c, ib, fs})
1600    tick.run(~A, ~penc, ~target, ~work, fuel, False{}, k)
1601
1602# One round: start an attempt for each due ticket the pool admits. Then read the inbox: as each attempt finishes, record its outcome,
1603# return its unit, and start the next due ticket in that unit; append and answer each ask from another fiber.
1604# The round ends when no attempt runs and the inbox is empty. Then compact the journal when it grew past Config.compact.
1605# Done{True} when an attempt ran or an ask was answered. work runs on its own; target names the breaker that guards it.
1606def tick(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), r: Runner<A>) -> IO(Runner<A> & Out(Bool)):
1607  do IO<Runner<A> & Out(Bool)>:
1608    now : Nat <- clock()
1609    t : Runner<A> & Out(Bool) <- tick.at(~A, ~penc, ~target, ~work, now, r)
1610    tick.grown(~A, ~penc, t)
1611
1612def finished.of(-A: Data, +quiet: Bool, t: List<&1, Flight<A>> & Bool, j: Log, s: State<A>, p: Res.Pool, c: Config, ib: Chan(Msg<A>)) ->
1613    Runner<A> & Bool:
1614  (fs, none) = t
1615  (Runner{j, s, p, c, ib, fs}, Bool.and(quiet, none))
1616
1617# The runner back, and whether no ticket is pending or running and no attempt runs.
1618def finished(-A: Data, r: Runner<A>) -> Runner<A> & Bool:
1619  Runner{j, +s, p, c, ib, fs} = r
1620  finished.of(A, idle(A, s), flights.none(A, fs), j, s, p, c, ib)
1621
1622def drain.handled(-A: Data, t: Runner<A> & Out(Bool), next: Runner<A> -> IO(Ran(A))) -> IO(Ran(A)):
1623  match t:
1624    case (r, Fail{e}):
1625      IO.pure(Ran(A), (r, Fail{e}))
1626    case (r, Done{b}):
1627      next(r)
1628
1629def drain.woke(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), +idle: U32,
1630    x: Poll<&1, &1, Maybe<&1, Msg<A>>, Unit>, r: Runner<A>, next: Runner<A> -> IO(Ran(A))) -> IO(Ran(A)):
1631  match x:
1632    case Ready{Some{m}}:
1633      do IO<Ran(A)>:
1634        t : Runner<A> & Out(Bool) <- tick.got(~A, ~penc, ~target, ~work, (r, Some{m}), True{}, 0n, Done{Unit{}},
1635          (k => tick.run(~A, ~penc, ~target, ~work, 0n, True{}, k)))
1636        drain.handled(A, t, next)
1637    case Ready{None{}}:
1638      do IO<Ran(A)>:
1639        IO.sleep(idle)
1640        next(r)
1641    case Wait{u}:
1642      next(r)
1643
1644def drain.wait(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), +idle: U32, r: Runner<A>,
1645    next: Runner<A> -> IO(Ran(A))) -> IO(Ran(A)):
1646  Runner{j, s, p, c, +ib, fs} = r
1647  do IO<Ran(A)>:
1648    x : Poll<&1, &1, Maybe<&1, Msg<A>>, Unit> <- Chan.try_recv(Msg<A>, ib, idle)
1649    drain.woke(~A, ~penc, ~target, ~work, idle, x, Runner{j, s, p, c, ib, fs}, next)
1650
1651def drain.ticked(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), +idle: U32,
1652    t: Runner<A> & Out(Bool), next: Runner<A> -> IO(Ran(A))) -> IO(Ran(A)):
1653  match t:
1654    case (r, Fail{e}):
1655      IO.pure(Ran(A), (r, Fail{e}))
1656    case (r, Done{True{}}):
1657      next(r)
1658    case (r, Done{False{}}):
1659      drain.wait(~A, ~penc, ~target, ~work, idle, r, next)
1660
1661def drain.if(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), done: Bool, r: Runner<A>, next: Runner<A> -> IO(Ran(A))) -> IO(Ran(A)):
1662  match done:
1663    case True{}:
1664      IO.pure(Ran(A), (r, Done{Unit{}}))
1665    case False{}:
1666      Runner{j, s, p, +c, ib, fs} = r
1667      Config{pol, circ, +idle, every} = c
1668      do IO<Ran(A)>:
1669        t : Runner<A> & Out(Bool) <- tick(~A, ~penc, ~target, ~work, Runner{j, s, p, c, ib, fs})
1670        drain.ticked(~A, ~penc, ~target, ~work, idle, t, next)
1671
1672def drain.at(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), x: Runner<A> & Bool, next: Runner<A> -> IO(Ran(A))) -> IO(Ran(A)):
1673  (r, done) = x
1674  drain.if(~A, ~penc, ~target, ~work, done, r, next)
1675
1676def drain.end(-A: Data, x: Runner<A> & Bool) -> Ran(A):
1677  (r, done) = x
1678  (r, Bool.pick(Out(Unit), done, Done{Unit{}}, Fail{(62, "runner: drain ran out of rounds")}))
1679
1680# Ticks until no ticket is pending or running and no attempt runs. After a round that did nothing, it waits up to idle ms
1681# for a message, and handles one that arrives at once.
1682# Fails when fuel rounds leave work.
1683def drain(~A: Data, ~penc: A -> Bytes.Bytes, ~target: A -> String, ~work: A -> IO(Retry.Outcome), fuel: Nat, r: Runner<A>) -> IO(Ran(A)):
1684  match fuel:
1685    case 0n:
1686      IO.pure(Ran(A), drain.end(A, finished(A, r)))
1687    case 1n+n:
1688      drain.at(~A, ~penc, ~target, ~work, finished(A, r), (r2 => drain(~A, ~penc, ~target, ~work, n, r2)))
1689
1690def orphans.next(-A: Data, y: Ran(A), err: Out(Unit), next: Runner<A> -> Out(Unit) -> IO(Ran(A))) -> IO(Ran(A)):
1691  (r, e) = y
1692  next(r, first(err, e))
1693
1694# A running ticket at open lost its attempt in a crash: it is requeued at now, as a failed attempt.
1695def orphans(~A: Data, ~penc: A -> Bytes.Bytes, ts: List<&2, Q.Ticket<A>>, +now: Nat, r: Runner<A>, err: Out(Unit)) -> IO(Ran(A)):
1696  match ts:
1697    case Nil{}:
1698      IO.pure(Ran(A), (r, err))
1699    case Con{Q.Ticket{id, d, x}, rest}:
1700      do IO<Ran(A)>:
1701        y : Ran(A) <- commit(~A, ~penc, r, Requeue{id, now})
1702        orphans.next(A, y, err, (r2 => e2 => orphans(~A, ~penc, rest, now, r2, e2)))
1703
1704def close.answer(-A: Data, m: Msg<A>) -> IO(Unit):
1705  match m:
1706    case Ended{id, o}:
1707      IO.pure(Unit, Unit{})
1708    case Add{d, x, rep}:
1709      do IO<Unit>:
1710        y : Result<&1, &1, Out(Nat), Unit> <- Chan.send(Out(Nat), rep, Fail{(32, "runner: the runner closed")})
1711        return Unit{}
1712    case Drop{i, rep}:
1713      do IO<Unit>:
1714        y : Result<&1, &1, Out(Unit), Unit> <- Chan.send(Out(Unit), rep, Fail{(32, "runner: the runner closed")})
1715        return Unit{}
1716
1717def close.polled(-A: Data, x: Poll<&1, &1, Maybe<&1, Msg<A>>, Unit>, next: Unit -> IO(Unit)) -> IO(Unit):
1718  match x:
1719    case Ready{Some{m}}:
1720      do IO<Unit>:
1721        close.answer(A, m)
1722        next(Unit{})
1723    case Ready{None{}}:
1724      IO.pure(Unit, Unit{})
1725    case Wait{u}:
1726      IO.pure(Unit, Unit{})
1727
1728# Answers each ask left in the closed inbox with a failure. fuel bounds the messages it reads.
1729def close.drain(-A: Data, fuel: Nat, +ib: Chan(Msg<A>)) -> IO(Unit):
1730  match fuel:
1731    case 0n:
1732      IO.pure(Unit, Unit{})
1733    case 1n+n:
1734      do IO<Unit>:
1735        x : Poll<&1, &1, Maybe<&1, Msg<A>>, Unit> <- Chan.try_recv(Msg<A>, ib, 0)
1736        close.polled(A, x, (u => close.drain(A, n, ib)))
1737
1738# Closes the inbox and the journal. Each ask still in the inbox gets a failure, and no op is appended for it.
1739def close(-A: Data, r: Runner<A>) -> IO(Unit):
1740  Runner{j, s, +p, c, +ib, fs} = r
1741  do IO<Unit>:
1742    Chan.close(Msg<A>, ib)
1743    close.drain(A, Nat.add(2n, Res.capacity(p)), ib)
1744    log.close(j)
1745
1746def open.done(-A: Data, y: Ran(A)) -> IO(Out(Runner<A>)):
1747  match y:
1748    case (r, Fail{e}):
1749      do IO<Out(Runner<A>)>:
1750        close(A, r)
1751        return Fail{e}
1752    case (r, Done{u}):
1753      IO.pure(Out(Runner<A>), Done{r})
1754
1755def open.got(~A: Data, ~penc: A -> Bytes.Bytes, x: Out(J.Journal & Maybe<&2, State<A>>), +max: U32, path: String, +limit: U32, c: Config, +capacity: Nat) ->
1756    IO(Out(Runner<A>)):
1757  match x:
1758    case Fail{e}:
1759      IO.pure(Out(Runner<A>), Fail{e})
1760    case Done{(j, None{})}:
1761      do IO<Out(Runner<A>)>:
1762        J.close(j)
1763        return Fail{(22, "runner: a journal record is not a runner record")}
1764    case Done{(j, Some{+s})}:
1765      do IO<Out(Runner<A>)>:
1766        now : Nat <- clock()
1767        ib : Chan(Msg<A>) <- Chan.new(Msg<A>, (U32.from_nat(capacity) + 1 : U32))
1768        y : Ran(A) <- orphans(~A, ~penc, Q.running(A, queue(A, s)), now, Runner{log.of(j, max, path, limit), calm(A, s), Res.new(0n, capacity), c, ib, Nil{}}, Done{Unit{}})
1769        open.done(A, y)
1770
1771def replay.step(~A: Data, ~pdec: Bytes.Bytes -> Maybe<&2, A>, acc: Maybe<&2, State<A>>, b: Bytes.Bytes) -> Maybe<&2, State<A>>:
1772  load(~A, ~Bytes.Bytes, ~(y => decode.rec(~A, ~pdec, y)), acc, b)
1773
1774# Opens the runner at path: replays its journal into the state, then requeues each ticket that was running.
1775# capacity bounds the attempts that run at once. max caps an op record's octets; limit caps the journal file and a snapshot.
1776# Fails when the journal fails to open, or a committed record is not a snapshot or an op.
1777def open(~A: Data, ~penc: A -> Bytes.Bytes, ~pdec: Bytes.Bytes -> Maybe<&2, A>, +path: String, +max: U32, +limit: U32, c: Config, +capacity: Nat) -> IO(Out(Runner<A>)):
1778  do IO<Out(Runner<A>)>:
1779    x : Out(J.Journal & Maybe<&2, State<A>>) <- J.open(~Maybe<&2, State<A>>, ~(acc => b => replay.step(~A, ~pdec, acc, b)), path, limit, limit, Some{new(A)})
1780    open.got(~A, ~penc, x, max, path, limit, c, capacity)
1781
1782# The runner back, and a copy of its state.
1783def state(-A: Data, r: Runner<A>) -> Runner<A> & State<A>:
1784  Runner{j, +s, p, c, ib, fs} = r
1785  (Runner{j, s, p, c, ib, fs}, s)