@mark1russell7/algebra 0.1.0 → 0.3.0

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.
package/README.md CHANGED
@@ -19,6 +19,8 @@ A machine document has the format `mark1russell7.machine/1`, and `machineSchema`
19
19
  ## The algebra
20
20
 
21
21
  - **Exact values.** `evaluate` and `timerOf` give a duration in the unit of its document, with exact rational arithmetic. Thus 0.2 s × 1023 is 204.6 s. A knob without a value gives an unknown result that names the knob. A knob that nothing sets gives a duration without an end.
22
+ - **No bound has a sign.** A step of the arithmetic can be no bound below. For example, a cap less a timer that nothing sets is −∞. Thus `max(cap − ∞, cap / 2)` is cap / 2, and `min` keeps −∞.
23
+ - **Results without a value.** A finite time over no bound is 0. A result that is no bound below is unknown, because a duration is not negative. No bound less no bound is unknown too.
22
24
  - **Models.** A model is the formula of an implementation. The package has these models:
23
25
  - `linux.retrans-budget`: the retransmission give-up of the kernel (`tcp_model_timeout`). At the defaults it is 924.6 s.
24
26
  - `linux.retrans-step`: how late the give-up comes after its budget, at the real RTO of the path.
@@ -26,8 +28,12 @@ A machine document has the format `mark1russell7.machine/1`, and `machineSchema`
26
28
  - `linux.keepalive-lateness`, `linux.wheel` and `linux.jiffy`: the rounding of the timer wheel at the HZ of the kernel.
27
29
  - `linux.syn-giveup`: the SYN give-up of 6.5 and later, with linear timeouts. At the defaults it is 131 s.
28
30
  - `ioredis.retry-base`: the reconnect delay of ioredis 6, min(2^(times − 1) × 50, 5000) ms.
31
+ - `linux.rto-wait-reverted` and `linux.retrans-step-reverted`: the retransmissions when each one gets an ICMP host or net unreachable. The revert of RFC 6069 (`tcp_ld_RTO_revert`) takes back each doubling, thus each wait is one RTO.
29
32
  - **Detection.** `detection` gives the minimum over the timers that are live in the situation of the connection. With no live timer, the failure is silent at this level. `stackedDetection` adds the timers of the machine below.
30
- - **Manifestations.** A manifestation tells which incoming events a failure lets through. A black hole lets nothing through. The kernel of a frozen process continues to send ACKs, which stop keepalive before it fires.
33
+ - **Manifestations.** A manifestation tells which incoming events a failure lets through. A black hole lets nothing through. The kernel of a frozen process continues to send ACKs, which stop keepalive before it fires. A manifestation can also tell:
34
+ - the events that the failure sends one time (`delivers`), for example the FIN of a process that stopped with SIGKILL. Such an event detects the failure at once (`Detection.delivered`).
35
+ - the errno that replaces ETIMEDOUT at a timeout (`errno`). An ICMP error on an established socket is a soft error, and the timeout gives it (`errnoOf`).
36
+ - the durations that the failure changes, by timer (`replaces`). `timerUnder` gives the bounds of a timer under the failure.
31
37
  - **Recovery.** `recovery` tells when a backoff timer moves a connection again after a stall. The connection moves at the first firing at the end of the stall or after it. A stall of 3.5 s on Linux TCP holds a request for approximately 6.5 s.
32
38
 
33
39
  ## Installation
package/build/index.d.ts CHANGED
@@ -271,6 +271,31 @@ export declare const modelSource: (name: string) => string | undefined;
271
271
  interface Manifestation {
272
272
  readonly name: string;
273
273
  readonly passes: readonly string[];
274
+ /**
275
+ * These are the events that the failure itself sends one time, for example the FIN of a process
276
+ * that stopped with SIGKILL. A delivered event that a transition takes from the state of the connection detects the
277
+ * failure at once.
278
+ */
279
+ readonly delivers?: readonly string[] | undefined;
280
+ /**
281
+ * This errno replaces ETIMEDOUT when one of these timers gives up. Linux keeps an ICMP error on
282
+ * an established socket as a soft error, and the timeout reports it (tcp_write_err). An ICMP
283
+ * counts only when it quotes a segment in the window (tcp_v4_err). A retransmission is in the
284
+ * window. A keepalive probe uses the sequence number before snd_una, thus its ICMP does not count.
285
+ */
286
+ readonly errno?: {
287
+ readonly errno: string;
288
+ readonly timers: readonly string[];
289
+ } | undefined;
290
+ /**
291
+ * These are the durations that the failure changes, by timer. For example, an ICMP host
292
+ * unreachable for each retransmission reverts the backoff of the retransmission timer.
293
+ */
294
+ readonly replaces?: Readonly<Record<string, {
295
+ readonly duration?: Expr;
296
+ readonly lateness?: Expr;
297
+ readonly early?: Expr;
298
+ }>> | undefined;
274
299
  }
275
300
  /** A situation is the activity of the connection when the failure started. */
276
301
  interface Situation {
@@ -300,6 +325,16 @@ interface Detection {
300
325
  readonly timer: string;
301
326
  readonly why: string;
302
327
  }>;
328
+ /**
329
+ * These are the events that the failure delivers and that a transition takes from the state:
330
+ * each detects the failure at once, before any timer. The errno is the errno of the transition,
331
+ * or null for an end of file.
332
+ */
333
+ readonly delivered: ReadonlyArray<{
334
+ readonly event: string;
335
+ readonly to: string;
336
+ readonly errno: string | null;
337
+ }>;
303
338
  }
304
339
  /**
305
340
  * This function gives the detection: the minimum over the detectors that are live in the
@@ -313,6 +348,20 @@ interface Detection {
313
348
  * as the events that the document names.
314
349
  */
315
350
  export declare const detection: (doc: Machine, situation: Situation, manifestation: Manifestation, values: KnobValues) => Detection;
351
+ /**
352
+ * This function gives the bounds of a timer of a machine under a failure: its own bounds, with each
353
+ * duration that the manifestation replaces.
354
+ */
355
+ export declare const timerUnder: (doc: Machine, timer: string, values: KnobValues, manifestation: Manifestation, fired?: number) => TimerBounds;
356
+ /**
357
+ * This function gives the errno of a detection by a timer: the errno of the transition that its
358
+ * event takes from the state. A soft error of the manifestation replaces ETIMEDOUT, but only for
359
+ * the timers whose segments its ICMP quotes in the window.
360
+ */
361
+ export declare const errnoOf: (doc: Machine, state: string, detector: {
362
+ readonly timer: string;
363
+ readonly fires: string;
364
+ }, manifestation: Manifestation) => string | null;
316
365
  /** This function gives the transition that a machine takes from a state on an event, by its document. */
317
366
  export declare const transitionOn: (doc: Machine, state: string, event: string) => TransitionDef | undefined;
318
367
  /**
package/build/index.js CHANGED
@@ -249,6 +249,14 @@ const exact = (n) => ({
249
249
  n
250
250
  });
251
251
  const INFINITE = { kind: "infinite" };
252
+ const NEGATIVE_INFINITE = {
253
+ kind: "infinite",
254
+ negative: true
255
+ };
256
+ /** This function gives the sign of a value that is not unknown: −1, 0 or 1. */
257
+ const signOf = (value) => value.kind === "infinite" ? value.negative === true ? -1 : 1 : value.kind === "exact" ? rationals.cmp(value.n, rationals.ZERO) : 0;
258
+ /** This function gives no bound with a sign. */
259
+ const unboundedOf = (sign) => sign < 0 ? NEGATIVE_INFINITE : INFINITE;
252
260
  const unknown = (why) => ({
253
261
  kind: "unknown",
254
262
  why
@@ -336,7 +344,7 @@ const run = (node, valueOf) => {
336
344
  if (node.op === "knob") return valueOf(node.name);
337
345
  if (node.op === "neg") {
338
346
  const a = run(node.a, valueOf);
339
- return a.kind === "exact" ? exact(rationals.neg(a.n)) : a.kind === "infinite" ? unknown("a negative unbounded time") : a;
347
+ return a.kind === "exact" ? exact(rationals.neg(a.n)) : a.kind === "infinite" ? unboundedOf(-signOf(a)) : a;
340
348
  }
341
349
  if ("args" in node) {
342
350
  const args = node.args.map((arg) => run(arg, valueOf));
@@ -347,7 +355,12 @@ const run = (node, valueOf) => {
347
355
  return a.kind === "exact" ? exact(node.op === "floor" ? rationals.floor(a.n) : rationals.ceil(a.n)) : a;
348
356
  }
349
357
  const [a, b] = args;
350
- if (a.kind === "infinite" || b.kind === "infinite") return node.op === "max" ? INFINITE : a.kind === "infinite" ? b : a;
358
+ if (a.kind === "infinite" || b.kind === "infinite") {
359
+ const above = (x, y) => x.kind === "infinite" ? signOf(x) > 0 || y.kind === "infinite" && signOf(y) < 0 : signOf(y) < 0;
360
+ const larger = above(a, b) ? a : b;
361
+ const smaller = larger === a ? b : a;
362
+ return node.op === "max" ? larger : smaller;
363
+ }
351
364
  if (a.kind !== "exact" || b.kind !== "exact") return unknown("not an amount");
352
365
  const aFirst = rationals.cmp(a.n, b.n) <= 0;
353
366
  if (node.op === "min") return aFirst ? a : b;
@@ -367,11 +380,20 @@ const run = (node, valueOf) => {
367
380
  }[node.op];
368
381
  return exact(op(a.n, b.n));
369
382
  }
370
- const zero = (value) => value.kind === "exact" && value.n.n === 0n;
371
- if (node.op === "+") return INFINITE;
372
- if (node.op === "*") return zero(a) || zero(b) ? unknown("zero times no bound") : INFINITE;
373
- if (node.op === "-") return a.kind === "infinite" && b.kind !== "infinite" ? INFINITE : unknown("no bound less no bound");
374
- return a.kind === "infinite" ? b.kind === "infinite" ? unknown("no bound over no bound") : INFINITE : exact(rationals.ZERO);
383
+ if (node.op === "+" || node.op === "-") {
384
+ const sa = signOf(a);
385
+ const sb = node.op === "-" ? -signOf(b) : signOf(b);
386
+ if (a.kind === "infinite" && b.kind === "infinite" && sa !== sb) return unknown("no bound less no bound");
387
+ return unboundedOf(a.kind === "infinite" ? sa : sb);
388
+ }
389
+ if (node.op === "*") {
390
+ const sign = signOf(a) * signOf(b);
391
+ return sign === 0 ? unknown("zero times no bound") : unboundedOf(sign);
392
+ }
393
+ if (a.kind === "infinite" && b.kind === "infinite") return unknown("no bound over no bound");
394
+ if (b.kind === "infinite") return exact(rationals.ZERO);
395
+ const sign = signOf(a) * signOf(b);
396
+ return sign === 0 ? unknown("no bound over zero") : unboundedOf(sign);
375
397
  };
376
398
  const integer = (value, what) => {
377
399
  if (!rationals.isInteger(value) || value.n < 0n) throw new Error(`${what} is not a whole count: ${rationals.toNumber(value)}`);
@@ -454,6 +476,18 @@ const rtoWait = (fired, min, max, rtt, hz) => {
454
476
  * probe, each rounded up on the wheel at its own level. Linux arms the idle timer, then one probe
455
477
  * interval for each probe without an answer.
456
478
  */
479
+ /**
480
+ * This function gives the lateness of the retransmission give-up after its budget, under an ICMP
481
+ * host or net unreachable for each RTO retransmission. Each ICMP reverts one doubling of the backoff
482
+ * (tcp_ld_RTO_revert in net/ipv4/tcp_ipv4.c at v6.6, RFC 6069). Then each wait after the first RTO
483
+ * firing is one RTO again, thus the give-up comes at most one RTO after the budget. Each firing up
484
+ * to it can fire up to the granularity of its level of the wheel late.
485
+ */
486
+ const retransLatenessReverted = (retries, min, max, rtt, hz) => {
487
+ const base = jiffiesOf(rationals.add(min, rtt), hz);
488
+ const firings = (jiffiesOf(retransBudget(retries, min, max), hz) + base - 1n) / base + 1n;
489
+ return rationals.div(whole(base + firings * granularity(base)), hz);
490
+ };
457
491
  const keepaliveLateness = (idle, interval, probes, hz) => {
458
492
  const late = (time) => whole(granularity(jiffiesOf(time, hz)));
459
493
  return rationals.div(rationals.add(late(idle), rationals.mul(whole(probes), late(interval))), hz);
@@ -490,6 +524,28 @@ const MODELS = {
490
524
  seconds: ([fired, min, max, rtt, hz]) => rationals.div(whole(rtoWait(integer(fired, FIRED), min, max, rtt, hz)), hz),
491
525
  source: "net/ipv4/tcp_timer.c tcp_retransmit_timer and tcp_output.c tcp_schedule_loss_probe at v6.6 (measured by @mark1russell7/harness, 2026-10-12)"
492
526
  },
527
+ "linux.rto-wait-reverted": {
528
+ knobs: [
529
+ null,
530
+ "s",
531
+ "s",
532
+ "s",
533
+ "Hz"
534
+ ],
535
+ seconds: ([, min, , rtt, hz]) => rationals.div(whole(jiffiesOf(rationals.add(min, rtt), hz)), hz),
536
+ source: "net/ipv4/tcp_ipv4.c tcp_v4_err and tcp_ld_RTO_revert at v6.6 (RFC 6069)"
537
+ },
538
+ "linux.retrans-step-reverted": {
539
+ knobs: [
540
+ null,
541
+ "s",
542
+ "s",
543
+ "s",
544
+ "Hz"
545
+ ],
546
+ seconds: ([retries, min, max, rtt, hz]) => retransLatenessReverted(integer(retries, "tcp_retries2"), min, max, rtt, hz),
547
+ source: "net/ipv4/tcp_ipv4.c tcp_ld_RTO_revert and net/ipv4/tcp_timer.c retransmits_timed_out at v6.6 (RFC 6069)"
548
+ },
493
549
  "linux.rto-wait-lateness": {
494
550
  knobs: [
495
551
  null,
@@ -551,7 +607,10 @@ const knobIn = (doc, name, unit, values, fired) => {
551
607
  const value = rationals.fromNumber(given.value);
552
608
  return exact(unit === null ? convertExact(value, given.unit, given.unit) : convertExact(value, given.unit, unit));
553
609
  };
554
- const out = (value, unit) => value.kind === "exact" ? quantity(rationals.toNumber(value.n), unit) : value.kind === "infinite" ? unbounded(unit) : {
610
+ const out = (value, unit) => value.kind === "exact" ? quantity(rationals.toNumber(value.n), unit) : value.kind === "infinite" ? value.negative === true ? {
611
+ unknown: "a negative unbounded time",
612
+ unit
613
+ } : unbounded(unit) : {
555
614
  unknown: value.why,
556
615
  unit
557
616
  };
@@ -773,21 +832,59 @@ const detection = (doc, situation, manifestation, values) => {
773
832
  });
774
833
  continue;
775
834
  }
835
+ const duration = manifestation.replaces?.[timer]?.duration ?? def.duration;
776
836
  detectors.push({
777
837
  timer,
778
838
  fires: def.fires,
779
- duration: evaluate(doc, def.duration, values)
839
+ duration: evaluate(doc, duration, values)
780
840
  });
781
841
  }
782
842
  detectors.sort(soonest);
783
843
  const [earliest] = detectors;
844
+ const finite = earliest !== void 0 && !("unknown" in earliest.duration) && earliest.duration.value !== "infinite";
845
+ const delivered = (manifestation.delivers ?? []).flatMap((event) => {
846
+ const taken = transitionOn(doc, situation.state, event);
847
+ return taken === void 0 ? [] : [{
848
+ event,
849
+ to: taken.to,
850
+ errno: taken.errno ?? null
851
+ }];
852
+ });
784
853
  return {
785
854
  detectors,
786
- first: earliest !== void 0 && !("unknown" in earliest.duration) && earliest.duration.value !== "infinite" ? earliest : null,
855
+ first: finite ? earliest : null,
787
856
  unsettled: detectors.filter((d) => "unknown" in d.duration).map((d) => d.timer),
788
- held
857
+ held,
858
+ delivered
859
+ };
860
+ };
861
+ /**
862
+ * This function gives the bounds of a timer of a machine under a failure: its own bounds, with each
863
+ * duration that the manifestation replaces.
864
+ */
865
+ const timerUnder = (doc, timer, values, manifestation, fired) => {
866
+ const def = doc.timers[timer];
867
+ if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
868
+ const replaced = manifestation.replaces?.[timer];
869
+ const duration = replaced?.duration ?? def.duration;
870
+ const lateness = replaced?.lateness ?? def.lateness;
871
+ const early = replaced?.early ?? def.early;
872
+ return {
873
+ duration: evaluate(doc, duration, values, fired),
874
+ ...lateness !== void 0 ? { lateness: evaluate(doc, lateness, values, fired) } : {},
875
+ ...early !== void 0 ? { early: evaluate(doc, early, values, fired) } : {}
789
876
  };
790
877
  };
878
+ /**
879
+ * This function gives the errno of a detection by a timer: the errno of the transition that its
880
+ * event takes from the state. A soft error of the manifestation replaces ETIMEDOUT, but only for
881
+ * the timers whose segments its ICMP quotes in the window.
882
+ */
883
+ const errnoOf = (doc, state, detector, manifestation) => {
884
+ const errno = transitionOn(doc, state, detector.fires)?.errno ?? null;
885
+ const soft = manifestation.errno;
886
+ return errno === "ETIMEDOUT" && soft !== void 0 && soft.timers.includes(detector.timer) ? soft.errno : errno;
887
+ };
791
888
  /** This function gives the transition that a machine takes from a state on an event, by its document. */
792
889
  const transitionOn = (doc, state, event) => doc.transitions.find((t) => fromStates(doc, t.from).includes(state) && arr(t.on).includes(event));
793
890
  /**
@@ -834,10 +931,11 @@ const stackedDetection = (upper, lower, situation, manifestation, upperValues, l
834
931
  held: [...own.held, ...below.held.map((h) => ({
835
932
  ...h,
836
933
  why: `${h.why}, beneath`
837
- }))]
934
+ }))],
935
+ delivered: below.delivered
838
936
  };
839
937
  };
840
938
  //#endregion
841
- export { FIRED, algebraProblems, arr, detection, evaluate, exprKnobs, fromStates, machineProblems, machineSchema, modelSource, overValues, parseExpr, readsFired, realizationKnobs, realizationOf, recovery, stackedDetection, timerOf, transitionOn };
939
+ export { FIRED, algebraProblems, arr, detection, errnoOf, evaluate, exprKnobs, fromStates, machineProblems, machineSchema, modelSource, overValues, parseExpr, readsFired, realizationKnobs, realizationOf, recovery, stackedDetection, timerOf, timerUnder, transitionOn };
842
940
 
843
941
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["r"],"sources":["../src/machine.ts","../src/algebra.ts"],"sourcesContent":["import { unitSchema } from \"@mark1russell7/quantity\";\nimport { z } from \"zod\";\n\n/**\n * `mark1russell7.machine/1` is a state machine as data.\n *\n * One document describes one machine, and three readers share it: the conformance checker\n * (states, transitions, observer mappings), the algebra (the closed forms of timers over knobs)\n * and the simulator (the arm, cancel and fire events of timers). The format is small on purpose:\n * no hierarchy, no actions other than `emits`, and guards as documented text.\n */\n\n/** A unit is a unit that @mark1russell7/quantity stores: a time or a count, which is all that the timers of a machine read. */\nexport type Unit = string;\n\n/** An expression is a duration: a constant, a knob, arithmetic over knobs, or a named model of them. */\nexport type Expr =\n | { readonly const: number; readonly unit: Unit }\n | { readonly knob: string; readonly unit: Unit }\n /** This text is arithmetic over knob names: + - * / min max floor ceil ( ) */\n | { readonly expr: string; readonly unit: Unit }\n /** This name is a named model of the algebra over these knobs, for example the retransmission ladder. */\n | { readonly model: string; readonly knobs: readonly string[]; readonly unit: Unit };\n\n/** A timer has a duration, the events that arm and cancel it, and the event that it fires. */\nexport interface Timer {\n readonly duration: Expr;\n readonly lateness?: Expr | undefined;\n readonly early?: Expr | undefined;\n readonly arms: readonly string[];\n readonly cancels?: readonly string[] | undefined;\n readonly fires: string;\n /**\n * A backoff timer starts again after it fires, and each wait is longer than the last. Examples\n * are the retransmission timer of the kernel and the reconnect of a driver. Its duration, lateness and\n * early bound are those of one wait. They can read `fired`: the number of times that it fired\n * after the last of its `resets`.\n */\n readonly backoff?: { readonly resets: readonly string[] } | undefined;\n readonly note?: string | undefined;\n}\n\n/**\n * This name is what the waits of a backoff timer read for the number of times that it fired after\n * a reset, from 0. It is not a knob, because nothing sets it. It is the count of the timer itself.\n */\nexport const FIRED = \"fired\";\n\n/**\n * A realization tells how long a mechanism takes where the machine operates. It is one of the\n * timers of the machine, whole, or a time of its own over the knobs of the machine. It has a\n * lateness and an early bound, as a timer has. The idle refresh of the Redis server is the idle\n * time of its keepalive, rounded on the timer wheel of the kernel. That is the first firing of its\n * keepalive timer, not the whole timer.\n */\nexport type Realization =\n | { readonly timer: string }\n | {\n readonly duration: Expr;\n readonly lateness?: Expr | undefined;\n readonly early?: Expr | undefined;\n readonly note?: string | undefined;\n };\n\n/**\n * An over tells the machine that this machine operates on, and how: a driver on its kernel socket.\n * Each state of this machine is on a state of the lower machine. Some knobs of this machine set\n * knobs of the lower machine. The end of the lower machine arrives as an event of this machine.\n *\n * The driver ioredis 6 sets the keepalive idle time of the kernel from its keepAlive option,\n * through setKeepAlive of Node. That function also sets the probe interval and count. The driver\n * learns of the end of the socket as stream.close.\n */\nexport interface Over {\n /** This identifier is the machine below, as a graph identifies its document. */\n readonly machine: string;\n /** This map gives the state of the lower machine that each state of this machine is on. */\n readonly states: Readonly<Record<string, string>>;\n /** These are the knobs of the lower machine that this machine sets, by their lower names, over its own knobs. */\n readonly sets: Readonly<Record<string, Expr>>;\n /** This event is the event of this machine that the end of the lower machine arrives as. */\n readonly ends: string;\n readonly note?: string | undefined;\n}\n\n/** A transition goes from one or more states to a state, on one or more events. */\nexport interface TransitionDef {\n readonly id: string;\n readonly from: string | readonly string[];\n readonly to: string;\n readonly on: string | readonly string[];\n readonly guard?: string | undefined;\n readonly timer?: string | undefined;\n readonly emits?: readonly string[] | undefined;\n readonly errno?: string | undefined;\n readonly note?: string | undefined;\n readonly source?: string | undefined;\n}\n\n/** A vantage is the layer that a machine is seen from. */\nexport type Vantage =\n \"wire\" | \"kernel\" | \"middlebox\" | \"proxy\" | \"driver\" | \"server\" | \"canary\" | \"injector\" | \"self\";\n\n/** A machine is one state machine document. */\nexport interface Machine {\n readonly format: \"mark1russell7.machine/1\";\n readonly id: string;\n readonly title: string;\n readonly layer: Vantage;\n readonly version: string;\n readonly conditions?: Readonly<Record<string, string>> | undefined;\n readonly sources: ReadonlyArray<{\n readonly ref: string;\n readonly rung: \"normative\" | \"implemented\" | \"documented\" | \"observed\" | \"derived\";\n readonly note?: string | undefined;\n }>;\n readonly states: Readonly<\n Record<\n string,\n {\n readonly initial?: boolean | undefined;\n readonly final?: boolean | undefined;\n readonly pseudo?: boolean | undefined;\n readonly note?: string | undefined;\n }\n >\n >;\n readonly events: Readonly<\n Record<\n string,\n {\n readonly kind: \"rx\" | \"tx\" | \"app\" | \"timer\" | \"local\" | \"packet\" | \"peer\";\n readonly note?: string | undefined;\n }\n >\n >;\n readonly knobs: Readonly<\n Record<\n string,\n {\n readonly key: string;\n readonly scope: string;\n readonly unit: Unit | null;\n readonly default: number | null;\n readonly note?: string | undefined;\n }\n >\n >;\n readonly timers: Readonly<Record<string, Timer>>;\n /** These are the mechanisms whose time this machine gives, by the identifier of each mechanism. */\n readonly realizes?: Readonly<Record<string, Realization>> | undefined;\n /** This is the machine that this machine operates on, for a machine on another machine. */\n readonly over?: Over | undefined;\n readonly transitions: readonly TransitionDef[];\n readonly observe?:\n | Readonly<\n Record<\n string,\n {\n readonly states: Readonly<Record<string, string>>;\n readonly hides?: readonly string[] | undefined;\n readonly fidelity: \"complete\" | \"sampled\" | \"lossy\" | \"derived\";\n readonly note?: string | undefined;\n }\n >\n >\n | undefined;\n readonly generated?: { readonly from: string; readonly by: string } | undefined;\n}\n\n// each time or count that a machine stores is a canonical unit: a jiffy among them, measured by\n// the HZ of the kernel\nconst unit = unitSchema([\"time\", \"count\"]);\n// a knob can also be a frequency: the HZ of the kernel itself, which the timer wheel counts in\nconst knobUnit = unitSchema([\"time\", \"count\", \"frequency\"]);\n\nconst expr: z.ZodType<Expr> = z.union([\n z.strictObject({ const: z.number(), unit }),\n z.strictObject({ knob: z.string(), unit }),\n z.strictObject({ expr: z.string(), unit }),\n z.strictObject({ model: z.string(), knobs: z.array(z.string()), unit }),\n]);\n\nconst timer = z.strictObject({\n duration: expr,\n /** This expression is how late the timer can fire, a tolerance on one side. */\n lateness: expr.optional(),\n /** This expression is how early the timer can fire, for example one jiffy. */\n early: expr.optional(),\n /** These are the events, or \"enter:<STATE>\", that start the timer or start it again. */\n arms: z.array(z.string()),\n cancels: z.array(z.string()).optional(),\n /** This event is the event that the timer raises. */\n fires: z.string(),\n /** A backoff timer starts again after it fires, and its waits read `fired`. */\n backoff: z.strictObject({ resets: z.array(z.string()) }).optional(),\n note: z.string().optional(),\n});\n\nconst realization: z.ZodType<Realization> = z.union([\n z.strictObject({ timer: z.string() }),\n z.strictObject({\n duration: expr,\n lateness: expr.optional(),\n early: expr.optional(),\n note: z.string().optional(),\n }),\n]);\n\nconst oneOrMany = z.union([z.string(), z.array(z.string())]);\n\nconst transition = z.strictObject({\n id: z.string(),\n /** The state \"*\" is each state that is not final. */\n from: oneOrMany,\n to: z.string(),\n on: oneOrMany,\n guard: z.string().optional(),\n timer: z.string().optional(),\n emits: z.array(z.string()).optional(),\n errno: z.string().optional(),\n note: z.string().optional(),\n /** This text is the file and line, or the section of a specification, that the transition comes from. */\n source: z.string().optional(),\n});\n\n/** These are the layers that a machine is seen from: the vantage layers of a trace. */\nconst VANTAGES = [\n \"wire\",\n \"kernel\",\n \"middlebox\",\n \"proxy\",\n \"driver\",\n \"server\",\n \"canary\",\n \"injector\",\n \"self\",\n] as const;\n\n/** This schema accepts a machine document. */\nexport const machineSchema: z.ZodType<Machine> = z.strictObject({\n format: z.literal(\"mark1russell7.machine/1\"),\n id: z.string(),\n title: z.string(),\n layer: z.enum(VANTAGES),\n version: z.string(),\n /** These are the conditions where the machine holds: a range of kernels, an architecture. */\n conditions: z.record(z.string(), z.string()).optional(),\n sources: z.array(\n z.strictObject({\n ref: z.string(),\n rung: z.enum([\"normative\", \"implemented\", \"documented\", \"observed\", \"derived\"]),\n note: z.string().optional(),\n }),\n ),\n states: z.record(\n z.string(),\n z.strictObject({\n initial: z.boolean().optional(),\n final: z.boolean().optional(),\n pseudo: z.boolean().optional(),\n note: z.string().optional(),\n }),\n ),\n events: z.record(\n z.string(),\n z.strictObject({\n kind: z.enum([\"rx\", \"tx\", \"app\", \"timer\", \"local\", \"packet\", \"peer\"]),\n note: z.string().optional(),\n }),\n ),\n /**\n * These are the names of the machine for the knobs that its timers and guards read. Each has\n * its key in its system, as a knob in a corpus has.\n */\n knobs: z.record(\n z.string(),\n z.strictObject({\n key: z.string(),\n scope: z.string(),\n /** The unit is null for a switch or a choice (nf_conntrack_tcp_loose), whose default is its code. */\n unit: knobUnit.nullable(),\n default: z.number().nullable(),\n note: z.string().optional(),\n }),\n ),\n timers: z.record(z.string(), timer),\n realizes: z.record(z.string(), realization).optional(),\n over: z\n .strictObject({\n machine: z.string(),\n states: z.record(z.string(), z.string()),\n sets: z.record(z.string(), expr),\n ends: z.string(),\n note: z.string().optional(),\n })\n .optional(),\n transitions: z.array(transition),\n /** This map tells what a source shows of the machine: its states as the source names them, and what it hides. */\n observe: z\n .record(\n z.string(),\n z.strictObject({\n states: z.record(z.string(), z.string()),\n hides: z.array(z.string()).optional(),\n fidelity: z.enum([\"complete\", \"sampled\", \"lossy\", \"derived\"]),\n note: z.string().optional(),\n }),\n )\n .optional(),\n generated: z.strictObject({ from: z.string(), by: z.string() }).optional(),\n});\n\n/** This function gives one value or many values as an array. */\nexport const arr = <T>(value: T | readonly T[]): readonly T[] =>\n Array.isArray(value) ? (value as readonly T[]) : [value as T];\n\n/** This function gives the names that a duration reads: its knobs, by the names of the machine, and `fired`. */\nconst exprNames = (e: Expr): string[] => {\n if (\"knob\" in e) return [e.knob];\n if (\"model\" in e) return [...e.knobs];\n if (\"expr\" in e) {\n return (e.expr.match(/[A-Za-z_][A-Za-z0-9_.]*/g) ?? []).filter(\n (word) => ![\"min\", \"max\", \"floor\", \"ceil\"].includes(word),\n );\n }\n return [];\n};\n\n/** This function gives the knobs that a duration reads, by the names of the machine for them. */\nexport const exprKnobs = (e: Expr): string[] => exprNames(e).filter((name) => name !== FIRED);\n\n/** This function tells if a duration reads the number of times that its timer fired, as the waits of a backoff do. */\nexport const readsFired = (e: Expr): boolean => exprNames(e).includes(FIRED);\n\n/** This function gives the states that a transition leaves. The state \"*\" is each state that is not final. */\nexport const fromStates = (m: Machine, from: string | readonly string[]): string[] => {\n const out = new Set<string>();\n for (const state of arr(from)) {\n if (state !== \"*\") out.add(state);\n else for (const [name, def] of Object.entries(m.states)) if (def.final !== true) out.add(name);\n }\n return [...out];\n};\n\n/**\n * This function gives the problems in the consistency of a document. Each state, event, timer and\n * knob that it refers to must exist, and it must have an initial state. A reader refuses a\n * machine with problems, and does not draw half of it.\n */\nexport const machineProblems = (m: Machine): string[] => {\n const problems: string[] = [];\n const states = new Set(Object.keys(m.states));\n if (!Object.values(m.states).some((state) => state.initial === true)) {\n problems.push(\"no initial state\");\n }\n for (const t of m.transitions) {\n for (const from of arr(t.from)) {\n if (from !== \"*\" && !states.has(from)) problems.push(`${t.id}: from ${from}`);\n }\n if (!states.has(t.to)) problems.push(`${t.id}: to ${t.to}`);\n for (const event of arr(t.on))\n if (m.events[event] === undefined) problems.push(`${t.id}: event ${event}`);\n if (t.timer !== undefined && m.timers[t.timer] === undefined) {\n problems.push(`${t.id}: timer ${t.timer}`);\n }\n }\n if (m.knobs[FIRED] !== undefined)\n problems.push(`knob ${FIRED}: the name is a backoff timer's count of its firings`);\n for (const [id, tm] of Object.entries(m.timers)) {\n if (m.events[tm.fires] === undefined) problems.push(`timer ${id}: fires ${tm.fires}`);\n for (const knob of exprKnobs(tm.duration)) {\n const def = m.knobs[knob];\n if (def === undefined) problems.push(`timer ${id}: knob ${knob}`);\n // a duration is an amount, thus a switch or a choice cannot give it\n else if (def.unit === null) problems.push(`timer ${id}: knob ${knob} is not an amount`);\n }\n // only a timer that starts again has a count of its firings to read\n const reads = [tm.duration, tm.lateness, tm.early].some(\n (e) => e !== undefined && readsFired(e),\n );\n if (reads && tm.backoff === undefined)\n problems.push(`timer ${id}: reads ${FIRED}, but has no backoff`);\n for (const event of tm.backoff?.resets ?? [])\n if (!event.startsWith(\"enter:\") && m.events[event] === undefined)\n problems.push(`timer ${id}: backoff resets on ${event}`);\n }\n for (const [mechanism, how] of Object.entries(m.realizes ?? {})) {\n if (\"timer\" in how) {\n // a machine on another machine can realize a timer of the machine below. Only a reader of\n // the two documents can examine that\n if (m.timers[how.timer] === undefined && m.over === undefined)\n problems.push(`realizes ${mechanism}: timer ${how.timer}`);\n continue;\n }\n if ([how.duration, how.lateness, how.early].some((e) => e !== undefined && readsFired(e)))\n problems.push(`realizes ${mechanism}: reads ${FIRED}, which only a backoff timer counts`);\n for (const knob of exprKnobs(how.duration)) {\n const def = m.knobs[knob];\n if (def === undefined) problems.push(`realizes ${mechanism}: knob ${knob}`);\n else if (def.unit === null)\n problems.push(`realizes ${mechanism}: knob ${knob} is not an amount`);\n }\n }\n if (m.over !== undefined) {\n for (const state of Object.keys(m.over.states)) {\n if (!states.has(state)) problems.push(`over: state ${state}`);\n }\n if (m.events[m.over.ends] === undefined) problems.push(`over: ends ${m.over.ends}`);\n for (const [lower, set] of Object.entries(m.over.sets)) {\n if (readsFired(set)) problems.push(`over: sets ${lower} from ${FIRED}, which is no knob`);\n for (const knob of exprKnobs(set)) {\n const def = m.knobs[knob];\n if (def === undefined) problems.push(`over: sets ${lower} from knob ${knob}`);\n else if (def.unit === null) problems.push(`over: sets ${lower} from ${knob}, no amount`);\n }\n }\n }\n for (const [source, view] of Object.entries(m.observe ?? {})) {\n for (const state of Object.values(view.states)) {\n if (!states.has(state)) problems.push(`observe ${source}: ${state}`);\n }\n }\n const ids = m.transitions.map((t) => t.id);\n for (const id of new Set(ids)) {\n if (ids.filter((other) => other === id).length > 1) problems.push(`transition ${id} twice`);\n }\n return problems;\n};\n","import type { Extent, Quantity, Rational, Unknown } from \"@mark1russell7/quantity\";\nimport {\n convertExact,\n isUnbounded,\n quantity,\n rationals as r,\n unbounded,\n} from \"@mark1russell7/quantity\";\nimport type { Expr, Machine, TransitionDef } from \"./machine.ts\";\nimport { FIRED, arr, exprKnobs, fromStates } from \"./machine.ts\";\n\n/**\n * This module has the closed forms of the algebra. They give the duration of a timer of a\n * machine, and how late and how early it can fire, from the values of its knobs.\n *\n * A machine document writes each duration in one of four forms (`machine.ts`): a constant, a knob,\n * arithmetic over its knobs, or a named model. The arithmetic uses the value of each knob in the\n * unit that the document gives to that knob. Thus `tcp_keepalive / 3` of Redis divides whole\n * seconds, as Redis does. A model is the formula of the implementation itself, for example the\n * retransmission budget of the kernel. The values are exact rationals, not floats: 0.2 s × 1023\n * is 204.6 s, not 204.60000000000002.\n *\n * A knob without a value makes the result unknown, and the result names the knob. A knob that\n * nothing sets (no bound) makes a duration without an end.\n */\n\n/** This function gives the value of each knob, by the name of the machine for it: an amount, no bound, or unknown and the reason. */\nexport type KnobValues = (name: string) => Extent | Unknown | undefined;\n\n/** Timer bounds tell how long a timer operates, how late it can fire and how early, each in the unit of its document. */\nexport interface TimerBounds {\n readonly duration: Extent | Unknown;\n readonly lateness?: Extent | Unknown | undefined;\n readonly early?: Extent | Unknown | undefined;\n}\n\ntype Value =\n | { readonly kind: \"exact\"; readonly n: Rational }\n | { readonly kind: \"infinite\" }\n | { readonly kind: \"unknown\"; readonly why: string };\n\nconst exact = (n: Rational): Value => ({ kind: \"exact\", n });\nconst INFINITE: Value = { kind: \"infinite\" };\nconst unknown = (why: string): Value => ({ kind: \"unknown\", why });\nconst whole = (n: bigint): Rational => r.rational(n);\n\n/** This function gives the first unknown among some values. An operation over them gets it. */\nconst unknownOf = (values: readonly Value[]): Value | undefined =>\n values.find((value) => value.kind === \"unknown\");\n\n// ---------------------------------------------------------------------------------------------\n// the arithmetic of the documents: + - * /, min, max, floor, ceil, parentheses, numbers, knob names\n// ---------------------------------------------------------------------------------------------\n\n/** A node is the arithmetic of a document, after the parse. */\nexport type Node =\n | { readonly op: \"num\"; readonly n: Rational }\n | { readonly op: \"knob\"; readonly name: string }\n | { readonly op: \"+\" | \"-\" | \"*\" | \"/\"; readonly a: Node; readonly b: Node }\n | { readonly op: \"neg\"; readonly a: Node }\n | { readonly op: \"min\" | \"max\" | \"floor\" | \"ceil\"; readonly args: readonly Node[] };\n\nconst FUNCTIONS = { min: 2, max: 2, floor: 1, ceil: 1 } as const;\n\n/** This function parses the arithmetic of a document, or it throws an error that tells where the text stops making sense. */\nexport const parseExpr = (text: string): Node => {\n const tokens = text.match(/\\d+(?:\\.\\d+)?|[A-Za-z_][A-Za-z0-9_.]*|[-+*/(),]|\\S/g) ?? [];\n let at = 0;\n const peek = (): string | undefined => tokens[at];\n const take = (expected?: string): string => {\n const token = tokens[at];\n if (token === undefined || (expected !== undefined && token !== expected)) {\n throw new Error(`\"${text}\": expected ${expected ?? \"more\"} at ${token ?? \"the end\"}`);\n }\n at += 1;\n return token;\n };\n const expr = (): Node => {\n let node = term();\n while (peek() === \"+\" || peek() === \"-\") {\n const op = take() as \"+\" | \"-\";\n node = { op, a: node, b: term() };\n }\n return node;\n };\n const term = (): Node => {\n let node = factor();\n while (peek() === \"*\" || peek() === \"/\") {\n const op = take() as \"*\" | \"/\";\n node = { op, a: node, b: factor() };\n }\n return node;\n };\n const factor = (): Node => {\n const token = take();\n if (token === \"(\") {\n const inner = expr();\n take(\")\");\n return inner;\n }\n if (token === \"-\") return { op: \"neg\", a: factor() };\n if (/^\\d/.test(token)) return { op: \"num\", n: r.fromDecimal(token) };\n if (!/^[A-Za-z_]/.test(token)) throw new Error(`\"${text}\": ${token} is not a term`);\n if (token in FUNCTIONS) {\n const name = token as keyof typeof FUNCTIONS;\n take(\"(\");\n const args = [expr()];\n while (peek() === \",\") {\n take(\",\");\n args.push(expr());\n }\n take(\")\");\n if (args.length !== FUNCTIONS[name]) {\n throw new Error(`\"${text}\": ${name} takes ${FUNCTIONS[name]}, not ${args.length}`);\n }\n return { op: name, args };\n }\n return { op: \"knob\", name: token };\n };\n const node = expr();\n if (at < tokens.length) throw new Error(`\"${text}\": ${tokens[at]} after the end`);\n return node;\n};\n\nconst run = (node: Node, valueOf: (name: string) => Value): Value => {\n if (node.op === \"num\") return exact(node.n);\n if (node.op === \"knob\") return valueOf(node.name);\n if (node.op === \"neg\") {\n const a = run(node.a, valueOf);\n return a.kind === \"exact\"\n ? exact(r.neg(a.n))\n : a.kind === \"infinite\"\n ? unknown(\"a negative unbounded time\")\n : a;\n }\n if (\"args\" in node) {\n const args = node.args.map((arg) => run(arg, valueOf));\n const lost = unknownOf(args);\n if (lost !== undefined) return lost;\n if (node.op === \"floor\" || node.op === \"ceil\") {\n const [a] = args as [Value];\n return a.kind === \"exact\" ? exact(node.op === \"floor\" ? r.floor(a.n) : r.ceil(a.n)) : a;\n }\n const [a, b] = args as [Value, Value];\n if (a.kind === \"infinite\" || b.kind === \"infinite\") {\n // no bound loses a min and wins a max\n return node.op === \"max\" ? INFINITE : a.kind === \"infinite\" ? b : a;\n }\n if (a.kind !== \"exact\" || b.kind !== \"exact\") return unknown(\"not an amount\");\n const aFirst = r.cmp(a.n, b.n) <= 0;\n if (node.op === \"min\") return aFirst ? a : b;\n return aFirst ? b : a;\n }\n const a = run(node.a, valueOf);\n const b = run(node.b, valueOf);\n const lost = unknownOf([a, b]);\n if (lost !== undefined) return lost;\n if (a.kind === \"exact\" && b.kind === \"exact\") {\n if (node.op === \"/\" && b.n.n === 0n) return unknown(\"a division by zero\");\n const op = { \"+\": r.add, \"-\": r.sub, \"*\": r.mul, \"/\": r.div }[node.op];\n return exact(op(a.n, b.n));\n }\n // a timer that nothing sets: it is longer than each sum and each positive multiple\n const zero = (value: Value): boolean => value.kind === \"exact\" && value.n.n === 0n;\n if (node.op === \"+\") return INFINITE;\n if (node.op === \"*\") return zero(a) || zero(b) ? unknown(\"zero times no bound\") : INFINITE;\n if (node.op === \"-\")\n return a.kind === \"infinite\" && b.kind !== \"infinite\"\n ? INFINITE\n : unknown(\"no bound less no bound\");\n return a.kind === \"infinite\"\n ? b.kind === \"infinite\"\n ? unknown(\"no bound over no bound\")\n : INFINITE\n : exact(r.ZERO);\n};\n\n// ---------------------------------------------------------------------------------------------\n// the named models: the formula of an implementation over its knobs, in seconds\n// ---------------------------------------------------------------------------------------------\n\nconst integer = (value: Rational, what: string): bigint => {\n if (!r.isInteger(value) || value.n < 0n)\n throw new Error(`${what} is not a whole count: ${r.toNumber(value)}`);\n return value.n;\n};\n/** This function gives min(base × 2^k, cap), exactly. */\nconst capped = (base: Rational, k: bigint, cap: Rational): Rational => {\n const doubled = r.mul(base, whole(2n ** k));\n return r.cmp(doubled, cap) <= 0 ? doubled : cap;\n};\n/**\n * This function gives the hypothetical retransmission timeout of the kernel, tcp_model_timeout in\n * net/ipv4/tcp_timer.c. The waits double from the minimum RTO until a step is more than the\n * maximum, and then the waits are capped. For tcp_retries2 = 15, it is 0.2 s × (2^10 − 1) +\n * 6 × 120 s = 924.6 s.\n */\nconst retransBudget = (retries: bigint, min: Rational, max: Rational): Rational => {\n let thresh = 0n;\n while (r.cmp(r.mul(min, whole(2n ** (thresh + 1n))), max) <= 0) thresh += 1n;\n if (retries <= thresh) return r.mul(min, whole(2n ** (retries + 1n) - 1n));\n return r.add(r.mul(min, whole(2n ** (thresh + 1n) - 1n)), r.mul(whole(retries - thresh), max));\n};\n\n/** These are TCP_TIMEOUT_INIT and TCP_RTO_MAX in include/net/tcp.h at v6.6: the first SYN RTO and the cap. */\nconst TCP_TIMEOUT_INIT = whole(1n);\nconst TCP_RTO_MAX = whole(120n);\n\n/** This function gives the whole jiffies of a time at HZ, rounded up, as msecs_to_jiffies and usecs_to_jiffies round. */\nconst jiffiesOf = (seconds: Rational, hz: Rational): bigint => r.ceil(r.mul(seconds, hz)).n;\n\n/**\n * This function gives how late the timer wheel can fire a timer that is due in `jiffies`\n * (calc_wheel_index in kernel/time/timer.c at v6.6). Level 0 holds the timers due in 63 jiffies\n * or less. Each level above holds eight times as long, at eight times the granularity. The wheel\n * rounds a timer up to the next boundary of its level, thus it fires up to one granularity late.\n * At HZ 250, a 2 h timer can be up to 131 s late.\n */\nconst granularity = (jiffies: bigint): bigint => {\n let level = 0n;\n while (level < 8n && jiffies >= 63n << (3n * level)) level += 1n;\n return 8n ** level;\n};\n\n/**\n * This function gives the lateness of the retransmission give-up after its budget. The first\n * retransmission sets the RTO to the round trip plus the minimum, rounded up to a jiffy\n * (tcp_set_rto). On a Docker network at HZ 250, that is 204 ms, not 200.\n *\n * Each firing doubles the RTO, up to the cap. The budget ends in the firing after the last one\n * that is short of it. Thus the give-up comes one step late at most, plus the rounding of each\n * firing on the wheel. The model assumes a steady path, whose variance stays below the minimum RTO.\n */\nconst retransLateness = (\n retries: bigint,\n min: Rational,\n max: Rational,\n rtt: Rational,\n hz: Rational,\n): Rational => {\n const base = jiffiesOf(r.add(min, rtt), hz);\n const cap = jiffiesOf(max, hz);\n let step = base;\n let wheel = 0n;\n for (let k = 1n; k <= retries + 1n; k += 1n) {\n step = base * 2n ** k < cap ? base * 2n ** k : cap;\n wheel += granularity(step);\n }\n return r.div(whole(step + wheel), hz);\n};\n\n/**\n * This function gives one wait of the retransmission timer with one segment in flight, in jiffies\n * (net/ipv4/tcp_timer.c, and tcp_schedule_loss_probe in tcp_output.c, at v6.6). Its first firing\n * is the tail loss probe. For one segment, the probe waits two round trips plus TCP_RTO_MIN, but\n * not longer than the RTO. Thus it waits the RTO itself: the round trip plus the minimum, in whole\n * jiffies.\n *\n * The probe arms the RTO again, and each RTO firing doubles it, up to the cap. Thus the\n * firing k comes 2^k RTOs after the send: 0.204, 0.408, 0.816 s on a Docker network at HZ 250.\n * With more than one segment in flight, the probe waits two round trips plus 2 jiffies.\n */\nconst rtoWait = (fired: bigint, min: Rational, max: Rational, rtt: Rational, hz: Rational) => {\n const base = jiffiesOf(r.add(min, rtt), hz);\n const cap = jiffiesOf(max, hz);\n if (fired === 0n) return base;\n const doubled = base * 2n ** (fired - 1n);\n return doubled < cap ? doubled : cap;\n};\n\n/**\n * This function gives the lateness of keepalive. It adds the idle timer and the interval of each\n * probe, each rounded up on the wheel at its own level. Linux arms the idle timer, then one probe\n * interval for each probe without an answer.\n */\nconst keepaliveLateness = (\n idle: Rational,\n interval: Rational,\n probes: bigint,\n hz: Rational,\n): Rational => {\n const late = (time: Rational) => whole(granularity(jiffiesOf(time, hz)));\n return r.div(r.add(late(idle), r.mul(whole(probes), late(interval))), hz);\n};\n\ninterface Model {\n /** These are the knobs that it reads, in sequence, and the unit to read each in (null for a count). */\n readonly knobs: readonly (string | null)[];\n /** This function gives the result in seconds. */\n readonly seconds: (args: readonly Rational[]) => Rational;\n readonly source: string;\n}\n\nconst MODELS: Readonly<Record<string, Model>> = {\n \"linux.retrans-budget\": {\n knobs: [null, \"s\", \"s\"],\n seconds: ([retries, min, max]) => retransBudget(integer(retries!, \"tcp_retries2\"), min!, max!),\n source: \"net/ipv4/tcp_timer.c tcp_model_timeout at v6.6\",\n },\n // the give-up comes at the first RTO firing at the budget or after it: one step later at most,\n // at the real RTO of the path, plus the rounding of each firing on the wheel\n \"linux.retrans-step\": {\n knobs: [null, \"s\", \"s\", \"s\", \"Hz\"],\n seconds: ([retries, min, max, rtt, hz]) =>\n retransLateness(integer(retries!, \"tcp_retries2\"), min!, max!, rtt!, hz!),\n source:\n \"net/ipv4/tcp_timer.c, tcp_input.c tcp_set_rto and kernel/time/timer.c at v6.6 (measured by @mark1russell7/harness, 2026-10-08)\",\n },\n // one wait of the retransmission timer, the first of the loss probe: 2^(fired − 1) RTOs after it\n \"linux.rto-wait\": {\n knobs: [null, \"s\", \"s\", \"s\", \"Hz\"],\n seconds: ([fired, min, max, rtt, hz]) =>\n r.div(whole(rtoWait(integer(fired!, FIRED), min!, max!, rtt!, hz!)), hz!),\n source:\n \"net/ipv4/tcp_timer.c tcp_retransmit_timer and tcp_output.c tcp_schedule_loss_probe at v6.6 (measured by @mark1russell7/harness, 2026-10-12)\",\n },\n // the rounding of that wait on the timer wheel, at the level that its length puts it in\n \"linux.rto-wait-lateness\": {\n knobs: [null, \"s\", \"s\", \"s\", \"Hz\"],\n seconds: ([fired, min, max, rtt, hz]) =>\n r.div(whole(granularity(rtoWait(integer(fired!, FIRED), min!, max!, rtt!, hz!))), hz!),\n source: \"kernel/time/timer.c calc_wheel_index at v6.6\",\n },\n // the idle timer of keepalive and the interval of each probe, each rounded on the wheel\n \"linux.keepalive-lateness\": {\n knobs: [\"s\", \"s\", null, \"Hz\"],\n seconds: ([idle, interval, probes, hz]) =>\n keepaliveLateness(idle!, interval!, integer(probes!, \"keepcnt\"), hz!),\n source: \"net/ipv4/tcp_timer.c tcp_keepalive_timer and kernel/time/timer.c at v6.6\",\n },\n // the rounding of one firing on the wheel: how late one timer due after this time can fire\n \"linux.wheel\": {\n knobs: [\"s\", \"Hz\"],\n seconds: ([time, hz]) => r.div(whole(granularity(jiffiesOf(time!, hz!))), hz!),\n source: \"kernel/time/timer.c calc_wheel_index at v6.6\",\n },\n // one jiffy: a timer counts from the tick before the event that arms it\n \"linux.jiffy\": {\n knobs: [\"Hz\"],\n seconds: ([hz]) => r.div(whole(1n), hz!),\n source: \"include/linux/jiffies.h\",\n },\n // 6.5 and later: the first tcp_syn_linear_timeouts retransmissions wait the initial RTO, the\n // others double it, and the SYN gives up after syn_retries + linear_timeouts retransmissions\n \"linux.syn-giveup\": {\n knobs: [null, null],\n seconds: ([retries, linear]) => {\n const n = integer(retries!, \"tcp_syn_retries\");\n let total = r.mul(whole(integer(linear!, \"tcp_syn_linear_timeouts\") + 1n), TCP_TIMEOUT_INIT);\n for (let i = 1n; i <= n; i += 1n)\n total = r.add(total, capped(TCP_TIMEOUT_INIT, i, TCP_RTO_MAX));\n return total;\n },\n source:\n \"net/ipv4/tcp_timer.c tcp_write_timeout and Documentation/networking/ip-sysctl.rst at v6.6\",\n },\n // the default retryStrategy of ioredis 6: min(2^(times - 1) × 50, 5000) ms, plus a jitter of up\n // to 199 ms, which the lateness of the timer carries. Its times counts attempts from 1 after the\n // last ready, thus it is one more than the number of firings of the timer. 5.x waited\n // min(times × 50, 2000) ms\n \"ioredis.retry-base\": {\n knobs: [null],\n seconds: ([fired]) => capped(r.fromDecimal(\"0.05\"), integer(fired!, FIRED), whole(5n)),\n source:\n \"ioredis 6.0.0 built/redis/RedisOptions.js retryStrategy and built/redis/event_handler.js\",\n },\n};\n\n// ---------------------------------------------------------------------------------------------\n// the evaluation of a duration and a timer\n// ---------------------------------------------------------------------------------------------\n\n/**\n * This function gives the value of a knob in the unit that the document gives it (or as a count\n * when it is a count). For `fired`, it gives which wait of a backoff timer it is.\n */\nconst knobIn = (\n doc: Machine,\n name: string,\n unit: string | null,\n values: KnobValues,\n fired: number | undefined,\n): Value => {\n if (name === FIRED)\n return fired === undefined\n ? unknown(\"one wait of a timer with a backoff: say which, by how many times it has fired\")\n : exact(r.fromNumber(fired));\n if (doc.knobs[name] === undefined) return unknown(`the machine names no knob ${name}`);\n const given = values(name);\n if (given === undefined) return unknown(`nothing gives ${name}'s value`);\n if (\"unknown\" in given) return unknown(`${name}: ${given.unknown}`);\n if (given.value === \"infinite\") return INFINITE;\n const value = r.fromNumber(given.value);\n return exact(\n unit === null\n ? convertExact(value, given.unit, given.unit)\n : convertExact(value, given.unit, unit),\n );\n};\n\nconst out = (value: Value, unit: string): Extent | Unknown =>\n value.kind === \"exact\"\n ? quantity(r.toNumber(value.n), unit)\n : value.kind === \"infinite\"\n ? unbounded(unit)\n : { unknown: value.why, unit };\n\n/**\n * This function evaluates one duration of a timer of a machine, in the unit that its document\n * gives it. The waits of a backoff timer read `fired`, which tells which wait.\n */\nexport const evaluate = (\n doc: Machine,\n expr: Expr,\n values: KnobValues,\n fired?: number,\n): Extent | Unknown => {\n if (\"const\" in expr) return quantity(expr.const, expr.unit);\n if (\"knob\" in expr) {\n return out(knobIn(doc, expr.knob, expr.unit, values, fired), expr.unit);\n }\n if (\"expr\" in expr) {\n const tree = parseExpr(expr.expr);\n const value = run(tree, (name) =>\n knobIn(doc, name, doc.knobs[name]?.unit ?? null, values, fired),\n );\n return out(value, expr.unit);\n }\n const model = MODELS[expr.model];\n if (model === undefined) return { unknown: `no model ${expr.model}`, unit: expr.unit };\n if (model.knobs.length !== expr.knobs.length) {\n return {\n unknown: `${expr.model} reads ${model.knobs.length} knobs, not ${expr.knobs.length}`,\n unit: expr.unit,\n };\n }\n const args = expr.knobs.map((name, index) =>\n knobIn(doc, name, model.knobs[index] ?? null, values, fired),\n );\n const lost = unknownOf(args);\n if (lost !== undefined) return out(lost, expr.unit);\n if (args.some((arg) => arg.kind === \"infinite\")) return unbounded(expr.unit);\n const seconds = model.seconds(args.map((arg) => (arg as { n: Rational }).n));\n return quantity(r.toNumber(convertExact(seconds, \"s\", expr.unit)), expr.unit);\n};\n\n/**\n * This function gives the bounds of a timer of a machine: how long it operates, how late it can\n * fire, how early. For a backoff timer, it gives one of its waits: the wait after `fired` firings.\n */\nexport const timerOf = (\n doc: Machine,\n timer: string,\n values: KnobValues,\n fired?: number,\n): TimerBounds => {\n const def = doc.timers[timer];\n if (def === undefined) throw new Error(`${doc.title} has no timer ${timer}`);\n return {\n duration: evaluate(doc, def.duration, values, fired),\n ...(def.lateness !== undefined ? { lateness: evaluate(doc, def.lateness, values, fired) } : {}),\n ...(def.early !== undefined ? { early: evaluate(doc, def.early, values, fired) } : {}),\n };\n};\n\n/** A firing is one firing of a backoff timer, after `fired` firings: its time from the arming. */\nexport interface Firing {\n readonly fired: number;\n /** This time is the sum of the waits to this firing, each less how early it can fire. */\n readonly low: Quantity;\n /** This time is the sum of the waits to this firing, each plus how late it can fire. */\n readonly high: Quantity;\n}\n\n/** A recovery tells when the firings of a backoff timer move a connection again after a stall. */\nexport interface Recovery {\n /** These are its firings from its arming, up to the first one that surely comes after the end of the stall. */\n readonly firings: readonly Firing[];\n /**\n * These are the firings that can be the first after the end of the stall. There is more than one\n * when the end falls in the bounds of a firing: that firing can come before the end or after it.\n */\n readonly first: readonly number[];\n /** This time is the earliest time of the first firing after the end of the stall, from the arming. */\n readonly low: Quantity;\n /** This time is the latest time of that firing, from the arming. */\n readonly high: Quantity;\n}\n\n/** This count is the most firings that `recovery` examines before it tells that the stall is longer than them. */\nconst FIRINGS = 4096;\n\n/**\n * This function gives the recovery from a stall. A backoff timer continues to fire through a\n * stall, and what each firing sends gets through only after the stall ends. Thus the connection\n * moves again at the first firing at the end or after it. That firing can be most of a wait after\n * the end. A stall that stops immediately after one firing costs almost all of the next, longer\n * wait.\n *\n * The stall counts from the arming of the timer, which is the send that the stall first lost. The\n * waits add, and so do how early and how late each can fire.\n */\nexport const recovery = (\n doc: Machine,\n timer: string,\n values: KnobValues,\n stall: Extent,\n): Recovery | Unknown => {\n const def = doc.timers[timer];\n if (def === undefined) throw new Error(`${doc.title} has no timer ${timer}`);\n if (def.backoff === undefined) throw new Error(`${doc.title}'s ${timer} has no backoff`);\n if (isUnbounded(stall))\n return { unknown: \"a stall that never ends: nothing recovers from it\", unit: \"s\" };\n const end = convertExact(r.fromNumber(stall.value), stall.unit, \"s\");\n const inSeconds = (extent: Extent | Unknown | undefined, what: string): Rational | string => {\n if (extent === undefined) return r.ZERO;\n if (\"unknown\" in extent) return `${what}: ${extent.unknown}`;\n if (isUnbounded(extent)) return `${what} has no bound, so the timer never fires again`;\n return convertExact(r.fromNumber(extent.value), extent.unit, \"s\");\n };\n const s = (value: Rational): Quantity => quantity(r.toNumber(value), \"s\");\n const sums: Array<{ fired: number; low: Rational; high: Rational }> = [];\n let low = r.ZERO;\n let high = r.ZERO;\n for (let fired = 0; fired < FIRINGS; fired += 1) {\n const bounds = timerOf(doc, timer, values, fired);\n const wait = inSeconds(bounds.duration, `wait ${fired}`);\n const early = inSeconds(bounds.early, `wait ${fired}'s early bound`);\n const late = inSeconds(bounds.lateness, `wait ${fired}'s lateness`);\n if (typeof wait === \"string\") return { unknown: wait, unit: \"s\" };\n if (typeof early === \"string\") return { unknown: early, unit: \"s\" };\n if (typeof late === \"string\") return { unknown: late, unit: \"s\" };\n low = r.add(low, r.sub(wait, early));\n high = r.add(high, r.add(wait, late));\n sums.push({ fired, low, high });\n if (r.cmp(low, end) < 0) continue;\n // a firing whose latest time is at the end or after it can be the first after the end\n const first = sums.filter((f) => r.cmp(f.high, end) >= 0);\n const earliest = first[0]!.low;\n return {\n firings: sums.map((f) => ({ fired: f.fired, low: s(f.low), high: s(f.high) })),\n first: first.map((f) => f.fired),\n low: s(r.cmp(earliest, end) >= 0 ? earliest : end),\n high: s(first.at(-1)!.high),\n };\n }\n return { unknown: `${FIRINGS} firings do not outlast the stall`, unit: \"s\" };\n};\n\n/**\n * This function gives how long a mechanism takes where a machine operates, from the realization\n * of its document. The realization is one of its timers, whole, or its own duration, lateness and\n * early bound over the knobs of the machine. It gives undefined when the document does not realize the mechanism.\n */\nexport const realizationOf = (\n doc: Machine,\n mechanism: string,\n values: KnobValues,\n): TimerBounds | undefined => {\n const how = doc.realizes?.[mechanism];\n if (how === undefined) return undefined;\n if (\"timer\" in how) return timerOf(doc, how.timer, values);\n return {\n duration: evaluate(doc, how.duration, values),\n ...(how.lateness !== undefined ? { lateness: evaluate(doc, how.lateness, values) } : {}),\n ...(how.early !== undefined ? { early: evaluate(doc, how.early, values) } : {}),\n };\n};\n\n/** This function gives the knobs that a realization reads, by the names of the machine for them. */\nexport const realizationKnobs = (doc: Machine, mechanism: string): string[] => {\n const how = doc.realizes?.[mechanism];\n if (how === undefined) return [];\n const def = \"timer\" in how ? doc.timers[how.timer] : how;\n if (def === undefined) return [];\n return [\n ...new Set(\n [def.duration, def.lateness, def.early].flatMap((e) => (e === undefined ? [] : exprKnobs(e))),\n ),\n ];\n};\n\n/** This function gives what in a document the algebra cannot read: arithmetic that does not parse, or a model that it does not have. */\nexport const algebraProblems = (doc: Machine): string[] => {\n const problems: string[] = [];\n const read = (where: string, exprs: ReadonlyArray<Expr | undefined>) => {\n for (const expr of exprs) {\n if (expr === undefined) continue;\n if (\"expr\" in expr) {\n try {\n parseExpr(expr.expr);\n } catch (error) {\n problems.push(`${where}: ${(error as Error).message}`);\n }\n }\n if (\"model\" in expr && MODELS[expr.model] === undefined)\n problems.push(`${where}: no model ${expr.model}`);\n }\n };\n for (const [id, def] of Object.entries(doc.timers)) {\n read(`timer ${id}`, [def.duration, def.lateness, def.early]);\n }\n for (const [mechanism, how] of Object.entries(doc.realizes ?? {})) {\n if (!(\"timer\" in how)) read(`realizes ${mechanism}`, [how.duration, how.lateness, how.early]);\n }\n for (const [lower, set] of Object.entries(doc.over?.sets ?? {}))\n read(`over sets ${lower}`, [set]);\n return problems;\n};\n\n/** This function gives the source of the formula of a named model, for a reader of a result. */\nexport const modelSource = (name: string): string | undefined => MODELS[name]?.source;\n\n// ---------------------------------------------------------------------------------------------\n// detection: the minimum over the detectors that are live in what the connection was doing\n// ---------------------------------------------------------------------------------------------\n\n/**\n * A manifestation is what a failure lets back to the machine: the incoming events that continue\n * to arrive while it lasts. A black hole lets nothing back. The kernel of a frozen process\n * continues to acknowledge what it gets and to answer keepalive probes, thus its ACKs continue to\n * arrive.\n */\nexport interface Manifestation {\n readonly name: string;\n readonly passes: readonly string[];\n}\n\n/** A situation is the activity of the connection when the failure started. */\nexport interface Situation {\n /** This name is the state of the machine, for example ESTABLISHED. */\n readonly state: string;\n /** This flag tells if it had sent data that the peer had not acknowledged. */\n readonly inFlight: boolean;\n}\n\n/** A detector is a timer that can still fire, how long it operates, and the event that it fires. */\nexport interface Detector {\n readonly timer: string;\n readonly fires: string;\n readonly duration: Extent | Unknown;\n /** This identifier is the machine below whose timer it is, when the timer is not of the machine itself (`over`). */\n readonly beneath?: string | undefined;\n}\n\n/** A detection is the result of the minimum over the live detectors. */\nexport interface Detection {\n /** These are the timers that can still fire, the soonest first. */\n readonly detectors: readonly Detector[];\n /** This detector is the first to fire, or null when none can fire in a known time: a silent failure. */\n readonly first: Detector | null;\n /** These are the live detectors whose time nothing gives. Then `first` is only an upper bound. */\n readonly unsettled: readonly string[];\n /** These are the timers that are armed but cannot fire, and the reason for each. */\n readonly held: ReadonlyArray<{ readonly timer: string; readonly why: string }>;\n}\n\nconst soonest = (a: Detector, b: Detector): number => {\n const rank = (d: Detector): number =>\n \"unknown\" in d.duration ? 2 : d.duration.value === \"infinite\" ? 1 : 0;\n if (rank(a) !== rank(b)) return rank(a) - rank(b);\n if (rank(a) !== 0) return a.timer.localeCompare(b.timer);\n const seconds = (d: Detector) => {\n const value = d.duration as Extent & { value: number };\n return r.toNumber(convertExact(r.fromNumber(value.value), value.unit, \"s\"));\n };\n return seconds(a) - seconds(b) || a.timer.localeCompare(b.timer);\n};\n\n/**\n * This function gives the detection: the minimum over the detectors that are live in the\n * situation. The entry to the state arms a timer, and so does what the failure causes: data in\n * flight without an acknowledgment gets a retransmission. An event that occurs cancels a timer.\n *\n * An event that arms the timer again, and that the failure continues to let through, stops it\n * before it fires. For example, the kernel of a frozen process answers each keepalive probe.\n * Without a live detector, the failure is silent at the level of this machine. Only something\n * above it, the timeout of an application or a heartbeat, can find it. The result is only as good\n * as the events that the document names.\n */\nexport const detection = (\n doc: Machine,\n situation: Situation,\n manifestation: Manifestation,\n values: KnobValues,\n): Detection => {\n const passes = new Set(manifestation.passes);\n const happened = new Set([`enter:${situation.state}`]);\n if (situation.inFlight && !passes.has(\"rx.ack\")) happened.add(\"tx.retransmit.first\");\n const occurs = (event: string): boolean => happened.has(event) || passes.has(event);\n const detectors: Detector[] = [];\n const held: Array<{ timer: string; why: string }> = [];\n for (const [timer, def] of Object.entries(doc.timers)) {\n // a backoff timer starts again when it fires: its firing is a new try of the machine, and\n // another timer gives up on it, as the retransmission give-up does\n if (def.backoff !== undefined) continue;\n if (!def.arms.some(occurs)) continue;\n const cancelled = (def.cancels ?? []).find(occurs);\n if (cancelled !== undefined) {\n held.push({ timer, why: `${cancelled} cancels it` });\n continue;\n }\n const rearmed = def.arms.find((event) => passes.has(event));\n if (rearmed !== undefined) {\n held.push({ timer, why: `${rearmed} keeps arriving and re-arms it` });\n continue;\n }\n detectors.push({ timer, fires: def.fires, duration: evaluate(doc, def.duration, values) });\n }\n detectors.sort(soonest);\n const [earliest] = detectors;\n const finite =\n earliest !== undefined &&\n !(\"unknown\" in earliest.duration) &&\n earliest.duration.value !== \"infinite\";\n return {\n detectors,\n first: finite ? earliest : null,\n unsettled: detectors.filter((d) => \"unknown\" in d.duration).map((d) => d.timer),\n held,\n };\n};\n\n// ---------------------------------------------------------------------------------------------\n// a machine on another machine: a driver on its kernel socket\n// ---------------------------------------------------------------------------------------------\n\n/** This function gives the transition that a machine takes from a state on an event, by its document. */\nexport const transitionOn = (\n doc: Machine,\n state: string,\n event: string,\n): TransitionDef | undefined =>\n doc.transitions.find((t) => fromStates(doc, t.from).includes(state) && arr(t.on).includes(event));\n\n/**\n * This function gives the values of a machine for the machine that it operates on. These are the\n * knobs that it sets, evaluated over its own knobs, and the other knobs of the lower machine. The\n * keepAlive of ioredis at 5000 ms is the keepidle of the kernel at 5 s.\n */\nexport const overValues =\n (upper: Machine, upperValues: KnobValues, lowerValues: KnobValues): KnobValues =>\n (name) => {\n const set = upper.over?.sets[name];\n return set === undefined ? lowerValues(name) : evaluate(upper, set, upperValues);\n };\n\n/**\n * This function gives the detection through the machine that a machine operates on. The detectors\n * of the lower machine are live in the state below the state of this machine. They use the knobs\n * that this machine sets.\n *\n * Each one reaches this machine as the event that the end of the lower\n * machine gives. They are beside the timers of this machine, and the first of all of them is the\n * first detection. A failure lets nothing new through to a machine above the socket, only the end\n * of the socket. Thus the timers of this machine see only what its state arms.\n */\nexport const stackedDetection = (\n upper: Machine,\n lower: Machine,\n situation: Situation,\n manifestation: Manifestation,\n upperValues: KnobValues,\n lowerValues: KnobValues,\n): Detection => {\n const over = upper.over;\n if (over === undefined) throw new Error(`${upper.title} runs on no other machine`);\n const sitsOn = over.states[situation.state];\n if (sitsOn === undefined) {\n throw new Error(`${upper.title}'s ${situation.state} sits on no state of ${lower.title}`);\n }\n const own = detection(upper, situation, { name: manifestation.name, passes: [] }, upperValues);\n const below = detection(\n lower,\n { ...situation, state: sitsOn },\n manifestation,\n overValues(upper, upperValues, lowerValues),\n );\n const detectors = [\n ...own.detectors,\n ...below.detectors.map((d) => ({ ...d, beneath: over.machine })),\n ].sort(soonest);\n const [earliest] = detectors;\n const finite =\n earliest !== undefined &&\n !(\"unknown\" in earliest.duration) &&\n earliest.duration.value !== \"infinite\";\n return {\n detectors,\n first: finite ? earliest : null,\n unsettled: detectors.filter((d) => \"unknown\" in d.duration).map((d) => d.timer),\n held: [...own.held, ...below.held.map((h) => ({ ...h, why: `${h.why}, beneath` }))],\n };\n};\n"],"mappings":";;;;;;;AA8CA,MAAa,QAAQ;AA8HrB,MAAM,OAAO,WAAW,CAAC,QAAQ,OAAO,CAAC;AAEzC,MAAM,WAAW,WAAW;CAAC;CAAQ;CAAS;AAAW,CAAC;AAE1D,MAAM,OAAwB,EAAE,MAAM;CACpC,EAAE,aAAa;EAAE,OAAO,EAAE,OAAO;EAAG;CAAK,CAAC;CAC1C,EAAE,aAAa;EAAE,MAAM,EAAE,OAAO;EA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AG;EAAG,SAAS,KAAK;CAAQ,EAAE,CACjE,CAAC,CAAC,KAAK,OAAO;CACd,MAAM,CAAC,YAAY;CAKnB,OAAO;EACL;EACA,OALA,aAAa,KAAA,KACb,EAAE,aAAa,SAAS,aACxB,SAAS,SAAS,UAAU,aAGZ,WAAW;EAC3B,WAAW,UAAU,QAAQ,MAAM,aAAa,EAAE,QAAQ,CAAC,CAAC,KAAK,MAAM,EAAE,KAAK;EAC9E,MAAM,CAAC,GAAG,IAAI,MAAM,GAAG,MAAM,KAAK,KAAK,OAAO;GAAE,GAAG;GAAG,KAAK,GAAG,EAAE,IAAI;EAAW,EAAE,CAAC;CACpF;AACF"}
1
+ {"version":3,"file":"index.js","names":["r"],"sources":["../src/machine.ts","../src/algebra.ts"],"sourcesContent":["import { unitSchema } from \"@mark1russell7/quantity\";\nimport { z } from \"zod\";\n\n/**\n * `mark1russell7.machine/1` is a state machine as data.\n *\n * One document describes one machine, and three readers share it: the conformance checker\n * (states, transitions, observer mappings), the algebra (the closed forms of timers over knobs)\n * and the simulator (the arm, cancel and fire events of timers). The format is small on purpose:\n * no hierarchy, no actions other than `emits`, and guards as documented text.\n */\n\n/** A unit is a unit that @mark1russell7/quantity stores: a time or a count, which is all that the timers of a machine read. */\nexport type Unit = string;\n\n/** An expression is a duration: a constant, a knob, arithmetic over knobs, or a named model of them. */\nexport type Expr =\n | { readonly const: number; readonly unit: Unit }\n | { readonly knob: string; readonly unit: Unit }\n /** This text is arithmetic over knob names: + - * / min max floor ceil ( ) */\n | { readonly expr: string; readonly unit: Unit }\n /** This name is a named model of the algebra over these knobs, for example the retransmission ladder. */\n | { readonly model: string; readonly knobs: readonly string[]; readonly unit: Unit };\n\n/** A timer has a duration, the events that arm and cancel it, and the event that it fires. */\nexport interface Timer {\n readonly duration: Expr;\n readonly lateness?: Expr | undefined;\n readonly early?: Expr | undefined;\n readonly arms: readonly string[];\n readonly cancels?: readonly string[] | undefined;\n readonly fires: string;\n /**\n * A backoff timer starts again after it fires, and each wait is longer than the last. Examples\n * are the retransmission timer of the kernel and the reconnect of a driver. Its duration, lateness and\n * early bound are those of one wait. They can read `fired`: the number of times that it fired\n * after the last of its `resets`.\n */\n readonly backoff?: { readonly resets: readonly string[] } | undefined;\n readonly note?: string | undefined;\n}\n\n/**\n * This name is what the waits of a backoff timer read for the number of times that it fired after\n * a reset, from 0. It is not a knob, because nothing sets it. It is the count of the timer itself.\n */\nexport const FIRED = \"fired\";\n\n/**\n * A realization tells how long a mechanism takes where the machine operates. It is one of the\n * timers of the machine, whole, or a time of its own over the knobs of the machine. It has a\n * lateness and an early bound, as a timer has. The idle refresh of the Redis server is the idle\n * time of its keepalive, rounded on the timer wheel of the kernel. That is the first firing of its\n * keepalive timer, not the whole timer.\n */\nexport type Realization =\n | { readonly timer: string }\n | {\n readonly duration: Expr;\n readonly lateness?: Expr | undefined;\n readonly early?: Expr | undefined;\n readonly note?: string | undefined;\n };\n\n/**\n * An over tells the machine that this machine operates on, and how: a driver on its kernel socket.\n * Each state of this machine is on a state of the lower machine. Some knobs of this machine set\n * knobs of the lower machine. The end of the lower machine arrives as an event of this machine.\n *\n * The driver ioredis 6 sets the keepalive idle time of the kernel from its keepAlive option,\n * through setKeepAlive of Node. That function also sets the probe interval and count. The driver\n * learns of the end of the socket as stream.close.\n */\nexport interface Over {\n /** This identifier is the machine below, as a graph identifies its document. */\n readonly machine: string;\n /** This map gives the state of the lower machine that each state of this machine is on. */\n readonly states: Readonly<Record<string, string>>;\n /** These are the knobs of the lower machine that this machine sets, by their lower names, over its own knobs. */\n readonly sets: Readonly<Record<string, Expr>>;\n /** This event is the event of this machine that the end of the lower machine arrives as. */\n readonly ends: string;\n readonly note?: string | undefined;\n}\n\n/** A transition goes from one or more states to a state, on one or more events. */\nexport interface TransitionDef {\n readonly id: string;\n readonly from: string | readonly string[];\n readonly to: string;\n readonly on: string | readonly string[];\n readonly guard?: string | undefined;\n readonly timer?: string | undefined;\n readonly emits?: readonly string[] | undefined;\n readonly errno?: string | undefined;\n readonly note?: string | undefined;\n readonly source?: string | undefined;\n}\n\n/** A vantage is the layer that a machine is seen from. */\nexport type Vantage =\n \"wire\" | \"kernel\" | \"middlebox\" | \"proxy\" | \"driver\" | \"server\" | \"canary\" | \"injector\" | \"self\";\n\n/** A machine is one state machine document. */\nexport interface Machine {\n readonly format: \"mark1russell7.machine/1\";\n readonly id: string;\n readonly title: string;\n readonly layer: Vantage;\n readonly version: string;\n readonly conditions?: Readonly<Record<string, string>> | undefined;\n readonly sources: ReadonlyArray<{\n readonly ref: string;\n readonly rung: \"normative\" | \"implemented\" | \"documented\" | \"observed\" | \"derived\";\n readonly note?: string | undefined;\n }>;\n readonly states: Readonly<\n Record<\n string,\n {\n readonly initial?: boolean | undefined;\n readonly final?: boolean | undefined;\n readonly pseudo?: boolean | undefined;\n readonly note?: string | undefined;\n }\n >\n >;\n readonly events: Readonly<\n Record<\n string,\n {\n readonly kind: \"rx\" | \"tx\" | \"app\" | \"timer\" | \"local\" | \"packet\" | \"peer\";\n readonly note?: string | undefined;\n }\n >\n >;\n readonly knobs: Readonly<\n Record<\n string,\n {\n readonly key: string;\n readonly scope: string;\n readonly unit: Unit | null;\n readonly default: number | null;\n readonly note?: string | undefined;\n }\n >\n >;\n readonly timers: Readonly<Record<string, Timer>>;\n /** These are the mechanisms whose time this machine gives, by the identifier of each mechanism. */\n readonly realizes?: Readonly<Record<string, Realization>> | undefined;\n /** This is the machine that this machine operates on, for a machine on another machine. */\n readonly over?: Over | undefined;\n readonly transitions: readonly TransitionDef[];\n readonly observe?:\n | Readonly<\n Record<\n string,\n {\n readonly states: Readonly<Record<string, string>>;\n readonly hides?: readonly string[] | undefined;\n readonly fidelity: \"complete\" | \"sampled\" | \"lossy\" | \"derived\";\n readonly note?: string | undefined;\n }\n >\n >\n | undefined;\n readonly generated?: { readonly from: string; readonly by: string } | undefined;\n}\n\n// each time or count that a machine stores is a canonical unit: a jiffy among them, measured by\n// the HZ of the kernel\nconst unit = unitSchema([\"time\", \"count\"]);\n// a knob can also be a frequency: the HZ of the kernel itself, which the timer wheel counts in\nconst knobUnit = unitSchema([\"time\", \"count\", \"frequency\"]);\n\nconst expr: z.ZodType<Expr> = z.union([\n z.strictObject({ const: z.number(), unit }),\n z.strictObject({ knob: z.string(), unit }),\n z.strictObject({ expr: z.string(), unit }),\n z.strictObject({ model: z.string(), knobs: z.array(z.string()), unit }),\n]);\n\nconst timer = z.strictObject({\n duration: expr,\n /** This expression is how late the timer can fire, a tolerance on one side. */\n lateness: expr.optional(),\n /** This expression is how early the timer can fire, for example one jiffy. */\n early: expr.optional(),\n /** These are the events, or \"enter:<STATE>\", that start the timer or start it again. */\n arms: z.array(z.string()),\n cancels: z.array(z.string()).optional(),\n /** This event is the event that the timer raises. */\n fires: z.string(),\n /** A backoff timer starts again after it fires, and its waits read `fired`. */\n backoff: z.strictObject({ resets: z.array(z.string()) }).optional(),\n note: z.string().optional(),\n});\n\nconst realization: z.ZodType<Realization> = z.union([\n z.strictObject({ timer: z.string() }),\n z.strictObject({\n duration: expr,\n lateness: expr.optional(),\n early: expr.optional(),\n note: z.string().optional(),\n }),\n]);\n\nconst oneOrMany = z.union([z.string(), z.array(z.string())]);\n\nconst transition = z.strictObject({\n id: z.string(),\n /** The state \"*\" is each state that is not final. */\n from: oneOrMany,\n to: z.string(),\n on: oneOrMany,\n guard: z.string().optional(),\n timer: z.string().optional(),\n emits: z.array(z.string()).optional(),\n errno: z.string().optional(),\n note: z.string().optional(),\n /** This text is the file and line, or the section of a specification, that the transition comes from. */\n source: z.string().optional(),\n});\n\n/** These are the layers that a machine is seen from: the vantage layers of a trace. */\nconst VANTAGES = [\n \"wire\",\n \"kernel\",\n \"middlebox\",\n \"proxy\",\n \"driver\",\n \"server\",\n \"canary\",\n \"injector\",\n \"self\",\n] as const;\n\n/** This schema accepts a machine document. */\nexport const machineSchema: z.ZodType<Machine> = z.strictObject({\n format: z.literal(\"mark1russell7.machine/1\"),\n id: z.string(),\n title: z.string(),\n layer: z.enum(VANTAGES),\n version: z.string(),\n /** These are the conditions where the machine holds: a range of kernels, an architecture. */\n conditions: z.record(z.string(), z.string()).optional(),\n sources: z.array(\n z.strictObject({\n ref: z.string(),\n rung: z.enum([\"normative\", \"implemented\", \"documented\", \"observed\", \"derived\"]),\n note: z.string().optional(),\n }),\n ),\n states: z.record(\n z.string(),\n z.strictObject({\n initial: z.boolean().optional(),\n final: z.boolean().optional(),\n pseudo: z.boolean().optional(),\n note: z.string().optional(),\n }),\n ),\n events: z.record(\n z.string(),\n z.strictObject({\n kind: z.enum([\"rx\", \"tx\", \"app\", \"timer\", \"local\", \"packet\", \"peer\"]),\n note: z.string().optional(),\n }),\n ),\n /**\n * These are the names of the machine for the knobs that its timers and guards read. Each has\n * its key in its system, as a knob in a corpus has.\n */\n knobs: z.record(\n z.string(),\n z.strictObject({\n key: z.string(),\n scope: z.string(),\n /** The unit is null for a switch or a choice (nf_conntrack_tcp_loose), whose default is its code. */\n unit: knobUnit.nullable(),\n default: z.number().nullable(),\n note: z.string().optional(),\n }),\n ),\n timers: z.record(z.string(), timer),\n realizes: z.record(z.string(), realization).optional(),\n over: z\n .strictObject({\n machine: z.string(),\n states: z.record(z.string(), z.string()),\n sets: z.record(z.string(), expr),\n ends: z.string(),\n note: z.string().optional(),\n })\n .optional(),\n transitions: z.array(transition),\n /** This map tells what a source shows of the machine: its states as the source names them, and what it hides. */\n observe: z\n .record(\n z.string(),\n z.strictObject({\n states: z.record(z.string(), z.string()),\n hides: z.array(z.string()).optional(),\n fidelity: z.enum([\"complete\", \"sampled\", \"lossy\", \"derived\"]),\n note: z.string().optional(),\n }),\n )\n .optional(),\n generated: z.strictObject({ from: z.string(), by: z.string() }).optional(),\n});\n\n/** This function gives one value or many values as an array. */\nexport const arr = <T>(value: T | readonly T[]): readonly T[] =>\n Array.isArray(value) ? (value as readonly T[]) : [value as T];\n\n/** This function gives the names that a duration reads: its knobs, by the names of the machine, and `fired`. */\nconst exprNames = (e: Expr): string[] => {\n if (\"knob\" in e) return [e.knob];\n if (\"model\" in e) return [...e.knobs];\n if (\"expr\" in e) {\n return (e.expr.match(/[A-Za-z_][A-Za-z0-9_.]*/g) ?? []).filter(\n (word) => ![\"min\", \"max\", \"floor\", \"ceil\"].includes(word),\n );\n }\n return [];\n};\n\n/** This function gives the knobs that a duration reads, by the names of the machine for them. */\nexport const exprKnobs = (e: Expr): string[] => exprNames(e).filter((name) => name !== FIRED);\n\n/** This function tells if a duration reads the number of times that its timer fired, as the waits of a backoff do. */\nexport const readsFired = (e: Expr): boolean => exprNames(e).includes(FIRED);\n\n/** This function gives the states that a transition leaves. The state \"*\" is each state that is not final. */\nexport const fromStates = (m: Machine, from: string | readonly string[]): string[] => {\n const out = new Set<string>();\n for (const state of arr(from)) {\n if (state !== \"*\") out.add(state);\n else for (const [name, def] of Object.entries(m.states)) if (def.final !== true) out.add(name);\n }\n return [...out];\n};\n\n/**\n * This function gives the problems in the consistency of a document. Each state, event, timer and\n * knob that it refers to must exist, and it must have an initial state. A reader refuses a\n * machine with problems, and does not draw half of it.\n */\nexport const machineProblems = (m: Machine): string[] => {\n const problems: string[] = [];\n const states = new Set(Object.keys(m.states));\n if (!Object.values(m.states).some((state) => state.initial === true)) {\n problems.push(\"no initial state\");\n }\n for (const t of m.transitions) {\n for (const from of arr(t.from)) {\n if (from !== \"*\" && !states.has(from)) problems.push(`${t.id}: from ${from}`);\n }\n if (!states.has(t.to)) problems.push(`${t.id}: to ${t.to}`);\n for (const event of arr(t.on))\n if (m.events[event] === undefined) problems.push(`${t.id}: event ${event}`);\n if (t.timer !== undefined && m.timers[t.timer] === undefined) {\n problems.push(`${t.id}: timer ${t.timer}`);\n }\n }\n if (m.knobs[FIRED] !== undefined)\n problems.push(`knob ${FIRED}: the name is a backoff timer's count of its firings`);\n for (const [id, tm] of Object.entries(m.timers)) {\n if (m.events[tm.fires] === undefined) problems.push(`timer ${id}: fires ${tm.fires}`);\n for (const knob of exprKnobs(tm.duration)) {\n const def = m.knobs[knob];\n if (def === undefined) problems.push(`timer ${id}: knob ${knob}`);\n // a duration is an amount, thus a switch or a choice cannot give it\n else if (def.unit === null) problems.push(`timer ${id}: knob ${knob} is not an amount`);\n }\n // only a timer that starts again has a count of its firings to read\n const reads = [tm.duration, tm.lateness, tm.early].some(\n (e) => e !== undefined && readsFired(e),\n );\n if (reads && tm.backoff === undefined)\n problems.push(`timer ${id}: reads ${FIRED}, but has no backoff`);\n for (const event of tm.backoff?.resets ?? [])\n if (!event.startsWith(\"enter:\") && m.events[event] === undefined)\n problems.push(`timer ${id}: backoff resets on ${event}`);\n }\n for (const [mechanism, how] of Object.entries(m.realizes ?? {})) {\n if (\"timer\" in how) {\n // a machine on another machine can realize a timer of the machine below. Only a reader of\n // the two documents can examine that\n if (m.timers[how.timer] === undefined && m.over === undefined)\n problems.push(`realizes ${mechanism}: timer ${how.timer}`);\n continue;\n }\n if ([how.duration, how.lateness, how.early].some((e) => e !== undefined && readsFired(e)))\n problems.push(`realizes ${mechanism}: reads ${FIRED}, which only a backoff timer counts`);\n for (const knob of exprKnobs(how.duration)) {\n const def = m.knobs[knob];\n if (def === undefined) problems.push(`realizes ${mechanism}: knob ${knob}`);\n else if (def.unit === null)\n problems.push(`realizes ${mechanism}: knob ${knob} is not an amount`);\n }\n }\n if (m.over !== undefined) {\n for (const state of Object.keys(m.over.states)) {\n if (!states.has(state)) problems.push(`over: state ${state}`);\n }\n if (m.events[m.over.ends] === undefined) problems.push(`over: ends ${m.over.ends}`);\n for (const [lower, set] of Object.entries(m.over.sets)) {\n if (readsFired(set)) problems.push(`over: sets ${lower} from ${FIRED}, which is no knob`);\n for (const knob of exprKnobs(set)) {\n const def = m.knobs[knob];\n if (def === undefined) problems.push(`over: sets ${lower} from knob ${knob}`);\n else if (def.unit === null) problems.push(`over: sets ${lower} from ${knob}, no amount`);\n }\n }\n }\n for (const [source, view] of Object.entries(m.observe ?? {})) {\n for (const state of Object.values(view.states)) {\n if (!states.has(state)) problems.push(`observe ${source}: ${state}`);\n }\n }\n const ids = m.transitions.map((t) => t.id);\n for (const id of new Set(ids)) {\n if (ids.filter((other) => other === id).length > 1) problems.push(`transition ${id} twice`);\n }\n return problems;\n};\n","import type { Extent, Quantity, Rational, Unknown } from \"@mark1russell7/quantity\";\nimport {\n convertExact,\n isUnbounded,\n quantity,\n rationals as r,\n unbounded,\n} from \"@mark1russell7/quantity\";\nimport type { Expr, Machine, TransitionDef } from \"./machine.ts\";\nimport { FIRED, arr, exprKnobs, fromStates } from \"./machine.ts\";\n\n/**\n * This module has the closed forms of the algebra. They give the duration of a timer of a\n * machine, and how late and how early it can fire, from the values of its knobs.\n *\n * A machine document writes each duration in one of four forms (`machine.ts`): a constant, a knob,\n * arithmetic over its knobs, or a named model. The arithmetic uses the value of each knob in the\n * unit that the document gives to that knob. Thus `tcp_keepalive / 3` of Redis divides whole\n * seconds, as Redis does. A model is the formula of the implementation itself, for example the\n * retransmission budget of the kernel. The values are exact rationals, not floats: 0.2 s × 1023\n * is 204.6 s, not 204.60000000000002.\n *\n * A knob without a value makes the result unknown, and the result names the knob. A knob that\n * nothing sets (no bound) makes a duration without an end.\n */\n\n/** This function gives the value of each knob, by the name of the machine for it: an amount, no bound, or unknown and the reason. */\nexport type KnobValues = (name: string) => Extent | Unknown | undefined;\n\n/** Timer bounds tell how long a timer operates, how late it can fire and how early, each in the unit of its document. */\nexport interface TimerBounds {\n readonly duration: Extent | Unknown;\n readonly lateness?: Extent | Unknown | undefined;\n readonly early?: Extent | Unknown | undefined;\n}\n\n/**\n * A value is an exact rational, no bound, or unknown with its reason. No bound has a sign. A\n * duration is not negative, but a step of the arithmetic can be: cap − ∞ is −∞, and\n * max(cap − ∞, cap / 2) is cap / 2.\n */\ntype Value =\n | { readonly kind: \"exact\"; readonly n: Rational }\n | { readonly kind: \"infinite\"; readonly negative?: true }\n | { readonly kind: \"unknown\"; readonly why: string };\n\nconst exact = (n: Rational): Value => ({ kind: \"exact\", n });\nconst INFINITE: Value = { kind: \"infinite\" };\nconst NEGATIVE_INFINITE: Value = { kind: \"infinite\", negative: true };\n/** This function gives the sign of a value that is not unknown: −1, 0 or 1. */\nconst signOf = (value: Value): number =>\n value.kind === \"infinite\"\n ? value.negative === true\n ? -1\n : 1\n : value.kind === \"exact\"\n ? r.cmp(value.n, r.ZERO)\n : 0;\n/** This function gives no bound with a sign. */\nconst unboundedOf = (sign: number): Value => (sign < 0 ? NEGATIVE_INFINITE : INFINITE);\nconst unknown = (why: string): Value => ({ kind: \"unknown\", why });\nconst whole = (n: bigint): Rational => r.rational(n);\n\n/** This function gives the first unknown among some values. An operation over them gets it. */\nconst unknownOf = (values: readonly Value[]): Value | undefined =>\n values.find((value) => value.kind === \"unknown\");\n\n// ---------------------------------------------------------------------------------------------\n// the arithmetic of the documents: + - * /, min, max, floor, ceil, parentheses, numbers, knob names\n// ---------------------------------------------------------------------------------------------\n\n/** A node is the arithmetic of a document, after the parse. */\nexport type Node =\n | { readonly op: \"num\"; readonly n: Rational }\n | { readonly op: \"knob\"; readonly name: string }\n | { readonly op: \"+\" | \"-\" | \"*\" | \"/\"; readonly a: Node; readonly b: Node }\n | { readonly op: \"neg\"; readonly a: Node }\n | { readonly op: \"min\" | \"max\" | \"floor\" | \"ceil\"; readonly args: readonly Node[] };\n\nconst FUNCTIONS = { min: 2, max: 2, floor: 1, ceil: 1 } as const;\n\n/** This function parses the arithmetic of a document, or it throws an error that tells where the text stops making sense. */\nexport const parseExpr = (text: string): Node => {\n const tokens = text.match(/\\d+(?:\\.\\d+)?|[A-Za-z_][A-Za-z0-9_.]*|[-+*/(),]|\\S/g) ?? [];\n let at = 0;\n const peek = (): string | undefined => tokens[at];\n const take = (expected?: string): string => {\n const token = tokens[at];\n if (token === undefined || (expected !== undefined && token !== expected)) {\n throw new Error(`\"${text}\": expected ${expected ?? \"more\"} at ${token ?? \"the end\"}`);\n }\n at += 1;\n return token;\n };\n const expr = (): Node => {\n let node = term();\n while (peek() === \"+\" || peek() === \"-\") {\n const op = take() as \"+\" | \"-\";\n node = { op, a: node, b: term() };\n }\n return node;\n };\n const term = (): Node => {\n let node = factor();\n while (peek() === \"*\" || peek() === \"/\") {\n const op = take() as \"*\" | \"/\";\n node = { op, a: node, b: factor() };\n }\n return node;\n };\n const factor = (): Node => {\n const token = take();\n if (token === \"(\") {\n const inner = expr();\n take(\")\");\n return inner;\n }\n if (token === \"-\") return { op: \"neg\", a: factor() };\n if (/^\\d/.test(token)) return { op: \"num\", n: r.fromDecimal(token) };\n if (!/^[A-Za-z_]/.test(token)) throw new Error(`\"${text}\": ${token} is not a term`);\n if (token in FUNCTIONS) {\n const name = token as keyof typeof FUNCTIONS;\n take(\"(\");\n const args = [expr()];\n while (peek() === \",\") {\n take(\",\");\n args.push(expr());\n }\n take(\")\");\n if (args.length !== FUNCTIONS[name]) {\n throw new Error(`\"${text}\": ${name} takes ${FUNCTIONS[name]}, not ${args.length}`);\n }\n return { op: name, args };\n }\n return { op: \"knob\", name: token };\n };\n const node = expr();\n if (at < tokens.length) throw new Error(`\"${text}\": ${tokens[at]} after the end`);\n return node;\n};\n\nconst run = (node: Node, valueOf: (name: string) => Value): Value => {\n if (node.op === \"num\") return exact(node.n);\n if (node.op === \"knob\") return valueOf(node.name);\n if (node.op === \"neg\") {\n const a = run(node.a, valueOf);\n return a.kind === \"exact\" ? exact(r.neg(a.n)) : a.kind === \"infinite\" ? unboundedOf(-signOf(a)) : a;\n }\n if (\"args\" in node) {\n const args = node.args.map((arg) => run(arg, valueOf));\n const lost = unknownOf(args);\n if (lost !== undefined) return lost;\n if (node.op === \"floor\" || node.op === \"ceil\") {\n const [a] = args as [Value];\n return a.kind === \"exact\" ? exact(node.op === \"floor\" ? r.floor(a.n) : r.ceil(a.n)) : a;\n }\n const [a, b] = args as [Value, Value];\n if (a.kind === \"infinite\" || b.kind === \"infinite\") {\n // +∞ wins a max and loses a min, and −∞ loses a max and wins a min\n const above = (x: Value, y: Value): boolean =>\n x.kind === \"infinite\" ? signOf(x) > 0 || (y.kind === \"infinite\" && signOf(y) < 0) : signOf(y) < 0;\n const larger = above(a, b) ? a : b;\n const smaller = larger === a ? b : a;\n return node.op === \"max\" ? larger : smaller;\n }\n if (a.kind !== \"exact\" || b.kind !== \"exact\") return unknown(\"not an amount\");\n const aFirst = r.cmp(a.n, b.n) <= 0;\n if (node.op === \"min\") return aFirst ? a : b;\n return aFirst ? b : a;\n }\n const a = run(node.a, valueOf);\n const b = run(node.b, valueOf);\n const lost = unknownOf([a, b]);\n if (lost !== undefined) return lost;\n if (a.kind === \"exact\" && b.kind === \"exact\") {\n if (node.op === \"/\" && b.n.n === 0n) return unknown(\"a division by zero\");\n const op = { \"+\": r.add, \"-\": r.sub, \"*\": r.mul, \"/\": r.div }[node.op];\n return exact(op(a.n, b.n));\n }\n // a timer that nothing sets is longer than each sum, and each positive multiple. Its sign\n // follows the arithmetic: cap − ∞ is −∞, which a max then discards\n if (node.op === \"+\" || node.op === \"-\") {\n const sa = signOf(a);\n const sb = node.op === \"-\" ? -signOf(b) : signOf(b);\n if (a.kind === \"infinite\" && b.kind === \"infinite\" && sa !== sb)\n return unknown(\"no bound less no bound\");\n return unboundedOf(a.kind === \"infinite\" ? sa : sb);\n }\n if (node.op === \"*\") {\n const sign = signOf(a) * signOf(b);\n return sign === 0 ? unknown(\"zero times no bound\") : unboundedOf(sign);\n }\n if (a.kind === \"infinite\" && b.kind === \"infinite\") return unknown(\"no bound over no bound\");\n if (b.kind === \"infinite\") return exact(r.ZERO);\n const sign = signOf(a) * signOf(b);\n return sign === 0 ? unknown(\"no bound over zero\") : unboundedOf(sign);\n};\n\n// ---------------------------------------------------------------------------------------------\n// the named models: the formula of an implementation over its knobs, in seconds\n// ---------------------------------------------------------------------------------------------\n\nconst integer = (value: Rational, what: string): bigint => {\n if (!r.isInteger(value) || value.n < 0n)\n throw new Error(`${what} is not a whole count: ${r.toNumber(value)}`);\n return value.n;\n};\n/** This function gives min(base × 2^k, cap), exactly. */\nconst capped = (base: Rational, k: bigint, cap: Rational): Rational => {\n const doubled = r.mul(base, whole(2n ** k));\n return r.cmp(doubled, cap) <= 0 ? doubled : cap;\n};\n/**\n * This function gives the hypothetical retransmission timeout of the kernel, tcp_model_timeout in\n * net/ipv4/tcp_timer.c. The waits double from the minimum RTO until a step is more than the\n * maximum, and then the waits are capped. For tcp_retries2 = 15, it is 0.2 s × (2^10 − 1) +\n * 6 × 120 s = 924.6 s.\n */\nconst retransBudget = (retries: bigint, min: Rational, max: Rational): Rational => {\n let thresh = 0n;\n while (r.cmp(r.mul(min, whole(2n ** (thresh + 1n))), max) <= 0) thresh += 1n;\n if (retries <= thresh) return r.mul(min, whole(2n ** (retries + 1n) - 1n));\n return r.add(r.mul(min, whole(2n ** (thresh + 1n) - 1n)), r.mul(whole(retries - thresh), max));\n};\n\n/** These are TCP_TIMEOUT_INIT and TCP_RTO_MAX in include/net/tcp.h at v6.6: the first SYN RTO and the cap. */\nconst TCP_TIMEOUT_INIT = whole(1n);\nconst TCP_RTO_MAX = whole(120n);\n\n/** This function gives the whole jiffies of a time at HZ, rounded up, as msecs_to_jiffies and usecs_to_jiffies round. */\nconst jiffiesOf = (seconds: Rational, hz: Rational): bigint => r.ceil(r.mul(seconds, hz)).n;\n\n/**\n * This function gives how late the timer wheel can fire a timer that is due in `jiffies`\n * (calc_wheel_index in kernel/time/timer.c at v6.6). Level 0 holds the timers due in 63 jiffies\n * or less. Each level above holds eight times as long, at eight times the granularity. The wheel\n * rounds a timer up to the next boundary of its level, thus it fires up to one granularity late.\n * At HZ 250, a 2 h timer can be up to 131 s late.\n */\nconst granularity = (jiffies: bigint): bigint => {\n let level = 0n;\n while (level < 8n && jiffies >= 63n << (3n * level)) level += 1n;\n return 8n ** level;\n};\n\n/**\n * This function gives the lateness of the retransmission give-up after its budget. The first\n * retransmission sets the RTO to the round trip plus the minimum, rounded up to a jiffy\n * (tcp_set_rto). On a Docker network at HZ 250, that is 204 ms, not 200.\n *\n * Each firing doubles the RTO, up to the cap. The budget ends in the firing after the last one\n * that is short of it. Thus the give-up comes one step late at most, plus the rounding of each\n * firing on the wheel. The model assumes a steady path, whose variance stays below the minimum RTO.\n */\nconst retransLateness = (\n retries: bigint,\n min: Rational,\n max: Rational,\n rtt: Rational,\n hz: Rational,\n): Rational => {\n const base = jiffiesOf(r.add(min, rtt), hz);\n const cap = jiffiesOf(max, hz);\n let step = base;\n let wheel = 0n;\n for (let k = 1n; k <= retries + 1n; k += 1n) {\n step = base * 2n ** k < cap ? base * 2n ** k : cap;\n wheel += granularity(step);\n }\n return r.div(whole(step + wheel), hz);\n};\n\n/**\n * This function gives one wait of the retransmission timer with one segment in flight, in jiffies\n * (net/ipv4/tcp_timer.c, and tcp_schedule_loss_probe in tcp_output.c, at v6.6). Its first firing\n * is the tail loss probe. For one segment, the probe waits two round trips plus TCP_RTO_MIN, but\n * not longer than the RTO. Thus it waits the RTO itself: the round trip plus the minimum, in whole\n * jiffies.\n *\n * The probe arms the RTO again, and each RTO firing doubles it, up to the cap. Thus the\n * firing k comes 2^k RTOs after the send: 0.204, 0.408, 0.816 s on a Docker network at HZ 250.\n * With more than one segment in flight, the probe waits two round trips plus 2 jiffies.\n */\nconst rtoWait = (fired: bigint, min: Rational, max: Rational, rtt: Rational, hz: Rational) => {\n const base = jiffiesOf(r.add(min, rtt), hz);\n const cap = jiffiesOf(max, hz);\n if (fired === 0n) return base;\n const doubled = base * 2n ** (fired - 1n);\n return doubled < cap ? doubled : cap;\n};\n\n/**\n * This function gives the lateness of keepalive. It adds the idle timer and the interval of each\n * probe, each rounded up on the wheel at its own level. Linux arms the idle timer, then one probe\n * interval for each probe without an answer.\n */\n/**\n * This function gives the lateness of the retransmission give-up after its budget, under an ICMP\n * host or net unreachable for each RTO retransmission. Each ICMP reverts one doubling of the backoff\n * (tcp_ld_RTO_revert in net/ipv4/tcp_ipv4.c at v6.6, RFC 6069). Then each wait after the first RTO\n * firing is one RTO again, thus the give-up comes at most one RTO after the budget. Each firing up\n * to it can fire up to the granularity of its level of the wheel late.\n */\nconst retransLatenessReverted = (\n retries: bigint,\n min: Rational,\n max: Rational,\n rtt: Rational,\n hz: Rational,\n): Rational => {\n const base = jiffiesOf(r.add(min, rtt), hz);\n const budget = jiffiesOf(retransBudget(retries, min, max), hz);\n const firings = (budget + base - 1n) / base + 1n;\n return r.div(whole(base + firings * granularity(base)), hz);\n};\n\nconst keepaliveLateness = (\n idle: Rational,\n interval: Rational,\n probes: bigint,\n hz: Rational,\n): Rational => {\n const late = (time: Rational) => whole(granularity(jiffiesOf(time, hz)));\n return r.div(r.add(late(idle), r.mul(whole(probes), late(interval))), hz);\n};\n\ninterface Model {\n /** These are the knobs that it reads, in sequence, and the unit to read each in (null for a count). */\n readonly knobs: readonly (string | null)[];\n /** This function gives the result in seconds. */\n readonly seconds: (args: readonly Rational[]) => Rational;\n readonly source: string;\n}\n\nconst MODELS: Readonly<Record<string, Model>> = {\n \"linux.retrans-budget\": {\n knobs: [null, \"s\", \"s\"],\n seconds: ([retries, min, max]) => retransBudget(integer(retries!, \"tcp_retries2\"), min!, max!),\n source: \"net/ipv4/tcp_timer.c tcp_model_timeout at v6.6\",\n },\n // the give-up comes at the first RTO firing at the budget or after it: one step later at most,\n // at the real RTO of the path, plus the rounding of each firing on the wheel\n \"linux.retrans-step\": {\n knobs: [null, \"s\", \"s\", \"s\", \"Hz\"],\n seconds: ([retries, min, max, rtt, hz]) =>\n retransLateness(integer(retries!, \"tcp_retries2\"), min!, max!, rtt!, hz!),\n source:\n \"net/ipv4/tcp_timer.c, tcp_input.c tcp_set_rto and kernel/time/timer.c at v6.6 (measured by @mark1russell7/harness, 2026-10-08)\",\n },\n // one wait of the retransmission timer, the first of the loss probe: 2^(fired − 1) RTOs after it\n \"linux.rto-wait\": {\n knobs: [null, \"s\", \"s\", \"s\", \"Hz\"],\n seconds: ([fired, min, max, rtt, hz]) =>\n r.div(whole(rtoWait(integer(fired!, FIRED), min!, max!, rtt!, hz!)), hz!),\n source:\n \"net/ipv4/tcp_timer.c tcp_retransmit_timer and tcp_output.c tcp_schedule_loss_probe at v6.6 (measured by @mark1russell7/harness, 2026-10-12)\",\n },\n // one wait of the retransmission timer when each RTO retransmission draws an ICMP host or net\n // unreachable: the revert of RFC 6069 takes back the doubling, thus each wait is one RTO\n \"linux.rto-wait-reverted\": {\n knobs: [null, \"s\", \"s\", \"s\", \"Hz\"],\n seconds: ([, min, , rtt, hz]) => r.div(whole(jiffiesOf(r.add(min!, rtt!), hz!)), hz!),\n source: \"net/ipv4/tcp_ipv4.c tcp_v4_err and tcp_ld_RTO_revert at v6.6 (RFC 6069)\",\n },\n // the give-up under that revert: at most one RTO after its budget, plus the rounding of each firing\n \"linux.retrans-step-reverted\": {\n knobs: [null, \"s\", \"s\", \"s\", \"Hz\"],\n seconds: ([retries, min, max, rtt, hz]) =>\n retransLatenessReverted(integer(retries!, \"tcp_retries2\"), min!, max!, rtt!, hz!),\n source:\n \"net/ipv4/tcp_ipv4.c tcp_ld_RTO_revert and net/ipv4/tcp_timer.c retransmits_timed_out at v6.6 (RFC 6069)\",\n },\n // the rounding of that wait on the timer wheel, at the level that its length puts it in\n \"linux.rto-wait-lateness\": {\n knobs: [null, \"s\", \"s\", \"s\", \"Hz\"],\n seconds: ([fired, min, max, rtt, hz]) =>\n r.div(whole(granularity(rtoWait(integer(fired!, FIRED), min!, max!, rtt!, hz!))), hz!),\n source: \"kernel/time/timer.c calc_wheel_index at v6.6\",\n },\n // the idle timer of keepalive and the interval of each probe, each rounded on the wheel\n \"linux.keepalive-lateness\": {\n knobs: [\"s\", \"s\", null, \"Hz\"],\n seconds: ([idle, interval, probes, hz]) =>\n keepaliveLateness(idle!, interval!, integer(probes!, \"keepcnt\"), hz!),\n source: \"net/ipv4/tcp_timer.c tcp_keepalive_timer and kernel/time/timer.c at v6.6\",\n },\n // the rounding of one firing on the wheel: how late one timer due after this time can fire\n \"linux.wheel\": {\n knobs: [\"s\", \"Hz\"],\n seconds: ([time, hz]) => r.div(whole(granularity(jiffiesOf(time!, hz!))), hz!),\n source: \"kernel/time/timer.c calc_wheel_index at v6.6\",\n },\n // one jiffy: a timer counts from the tick before the event that arms it\n \"linux.jiffy\": {\n knobs: [\"Hz\"],\n seconds: ([hz]) => r.div(whole(1n), hz!),\n source: \"include/linux/jiffies.h\",\n },\n // 6.5 and later: the first tcp_syn_linear_timeouts retransmissions wait the initial RTO, the\n // others double it, and the SYN gives up after syn_retries + linear_timeouts retransmissions\n \"linux.syn-giveup\": {\n knobs: [null, null],\n seconds: ([retries, linear]) => {\n const n = integer(retries!, \"tcp_syn_retries\");\n let total = r.mul(whole(integer(linear!, \"tcp_syn_linear_timeouts\") + 1n), TCP_TIMEOUT_INIT);\n for (let i = 1n; i <= n; i += 1n)\n total = r.add(total, capped(TCP_TIMEOUT_INIT, i, TCP_RTO_MAX));\n return total;\n },\n source:\n \"net/ipv4/tcp_timer.c tcp_write_timeout and Documentation/networking/ip-sysctl.rst at v6.6\",\n },\n // the default retryStrategy of ioredis 6: min(2^(times - 1) × 50, 5000) ms, plus a jitter of up\n // to 199 ms, which the lateness of the timer carries. Its times counts attempts from 1 after the\n // last ready, thus it is one more than the number of firings of the timer. 5.x waited\n // min(times × 50, 2000) ms\n \"ioredis.retry-base\": {\n knobs: [null],\n seconds: ([fired]) => capped(r.fromDecimal(\"0.05\"), integer(fired!, FIRED), whole(5n)),\n source:\n \"ioredis 6.0.0 built/redis/RedisOptions.js retryStrategy and built/redis/event_handler.js\",\n },\n};\n\n// ---------------------------------------------------------------------------------------------\n// the evaluation of a duration and a timer\n// ---------------------------------------------------------------------------------------------\n\n/**\n * This function gives the value of a knob in the unit that the document gives it (or as a count\n * when it is a count). For `fired`, it gives which wait of a backoff timer it is.\n */\nconst knobIn = (\n doc: Machine,\n name: string,\n unit: string | null,\n values: KnobValues,\n fired: number | undefined,\n): Value => {\n if (name === FIRED)\n return fired === undefined\n ? unknown(\"one wait of a timer with a backoff: say which, by how many times it has fired\")\n : exact(r.fromNumber(fired));\n if (doc.knobs[name] === undefined) return unknown(`the machine names no knob ${name}`);\n const given = values(name);\n if (given === undefined) return unknown(`nothing gives ${name}'s value`);\n if (\"unknown\" in given) return unknown(`${name}: ${given.unknown}`);\n if (given.value === \"infinite\") return INFINITE;\n const value = r.fromNumber(given.value);\n return exact(\n unit === null\n ? convertExact(value, given.unit, given.unit)\n : convertExact(value, given.unit, unit),\n );\n};\n\nconst out = (value: Value, unit: string): Extent | Unknown =>\n value.kind === \"exact\"\n ? quantity(r.toNumber(value.n), unit)\n : value.kind === \"infinite\"\n ? value.negative === true\n ? { unknown: \"a negative unbounded time\", unit }\n : unbounded(unit)\n : { unknown: value.why, unit };\n\n/**\n * This function evaluates one duration of a timer of a machine, in the unit that its document\n * gives it. The waits of a backoff timer read `fired`, which tells which wait.\n */\nexport const evaluate = (\n doc: Machine,\n expr: Expr,\n values: KnobValues,\n fired?: number,\n): Extent | Unknown => {\n if (\"const\" in expr) return quantity(expr.const, expr.unit);\n if (\"knob\" in expr) {\n return out(knobIn(doc, expr.knob, expr.unit, values, fired), expr.unit);\n }\n if (\"expr\" in expr) {\n const tree = parseExpr(expr.expr);\n const value = run(tree, (name) =>\n knobIn(doc, name, doc.knobs[name]?.unit ?? null, values, fired),\n );\n return out(value, expr.unit);\n }\n const model = MODELS[expr.model];\n if (model === undefined) return { unknown: `no model ${expr.model}`, unit: expr.unit };\n if (model.knobs.length !== expr.knobs.length) {\n return {\n unknown: `${expr.model} reads ${model.knobs.length} knobs, not ${expr.knobs.length}`,\n unit: expr.unit,\n };\n }\n const args = expr.knobs.map((name, index) =>\n knobIn(doc, name, model.knobs[index] ?? null, values, fired),\n );\n const lost = unknownOf(args);\n if (lost !== undefined) return out(lost, expr.unit);\n if (args.some((arg) => arg.kind === \"infinite\")) return unbounded(expr.unit);\n const seconds = model.seconds(args.map((arg) => (arg as { n: Rational }).n));\n return quantity(r.toNumber(convertExact(seconds, \"s\", expr.unit)), expr.unit);\n};\n\n/**\n * This function gives the bounds of a timer of a machine: how long it operates, how late it can\n * fire, how early. For a backoff timer, it gives one of its waits: the wait after `fired` firings.\n */\nexport const timerOf = (\n doc: Machine,\n timer: string,\n values: KnobValues,\n fired?: number,\n): TimerBounds => {\n const def = doc.timers[timer];\n if (def === undefined) throw new Error(`${doc.title} has no timer ${timer}`);\n return {\n duration: evaluate(doc, def.duration, values, fired),\n ...(def.lateness !== undefined ? { lateness: evaluate(doc, def.lateness, values, fired) } : {}),\n ...(def.early !== undefined ? { early: evaluate(doc, def.early, values, fired) } : {}),\n };\n};\n\n/** A firing is one firing of a backoff timer, after `fired` firings: its time from the arming. */\nexport interface Firing {\n readonly fired: number;\n /** This time is the sum of the waits to this firing, each less how early it can fire. */\n readonly low: Quantity;\n /** This time is the sum of the waits to this firing, each plus how late it can fire. */\n readonly high: Quantity;\n}\n\n/** A recovery tells when the firings of a backoff timer move a connection again after a stall. */\nexport interface Recovery {\n /** These are its firings from its arming, up to the first one that surely comes after the end of the stall. */\n readonly firings: readonly Firing[];\n /**\n * These are the firings that can be the first after the end of the stall. There is more than one\n * when the end falls in the bounds of a firing: that firing can come before the end or after it.\n */\n readonly first: readonly number[];\n /** This time is the earliest time of the first firing after the end of the stall, from the arming. */\n readonly low: Quantity;\n /** This time is the latest time of that firing, from the arming. */\n readonly high: Quantity;\n}\n\n/** This count is the most firings that `recovery` examines before it tells that the stall is longer than them. */\nconst FIRINGS = 4096;\n\n/**\n * This function gives the recovery from a stall. A backoff timer continues to fire through a\n * stall, and what each firing sends gets through only after the stall ends. Thus the connection\n * moves again at the first firing at the end or after it. That firing can be most of a wait after\n * the end. A stall that stops immediately after one firing costs almost all of the next, longer\n * wait.\n *\n * The stall counts from the arming of the timer, which is the send that the stall first lost. The\n * waits add, and so do how early and how late each can fire.\n */\nexport const recovery = (\n doc: Machine,\n timer: string,\n values: KnobValues,\n stall: Extent,\n): Recovery | Unknown => {\n const def = doc.timers[timer];\n if (def === undefined) throw new Error(`${doc.title} has no timer ${timer}`);\n if (def.backoff === undefined) throw new Error(`${doc.title}'s ${timer} has no backoff`);\n if (isUnbounded(stall))\n return { unknown: \"a stall that never ends: nothing recovers from it\", unit: \"s\" };\n const end = convertExact(r.fromNumber(stall.value), stall.unit, \"s\");\n const inSeconds = (extent: Extent | Unknown | undefined, what: string): Rational | string => {\n if (extent === undefined) return r.ZERO;\n if (\"unknown\" in extent) return `${what}: ${extent.unknown}`;\n if (isUnbounded(extent)) return `${what} has no bound, so the timer never fires again`;\n return convertExact(r.fromNumber(extent.value), extent.unit, \"s\");\n };\n const s = (value: Rational): Quantity => quantity(r.toNumber(value), \"s\");\n const sums: Array<{ fired: number; low: Rational; high: Rational }> = [];\n let low = r.ZERO;\n let high = r.ZERO;\n for (let fired = 0; fired < FIRINGS; fired += 1) {\n const bounds = timerOf(doc, timer, values, fired);\n const wait = inSeconds(bounds.duration, `wait ${fired}`);\n const early = inSeconds(bounds.early, `wait ${fired}'s early bound`);\n const late = inSeconds(bounds.lateness, `wait ${fired}'s lateness`);\n if (typeof wait === \"string\") return { unknown: wait, unit: \"s\" };\n if (typeof early === \"string\") return { unknown: early, unit: \"s\" };\n if (typeof late === \"string\") return { unknown: late, unit: \"s\" };\n low = r.add(low, r.sub(wait, early));\n high = r.add(high, r.add(wait, late));\n sums.push({ fired, low, high });\n if (r.cmp(low, end) < 0) continue;\n // a firing whose latest time is at the end or after it can be the first after the end\n const first = sums.filter((f) => r.cmp(f.high, end) >= 0);\n const earliest = first[0]!.low;\n return {\n firings: sums.map((f) => ({ fired: f.fired, low: s(f.low), high: s(f.high) })),\n first: first.map((f) => f.fired),\n low: s(r.cmp(earliest, end) >= 0 ? earliest : end),\n high: s(first.at(-1)!.high),\n };\n }\n return { unknown: `${FIRINGS} firings do not outlast the stall`, unit: \"s\" };\n};\n\n/**\n * This function gives how long a mechanism takes where a machine operates, from the realization\n * of its document. The realization is one of its timers, whole, or its own duration, lateness and\n * early bound over the knobs of the machine. It gives undefined when the document does not realize the mechanism.\n */\nexport const realizationOf = (\n doc: Machine,\n mechanism: string,\n values: KnobValues,\n): TimerBounds | undefined => {\n const how = doc.realizes?.[mechanism];\n if (how === undefined) return undefined;\n if (\"timer\" in how) return timerOf(doc, how.timer, values);\n return {\n duration: evaluate(doc, how.duration, values),\n ...(how.lateness !== undefined ? { lateness: evaluate(doc, how.lateness, values) } : {}),\n ...(how.early !== undefined ? { early: evaluate(doc, how.early, values) } : {}),\n };\n};\n\n/** This function gives the knobs that a realization reads, by the names of the machine for them. */\nexport const realizationKnobs = (doc: Machine, mechanism: string): string[] => {\n const how = doc.realizes?.[mechanism];\n if (how === undefined) return [];\n const def = \"timer\" in how ? doc.timers[how.timer] : how;\n if (def === undefined) return [];\n return [\n ...new Set(\n [def.duration, def.lateness, def.early].flatMap((e) => (e === undefined ? [] : exprKnobs(e))),\n ),\n ];\n};\n\n/** This function gives what in a document the algebra cannot read: arithmetic that does not parse, or a model that it does not have. */\nexport const algebraProblems = (doc: Machine): string[] => {\n const problems: string[] = [];\n const read = (where: string, exprs: ReadonlyArray<Expr | undefined>) => {\n for (const expr of exprs) {\n if (expr === undefined) continue;\n if (\"expr\" in expr) {\n try {\n parseExpr(expr.expr);\n } catch (error) {\n problems.push(`${where}: ${(error as Error).message}`);\n }\n }\n if (\"model\" in expr && MODELS[expr.model] === undefined)\n problems.push(`${where}: no model ${expr.model}`);\n }\n };\n for (const [id, def] of Object.entries(doc.timers)) {\n read(`timer ${id}`, [def.duration, def.lateness, def.early]);\n }\n for (const [mechanism, how] of Object.entries(doc.realizes ?? {})) {\n if (!(\"timer\" in how)) read(`realizes ${mechanism}`, [how.duration, how.lateness, how.early]);\n }\n for (const [lower, set] of Object.entries(doc.over?.sets ?? {}))\n read(`over sets ${lower}`, [set]);\n return problems;\n};\n\n/** This function gives the source of the formula of a named model, for a reader of a result. */\nexport const modelSource = (name: string): string | undefined => MODELS[name]?.source;\n\n// ---------------------------------------------------------------------------------------------\n// detection: the minimum over the detectors that are live in what the connection was doing\n// ---------------------------------------------------------------------------------------------\n\n/**\n * A manifestation is what a failure lets back to the machine: the incoming events that continue\n * to arrive while it lasts. A black hole lets nothing back. The kernel of a frozen process\n * continues to acknowledge what it gets and to answer keepalive probes, thus its ACKs continue to\n * arrive.\n */\nexport interface Manifestation {\n readonly name: string;\n readonly passes: readonly string[];\n /**\n * These are the events that the failure itself sends one time, for example the FIN of a process\n * that stopped with SIGKILL. A delivered event that a transition takes from the state of the connection detects the\n * failure at once.\n */\n readonly delivers?: readonly string[] | undefined;\n /**\n * This errno replaces ETIMEDOUT when one of these timers gives up. Linux keeps an ICMP error on\n * an established socket as a soft error, and the timeout reports it (tcp_write_err). An ICMP\n * counts only when it quotes a segment in the window (tcp_v4_err). A retransmission is in the\n * window. A keepalive probe uses the sequence number before snd_una, thus its ICMP does not count.\n */\n readonly errno?: { readonly errno: string; readonly timers: readonly string[] } | undefined;\n /**\n * These are the durations that the failure changes, by timer. For example, an ICMP host\n * unreachable for each retransmission reverts the backoff of the retransmission timer.\n */\n readonly replaces?:\n | Readonly<\n Record<string, { readonly duration?: Expr; readonly lateness?: Expr; readonly early?: Expr }>\n >\n | undefined;\n}\n\n/** A situation is the activity of the connection when the failure started. */\nexport interface Situation {\n /** This name is the state of the machine, for example ESTABLISHED. */\n readonly state: string;\n /** This flag tells if it had sent data that the peer had not acknowledged. */\n readonly inFlight: boolean;\n}\n\n/** A detector is a timer that can still fire, how long it operates, and the event that it fires. */\nexport interface Detector {\n readonly timer: string;\n readonly fires: string;\n readonly duration: Extent | Unknown;\n /** This identifier is the machine below whose timer it is, when the timer is not of the machine itself (`over`). */\n readonly beneath?: string | undefined;\n}\n\n/** A detection is the result of the minimum over the live detectors. */\nexport interface Detection {\n /** These are the timers that can still fire, the soonest first. */\n readonly detectors: readonly Detector[];\n /** This detector is the first to fire, or null when none can fire in a known time: a silent failure. */\n readonly first: Detector | null;\n /** These are the live detectors whose time nothing gives. Then `first` is only an upper bound. */\n readonly unsettled: readonly string[];\n /** These are the timers that are armed but cannot fire, and the reason for each. */\n readonly held: ReadonlyArray<{ readonly timer: string; readonly why: string }>;\n /**\n * These are the events that the failure delivers and that a transition takes from the state:\n * each detects the failure at once, before any timer. The errno is the errno of the transition,\n * or null for an end of file.\n */\n readonly delivered: ReadonlyArray<{\n readonly event: string;\n readonly to: string;\n readonly errno: string | null;\n }>;\n}\n\nconst soonest = (a: Detector, b: Detector): number => {\n const rank = (d: Detector): number =>\n \"unknown\" in d.duration ? 2 : d.duration.value === \"infinite\" ? 1 : 0;\n if (rank(a) !== rank(b)) return rank(a) - rank(b);\n if (rank(a) !== 0) return a.timer.localeCompare(b.timer);\n const seconds = (d: Detector) => {\n const value = d.duration as Extent & { value: number };\n return r.toNumber(convertExact(r.fromNumber(value.value), value.unit, \"s\"));\n };\n return seconds(a) - seconds(b) || a.timer.localeCompare(b.timer);\n};\n\n/**\n * This function gives the detection: the minimum over the detectors that are live in the\n * situation. The entry to the state arms a timer, and so does what the failure causes: data in\n * flight without an acknowledgment gets a retransmission. An event that occurs cancels a timer.\n *\n * An event that arms the timer again, and that the failure continues to let through, stops it\n * before it fires. For example, the kernel of a frozen process answers each keepalive probe.\n * Without a live detector, the failure is silent at the level of this machine. Only something\n * above it, the timeout of an application or a heartbeat, can find it. The result is only as good\n * as the events that the document names.\n */\nexport const detection = (\n doc: Machine,\n situation: Situation,\n manifestation: Manifestation,\n values: KnobValues,\n): Detection => {\n const passes = new Set(manifestation.passes);\n const happened = new Set([`enter:${situation.state}`]);\n if (situation.inFlight && !passes.has(\"rx.ack\")) happened.add(\"tx.retransmit.first\");\n const occurs = (event: string): boolean => happened.has(event) || passes.has(event);\n const detectors: Detector[] = [];\n const held: Array<{ timer: string; why: string }> = [];\n for (const [timer, def] of Object.entries(doc.timers)) {\n // a backoff timer starts again when it fires: its firing is a new try of the machine, and\n // another timer gives up on it, as the retransmission give-up does\n if (def.backoff !== undefined) continue;\n if (!def.arms.some(occurs)) continue;\n const cancelled = (def.cancels ?? []).find(occurs);\n if (cancelled !== undefined) {\n held.push({ timer, why: `${cancelled} cancels it` });\n continue;\n }\n const rearmed = def.arms.find((event) => passes.has(event));\n if (rearmed !== undefined) {\n held.push({ timer, why: `${rearmed} keeps arriving and re-arms it` });\n continue;\n }\n const duration = manifestation.replaces?.[timer]?.duration ?? def.duration;\n detectors.push({ timer, fires: def.fires, duration: evaluate(doc, duration, values) });\n }\n detectors.sort(soonest);\n const [earliest] = detectors;\n const finite =\n earliest !== undefined &&\n !(\"unknown\" in earliest.duration) &&\n earliest.duration.value !== \"infinite\";\n const delivered = (manifestation.delivers ?? []).flatMap((event) => {\n const taken = transitionOn(doc, situation.state, event);\n return taken === undefined ? [] : [{ event, to: taken.to, errno: taken.errno ?? null }];\n });\n return {\n detectors,\n first: finite ? earliest : null,\n unsettled: detectors.filter((d) => \"unknown\" in d.duration).map((d) => d.timer),\n held,\n delivered,\n };\n};\n\n/**\n * This function gives the bounds of a timer of a machine under a failure: its own bounds, with each\n * duration that the manifestation replaces.\n */\nexport const timerUnder = (\n doc: Machine,\n timer: string,\n values: KnobValues,\n manifestation: Manifestation,\n fired?: number,\n): TimerBounds => {\n const def = doc.timers[timer];\n if (def === undefined) throw new Error(`${doc.title} has no timer ${timer}`);\n const replaced = manifestation.replaces?.[timer];\n const duration = replaced?.duration ?? def.duration;\n const lateness = replaced?.lateness ?? def.lateness;\n const early = replaced?.early ?? def.early;\n return {\n duration: evaluate(doc, duration, values, fired),\n ...(lateness !== undefined ? { lateness: evaluate(doc, lateness, values, fired) } : {}),\n ...(early !== undefined ? { early: evaluate(doc, early, values, fired) } : {}),\n };\n};\n\n/**\n * This function gives the errno of a detection by a timer: the errno of the transition that its\n * event takes from the state. A soft error of the manifestation replaces ETIMEDOUT, but only for\n * the timers whose segments its ICMP quotes in the window.\n */\nexport const errnoOf = (\n doc: Machine,\n state: string,\n detector: { readonly timer: string; readonly fires: string },\n manifestation: Manifestation,\n): string | null => {\n const errno = transitionOn(doc, state, detector.fires)?.errno ?? null;\n const soft = manifestation.errno;\n return errno === \"ETIMEDOUT\" && soft !== undefined && soft.timers.includes(detector.timer)\n ? soft.errno\n : errno;\n};\n\n// ---------------------------------------------------------------------------------------------\n// a machine on another machine: a driver on its kernel socket\n// ---------------------------------------------------------------------------------------------\n\n/** This function gives the transition that a machine takes from a state on an event, by its document. */\nexport const transitionOn = (\n doc: Machine,\n state: string,\n event: string,\n): TransitionDef | undefined =>\n doc.transitions.find((t) => fromStates(doc, t.from).includes(state) && arr(t.on).includes(event));\n\n/**\n * This function gives the values of a machine for the machine that it operates on. These are the\n * knobs that it sets, evaluated over its own knobs, and the other knobs of the lower machine. The\n * keepAlive of ioredis at 5000 ms is the keepidle of the kernel at 5 s.\n */\nexport const overValues =\n (upper: Machine, upperValues: KnobValues, lowerValues: KnobValues): KnobValues =>\n (name) => {\n const set = upper.over?.sets[name];\n return set === undefined ? lowerValues(name) : evaluate(upper, set, upperValues);\n };\n\n/**\n * This function gives the detection through the machine that a machine operates on. The detectors\n * of the lower machine are live in the state below the state of this machine. They use the knobs\n * that this machine sets.\n *\n * Each one reaches this machine as the event that the end of the lower\n * machine gives. They are beside the timers of this machine, and the first of all of them is the\n * first detection. A failure lets nothing new through to a machine above the socket, only the end\n * of the socket. Thus the timers of this machine see only what its state arms.\n */\nexport const stackedDetection = (\n upper: Machine,\n lower: Machine,\n situation: Situation,\n manifestation: Manifestation,\n upperValues: KnobValues,\n lowerValues: KnobValues,\n): Detection => {\n const over = upper.over;\n if (over === undefined) throw new Error(`${upper.title} runs on no other machine`);\n const sitsOn = over.states[situation.state];\n if (sitsOn === undefined) {\n throw new Error(`${upper.title}'s ${situation.state} sits on no state of ${lower.title}`);\n }\n const own = detection(upper, situation, { name: manifestation.name, passes: [] }, upperValues);\n const below = detection(\n lower,\n { ...situation, state: sitsOn },\n manifestation,\n overValues(upper, upperValues, lowerValues),\n );\n const detectors = [\n ...own.detectors,\n ...below.detectors.map((d) => ({ ...d, beneath: over.machine })),\n ].sort(soonest);\n const [earliest] = detectors;\n const finite =\n earliest !== undefined &&\n !(\"unknown\" in earliest.duration) &&\n earliest.duration.value !== \"infinite\";\n return {\n detectors,\n first: finite ? earliest : null,\n unsettled: detectors.filter((d) => \"unknown\" in d.duration).map((d) => d.timer),\n held: [...own.held, ...below.held.map((h) => ({ ...h, why: `${h.why}, beneath` }))],\n // what the failure delivers reaches the socket below: its end is the end of this machine\n delivered: below.delivered,\n };\n};\n"],"mappings":";;;;;;;AA8CA,MAAa,QAAQ;AA8HrB,MAAM,OAAO,WAAW,CAAC,QAAQ,OAAO,CAAC;AAEzC,MAAM,WAAW,WAAW;CAAC;CAAQ;CAAS;AAAW,CAAC;AAE1D,MAAM,OAAwB,EAAE,MAAM;CACpC,EAAE,aAAa;EAAE,OAAO,EAAE,OAAO;EAAG;CAAK,CAAC;CAC1C,EAAE,aAAa;EAAE,MAAM,EAAE,OAAO;EAAG;CAAK,CAAC;CACzC,EAAE,aAAa;EAAE,MAAM,EAAE,OAAO;EAAG;CAAK,CAAC;CACzC,EAAE,aAAa;EAAE,OAAO,EAAE,OAAO;EAAG,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC;EAAG;CAAK,CAAC;AACxE,CAAC;AAED,MAAM,QAAQ,EAAE,aAAa;CAC3B,UAAU;;CAEV,UAAU,KAAK,SAAS;;CAExB,OAAO,KAAK,SAAS;;CAErB,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC;CACxB,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;;CAEtC,OAAO,EAAE,OAAO;;CAEhB,SAAS,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS;CAClE,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS;AAC5B,CAAC;AAED,MAAM,cAAsC,EAAE,MAAM,CAClD,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,GACpC,EAAE,aAAa;CACb,UAAU;CACV,UAAU,KAAK,SAAS;CACxB,OAAO,K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ACjF;;;;;;;;;;;AAYF,MAAa,oBACX,OACA,OACA,WACA,eACA,aACA,gBACc;CACd,MAAM,OAAO,MAAM;CACnB,IAAI,SAAS,KAAA,GAAW,MAAM,IAAI,MAAM,GAAG,MAAM,MAAM,0BAA0B;CACjF,MAAM,SAAS,KAAK,OAAO,UAAU;CACrC,IAAI,WAAW,KAAA,GACb,MAAM,IAAI,MAAM,GAAG,MAAM,MAAM,KAAK,UAAU,MAAM,uBAAuB,MAAM,OAAO;CAE1F,MAAM,MAAM,UAAU,OAAO,WAAW;EAAE,MAAM,cAAc;EAAM,QAAQ,CAAC;CAAE,GAAG,WAAW;CAC7F,MAAM,QAAQ,UACZ,OACA;EAAE,GAAG;EAAW,OAAO;CAAO,GAC9B,eACA,WAAW,OAAO,aAAa,WAAW,CAC5C;CACA,MAAM,YAAY,CAChB,GAAG,IAAI,WACP,GAAG,MAAM,UAAU,KAAK,OAAO;EAAE,GAAG;EAAG,SAAS,KAAK;CAAQ,EAAE,CACjE,CAAC,CAAC,KAAK,OAAO;CACd,MAAM,CAAC,YAAY;CAKnB,OAAO;EACL;EACA,OALA,aAAa,KAAA,KACb,EAAE,aAAa,SAAS,aACxB,SAAS,SAAS,UAAU,aAGZ,WAAW;EAC3B,WAAW,UAAU,QAAQ,MAAM,aAAa,EAAE,QAAQ,CAAC,CAAC,KAAK,MAAM,EAAE,KAAK;EAC9E,MAAM,CAAC,GAAG,IAAI,MAAM,GAAG,MAAM,KAAK,KAAK,OAAO;GAAE,GAAG;GAAG,KAAK,GAAG,EAAE,IAAI;EAAW,EAAE,CAAC;EAElF,WAAW,MAAM;CACnB;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/algebra",
4
- "version": "0.1.0",
4
+ "version": "0.3.0",
5
5
  "description": "State machines as data, and the timer algebra over them: closed forms for a machine's timers in exact rationals, detection as the first live timer, and recovery after a stall.",
6
6
  "keywords": [
7
7
  "state-machine",