@mark1russell7/algebra 0.4.0 → 0.5.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
@@ -36,6 +36,22 @@ A machine document has the format `mark1russell7.machine/1`, and `machineSchema`
36
36
  - the durations that the failure changes, by timer (`replaces`). `timerUnder` gives the bounds of a timer under the failure.
37
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.
38
38
 
39
+ ## The replay
40
+
41
+ `replay(doc, trace, options)` replays a trace against a machine document, and gives each disagreement. A trace is a list of transitions. Each transition has an instance, the state that it leaves, an event and the state that it enters.
42
+
43
+ - **Each instance on its own.** Each instance starts in the state that its first transition leaves. Each transition must leave the state where the replay of its instance is.
44
+ - **The document permits each transition.** The document must have a transition from that state, on that event, to that state. The state `"*"` is each state that is not final.
45
+ - **Open names.** Each program names its own machines, states and events. `options.machine` selects the transitions of one machine in a trace of many machines.
46
+ - **A small entry.** `@mark1russell7/algebra/replay` gives only the replay, in less than 0.5 kB of gzip. It does not import zod, thus a client in a browser can replay its own transitions.
47
+
48
+ ```ts
49
+ import { replay } from "@mark1russell7/algebra/replay";
50
+
51
+ const problems = replay(CONNECTION_MACHINE, recorded, { machine: CONNECTION_MACHINE.id });
52
+ // for example ["c1: app.machine.connection has no transition from OPEN on open to OPEN"]
53
+ ```
54
+
39
55
  ## Installation
40
56
 
41
57
  ```sh
@@ -65,6 +81,6 @@ detection(tcp, idle, { name: "blackhole", passes: [] }, values).first?.timer; //
65
81
 
66
82
  ## Tests
67
83
 
68
- `pnpm --filter @mark1russell7/algebra test` starts the tests. Four machine documents are their fixtures: Linux TCP, conntrack TCP, the Redis server and ioredis. The tests compute the defaults of Linux 6.6 and the rounding of the timer wheel. They also compute the scaled cells of the harness, the backoff waits, recovery after a stall, and detection for each fault.
84
+ `pnpm --filter @mark1russell7/algebra test` starts the tests. Four machine documents are their fixtures: Linux TCP, conntrack TCP, the Redis server and ioredis. The tests compute the defaults of Linux 6.6 and the rounding of the timer wheel. They also compute the scaled cells of the harness, the backoff waits, recovery after a stall, and detection for each fault. The replay tests use a machine with its own names, and they hold the entry of the replay without zod.
69
85
 
70
86
  `pnpm --filter @mark1russell7/algebra build` writes the package for npm into `build/`.
package/build/index.d.ts CHANGED
@@ -1,169 +1,5 @@
1
- import { z } from "zod";
1
+ import { _ as readsFired, a as Expr, c as Over, d as TransitionDef, f as Unit, g as machineSchema, h as machineProblems, i as replay, l as Realization, m as exprKnobs, n as Replayable, o as FIRED, p as Vantage, r as Transition, s as Machine, t as ReplayOptions, u as Timer, v as arr, y as fromStates } from "./replay-rLMi4IqH.js";
2
2
  import { Extent, Quantity, Rational, Unknown } from "@mark1russell7/quantity";
3
- //#region src/machine.d.ts
4
- /**
5
- * `mark1russell7.machine/1` is a state machine as data.
6
- *
7
- * One document describes one machine, and three readers share it: the conformance checker
8
- * (states, transitions, observer mappings), the algebra (the closed forms of timers over knobs)
9
- * and the simulator (the arm, cancel and fire events of timers). The format is small on purpose:
10
- * no hierarchy, no actions other than `emits`, and guards as documented text.
11
- */
12
- /** A unit is a unit that @mark1russell7/quantity stores: a time or a count, which is all that the timers of a machine read. */
13
- type Unit = string;
14
- /** An expression is a duration: a constant, a knob, arithmetic over knobs, or a named model of them. */
15
- type Expr = {
16
- readonly const: number;
17
- readonly unit: Unit;
18
- } | {
19
- readonly knob: string;
20
- readonly unit: Unit;
21
- } | {
22
- readonly expr: string;
23
- readonly unit: Unit;
24
- } | {
25
- readonly model: string;
26
- readonly knobs: readonly string[];
27
- readonly unit: Unit;
28
- };
29
- /** A timer has a duration, the events that arm and cancel it, and the event that it fires. */
30
- interface Timer {
31
- readonly duration: Expr;
32
- readonly lateness?: Expr | undefined;
33
- readonly early?: Expr | undefined;
34
- readonly arms: readonly string[];
35
- readonly cancels?: readonly string[] | undefined;
36
- readonly fires: string;
37
- /**
38
- * A backoff timer starts again after it fires, and each wait is longer than the last. Examples
39
- * are the retransmission timer of the kernel and the reconnect of a driver. Its duration, lateness and
40
- * early bound are those of one wait. They can read `fired`: the number of times that it fired
41
- * after the last of its `resets`.
42
- */
43
- readonly backoff?: {
44
- readonly resets: readonly string[];
45
- } | undefined;
46
- readonly note?: string | undefined;
47
- }
48
- /**
49
- * This name is what the waits of a backoff timer read for the number of times that it fired after
50
- * a reset, from 0. It is not a knob, because nothing sets it. It is the count of the timer itself.
51
- */
52
- export declare const FIRED = "fired";
53
- /**
54
- * A realization tells how long a mechanism takes where the machine operates. It is one of the
55
- * timers of the machine, whole, or a time of its own over the knobs of the machine. It has a
56
- * lateness and an early bound, as a timer has. The idle refresh of the Redis server is the idle
57
- * time of its keepalive, rounded on the timer wheel of the kernel. That is the first firing of its
58
- * keepalive timer, not the whole timer.
59
- */
60
- type Realization = {
61
- readonly timer: string;
62
- } | {
63
- readonly duration: Expr;
64
- readonly lateness?: Expr | undefined;
65
- readonly early?: Expr | undefined;
66
- readonly note?: string | undefined;
67
- };
68
- /**
69
- * An over tells the machine that this machine operates on, and how: a driver on its kernel socket.
70
- * Each state of this machine is on a state of the lower machine. Some knobs of this machine set
71
- * knobs of the lower machine. The end of the lower machine arrives as an event of this machine.
72
- *
73
- * The driver ioredis 6 sets the keepalive idle time of the kernel from its keepAlive option,
74
- * through setKeepAlive of Node. That function also sets the probe interval and count. The driver
75
- * learns of the end of the socket as stream.close.
76
- */
77
- interface Over {
78
- /** This identifier is the machine below, as a graph identifies its document. */
79
- readonly machine: string;
80
- /** This map gives the state of the lower machine that each state of this machine is on. */
81
- readonly states: Readonly<Record<string, string>>;
82
- /** These are the knobs of the lower machine that this machine sets, by their lower names, over its own knobs. */
83
- readonly sets: Readonly<Record<string, Expr>>;
84
- /** This event is the event of this machine that the end of the lower machine arrives as. */
85
- readonly ends: string;
86
- readonly note?: string | undefined;
87
- }
88
- /** A transition goes from one or more states to a state, on one or more events. */
89
- interface TransitionDef {
90
- readonly id: string;
91
- readonly from: string | readonly string[];
92
- readonly to: string;
93
- readonly on: string | readonly string[];
94
- readonly guard?: string | undefined;
95
- readonly timer?: string | undefined;
96
- readonly emits?: readonly string[] | undefined;
97
- readonly errno?: string | undefined;
98
- readonly note?: string | undefined;
99
- readonly source?: string | undefined;
100
- }
101
- /** A vantage is the layer that a machine is seen from. */
102
- type Vantage = "wire" | "kernel" | "middlebox" | "proxy" | "driver" | "server" | "canary" | "injector" | "self";
103
- /** A machine is one state machine document. */
104
- interface Machine {
105
- readonly format: "mark1russell7.machine/1";
106
- readonly id: string;
107
- readonly title: string;
108
- readonly layer: Vantage;
109
- readonly version: string;
110
- readonly conditions?: Readonly<Record<string, string>> | undefined;
111
- readonly sources: ReadonlyArray<{
112
- readonly ref: string;
113
- readonly rung: "normative" | "implemented" | "documented" | "observed" | "derived";
114
- readonly note?: string | undefined;
115
- }>;
116
- readonly states: Readonly<Record<string, {
117
- readonly initial?: boolean | undefined;
118
- readonly final?: boolean | undefined;
119
- readonly pseudo?: boolean | undefined;
120
- readonly note?: string | undefined;
121
- }>>;
122
- readonly events: Readonly<Record<string, {
123
- readonly kind: "rx" | "tx" | "app" | "timer" | "local" | "packet" | "peer";
124
- readonly note?: string | undefined;
125
- }>>;
126
- readonly knobs: Readonly<Record<string, {
127
- readonly key: string;
128
- readonly scope: string;
129
- readonly unit: Unit | null;
130
- readonly default: number | null;
131
- readonly note?: string | undefined;
132
- }>>;
133
- readonly timers: Readonly<Record<string, Timer>>;
134
- /** These are the mechanisms whose time this machine gives, by the identifier of each mechanism. */
135
- readonly realizes?: Readonly<Record<string, Realization>> | undefined;
136
- /** This is the machine that this machine operates on, for a machine on another machine. */
137
- readonly over?: Over | undefined;
138
- readonly transitions: readonly TransitionDef[];
139
- readonly observe?: Readonly<Record<string, {
140
- readonly states: Readonly<Record<string, string>>;
141
- readonly hides?: readonly string[] | undefined;
142
- readonly fidelity: "complete" | "sampled" | "lossy" | "derived";
143
- readonly note?: string | undefined;
144
- }>> | undefined;
145
- readonly generated?: {
146
- readonly from: string;
147
- readonly by: string;
148
- } | undefined;
149
- }
150
- /** This schema accepts a machine document. */
151
- export declare const machineSchema: z.ZodType<Machine>;
152
- /** This function gives one value or many values as an array. */
153
- export declare const arr: <T>(value: T | readonly T[]) => readonly T[];
154
- /** This function gives the knobs that a duration reads, by the names of the machine for them. */
155
- export declare const exprKnobs: (e: Expr) => string[];
156
- /** This function tells if a duration reads the number of times that its timer fired, as the waits of a backoff do. */
157
- export declare const readsFired: (e: Expr) => boolean;
158
- /** This function gives the states that a transition leaves. The state "*" is each state that is not final. */
159
- export declare const fromStates: (m: Machine, from: string | readonly string[]) => string[];
160
- /**
161
- * This function gives the problems in the consistency of a document. Each state, event, timer and
162
- * knob that it refers to must exist, and it must have an initial state. A reader refuses a
163
- * machine with problems, and does not draw half of it.
164
- */
165
- export declare const machineProblems: (m: Machine) => string[];
166
- //#endregion
167
3
  //#region src/algebra.d.ts
168
4
  /**
169
5
  * This module has the closed forms of the algebra. They give the duration of a timer of a
@@ -382,5 +218,5 @@ export declare const overValues: (upper: Machine, upperValues: KnobValues, lower
382
218
  */
383
219
  export declare const stackedDetection: (upper: Machine, lower: Machine, situation: Situation, manifestation: Manifestation, upperValues: KnobValues, lowerValues: KnobValues) => Detection;
384
220
  //#endregion
385
- export type { Detection, Detector, Expr, Firing, KnobValues, Machine, Manifestation, Node, Over, Realization, Recovery, Situation, Timer, TimerBounds, TransitionDef, Unit, Vantage };
221
+ export { type Detection, type Detector, type Expr, FIRED, type Firing, type KnobValues, type Machine, type Manifestation, type Node, type Over, type Realization, type Recovery, type ReplayOptions, type Replayable, type Situation, type Timer, type TimerBounds, type Transition, type TransitionDef, type Unit, type Vantage, arr, exprKnobs, fromStates, machineProblems, machineSchema, readsFired, replay };
386
222
  //# sourceMappingURL=index.d.ts.map
package/build/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { n as arr, r as fromStates, t as replay } from "./replay-BcRPW0Ld.js";
1
2
  import { unitSchema } from "@mark1russell7/quantity/schema";
2
3
  import { z } from "zod";
3
4
  import { convertExact, isUnbounded, quantity, rationals, unbounded } from "@mark1russell7/quantity";
@@ -155,8 +156,6 @@ const machineSchema = z.strictObject({
155
156
  by: z.string()
156
157
  }).optional()
157
158
  });
158
- /** This function gives one value or many values as an array. */
159
- const arr = (value) => Array.isArray(value) ? value : [value];
160
159
  /** This function gives the names that a duration reads: its knobs, by the names of the machine, and `fired`. */
161
160
  const exprNames = (e) => {
162
161
  if ("knob" in e) return [e.knob];
@@ -173,13 +172,6 @@ const exprNames = (e) => {
173
172
  const exprKnobs = (e) => exprNames(e).filter((name) => name !== FIRED);
174
173
  /** This function tells if a duration reads the number of times that its timer fired, as the waits of a backoff do. */
175
174
  const readsFired = (e) => exprNames(e).includes(FIRED);
176
- /** This function gives the states that a transition leaves. The state "*" is each state that is not final. */
177
- const fromStates = (m, from) => {
178
- const out = /* @__PURE__ */ new Set();
179
- for (const state of arr(from)) if (state !== "*") out.add(state);
180
- else for (const [name, def] of Object.entries(m.states)) if (def.final !== true) out.add(name);
181
- return [...out];
182
- };
183
175
  /**
184
176
  * This function gives the problems in the consistency of a document. Each state, event, timer and
185
177
  * knob that it refers to must exist, and it must have an initial state. A reader refuses a
@@ -937,6 +929,6 @@ const stackedDetection = (upper, lower, situation, manifestation, upperValues, l
937
929
  };
938
930
  };
939
931
  //#endregion
940
- export { FIRED, algebraProblems, arr, detection, errnoOf, evaluate, exprKnobs, fromStates, machineProblems, machineSchema, modelSource, overValues, parseExpr, readsFired, realizationKnobs, realizationOf, recovery, stackedDetection, timerOf, timerUnder, transitionOn };
932
+ export { FIRED, algebraProblems, arr, detection, errnoOf, evaluate, exprKnobs, fromStates, machineProblems, machineSchema, modelSource, overValues, parseExpr, readsFired, realizationKnobs, realizationOf, recovery, replay, stackedDetection, timerOf, timerUnder, transitionOn };
941
933
 
942
934
  //# 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/schema\";\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;EA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AE,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"}
1
+ {"version":3,"file":"index.js","names":["r"],"sources":["../src/machine.ts","../src/algebra.ts"],"sourcesContent":["import { unitSchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { arr } from \"./states.ts\";\n\nexport { arr, fromStates } from \"./states.ts\";\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 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/**\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":";;;;;;;;;AAiDA,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,KAAK,SAAS;CACrB,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS;AAC5B,CAAC,CAC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AAG;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"}
@@ -0,0 +1,35 @@
1
+ //#region src/states.ts
2
+ /** This function gives one value or many values as an array. */
3
+ const arr = (value) => Array.isArray(value) ? value : [value];
4
+ /** This function gives the states that a transition leaves. The state "*" is each state that is not final. */
5
+ const fromStates = (m, from) => {
6
+ const out = /* @__PURE__ */ new Set();
7
+ for (const state of arr(from)) if (state !== "*") out.add(state);
8
+ else for (const [name, def] of Object.entries(m.states)) if (def.final !== true) out.add(name);
9
+ return [...out];
10
+ };
11
+ //#endregion
12
+ //#region src/replay.ts
13
+ /**
14
+ * This function replays a trace against a machine document, and it gives each disagreement:
15
+ * - Each instance starts in the state that its first transition leaves.
16
+ * - Each transition must leave the state where the replay of its instance is, and that state must be in the document.
17
+ * - The document must have a transition from that state, on that event, to that state. The state "*" is each state that is not final.
18
+ */
19
+ const replay = (doc, transitions, options = {}) => {
20
+ const problems = [];
21
+ const at = /* @__PURE__ */ new Map();
22
+ for (const event of transitions) {
23
+ if (options.machine !== void 0 && event.machine !== options.machine) continue;
24
+ const where = at.get(event.instance) ?? event.from;
25
+ if (doc.states[where] === void 0) problems.push(`${event.instance}: the state ${where} is not in ${doc.id}`);
26
+ if (event.from !== where) problems.push(`${event.instance}: the runtime left ${event.from} on ${event.on}, but the replay is in ${where}`);
27
+ if (!doc.transitions.some((each) => fromStates(doc, each.from).includes(event.from) && arr(each.on).includes(event.on) && each.to === event.to)) problems.push(`${event.instance}: ${doc.id} has no transition from ${event.from} on ${event.on} to ${event.to}`);
28
+ at.set(event.instance, event.to);
29
+ }
30
+ return problems;
31
+ };
32
+ //#endregion
33
+ export { arr as n, fromStates as r, replay as t };
34
+
35
+ //# sourceMappingURL=replay-BcRPW0Ld.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-BcRPW0Ld.js","names":[],"sources":["../src/states.ts","../src/replay.ts"],"sourcesContent":["import type { Machine } from \"./machine.ts\";\n\n// The states of a document, without the schema: the replay reads them, and it does not import zod.\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 states that a transition leaves. The state \"*\" is each state that is not final. */\nexport const fromStates = (m: Pick<Machine, \"states\">, 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","// @mark1russell7/algebra/replay: the replay of a trace against a machine document. A machine of\n// any name, with its own states and events, replays here. The entry does not import zod. Thus\n// a client in a browser can replay its own transitions.\n\nimport type { Machine } from \"./machine.ts\";\nimport { arr, fromStates } from \"./states.ts\";\n\n/**\n * A transition is one change of state that a running machine reports. A lifecycle event of\n * `@mark1russell7/service` is a transition, and so is a report of any other machine.\n */\nexport interface Transition {\n /** This name identifies the machine that reported. Each program names its own machines. */\n readonly machine?: string | undefined;\n /** This name identifies one machine among others of its kind: a connection, a check. */\n readonly instance: string;\n readonly from: string;\n readonly on: string;\n readonly to: string;\n /** This time is when the transition occurred, in milliseconds. The replay does not read it. */\n readonly at?: number | undefined;\n}\n\n/** These are the parts of a machine document that a replay reads. */\nexport type Replayable = Pick<Machine, \"id\" | \"states\" | \"transitions\">;\n\n/** These options tell which transitions of a trace replay. */\nexport interface ReplayOptions {\n /** Only the transitions of this machine replay. Without it, each transition of the trace replays. */\n readonly machine?: string | undefined;\n}\n\n/**\n * This function replays a trace against a machine document, and it gives each disagreement:\n * - Each instance starts in the state that its first transition leaves.\n * - Each transition must leave the state where the replay of its instance is, and that state must be in the document.\n * - The document must have a transition from that state, on that event, to that state. The state \"*\" is each state that is not final.\n */\nexport const replay = (doc: Replayable, transitions: readonly Transition[], options: ReplayOptions = {}): string[] => {\n const problems: string[] = [];\n const at = new Map<string, string>();\n for (const event of transitions) {\n if (options.machine !== undefined && event.machine !== options.machine) continue;\n const where = at.get(event.instance) ?? event.from;\n if (doc.states[where] === undefined) problems.push(`${event.instance}: the state ${where} is not in ${doc.id}`);\n if (event.from !== where)\n problems.push(`${event.instance}: the runtime left ${event.from} on ${event.on}, but the replay is in ${where}`);\n const allowed = doc.transitions.some(\n (each) => fromStates(doc, each.from).includes(event.from) && arr(each.on).includes(event.on) && each.to === event.to,\n );\n if (!allowed) problems.push(`${event.instance}: ${doc.id} has no transition from ${event.from} on ${event.on} to ${event.to}`);\n at.set(event.instance, event.to);\n }\n return problems;\n};\n"],"mappings":";;AAKA,MAAa,OAAU,UACrB,MAAM,QAAQ,KAAK,IAAK,QAAyB,CAAC,KAAU;;AAG9D,MAAa,cAAc,GAA4B,SAA+C;CACpG,MAAM,sBAAM,IAAI,IAAY;CAC5B,KAAK,MAAM,SAAS,IAAI,IAAI,GAC1B,IAAI,UAAU,KAAK,IAAI,IAAI,KAAK;MAC3B,KAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,EAAE,MAAM,GAAG,IAAI,IAAI,UAAU,MAAM,IAAI,IAAI,IAAI;CAE/F,OAAO,CAAC,GAAG,GAAG;AAChB;;;;;;;;;ACsBA,MAAa,UAAU,KAAiB,aAAoC,UAAyB,CAAC,MAAgB;CACpH,MAAM,WAAqB,CAAC;CAC5B,MAAM,qBAAK,IAAI,IAAoB;CACnC,KAAK,MAAM,SAAS,aAAa;EAC/B,IAAI,QAAQ,YAAY,KAAA,KAAa,MAAM,YAAY,QAAQ,SAAS;EACxE,MAAM,QAAQ,GAAG,IAAI,MAAM,QAAQ,KAAK,MAAM;EAC9C,IAAI,IAAI,OAAO,WAAW,KAAA,GAAW,SAAS,KAAK,GAAG,MAAM,SAAS,cAAc,MAAM,aAAa,IAAI,IAAI;EAC9G,IAAI,MAAM,SAAS,OACjB,SAAS,KAAK,GAAG,MAAM,SAAS,qBAAqB,MAAM,KAAK,MAAM,MAAM,GAAG,yBAAyB,OAAO;EAIjH,IAAI,CAHY,IAAI,YAAY,MAC7B,SAAS,WAAW,KAAK,KAAK,IAAI,CAAC,CAAC,SAAS,MAAM,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,KAAK,OAAO,MAAM,EAEzG,GAAG,SAAS,KAAK,GAAG,MAAM,SAAS,IAAI,IAAI,GAAG,0BAA0B,MAAM,KAAK,MAAM,MAAM,GAAG,MAAM,MAAM,IAAI;EAC7H,GAAG,IAAI,MAAM,UAAU,MAAM,EAAE;CACjC;CACA,OAAO;AACT"}
@@ -0,0 +1,200 @@
1
+ import { z } from "zod";
2
+ //#region src/states.d.ts
3
+ /** This function gives one value or many values as an array. */
4
+ declare const arr: <T>(value: T | readonly T[]) => readonly T[];
5
+ /** This function gives the states that a transition leaves. The state "*" is each state that is not final. */
6
+ declare const fromStates: (m: Pick<Machine, "states">, from: string | readonly string[]) => string[];
7
+ //#endregion
8
+ //#region src/machine.d.ts
9
+ /**
10
+ * `mark1russell7.machine/1` is a state machine as data.
11
+ *
12
+ * One document describes one machine, and three readers share it: the conformance checker
13
+ * (states, transitions, observer mappings), the algebra (the closed forms of timers over knobs)
14
+ * and the simulator (the arm, cancel and fire events of timers). The format is small on purpose:
15
+ * no hierarchy, no actions other than `emits`, and guards as documented text.
16
+ */
17
+ /** A unit is a unit that @mark1russell7/quantity stores: a time or a count, which is all that the timers of a machine read. */
18
+ type Unit = string;
19
+ /** An expression is a duration: a constant, a knob, arithmetic over knobs, or a named model of them. */
20
+ type Expr = {
21
+ readonly const: number;
22
+ readonly unit: Unit;
23
+ } | {
24
+ readonly knob: string;
25
+ readonly unit: Unit;
26
+ } | {
27
+ readonly expr: string;
28
+ readonly unit: Unit;
29
+ } | {
30
+ readonly model: string;
31
+ readonly knobs: readonly string[];
32
+ readonly unit: Unit;
33
+ };
34
+ /** A timer has a duration, the events that arm and cancel it, and the event that it fires. */
35
+ interface Timer {
36
+ readonly duration: Expr;
37
+ readonly lateness?: Expr | undefined;
38
+ readonly early?: Expr | undefined;
39
+ readonly arms: readonly string[];
40
+ readonly cancels?: readonly string[] | undefined;
41
+ readonly fires: string;
42
+ /**
43
+ * A backoff timer starts again after it fires, and each wait is longer than the last. Examples
44
+ * are the retransmission timer of the kernel and the reconnect of a driver. Its duration, lateness and
45
+ * early bound are those of one wait. They can read `fired`: the number of times that it fired
46
+ * after the last of its `resets`.
47
+ */
48
+ readonly backoff?: {
49
+ readonly resets: readonly string[];
50
+ } | undefined;
51
+ readonly note?: string | undefined;
52
+ }
53
+ /**
54
+ * This name is what the waits of a backoff timer read for the number of times that it fired after
55
+ * a reset, from 0. It is not a knob, because nothing sets it. It is the count of the timer itself.
56
+ */
57
+ declare const FIRED = "fired";
58
+ /**
59
+ * A realization tells how long a mechanism takes where the machine operates. It is one of the
60
+ * timers of the machine, whole, or a time of its own over the knobs of the machine. It has a
61
+ * lateness and an early bound, as a timer has. The idle refresh of the Redis server is the idle
62
+ * time of its keepalive, rounded on the timer wheel of the kernel. That is the first firing of its
63
+ * keepalive timer, not the whole timer.
64
+ */
65
+ type Realization = {
66
+ readonly timer: string;
67
+ } | {
68
+ readonly duration: Expr;
69
+ readonly lateness?: Expr | undefined;
70
+ readonly early?: Expr | undefined;
71
+ readonly note?: string | undefined;
72
+ };
73
+ /**
74
+ * An over tells the machine that this machine operates on, and how: a driver on its kernel socket.
75
+ * Each state of this machine is on a state of the lower machine. Some knobs of this machine set
76
+ * knobs of the lower machine. The end of the lower machine arrives as an event of this machine.
77
+ *
78
+ * The driver ioredis 6 sets the keepalive idle time of the kernel from its keepAlive option,
79
+ * through setKeepAlive of Node. That function also sets the probe interval and count. The driver
80
+ * learns of the end of the socket as stream.close.
81
+ */
82
+ interface Over {
83
+ /** This identifier is the machine below, as a graph identifies its document. */
84
+ readonly machine: string;
85
+ /** This map gives the state of the lower machine that each state of this machine is on. */
86
+ readonly states: Readonly<Record<string, string>>;
87
+ /** These are the knobs of the lower machine that this machine sets, by their lower names, over its own knobs. */
88
+ readonly sets: Readonly<Record<string, Expr>>;
89
+ /** This event is the event of this machine that the end of the lower machine arrives as. */
90
+ readonly ends: string;
91
+ readonly note?: string | undefined;
92
+ }
93
+ /** A transition goes from one or more states to a state, on one or more events. */
94
+ interface TransitionDef {
95
+ readonly id: string;
96
+ readonly from: string | readonly string[];
97
+ readonly to: string;
98
+ readonly on: string | readonly string[];
99
+ readonly guard?: string | undefined;
100
+ readonly timer?: string | undefined;
101
+ readonly emits?: readonly string[] | undefined;
102
+ readonly errno?: string | undefined;
103
+ readonly note?: string | undefined;
104
+ readonly source?: string | undefined;
105
+ }
106
+ /** A vantage is the layer that a machine is seen from. */
107
+ type Vantage = "wire" | "kernel" | "middlebox" | "proxy" | "driver" | "server" | "canary" | "injector" | "self";
108
+ /** A machine is one state machine document. */
109
+ interface Machine {
110
+ readonly format: "mark1russell7.machine/1";
111
+ readonly id: string;
112
+ readonly title: string;
113
+ readonly layer: Vantage;
114
+ readonly version: string;
115
+ readonly conditions?: Readonly<Record<string, string>> | undefined;
116
+ readonly sources: ReadonlyArray<{
117
+ readonly ref: string;
118
+ readonly rung: "normative" | "implemented" | "documented" | "observed" | "derived";
119
+ readonly note?: string | undefined;
120
+ }>;
121
+ readonly states: Readonly<Record<string, {
122
+ readonly initial?: boolean | undefined;
123
+ readonly final?: boolean | undefined;
124
+ readonly pseudo?: boolean | undefined;
125
+ readonly note?: string | undefined;
126
+ }>>;
127
+ readonly events: Readonly<Record<string, {
128
+ readonly kind: "rx" | "tx" | "app" | "timer" | "local" | "packet" | "peer";
129
+ readonly note?: string | undefined;
130
+ }>>;
131
+ readonly knobs: Readonly<Record<string, {
132
+ readonly key: string;
133
+ readonly scope: string;
134
+ readonly unit: Unit | null;
135
+ readonly default: number | null;
136
+ readonly note?: string | undefined;
137
+ }>>;
138
+ readonly timers: Readonly<Record<string, Timer>>;
139
+ /** These are the mechanisms whose time this machine gives, by the identifier of each mechanism. */
140
+ readonly realizes?: Readonly<Record<string, Realization>> | undefined;
141
+ /** This is the machine that this machine operates on, for a machine on another machine. */
142
+ readonly over?: Over | undefined;
143
+ readonly transitions: readonly TransitionDef[];
144
+ readonly observe?: Readonly<Record<string, {
145
+ readonly states: Readonly<Record<string, string>>;
146
+ readonly hides?: readonly string[] | undefined;
147
+ readonly fidelity: "complete" | "sampled" | "lossy" | "derived";
148
+ readonly note?: string | undefined;
149
+ }>> | undefined;
150
+ readonly generated?: {
151
+ readonly from: string;
152
+ readonly by: string;
153
+ } | undefined;
154
+ }
155
+ /** This schema accepts a machine document. */
156
+ declare const machineSchema: z.ZodType<Machine>;
157
+ /** This function gives the knobs that a duration reads, by the names of the machine for them. */
158
+ declare const exprKnobs: (e: Expr) => string[];
159
+ /** This function tells if a duration reads the number of times that its timer fired, as the waits of a backoff do. */
160
+ declare const readsFired: (e: Expr) => boolean;
161
+ /**
162
+ * This function gives the problems in the consistency of a document. Each state, event, timer and
163
+ * knob that it refers to must exist, and it must have an initial state. A reader refuses a
164
+ * machine with problems, and does not draw half of it.
165
+ */
166
+ declare const machineProblems: (m: Machine) => string[];
167
+ //#endregion
168
+ //#region src/replay.d.ts
169
+ /**
170
+ * A transition is one change of state that a running machine reports. A lifecycle event of
171
+ * `@mark1russell7/service` is a transition, and so is a report of any other machine.
172
+ */
173
+ interface Transition {
174
+ /** This name identifies the machine that reported. Each program names its own machines. */
175
+ readonly machine?: string | undefined;
176
+ /** This name identifies one machine among others of its kind: a connection, a check. */
177
+ readonly instance: string;
178
+ readonly from: string;
179
+ readonly on: string;
180
+ readonly to: string;
181
+ /** This time is when the transition occurred, in milliseconds. The replay does not read it. */
182
+ readonly at?: number | undefined;
183
+ }
184
+ /** These are the parts of a machine document that a replay reads. */
185
+ type Replayable = Pick<Machine, "id" | "states" | "transitions">;
186
+ /** These options tell which transitions of a trace replay. */
187
+ interface ReplayOptions {
188
+ /** Only the transitions of this machine replay. Without it, each transition of the trace replays. */
189
+ readonly machine?: string | undefined;
190
+ }
191
+ /**
192
+ * This function replays a trace against a machine document, and it gives each disagreement:
193
+ * - Each instance starts in the state that its first transition leaves.
194
+ * - Each transition must leave the state where the replay of its instance is, and that state must be in the document.
195
+ * - The document must have a transition from that state, on that event, to that state. The state "*" is each state that is not final.
196
+ */
197
+ declare const replay: (doc: Replayable, transitions: readonly Transition[], options?: ReplayOptions) => string[];
198
+ //#endregion
199
+ export { readsFired as _, Expr as a, Over as c, TransitionDef as d, Unit as f, machineSchema as g, machineProblems as h, replay as i, Realization as l, exprKnobs as m, Replayable as n, FIRED as o, Vantage as p, Transition as r, Machine as s, ReplayOptions as t, Timer as u, arr as v, fromStates as y };
200
+ //# sourceMappingURL=replay-rLMi4IqH.d.ts.map
@@ -0,0 +1,2 @@
1
+ import { i as replay, n as Replayable, r as Transition, t as ReplayOptions } from "./replay-rLMi4IqH.js";
2
+ export { ReplayOptions, Replayable, Transition, replay };
@@ -0,0 +1 @@
1
+ export { t as replay } from "./replay-BcRPW0Ld.js";
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/algebra",
4
- "version": "0.4.0",
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.",
4
+ "version": "0.5.0",
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, recovery after a stall, and the replay of a trace.",
6
6
  "keywords": [
7
7
  "state-machine",
8
8
  "timers",
@@ -33,6 +33,10 @@
33
33
  "types": "./build/index.d.ts",
34
34
  "default": "./build/index.js"
35
35
  },
36
+ "./replay": {
37
+ "types": "./build/replay.d.ts",
38
+ "default": "./build/replay.js"
39
+ },
36
40
  "./package.json": "./package.json"
37
41
  },
38
42
  "files": [