@mark1russell7/algebra 0.8.10 → 0.9.1
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 +15 -1
- package/build/{clock-CjLibabw.d.ts → clock-oJqrb5Q4.d.ts} +30 -6
- package/build/clock.d.ts +2 -2
- package/build/clock.js +38 -7
- package/build/clock.js.map +1 -1
- package/build/index.d.ts +5 -1
- package/build/index.js +27 -2
- package/build/index.js.map +1 -1
- package/build/{run-sAafntBU.d.ts → run-BgUWHAcf.d.ts} +1 -1
- package/build/{run-DTmtHPlK.js → run-J6kGNoF8.js} +39 -1
- package/build/run-J6kGNoF8.js.map +1 -0
- package/build/run.d.ts +1 -1
- package/build/run.js +1 -1
- package/package.json +2 -2
- package/build/run-DTmtHPlK.js.map +0 -1
package/README.md
CHANGED
|
@@ -32,8 +32,11 @@ The documents of the systems program are in [`@mark1russell7/machines`](https://
|
|
|
32
32
|
- `linux.delack` and `linux.delack-lateness`: the longest wait of the delayed ACK, and its rounding. The wait is the smoothed round trip in whole jiffies, from `TCP_DELACK_MIN` (HZ/25, 40 ms) to `TCP_DELACK_MAX` (HZ/5, 200 ms).
|
|
33
33
|
- `linux.syn-giveup` and `linux.syn-giveup-lateness`: the SYN give-up of 6.5 and later, with linear timeouts, and the rounding of each of its waits on the wheel. At the defaults the give-up is 131 s, up to 6.08 s late at HZ 1000.
|
|
34
34
|
- `linux.syn-wait` and `linux.syn-wait-lateness`: one wait of the SYN timer, after `fired` firings, and its rounding. At the defaults the waits 0 to 4 are 1 s, up to 64 ms late at HZ 1000.
|
|
35
|
+
- `linux.synack-wait` and `linux.synack-wait-lateness`: one wait of the SYN-ACK timer of a request in `SYN_RECV`, after `fired` firings, and its rounding. The wait doubles from 1 s up to 120 s.
|
|
36
|
+
- `linux.synack-giveup`, `linux.synack-giveup-lateness` and `linux.synack-giveup-early`: the expiry of a request after `tcp_synack_retries` + 1 waits, and its bounds. At the default 5 the expiry is 63 s, up to 1.728 s late at HZ 1000.
|
|
35
37
|
- `ioredis.retry-base`: the reconnect delay of ioredis 6, min(2^(times − 1) × 50, 5000) ms.
|
|
36
38
|
- `linux.rto-wait-reverted` and `linux.retrans-step-reverted`: the retransmissions when each one gets an ICMP host or net unreachable. The revert of RFC 6069 (`tcp_ld_RTO_revert`) takes back each doubling, thus each wait is one RTO.
|
|
39
|
+
- **The accept queue.** `acceptQueueLimit` gives the limit of the accept queue of a listener: the backlog of listen(2), with `somaxconn` as its cap. A negative backlog gives `somaxconn`. `acceptQueueHeld` gives the count of connections that the queue holds. This count is the limit plus one, because the kernel finds the queue full only above its limit.
|
|
37
40
|
- **Detection.** `detection` gives the minimum over the timers that are live in the situation of the connection. With no live timer, the failure is silent at this level. `stackedDetection` adds the timers of the machine below.
|
|
38
41
|
- **Manifestations.** A manifestation tells which incoming events a failure lets through. A black hole lets nothing through. The kernel of a frozen process continues to send ACKs, which stop keepalive before it fires. A manifestation can also tell:
|
|
39
42
|
- the events that the failure sends one time (`delivers`), for example the FIN of a process that stopped with SIGKILL. Such an event detects the failure at once (`Detection.delivered`).
|
|
@@ -125,7 +128,8 @@ An app gives `realClock` of `@mark1russell7/algebra/clock` in place of the fake
|
|
|
125
128
|
| --- | --- |
|
|
126
129
|
| `Clock` | `now()` gives the monotonic time in milliseconds. `after(ms, run)` starts `run` after `ms` and gives its `Cancel`. |
|
|
127
130
|
| `platformClock({ unref, speed, start })` | A clock on `performance.now()` and `setTimeout`. With `unref: true`, its timers do not keep a Node process alive. With a speed or a start, the clock is scaled. |
|
|
128
|
-
| `realClock` |
|
|
131
|
+
| `realClock` | `platformClock()`: its timers keep a Node process alive, as `setTimeout` does. |
|
|
132
|
+
| `unrefClock(clock)` | A clock with the time of `clock`, whose timers do not keep a Node process alive. A wall clock stays a wall clock. |
|
|
129
133
|
| `wallClock({ unref, speed, start })` | A `WallClock`: `now()` gives the instant of `Date.now()`, and its timers are the timers of `platformClock`. With a speed or a start, the clock is scaled. |
|
|
130
134
|
| `fakeClock(start)` | A clock that moves only on `advance(ms)`. `block(ms)` moves it and starts no timer, as a blocked event loop does. `pending` counts the live timers. |
|
|
131
135
|
| `fakeWallClock(start)` | A fake `WallClock`. `set(instant)` steps its instant forward or back, and no timer moves. |
|
|
@@ -142,6 +146,16 @@ await clock.advance(30_000); // the sweep runs, at 30 s exactly
|
|
|
142
146
|
await delay(realClock, retryAfter, controller.signal);
|
|
143
147
|
```
|
|
144
148
|
|
|
149
|
+
### The rule of `unref`
|
|
150
|
+
|
|
151
|
+
Each timer of `realClock` keeps a Node process alive, as `setTimeout` does. Thus a process does not end in a wait that a caller awaits, for example the wait of a retry.
|
|
152
|
+
|
|
153
|
+
- The owner of a timer uses the `unref` of its cancel only when a socket, a child process or another hold keeps the process alive. Examples are the heartbeat of a connection and the health checks of a service.
|
|
154
|
+
- Each other timer stays referenced, a ticker too. Its caller stops it.
|
|
155
|
+
- `unrefClock(clock)` gives a part a clock whose timers do not keep the process alive. The owner of the part gives it only when another hold keeps the process alive.
|
|
156
|
+
- `platformClock({ unref: true })` makes each timer of a new clock an exception, with the same condition.
|
|
157
|
+
- A hang shows. A silent exit with the code 0 and lost work does not. Before algebra 0.9.0, the timers of `realClock` did not keep the process alive, and a command-line tool ended in the wait of a retry.
|
|
158
|
+
|
|
145
159
|
### A scaled clock
|
|
146
160
|
|
|
147
161
|
A scaled clock runs a long schedule in a short real time, on the real timers. A fake clock moves only on `advance`. Thus it cannot drive a server, a proxy or a socket that waits on real time.
|
|
@@ -59,6 +59,13 @@ interface PlatformClockOptions {
|
|
|
59
59
|
* This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel
|
|
60
60
|
* that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.
|
|
61
61
|
*
|
|
62
|
+
* The rule of `unref`: each timer keeps a Node process alive, as `setTimeout` does. Thus a process
|
|
63
|
+
* does not end in a wait that a caller awaits. A hang shows, but a silent exit with lost work does not.
|
|
64
|
+
*
|
|
65
|
+
* The owner of a timer uses its `unref` only when a socket, a child process or another hold keeps the
|
|
66
|
+
* process alive. An example is the heartbeat of a connection. Each other timer stays referenced, a
|
|
67
|
+
* ticker too: its caller stops it. The option `unref` makes each timer of the clock an exception.
|
|
68
|
+
*
|
|
62
69
|
* With a speed or a start, `now()` is the start plus the monotonic time since the call, times the
|
|
63
70
|
* speed. A scaled clock reads `performance.now()` at each timer. Thus the fake timers of a test
|
|
64
71
|
* also fake `performance`, else its timers wait again and again.
|
|
@@ -67,10 +74,27 @@ interface PlatformClockOptions {
|
|
|
67
74
|
*/
|
|
68
75
|
declare const platformClock: (options?: PlatformClockOptions) => Clock;
|
|
69
76
|
/**
|
|
70
|
-
* This clock reads `performance.now()` and uses `setTimeout`.
|
|
71
|
-
* process alive,
|
|
77
|
+
* This clock reads `performance.now()` and uses `setTimeout`. It is `platformClock()`, thus its
|
|
78
|
+
* timers keep a Node process alive, as `setTimeout` does. A process does not end in a wait that a
|
|
79
|
+
* caller awaits, for example a retry.
|
|
80
|
+
*
|
|
81
|
+
* The owner of a timer uses its `unref` only when a socket, a child process or another hold keeps the
|
|
82
|
+
* process alive. Each other timer stays referenced: its caller stops it. A timer that is not stopped
|
|
83
|
+
* delays the exit, and that delay shows.
|
|
84
|
+
*
|
|
85
|
+
* Before algebra 0.9.0, the timers of this clock did not keep the process alive. A process then ended
|
|
86
|
+
* with the code 0 in a wait, and lost its work.
|
|
72
87
|
*/
|
|
73
88
|
declare const realClock: Clock;
|
|
89
|
+
/**
|
|
90
|
+
* This function gives a clock with the time of `clock`. Its timers do not keep a Node process alive:
|
|
91
|
+
* each timer uses the `unref` of its cancel. The owner of a part gives it to the part only
|
|
92
|
+
* when a socket, a child process or another hold keeps the process alive. An example is the
|
|
93
|
+
* heartbeat of a connection. A wall clock stays a wall clock. The timers of a fake clock have no
|
|
94
|
+
* `unref`, thus they do not change.
|
|
95
|
+
*/
|
|
96
|
+
declare function unrefClock(clock: Clock): Clock;
|
|
97
|
+
declare function unrefClock(clock: WallClock): WallClock;
|
|
74
98
|
/**
|
|
75
99
|
* This function makes the wall clock of the platform: `Date.now()`, and the timers of
|
|
76
100
|
* `platformClock`. The options are the options of `platformClock`.
|
|
@@ -86,9 +110,9 @@ declare const wallClock: (options?: PlatformClockOptions) => WallClock;
|
|
|
86
110
|
* This function gives a promise that resolves after `ms` milliseconds on the clock. When the signal
|
|
87
111
|
* aborts, the promise stops its timer and rejects with the reason of the signal. A signal that
|
|
88
112
|
* aborted before the call rejects at once, and starts no timer. Each end removes the listener from
|
|
89
|
-
* the signal. A timer of `realClock`
|
|
90
|
-
*
|
|
91
|
-
*
|
|
113
|
+
* the signal. A timer of `realClock` keeps a Node process alive until the delay ends. The clock is
|
|
114
|
+
* a `Clock` or a `WallClock`: the function uses only its timers, and each timer of the two waits
|
|
115
|
+
* on the monotonic time.
|
|
92
116
|
*/
|
|
93
117
|
declare const delay: (clock: Pick<Clock, "after">, ms: number, signal?: AbortSignal) => Promise<void>;
|
|
94
118
|
/** A fake clock moves only when a test tells it to. */
|
|
@@ -224,4 +248,4 @@ declare function firstInstantOf(wall: number, zone: string): number | undefined;
|
|
|
224
248
|
declare function nextBoundary(instant: number, window: TimeWindow): WindowBoundary | undefined;
|
|
225
249
|
/** This function gives the problems of a window. With a problem, `inWindow` gives `false` and `nextBoundary` gives `undefined`. */
|
|
226
250
|
declare function windowProblems(window: TimeWindow): string[];
|
|
227
|
-
export { windowProblems as S, nextBoundary as _, LocalTime as a, realClock as b, WallClock as c, fakeClock as d, fakeWallClock as f, localTime as g, instantsOf as h, FakeWallClock as i, WindowBoundary as l, inWindow as m, Clock as n, PlatformClockOptions as o, firstInstantOf as p, FakeClock as r, TimeWindow as s, Cancel as t, delay as u, offsetChanges as v,
|
|
251
|
+
export { windowProblems as C, wallClock as S, nextBoundary as _, LocalTime as a, realClock as b, WallClock as c, fakeClock as d, fakeWallClock as f, localTime as g, instantsOf as h, FakeWallClock as i, WindowBoundary as l, inWindow as m, Clock as n, PlatformClockOptions as o, firstInstantOf as p, FakeClock as r, TimeWindow as s, Cancel as t, delay as u, offsetChanges as v, unrefClock as x, platformClock as y };
|
package/build/clock.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { Cancel, Clock, FakeClock, FakeWallClock, LocalTime, PlatformClockOptions, TimeWindow, WallClock, WindowBoundary, delay, fakeClock, fakeWallClock, firstInstantOf, inWindow, instantsOf, localTime, nextBoundary, offsetChanges, platformClock, realClock, wallClock, windowProblems };
|
|
1
|
+
import { C as windowProblems, S as wallClock, _ as nextBoundary, a as LocalTime, b as realClock, c as WallClock, d as fakeClock, f as fakeWallClock, g as localTime, h as instantsOf, i as FakeWallClock, l as WindowBoundary, m as inWindow, n as Clock, o as PlatformClockOptions, p as firstInstantOf, r as FakeClock, s as TimeWindow, t as Cancel, u as delay, v as offsetChanges, x as unrefClock, y as platformClock } from "./clock-oJqrb5Q4.js";
|
|
2
|
+
export { Cancel, Clock, FakeClock, FakeWallClock, LocalTime, PlatformClockOptions, TimeWindow, WallClock, WindowBoundary, delay, fakeClock, fakeWallClock, firstInstantOf, inWindow, instantsOf, localTime, nextBoundary, offsetChanges, platformClock, realClock, unrefClock, wallClock, windowProblems };
|
package/build/clock.js
CHANGED
|
@@ -44,6 +44,13 @@ const timersOf = (unrefAll, speed, now) => (ms, run) => {
|
|
|
44
44
|
* This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel
|
|
45
45
|
* that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.
|
|
46
46
|
*
|
|
47
|
+
* The rule of `unref`: each timer keeps a Node process alive, as `setTimeout` does. Thus a process
|
|
48
|
+
* does not end in a wait that a caller awaits. A hang shows, but a silent exit with lost work does not.
|
|
49
|
+
*
|
|
50
|
+
* The owner of a timer uses its `unref` only when a socket, a child process or another hold keeps the
|
|
51
|
+
* process alive. An example is the heartbeat of a connection. Each other timer stays referenced, a
|
|
52
|
+
* ticker too: its caller stops it. The option `unref` makes each timer of the clock an exception.
|
|
53
|
+
*
|
|
47
54
|
* With a speed or a start, `now()` is the start plus the monotonic time since the call, times the
|
|
48
55
|
* speed. A scaled clock reads `performance.now()` at each timer. Thus the fake timers of a test
|
|
49
56
|
* also fake `performance`, else its timers wait again and again.
|
|
@@ -66,10 +73,34 @@ const platformClock = (options = {}) => {
|
|
|
66
73
|
};
|
|
67
74
|
};
|
|
68
75
|
/**
|
|
69
|
-
* This clock reads `performance.now()` and uses `setTimeout`.
|
|
70
|
-
* process alive,
|
|
76
|
+
* This clock reads `performance.now()` and uses `setTimeout`. It is `platformClock()`, thus its
|
|
77
|
+
* timers keep a Node process alive, as `setTimeout` does. A process does not end in a wait that a
|
|
78
|
+
* caller awaits, for example a retry.
|
|
79
|
+
*
|
|
80
|
+
* The owner of a timer uses its `unref` only when a socket, a child process or another hold keeps the
|
|
81
|
+
* process alive. Each other timer stays referenced: its caller stops it. A timer that is not stopped
|
|
82
|
+
* delays the exit, and that delay shows.
|
|
83
|
+
*
|
|
84
|
+
* Before algebra 0.9.0, the timers of this clock did not keep the process alive. A process then ended
|
|
85
|
+
* with the code 0 in a wait, and lost its work.
|
|
71
86
|
*/
|
|
72
|
-
const realClock = /* @__PURE__ */ platformClock(
|
|
87
|
+
const realClock = /* @__PURE__ */ platformClock();
|
|
88
|
+
function unrefClock(clock) {
|
|
89
|
+
const after = (ms, run) => {
|
|
90
|
+
const cancel = clock.after(ms, run);
|
|
91
|
+
cancel.unref?.();
|
|
92
|
+
return cancel;
|
|
93
|
+
};
|
|
94
|
+
const now = () => clock.now();
|
|
95
|
+
return clock.time === "wall" ? {
|
|
96
|
+
time: "wall",
|
|
97
|
+
now,
|
|
98
|
+
after
|
|
99
|
+
} : {
|
|
100
|
+
now,
|
|
101
|
+
after
|
|
102
|
+
};
|
|
103
|
+
}
|
|
73
104
|
/**
|
|
74
105
|
* This function makes the wall clock of the platform: `Date.now()`, and the timers of
|
|
75
106
|
* `platformClock`. The options are the options of `platformClock`.
|
|
@@ -101,9 +132,9 @@ const wallClock = (options = {}) => {
|
|
|
101
132
|
* This function gives a promise that resolves after `ms` milliseconds on the clock. When the signal
|
|
102
133
|
* aborts, the promise stops its timer and rejects with the reason of the signal. A signal that
|
|
103
134
|
* aborted before the call rejects at once, and starts no timer. Each end removes the listener from
|
|
104
|
-
* the signal. A timer of `realClock`
|
|
105
|
-
*
|
|
106
|
-
*
|
|
135
|
+
* the signal. A timer of `realClock` keeps a Node process alive until the delay ends. The clock is
|
|
136
|
+
* a `Clock` or a `WallClock`: the function uses only its timers, and each timer of the two waits
|
|
137
|
+
* on the monotonic time.
|
|
107
138
|
*/
|
|
108
139
|
const delay = (clock, ms, signal) => new Promise((resolve, reject) => {
|
|
109
140
|
if (signal?.aborted === true) {
|
|
@@ -455,6 +486,6 @@ function windowProblems(window) {
|
|
|
455
486
|
if (window.days !== void 0 && window.days.length === 0) problems.push("The window has no day, thus it does not open.");
|
|
456
487
|
return problems;
|
|
457
488
|
}
|
|
458
|
-
export { delay, fakeClock, fakeWallClock, firstInstantOf, inWindow, instantsOf, localTime, nextBoundary, offsetChanges, platformClock, realClock, wallClock, windowProblems };
|
|
489
|
+
export { delay, fakeClock, fakeWallClock, firstInstantOf, inWindow, instantsOf, localTime, nextBoundary, offsetChanges, platformClock, realClock, unrefClock, wallClock, windowProblems };
|
|
459
490
|
|
|
460
491
|
//# sourceMappingURL=clock.js.map
|
package/build/clock.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clock.js","names":[],"sources":["../src/clock.ts"],"sourcesContent":["// @mark1russell7/algebra/clock: the clock of a runtime, a fake clock for tests, and civil time. It imports\n// nothing: no `node:` module, no zod and no other package. Thus a client in a browser can use it.\n// The service gives this clock again as @mark1russell7/service/clock.\n\n/**\n * This function stops a timer that `Clock.after` started. A second use does nothing. A clock of\n * the platform also gives `unref`: after it, the timer does not keep a Node process alive.\n */\nexport type Cancel = (() => void) & { readonly unref?: (() => void) | undefined };\n\n/**\n * A clock gives the monotonic time in milliseconds, and it starts a function after a delay. The\n * runtime reads time only through a clock. Thus a test can give a fake clock, and the timing of\n * the runtime is then exact and repeatable.\n */\nexport interface Clock {\n /**\n * This mark tells the time of `now()`. A clock gives the monotonic time, thus the mark is\n * `\"monotonic\"` or absent. A `WallClock` has the mark `\"wall\"`, thus it is not a `Clock`.\n */\n readonly time?: \"monotonic\" | undefined;\n /** This method gives the monotonic time, in milliseconds. A step of the wall clock does not move it. */\n now(): number;\n /** This method starts `run` after `ms` milliseconds, and gives the function that stops it. */\n after(ms: number, run: () => void): Cancel;\n}\n\n/**\n * A wall clock gives the instant: the time in milliseconds from 1970-01-01T00:00:00Z, as `Date.now()`\n * gives it. Civil time, a calendar and a time that another computer sends need the instant. A step\n * of the wall clock moves `now()`, also back. Each timer waits on the monotonic time, thus a step\n * does not move a timer. The mark `\"wall\"` keeps the two clocks apart: a function that needs the\n * monotonic time does not get a wall clock, and the reverse.\n */\nexport interface WallClock {\n readonly time: \"wall\";\n /** This method gives the instant, in milliseconds from the epoch. A step of the wall clock moves it. */\n now(): number;\n /** This method starts `run` after `ms` milliseconds of monotonic time, and gives the function that stops it. */\n after(ms: number, run: () => void): Cancel;\n}\n\n/**\n * These options make a clock of the platform. With a speed or a start, the clock is scaled: it\n * counts from its start on the monotonic time of the platform, `speed` times faster. Thus a test\n * runs a long schedule in a short real time, on the real timers.\n */\nexport interface PlatformClockOptions {\n /** True makes each timer not keep a Node process alive. The default is false, as with `setTimeout`. */\n readonly unref?: boolean | undefined;\n /**\n * The milliseconds of the clock in one real millisecond: a finite number above 0. The default is 1.\n * At the speed 60, `now()` moves 60 ms in each real millisecond, and a timer of 60 s ends after 1\n * real second. A speed below 1 gives a slow clock.\n */\n readonly speed?: number | undefined;\n /**\n * The time of `now()` when the clock is made, in milliseconds: a finite number. A wall clock reads\n * it as an instant. The default is the time of the platform at that moment.\n */\n readonly start?: number | undefined;\n}\n\n/** This function gives the monotonic time: `performance.now()`, or `Date.now()` on a platform without `performance`. */\nconst monotonic = (): number => {\n const performance = (globalThis as { performance?: { now(): number } }).performance;\n return performance === undefined ? Date.now() : performance.now();\n};\n\n/** This delay is the longest that `setTimeout` takes, in milliseconds. A longer delay starts the function after 1 ms. */\nconst LONGEST_DELAY = 0x7fffffff;\n\n/** This function gives the speed of the options. It throws a `RangeError` for a bad speed or a bad start. */\nconst speedOf = (options: PlatformClockOptions): number => {\n const speed = options.speed ?? 1;\n if (typeof speed !== \"number\" || !Number.isFinite(speed) || speed <= 0) throw new RangeError(`The speed ${String(speed)} is not a finite number above 0.`);\n const start = options.start;\n if (start !== undefined && (typeof start !== \"number\" || !Number.isFinite(start))) throw new RangeError(`The start ${String(start)} is not a finite number.`);\n return speed;\n};\n\n/**\n * This function makes the timers of a clock of the platform. A timer of `ms` milliseconds on the\n * clock waits `ms / speed` real milliseconds, in steps when `setTimeout` does not take that delay.\n * With `now`, the timer reads the clock when the platform starts it. When the clock is before the\n * due time, the timer waits again for the rest. Thus `run` reads its due time or a later time.\n */\nconst timersOf =\n (unrefAll: boolean, speed: number, now?: () => number): Clock[\"after\"] =>\n (ms, run) => {\n let unrefed = unrefAll;\n const due = now === undefined ? 0 : now() + Math.max(0, ms);\n const fire = (): void => {\n const early = now === undefined ? 0 : due - now();\n if (early > 0) timer = arm(early / speed);\n else run();\n };\n const arm = (left: number): ReturnType<typeof setTimeout> => {\n const step =\n left > LONGEST_DELAY ? setTimeout(() => (timer = arm(left - LONGEST_DELAY)), LONGEST_DELAY) : setTimeout(fire, Math.max(0, left));\n if (unrefed) (step as { unref?: () => void }).unref?.();\n return step;\n };\n let timer = arm(ms / speed);\n const unref = (): void => {\n unrefed = true;\n (timer as { unref?: () => void }).unref?.();\n };\n return Object.assign(() => clearTimeout(timer), { unref });\n };\n\n/**\n * This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel\n * that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.\n *\n * With a speed or a start, `now()` is the start plus the monotonic time since the call, times the\n * speed. A scaled clock reads `performance.now()` at each timer. Thus the fake timers of a test\n * also fake `performance`, else its timers wait again and again.\n *\n * @throws {RangeError} for a speed that is not a finite number above 0, and for a start that is not finite.\n */\nexport const platformClock = (options: PlatformClockOptions = {}): Clock => {\n const speed = speedOf(options);\n const unref = options.unref === true;\n if (speed === 1 && options.start === undefined) return { now: monotonic, after: timersOf(unref, 1) };\n const origin = monotonic();\n const start = options.start ?? origin;\n const now = (): number => start + (monotonic() - origin) * speed;\n return { now, after: timersOf(unref, speed, now) };\n};\n\n/**\n * This clock reads `performance.now()` and uses `setTimeout`. Its timers do not keep a Node\n * process alive, thus a timer that is not stopped cannot stop the exit of the process.\n */\nexport const realClock: Clock = /* @__PURE__ */ platformClock({ unref: true });\n\n/**\n * This function makes the wall clock of the platform: `Date.now()`, and the timers of\n * `platformClock`. The options are the options of `platformClock`.\n *\n * With a speed or a start, `now()` is the start plus the monotonic time since the call, times the\n * speed. It gives whole milliseconds, as `Date.now()` does. The default start is `Date.now()`.\n * A step of the wall clock of the platform does not move a scaled clock.\n *\n * @throws {RangeError} for a speed that is not a finite number above 0, and for a start that is not finite.\n */\nexport const wallClock = (options: PlatformClockOptions = {}): WallClock => {\n const speed = speedOf(options);\n const unref = options.unref === true;\n if (speed === 1 && options.start === undefined) return { time: \"wall\", now: () => Date.now(), after: timersOf(unref, 1) };\n const origin = monotonic();\n const start = options.start ?? Date.now();\n const now = (): number => Math.floor(start + (monotonic() - origin) * speed);\n return { time: \"wall\", now, after: timersOf(unref, speed, now) };\n};\n\n/**\n * This function gives a promise that resolves after `ms` milliseconds on the clock. When the signal\n * aborts, the promise stops its timer and rejects with the reason of the signal. A signal that\n * aborted before the call rejects at once, and starts no timer. Each end removes the listener from\n * the signal. A timer of `realClock` does not keep a Node process alive: give `platformClock()` to\n * keep the process alive until the delay ends. The clock is a `Clock` or a `WallClock`: the\n * function uses only its timers, and each timer of the two waits on the monotonic time.\n */\nexport const delay = (clock: Pick<Clock, \"after\">, ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted === true) {\n reject(signal.reason);\n return;\n }\n const abort = (): void => {\n cancel();\n reject(signal?.reason);\n };\n const cancel = clock.after(ms, () => {\n signal?.removeEventListener(\"abort\", abort);\n resolve();\n });\n signal?.addEventListener(\"abort\", abort, { once: true });\n });\n\n/** A fake clock moves only when a test tells it to. */\nexport interface FakeClock extends Clock {\n /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /**\n * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.\n * The next `advance` then starts each timer that came due during the block, late.\n */\n block(ms: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/** This function lets the promises that are ready continue, before the clock moves again. */\nconst settle = async (): Promise<void> => {\n for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();\n};\n\n/** This function makes a fake clock. Its time starts at `start` milliseconds. */\nexport const fakeClock = (start = 0): FakeClock => {\n let now = start;\n let sequence = 0;\n const timers: Array<{ at: number; order: number; run: () => void; live: boolean }> = [];\n const due = (end: number) => {\n let best: (typeof timers)[number] | undefined;\n for (const timer of timers)\n if (timer.live && timer.at <= end && (best === undefined || timer.at < best.at || (timer.at === best.at && timer.order < best.order)))\n best = timer;\n return best;\n };\n return {\n now: () => now,\n after(ms, run): Cancel {\n const timer = { at: now + Math.max(0, ms), order: sequence++, run, live: true };\n timers.push(timer);\n return () => {\n timer.live = false;\n };\n },\n async advance(ms) {\n // a monotonic clock does not go back\n const end = now + Math.max(0, ms);\n await settle();\n for (;;) {\n const timer = due(end);\n if (timer === undefined) break;\n timer.live = false;\n // a timer that came due during a block runs late, at the time of the clock\n now = Math.max(now, timer.at);\n timer.run();\n await settle();\n }\n now = Math.max(now, end);\n for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at]!.live) timers.splice(at, 1);\n await settle();\n },\n block(ms) {\n now += Math.max(0, ms);\n },\n get pending() {\n return timers.filter((timer) => timer.live).length;\n },\n };\n};\n\n/** A fake wall clock moves only when a test tells it to. A test can also step its instant, as a wall clock steps. */\nexport interface FakeWallClock extends WallClock {\n /** This method moves the instant and the monotonic time forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /** This method moves the instant and the monotonic time forward by `ms`, and starts no timer, as a blocked event loop does. */\n block(ms: number): void;\n /** This method steps the instant to `instant`, forward or back. The monotonic time does not move, thus no timer comes due. */\n set(instant: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/**\n * This function makes a fake wall clock. Its instant starts at `start`, in milliseconds from the\n * epoch. Its timers are the timers of a `fakeClock`, thus a step of the instant moves no timer.\n */\nexport const fakeWallClock = (start: number): FakeWallClock => {\n const monotonicTime = fakeClock(0);\n let offset = start;\n return {\n time: \"wall\",\n now: () => monotonicTime.now() + offset,\n after: (ms, run) => monotonicTime.after(ms, run),\n advance: (ms) => monotonicTime.advance(ms),\n block(ms) {\n monotonicTime.block(ms);\n },\n set(instant) {\n offset = instant - monotonicTime.now();\n },\n get pending() {\n return monotonicTime.pending;\n },\n };\n};\n\n// Civil time: the wall-clock time of an instant in a time zone, and windows of local time. A clock\n// gives instants, and civil time maps an instant to the time on the wall of a zone. It uses only\n// `Intl.DateTimeFormat`, thus this entry still imports nothing.\n\n/**\n * The wall-clock time of an instant in a time zone. An instant is a time in milliseconds from\n * 1970-01-01T00:00:00Z, as `Date.now()` and `WallClock.now()` give. It is not the monotonic time of `Clock.now()`.\n */\nexport interface LocalTime {\n readonly year: number;\n /** The month, from 1 (January) to 12. */\n readonly month: number;\n /** The day of the month, from 1. */\n readonly day: number;\n /** The hour, from 0 to 23. */\n readonly hour: number;\n readonly minute: number;\n readonly second: number;\n /** The day of the week, from 0 (Sunday) to 6 (Saturday). */\n readonly weekday: number;\n /** The offset of the zone from UTC at the instant, in minutes. It is positive east of Greenwich. */\n readonly offset: number;\n}\n\n/**\n * A window of local time that occurs on each day, or on some days of the week. The window is\n * data, thus a configuration can hold it.\n *\n * - The start is in the window, and the end is not.\n * - An end before the start crosses midnight. An end equal to the start gives a window of a full day.\n * - In a change of the clock, the window follows the time on the wall. A start or an end in a gap\n * moves to the end of the gap. Thus a window with its start and its end in one gap does not open.\n * - A local time that occurs two times is in the window two times.\n */\nexport interface TimeWindow {\n /** The IANA name of the time zone, for example `Europe/Berlin`. */\n readonly zone: string;\n /** The start, a local time `HH:MM` from `00:00` to `23:59`. */\n readonly start: string;\n /** The end, a local time `HH:MM` from `00:00` to `23:59`. */\n readonly end: string;\n /**\n * The days of the week on which the window starts, from 0 (Sunday) to 6. When it is absent, the\n * window starts on each day. A window across midnight continues into the next day.\n */\n readonly days?: readonly number[] | undefined;\n}\n\n/** A change of a window: the instant at which it opens or closes. */\nexport interface WindowBoundary {\n readonly at: number;\n /** True: the window opens at `at`. False: it closes. */\n readonly opens: boolean;\n}\n\nconst MINUTE_MS = 60_000;\nconst DAY_MS = 86_400_000;\nconst WEEKDAYS: Readonly<Record<string, number>> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };\nconst LOCAL_TIME = /^([01]\\d|2[0-3]):([0-5]\\d)$/;\n\n/**\n * The cache has one format for each good zone name. It keeps no bad name, and it starts again at\n * `ZONE_CACHE_MAX` names. Thus names from configuration input cannot make it grow without a limit.\n */\nconst ZONE_FORMATS = new Map<string, Intl.DateTimeFormat>();\nconst ZONE_CACHE_MAX = 512;\n/** The longest IANA name has 32 characters. A longer name than this limit is not a zone. */\nconst ZONE_NAME_MAX = 100;\n\nconst zoneFormat = (zone: string): Intl.DateTimeFormat | undefined => {\n let format = ZONE_FORMATS.get(zone);\n if (format === undefined) {\n if (typeof zone !== \"string\" || zone.length > ZONE_NAME_MAX) return undefined;\n try {\n format = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n hourCycle: \"h23\",\n era: \"short\",\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n weekday: \"short\",\n });\n } catch {\n return undefined;\n }\n if (ZONE_FORMATS.size >= ZONE_CACHE_MAX) ZONE_FORMATS.clear();\n ZONE_FORMATS.set(zone, format);\n }\n return format;\n};\n\n/**\n * This function gives the wall-clock time of `instant` in `zone`. It gives `undefined` for a name\n * that is not a time zone, and for an instant that is not a date.\n */\nexport function localTime(instant: number, zone: string): LocalTime | undefined {\n const format = zoneFormat(zone);\n if (format === undefined || !Number.isFinite(instant)) return undefined;\n let parts: Intl.DateTimeFormatPart[];\n try {\n parts = format.formatToParts(instant);\n } catch {\n // an instant out of the range of a date\n return undefined;\n }\n const field: Record<string, string> = {};\n for (const part of parts) field[part.type] = part.value;\n const before = field[\"era\"] === \"BC\" || field[\"era\"] === \"B\";\n const year = before ? 1 - Number(field[\"year\"]) : Number(field[\"year\"]);\n const month = Number(field[\"month\"]);\n const day = Number(field[\"day\"]);\n const hour = Number(field[\"hour\"]) % 24;\n const minute = Number(field[\"minute\"]);\n const second = Number(field[\"second\"]);\n const whole = Math.floor(instant / 1000) * 1000;\n return { year, month, day, hour, minute, second, weekday: WEEKDAYS[field[\"weekday\"] ?? \"\"] ?? 0, offset: (wallOf(year, month, day, hour, minute, second) - whole) / MINUTE_MS };\n}\n\n/** The wall-clock time as an instant in UTC. `Date.UTC` reads a year from 0 to 99 as 1900 to 1999, thus this function sets the year by itself. */\nconst wallOf = (year: number, month: number, day: number, hour: number, minute: number, second: number): number => {\n const wall = new Date(0);\n wall.setUTCFullYear(year, month - 1, day);\n wall.setUTCHours(hour, minute, second, 0);\n return wall.getTime();\n};\n\n/** The minutes from midnight of a local time `HH:MM`. */\nconst minutesOf = (time: string): number | undefined => {\n const match = LOCAL_TIME.exec(time);\n return match === null ? undefined : Number(match[1]) * 60 + Number(match[2]);\n};\n\ninterface CheckedWindow {\n readonly start: number;\n readonly end: number;\n readonly days: ReadonlySet<number> | undefined;\n}\n\nconst isDay = (day: number): boolean => Number.isInteger(day) && day >= 0 && day <= 6;\n\nconst checked = (window: TimeWindow): CheckedWindow | undefined => {\n const start = minutesOf(window.start);\n const end = minutesOf(window.end);\n if (start === undefined || end === undefined || zoneFormat(window.zone) === undefined) return undefined;\n if (window.days !== undefined && !window.days.every(isDay)) return undefined;\n return { start, end, days: window.days === undefined ? undefined : new Set(window.days) };\n};\n\nconst within = (window: CheckedWindow, local: LocalTime): boolean => {\n const minute = local.hour * 60 + local.minute;\n const startsOn = (weekday: number): boolean => window.days === undefined || window.days.has(weekday);\n if (window.start < window.end) return window.start <= minute && minute < window.end && startsOn(local.weekday);\n // across midnight, or a full day: the part from the start, then the part before the end on the next day\n return (minute >= window.start && startsOn(local.weekday)) || (minute < window.end && startsOn((local.weekday + 6) % 7));\n};\n\n/**\n * This function tells if `instant` is in the window. It does not throw. A bad window or a bad\n * instant gives `false`, and `windowProblems` finds the bad window.\n */\nexport function inWindow(instant: number, window: TimeWindow): boolean {\n const valid = checked(window);\n const local = valid === undefined ? undefined : localTime(instant, window.zone);\n return valid !== undefined && local !== undefined && within(valid, local);\n}\n\n/**\n * This function gives the instants at which the wall clock of `zone` shows `wall`, in order. It is\n * the inverse of `localTime`. The wall-clock time is in milliseconds with the arithmetic of UTC: the\n * UTC fields of `new Date(wall)` are the fields of the wall clock.\n *\n * - A wall-clock time in the gap of a change forward gives no instant.\n * - A wall-clock time in the hour of a change back gives two instants.\n * - A name that is not a time zone, or a wall-clock time that is not a date, gives `undefined`.\n *\n * The rule for a gap or for two instants is a choice of the caller. For example, RFC 5545 takes the\n * first of two instants, and in a gap it takes the offset before the gap. The search reads the\n * offset one day before and one day after `wall`. Thus it finds each instant when the offset\n * changes at most one time in these 2 days.\n */\nexport function instantsOf(wall: number, zone: string): number[] | undefined {\n if (zoneFormat(zone) === undefined || !Number.isFinite(wall)) return undefined;\n // localTime gives whole seconds: the search uses the whole second, and adds the milliseconds at the end\n const whole = Math.floor(wall / 1000) * 1000;\n const offsets = new Set<number>();\n for (const probe of [whole - DAY_MS, whole, whole + DAY_MS]) {\n const local = localTime(probe, zone);\n if (local !== undefined) offsets.add(local.offset);\n }\n // no offset: the wall-clock time is out of the range of a date\n if (offsets.size === 0) return undefined;\n const found: number[] = [];\n for (const offset of offsets) {\n // an old offset of local mean time has seconds, thus the product is rounded to the millisecond\n const instant = whole - Math.round(offset * MINUTE_MS);\n const local = localTime(instant, zone);\n if (local === undefined) continue;\n const back = wallOf(local.year, local.month, local.day, local.hour, local.minute, local.second);\n if (back === whole && !found.includes(instant)) found.push(instant);\n }\n return found.sort((a, b) => a - b).map((instant) => instant + (wall - whole));\n}\n\n/**\n * This function gives the instants in `(from, to]` at which the offset of `zone` changes, in order\n * and exact to the millisecond. At each instant, the new offset starts. The search reads the offset\n * each 6 hours of the range, thus a long range costs more reads. No zone changes its offset two\n * times in 6 hours. A name that is not a time zone, or a bound that is not a date, gives `undefined`.\n */\nexport function offsetChanges(from: number, to: number, zone: string): number[] | undefined {\n if (localTime(from, zone) === undefined || localTime(to, zone) === undefined) return undefined;\n return changesOf(from, to, zone);\n}\n\n/** The instants in (from, to] at which the offset of the zone changes. `offsetChanges` tells the rule. */\nconst changesOf = (from: number, to: number, zone: string): number[] => {\n const offsetAt = (instant: number): number | undefined => localTime(instant, zone)?.offset;\n const found: number[] = [];\n let low = from;\n let before = offsetAt(low);\n while (low < to) {\n const high = Math.min(low + DAY_MS / 4, to);\n const after = offsetAt(high);\n if (before !== undefined && after !== undefined && after !== before) {\n // the first instant with the new offset\n let left = low;\n let right = high;\n while (right - left > 1) {\n const middle = Math.floor((left + right) / 2);\n if (offsetAt(middle) === before) left = middle;\n else right = middle;\n }\n found.push(right);\n }\n low = high;\n before = after;\n }\n return found;\n};\n\n/**\n * This function gives the first instant at which the wall clock of `zone` shows `wall` or a later\n * wall-clock time. The wall-clock time is in milliseconds with the arithmetic of UTC, as for\n * `instantsOf`. Thus a time on the wall, for example the start of a day, always has an instant.\n *\n * - A wall-clock time that occurs one time gives its instant.\n * - A wall-clock time in the hour of a change back gives the first of its two instants.\n * - A wall-clock time in the gap of a change forward gives the instant of the change: the end of the gap.\n * - A name that is not a time zone, or a wall-clock time that is not a date, gives `undefined`.\n *\n * The search reads the offset one day before and one day after `wall`, as `instantsOf` does. A gap\n * that is not in these 2 days also gives `undefined`.\n */\nexport function firstInstantOf(wall: number, zone: string): number | undefined {\n const instants = instantsOf(wall, zone);\n if (instants === undefined) return undefined;\n if (instants.length > 0) return instants[0];\n const whole = Math.floor(wall / 1000) * 1000;\n const offsets: number[] = [];\n for (const probe of [whole - DAY_MS, whole, whole + DAY_MS]) {\n const local = localTime(probe, zone);\n if (local !== undefined) offsets.push(Math.round(local.offset * MINUTE_MS));\n }\n // A change at the instant c, from the offset o1 to the larger offset o2, skips the wall-clock times\n // from c + o1 to c + o2, without the end. Thus c is after wall - o2, and at or before wall - o1.\n const from = wall - Math.max(...offsets);\n const to = wall - Math.min(...offsets);\n const offsetAt = (instant: number): number | undefined => {\n const local = localTime(instant, zone);\n return local === undefined ? undefined : Math.round(local.offset * MINUTE_MS);\n };\n for (const change of changesOf(from, to, zone)) {\n const before = offsetAt(change - 1);\n const after = offsetAt(change);\n if (before !== undefined && after !== undefined && change + before <= wall && wall < change + after) return change;\n }\n return undefined;\n}\n\n/**\n * This function gives the next change of the window after `instant`: the first later instant at\n * which the window opens or closes. A timer can wait for it in closed form. It gives `undefined`\n * for a bad window, and when the window does not change in the 9 days after `instant`. A window\n * with no day and a full-day window on each day do not change.\n */\nexport function nextBoundary(instant: number, window: TimeWindow): WindowBoundary | undefined {\n const valid = checked(window);\n const local = valid === undefined ? undefined : localTime(instant, window.zone);\n if (valid === undefined || local === undefined) return undefined;\n const inside = within(valid, local);\n const horizon = instant + 9 * DAY_MS;\n // The state changes only where the wall clock shows the start or the end, or where the offset changes.\n const candidates = changesOf(instant, horizon, window.zone);\n const midnight = wallOf(local.year, local.month, local.day, 0, 0, 0);\n for (let day = -1; day <= 10; day += 1) {\n for (const minutes of [valid.start, valid.end]) candidates.push(...(instantsOf(midnight + day * DAY_MS + minutes * MINUTE_MS, window.zone) ?? []));\n }\n candidates.sort((a, b) => a - b);\n for (const at of candidates) {\n if (at <= instant || at > horizon) continue;\n const there = localTime(at, window.zone);\n if (there !== undefined && within(valid, there) !== inside) return { at, opens: !inside };\n }\n return undefined;\n}\n\n/** This function gives the problems of a window. With a problem, `inWindow` gives `false` and `nextBoundary` gives `undefined`. */\nexport function windowProblems(window: TimeWindow): string[] {\n const problems: string[] = [];\n if (zoneFormat(window.zone) === undefined) problems.push(`\"${window.zone}\" is not the IANA name of a time zone.`);\n if (minutesOf(window.start) === undefined) problems.push(`The start \"${window.start}\" is not a local time HH:MM from 00:00 to 23:59.`);\n if (minutesOf(window.end) === undefined) problems.push(`The end \"${window.end}\" is not a local time HH:MM from 00:00 to 23:59.`);\n for (const day of window.days ?? []) {\n if (!isDay(day)) problems.push(`The day ${day} is not a day of the week from 0 (Sunday) to 6.`);\n }\n if (window.days !== undefined && window.days.length === 0) problems.push(\"The window has no day, thus it does not open.\");\n return problems;\n}\n"],"mappings":";;AAgEA,MAAM,kBAA0B;CAC9B,MAAM,cAAe,WAAmD;CACxE,OAAO,gBAAgB,KAAA,IAAY,KAAK,IAAI,IAAI,YAAY,IAAI;AAClE;;AAGA,MAAM,gBAAgB;;AAGtB,MAAM,WAAW,YAA0C;CACzD,MAAM,QAAQ,QAAQ,SAAS;CAC/B,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,GAAG,MAAM,IAAI,WAAW,aAAa,OAAO,KAAK,EAAE,iCAAiC;CACzJ,MAAM,QAAQ,QAAQ;CACtB,IAAI,UAAU,KAAA,MAAc,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,IAAI,MAAM,IAAI,WAAW,aAAa,OAAO,KAAK,EAAE,yBAAyB;CAC5J,OAAO;AACT;;;;;;;AAQA,MAAM,YACH,UAAmB,OAAe,SAClC,IAAI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AAW,OAAO,IAAI,MAAM,KAAA,GAAW,SAAS,KAAK,IAAI,OAAO,KAAK,uCAAuC;CAChH,IAAI,UAAU,OAAO,KAAK,MAAM,KAAA,GAAW,SAAS,KAAK,cAAc,OAAO,MAAM,iDAAiD;CACrI,IAAI,UAAU,OAAO,GAAG,MAAM,KAAA,GAAW,SAAS,KAAK,YAAY,OAAO,IAAI,iDAAiD;CAC/H,KAAK,MAAM,OAAO,OAAO,QAAQ,CAAC,GAChC,IAAI,CAAC,MAAM,GAAG,GAAG,SAAS,KAAK,WAAW,IAAI,gDAAgD;CAEhG,IAAI,OAAO,SAAS,KAAA,KAAa,OAAO,KAAK,WAAW,GAAG,SAAS,KAAK,+CAA+C;CACxH,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"clock.js","names":[],"sources":["../src/clock.ts"],"sourcesContent":["// @mark1russell7/algebra/clock: the clock of a runtime, a fake clock for tests, and civil time. It imports\n// nothing: no `node:` module, no zod and no other package. Thus a client in a browser can use it.\n// The service gives this clock again as @mark1russell7/service/clock.\n\n/**\n * This function stops a timer that `Clock.after` started. A second use does nothing. A clock of\n * the platform also gives `unref`: after it, the timer does not keep a Node process alive.\n */\nexport type Cancel = (() => void) & { readonly unref?: (() => void) | undefined };\n\n/**\n * A clock gives the monotonic time in milliseconds, and it starts a function after a delay. The\n * runtime reads time only through a clock. Thus a test can give a fake clock, and the timing of\n * the runtime is then exact and repeatable.\n */\nexport interface Clock {\n /**\n * This mark tells the time of `now()`. A clock gives the monotonic time, thus the mark is\n * `\"monotonic\"` or absent. A `WallClock` has the mark `\"wall\"`, thus it is not a `Clock`.\n */\n readonly time?: \"monotonic\" | undefined;\n /** This method gives the monotonic time, in milliseconds. A step of the wall clock does not move it. */\n now(): number;\n /** This method starts `run` after `ms` milliseconds, and gives the function that stops it. */\n after(ms: number, run: () => void): Cancel;\n}\n\n/**\n * A wall clock gives the instant: the time in milliseconds from 1970-01-01T00:00:00Z, as `Date.now()`\n * gives it. Civil time, a calendar and a time that another computer sends need the instant. A step\n * of the wall clock moves `now()`, also back. Each timer waits on the monotonic time, thus a step\n * does not move a timer. The mark `\"wall\"` keeps the two clocks apart: a function that needs the\n * monotonic time does not get a wall clock, and the reverse.\n */\nexport interface WallClock {\n readonly time: \"wall\";\n /** This method gives the instant, in milliseconds from the epoch. A step of the wall clock moves it. */\n now(): number;\n /** This method starts `run` after `ms` milliseconds of monotonic time, and gives the function that stops it. */\n after(ms: number, run: () => void): Cancel;\n}\n\n/**\n * These options make a clock of the platform. With a speed or a start, the clock is scaled: it\n * counts from its start on the monotonic time of the platform, `speed` times faster. Thus a test\n * runs a long schedule in a short real time, on the real timers.\n */\nexport interface PlatformClockOptions {\n /** True makes each timer not keep a Node process alive. The default is false, as with `setTimeout`. */\n readonly unref?: boolean | undefined;\n /**\n * The milliseconds of the clock in one real millisecond: a finite number above 0. The default is 1.\n * At the speed 60, `now()` moves 60 ms in each real millisecond, and a timer of 60 s ends after 1\n * real second. A speed below 1 gives a slow clock.\n */\n readonly speed?: number | undefined;\n /**\n * The time of `now()` when the clock is made, in milliseconds: a finite number. A wall clock reads\n * it as an instant. The default is the time of the platform at that moment.\n */\n readonly start?: number | undefined;\n}\n\n/** This function gives the monotonic time: `performance.now()`, or `Date.now()` on a platform without `performance`. */\nconst monotonic = (): number => {\n const performance = (globalThis as { performance?: { now(): number } }).performance;\n return performance === undefined ? Date.now() : performance.now();\n};\n\n/** This delay is the longest that `setTimeout` takes, in milliseconds. A longer delay starts the function after 1 ms. */\nconst LONGEST_DELAY = 0x7fffffff;\n\n/** This function gives the speed of the options. It throws a `RangeError` for a bad speed or a bad start. */\nconst speedOf = (options: PlatformClockOptions): number => {\n const speed = options.speed ?? 1;\n if (typeof speed !== \"number\" || !Number.isFinite(speed) || speed <= 0) throw new RangeError(`The speed ${String(speed)} is not a finite number above 0.`);\n const start = options.start;\n if (start !== undefined && (typeof start !== \"number\" || !Number.isFinite(start))) throw new RangeError(`The start ${String(start)} is not a finite number.`);\n return speed;\n};\n\n/**\n * This function makes the timers of a clock of the platform. A timer of `ms` milliseconds on the\n * clock waits `ms / speed` real milliseconds, in steps when `setTimeout` does not take that delay.\n * With `now`, the timer reads the clock when the platform starts it. When the clock is before the\n * due time, the timer waits again for the rest. Thus `run` reads its due time or a later time.\n */\nconst timersOf =\n (unrefAll: boolean, speed: number, now?: () => number): Clock[\"after\"] =>\n (ms, run) => {\n let unrefed = unrefAll;\n const due = now === undefined ? 0 : now() + Math.max(0, ms);\n const fire = (): void => {\n const early = now === undefined ? 0 : due - now();\n if (early > 0) timer = arm(early / speed);\n else run();\n };\n const arm = (left: number): ReturnType<typeof setTimeout> => {\n const step =\n left > LONGEST_DELAY ? setTimeout(() => (timer = arm(left - LONGEST_DELAY)), LONGEST_DELAY) : setTimeout(fire, Math.max(0, left));\n if (unrefed) (step as { unref?: () => void }).unref?.();\n return step;\n };\n let timer = arm(ms / speed);\n const unref = (): void => {\n unrefed = true;\n (timer as { unref?: () => void }).unref?.();\n };\n return Object.assign(() => clearTimeout(timer), { unref });\n };\n\n/**\n * This function makes a clock of the platform: `performance.now()` and `setTimeout`. Each cancel\n * that it gives also has `unref`. A delay longer than `setTimeout` takes waits in steps.\n *\n * The rule of `unref`: each timer keeps a Node process alive, as `setTimeout` does. Thus a process\n * does not end in a wait that a caller awaits. A hang shows, but a silent exit with lost work does not.\n *\n * The owner of a timer uses its `unref` only when a socket, a child process or another hold keeps the\n * process alive. An example is the heartbeat of a connection. Each other timer stays referenced, a\n * ticker too: its caller stops it. The option `unref` makes each timer of the clock an exception.\n *\n * With a speed or a start, `now()` is the start plus the monotonic time since the call, times the\n * speed. A scaled clock reads `performance.now()` at each timer. Thus the fake timers of a test\n * also fake `performance`, else its timers wait again and again.\n *\n * @throws {RangeError} for a speed that is not a finite number above 0, and for a start that is not finite.\n */\nexport const platformClock = (options: PlatformClockOptions = {}): Clock => {\n const speed = speedOf(options);\n const unref = options.unref === true;\n if (speed === 1 && options.start === undefined) return { now: monotonic, after: timersOf(unref, 1) };\n const origin = monotonic();\n const start = options.start ?? origin;\n const now = (): number => start + (monotonic() - origin) * speed;\n return { now, after: timersOf(unref, speed, now) };\n};\n\n/**\n * This clock reads `performance.now()` and uses `setTimeout`. It is `platformClock()`, thus its\n * timers keep a Node process alive, as `setTimeout` does. A process does not end in a wait that a\n * caller awaits, for example a retry.\n *\n * The owner of a timer uses its `unref` only when a socket, a child process or another hold keeps the\n * process alive. Each other timer stays referenced: its caller stops it. A timer that is not stopped\n * delays the exit, and that delay shows.\n *\n * Before algebra 0.9.0, the timers of this clock did not keep the process alive. A process then ended\n * with the code 0 in a wait, and lost its work.\n */\nexport const realClock: Clock = /* @__PURE__ */ platformClock();\n\n/**\n * This function gives a clock with the time of `clock`. Its timers do not keep a Node process alive:\n * each timer uses the `unref` of its cancel. The owner of a part gives it to the part only\n * when a socket, a child process or another hold keeps the process alive. An example is the\n * heartbeat of a connection. A wall clock stays a wall clock. The timers of a fake clock have no\n * `unref`, thus they do not change.\n */\nexport function unrefClock(clock: Clock): Clock;\nexport function unrefClock(clock: WallClock): WallClock;\nexport function unrefClock(clock: Clock | WallClock): Clock | WallClock {\n const after = (ms: number, run: () => void): Cancel => {\n const cancel = clock.after(ms, run);\n cancel.unref?.();\n return cancel;\n };\n const now = (): number => clock.now();\n return clock.time === \"wall\" ? { time: \"wall\", now, after } : { now, after };\n}\n\n/**\n * This function makes the wall clock of the platform: `Date.now()`, and the timers of\n * `platformClock`. The options are the options of `platformClock`.\n *\n * With a speed or a start, `now()` is the start plus the monotonic time since the call, times the\n * speed. It gives whole milliseconds, as `Date.now()` does. The default start is `Date.now()`.\n * A step of the wall clock of the platform does not move a scaled clock.\n *\n * @throws {RangeError} for a speed that is not a finite number above 0, and for a start that is not finite.\n */\nexport const wallClock = (options: PlatformClockOptions = {}): WallClock => {\n const speed = speedOf(options);\n const unref = options.unref === true;\n if (speed === 1 && options.start === undefined) return { time: \"wall\", now: () => Date.now(), after: timersOf(unref, 1) };\n const origin = monotonic();\n const start = options.start ?? Date.now();\n const now = (): number => Math.floor(start + (monotonic() - origin) * speed);\n return { time: \"wall\", now, after: timersOf(unref, speed, now) };\n};\n\n/**\n * This function gives a promise that resolves after `ms` milliseconds on the clock. When the signal\n * aborts, the promise stops its timer and rejects with the reason of the signal. A signal that\n * aborted before the call rejects at once, and starts no timer. Each end removes the listener from\n * the signal. A timer of `realClock` keeps a Node process alive until the delay ends. The clock is\n * a `Clock` or a `WallClock`: the function uses only its timers, and each timer of the two waits\n * on the monotonic time.\n */\nexport const delay = (clock: Pick<Clock, \"after\">, ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted === true) {\n reject(signal.reason);\n return;\n }\n const abort = (): void => {\n cancel();\n reject(signal?.reason);\n };\n const cancel = clock.after(ms, () => {\n signal?.removeEventListener(\"abort\", abort);\n resolve();\n });\n signal?.addEventListener(\"abort\", abort, { once: true });\n });\n\n/** A fake clock moves only when a test tells it to. */\nexport interface FakeClock extends Clock {\n /** This method moves the clock forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /**\n * This method moves the clock forward by `ms` and starts no timer, as a blocked event loop does.\n * The next `advance` then starts each timer that came due during the block, late.\n */\n block(ms: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/** This function lets the promises that are ready continue, before the clock moves again. */\nconst settle = async (): Promise<void> => {\n for (let turn = 0; turn < 64; turn += 1) await Promise.resolve();\n};\n\n/** This function makes a fake clock. Its time starts at `start` milliseconds. */\nexport const fakeClock = (start = 0): FakeClock => {\n let now = start;\n let sequence = 0;\n const timers: Array<{ at: number; order: number; run: () => void; live: boolean }> = [];\n const due = (end: number) => {\n let best: (typeof timers)[number] | undefined;\n for (const timer of timers)\n if (timer.live && timer.at <= end && (best === undefined || timer.at < best.at || (timer.at === best.at && timer.order < best.order)))\n best = timer;\n return best;\n };\n return {\n now: () => now,\n after(ms, run): Cancel {\n const timer = { at: now + Math.max(0, ms), order: sequence++, run, live: true };\n timers.push(timer);\n return () => {\n timer.live = false;\n };\n },\n async advance(ms) {\n // a monotonic clock does not go back\n const end = now + Math.max(0, ms);\n await settle();\n for (;;) {\n const timer = due(end);\n if (timer === undefined) break;\n timer.live = false;\n // a timer that came due during a block runs late, at the time of the clock\n now = Math.max(now, timer.at);\n timer.run();\n await settle();\n }\n now = Math.max(now, end);\n for (let at = timers.length - 1; at >= 0; at -= 1) if (!timers[at]!.live) timers.splice(at, 1);\n await settle();\n },\n block(ms) {\n now += Math.max(0, ms);\n },\n get pending() {\n return timers.filter((timer) => timer.live).length;\n },\n };\n};\n\n/** A fake wall clock moves only when a test tells it to. A test can also step its instant, as a wall clock steps. */\nexport interface FakeWallClock extends WallClock {\n /** This method moves the instant and the monotonic time forward by `ms`, and it starts each timer that comes due, in sequence. */\n advance(ms: number): Promise<void>;\n /** This method moves the instant and the monotonic time forward by `ms`, and starts no timer, as a blocked event loop does. */\n block(ms: number): void;\n /** This method steps the instant to `instant`, forward or back. The monotonic time does not move, thus no timer comes due. */\n set(instant: number): void;\n /** This count is the number of timers that are not stopped and not called. */\n readonly pending: number;\n}\n\n/**\n * This function makes a fake wall clock. Its instant starts at `start`, in milliseconds from the\n * epoch. Its timers are the timers of a `fakeClock`, thus a step of the instant moves no timer.\n */\nexport const fakeWallClock = (start: number): FakeWallClock => {\n const monotonicTime = fakeClock(0);\n let offset = start;\n return {\n time: \"wall\",\n now: () => monotonicTime.now() + offset,\n after: (ms, run) => monotonicTime.after(ms, run),\n advance: (ms) => monotonicTime.advance(ms),\n block(ms) {\n monotonicTime.block(ms);\n },\n set(instant) {\n offset = instant - monotonicTime.now();\n },\n get pending() {\n return monotonicTime.pending;\n },\n };\n};\n\n// Civil time: the wall-clock time of an instant in a time zone, and windows of local time. A clock\n// gives instants, and civil time maps an instant to the time on the wall of a zone. It uses only\n// `Intl.DateTimeFormat`, thus this entry still imports nothing.\n\n/**\n * The wall-clock time of an instant in a time zone. An instant is a time in milliseconds from\n * 1970-01-01T00:00:00Z, as `Date.now()` and `WallClock.now()` give. It is not the monotonic time of `Clock.now()`.\n */\nexport interface LocalTime {\n readonly year: number;\n /** The month, from 1 (January) to 12. */\n readonly month: number;\n /** The day of the month, from 1. */\n readonly day: number;\n /** The hour, from 0 to 23. */\n readonly hour: number;\n readonly minute: number;\n readonly second: number;\n /** The day of the week, from 0 (Sunday) to 6 (Saturday). */\n readonly weekday: number;\n /** The offset of the zone from UTC at the instant, in minutes. It is positive east of Greenwich. */\n readonly offset: number;\n}\n\n/**\n * A window of local time that occurs on each day, or on some days of the week. The window is\n * data, thus a configuration can hold it.\n *\n * - The start is in the window, and the end is not.\n * - An end before the start crosses midnight. An end equal to the start gives a window of a full day.\n * - In a change of the clock, the window follows the time on the wall. A start or an end in a gap\n * moves to the end of the gap. Thus a window with its start and its end in one gap does not open.\n * - A local time that occurs two times is in the window two times.\n */\nexport interface TimeWindow {\n /** The IANA name of the time zone, for example `Europe/Berlin`. */\n readonly zone: string;\n /** The start, a local time `HH:MM` from `00:00` to `23:59`. */\n readonly start: string;\n /** The end, a local time `HH:MM` from `00:00` to `23:59`. */\n readonly end: string;\n /**\n * The days of the week on which the window starts, from 0 (Sunday) to 6. When it is absent, the\n * window starts on each day. A window across midnight continues into the next day.\n */\n readonly days?: readonly number[] | undefined;\n}\n\n/** A change of a window: the instant at which it opens or closes. */\nexport interface WindowBoundary {\n readonly at: number;\n /** True: the window opens at `at`. False: it closes. */\n readonly opens: boolean;\n}\n\nconst MINUTE_MS = 60_000;\nconst DAY_MS = 86_400_000;\nconst WEEKDAYS: Readonly<Record<string, number>> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };\nconst LOCAL_TIME = /^([01]\\d|2[0-3]):([0-5]\\d)$/;\n\n/**\n * The cache has one format for each good zone name. It keeps no bad name, and it starts again at\n * `ZONE_CACHE_MAX` names. Thus names from configuration input cannot make it grow without a limit.\n */\nconst ZONE_FORMATS = new Map<string, Intl.DateTimeFormat>();\nconst ZONE_CACHE_MAX = 512;\n/** The longest IANA name has 32 characters. A longer name than this limit is not a zone. */\nconst ZONE_NAME_MAX = 100;\n\nconst zoneFormat = (zone: string): Intl.DateTimeFormat | undefined => {\n let format = ZONE_FORMATS.get(zone);\n if (format === undefined) {\n if (typeof zone !== \"string\" || zone.length > ZONE_NAME_MAX) return undefined;\n try {\n format = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n hourCycle: \"h23\",\n era: \"short\",\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n weekday: \"short\",\n });\n } catch {\n return undefined;\n }\n if (ZONE_FORMATS.size >= ZONE_CACHE_MAX) ZONE_FORMATS.clear();\n ZONE_FORMATS.set(zone, format);\n }\n return format;\n};\n\n/**\n * This function gives the wall-clock time of `instant` in `zone`. It gives `undefined` for a name\n * that is not a time zone, and for an instant that is not a date.\n */\nexport function localTime(instant: number, zone: string): LocalTime | undefined {\n const format = zoneFormat(zone);\n if (format === undefined || !Number.isFinite(instant)) return undefined;\n let parts: Intl.DateTimeFormatPart[];\n try {\n parts = format.formatToParts(instant);\n } catch {\n // an instant out of the range of a date\n return undefined;\n }\n const field: Record<string, string> = {};\n for (const part of parts) field[part.type] = part.value;\n const before = field[\"era\"] === \"BC\" || field[\"era\"] === \"B\";\n const year = before ? 1 - Number(field[\"year\"]) : Number(field[\"year\"]);\n const month = Number(field[\"month\"]);\n const day = Number(field[\"day\"]);\n const hour = Number(field[\"hour\"]) % 24;\n const minute = Number(field[\"minute\"]);\n const second = Number(field[\"second\"]);\n const whole = Math.floor(instant / 1000) * 1000;\n return { year, month, day, hour, minute, second, weekday: WEEKDAYS[field[\"weekday\"] ?? \"\"] ?? 0, offset: (wallOf(year, month, day, hour, minute, second) - whole) / MINUTE_MS };\n}\n\n/** The wall-clock time as an instant in UTC. `Date.UTC` reads a year from 0 to 99 as 1900 to 1999, thus this function sets the year by itself. */\nconst wallOf = (year: number, month: number, day: number, hour: number, minute: number, second: number): number => {\n const wall = new Date(0);\n wall.setUTCFullYear(year, month - 1, day);\n wall.setUTCHours(hour, minute, second, 0);\n return wall.getTime();\n};\n\n/** The minutes from midnight of a local time `HH:MM`. */\nconst minutesOf = (time: string): number | undefined => {\n const match = LOCAL_TIME.exec(time);\n return match === null ? undefined : Number(match[1]) * 60 + Number(match[2]);\n};\n\ninterface CheckedWindow {\n readonly start: number;\n readonly end: number;\n readonly days: ReadonlySet<number> | undefined;\n}\n\nconst isDay = (day: number): boolean => Number.isInteger(day) && day >= 0 && day <= 6;\n\nconst checked = (window: TimeWindow): CheckedWindow | undefined => {\n const start = minutesOf(window.start);\n const end = minutesOf(window.end);\n if (start === undefined || end === undefined || zoneFormat(window.zone) === undefined) return undefined;\n if (window.days !== undefined && !window.days.every(isDay)) return undefined;\n return { start, end, days: window.days === undefined ? undefined : new Set(window.days) };\n};\n\nconst within = (window: CheckedWindow, local: LocalTime): boolean => {\n const minute = local.hour * 60 + local.minute;\n const startsOn = (weekday: number): boolean => window.days === undefined || window.days.has(weekday);\n if (window.start < window.end) return window.start <= minute && minute < window.end && startsOn(local.weekday);\n // across midnight, or a full day: the part from the start, then the part before the end on the next day\n return (minute >= window.start && startsOn(local.weekday)) || (minute < window.end && startsOn((local.weekday + 6) % 7));\n};\n\n/**\n * This function tells if `instant` is in the window. It does not throw. A bad window or a bad\n * instant gives `false`, and `windowProblems` finds the bad window.\n */\nexport function inWindow(instant: number, window: TimeWindow): boolean {\n const valid = checked(window);\n const local = valid === undefined ? undefined : localTime(instant, window.zone);\n return valid !== undefined && local !== undefined && within(valid, local);\n}\n\n/**\n * This function gives the instants at which the wall clock of `zone` shows `wall`, in order. It is\n * the inverse of `localTime`. The wall-clock time is in milliseconds with the arithmetic of UTC: the\n * UTC fields of `new Date(wall)` are the fields of the wall clock.\n *\n * - A wall-clock time in the gap of a change forward gives no instant.\n * - A wall-clock time in the hour of a change back gives two instants.\n * - A name that is not a time zone, or a wall-clock time that is not a date, gives `undefined`.\n *\n * The rule for a gap or for two instants is a choice of the caller. For example, RFC 5545 takes the\n * first of two instants, and in a gap it takes the offset before the gap. The search reads the\n * offset one day before and one day after `wall`. Thus it finds each instant when the offset\n * changes at most one time in these 2 days.\n */\nexport function instantsOf(wall: number, zone: string): number[] | undefined {\n if (zoneFormat(zone) === undefined || !Number.isFinite(wall)) return undefined;\n // localTime gives whole seconds: the search uses the whole second, and adds the milliseconds at the end\n const whole = Math.floor(wall / 1000) * 1000;\n const offsets = new Set<number>();\n for (const probe of [whole - DAY_MS, whole, whole + DAY_MS]) {\n const local = localTime(probe, zone);\n if (local !== undefined) offsets.add(local.offset);\n }\n // no offset: the wall-clock time is out of the range of a date\n if (offsets.size === 0) return undefined;\n const found: number[] = [];\n for (const offset of offsets) {\n // an old offset of local mean time has seconds, thus the product is rounded to the millisecond\n const instant = whole - Math.round(offset * MINUTE_MS);\n const local = localTime(instant, zone);\n if (local === undefined) continue;\n const back = wallOf(local.year, local.month, local.day, local.hour, local.minute, local.second);\n if (back === whole && !found.includes(instant)) found.push(instant);\n }\n return found.sort((a, b) => a - b).map((instant) => instant + (wall - whole));\n}\n\n/**\n * This function gives the instants in `(from, to]` at which the offset of `zone` changes, in order\n * and exact to the millisecond. At each instant, the new offset starts. The search reads the offset\n * each 6 hours of the range, thus a long range costs more reads. No zone changes its offset two\n * times in 6 hours. A name that is not a time zone, or a bound that is not a date, gives `undefined`.\n */\nexport function offsetChanges(from: number, to: number, zone: string): number[] | undefined {\n if (localTime(from, zone) === undefined || localTime(to, zone) === undefined) return undefined;\n return changesOf(from, to, zone);\n}\n\n/** The instants in (from, to] at which the offset of the zone changes. `offsetChanges` tells the rule. */\nconst changesOf = (from: number, to: number, zone: string): number[] => {\n const offsetAt = (instant: number): number | undefined => localTime(instant, zone)?.offset;\n const found: number[] = [];\n let low = from;\n let before = offsetAt(low);\n while (low < to) {\n const high = Math.min(low + DAY_MS / 4, to);\n const after = offsetAt(high);\n if (before !== undefined && after !== undefined && after !== before) {\n // the first instant with the new offset\n let left = low;\n let right = high;\n while (right - left > 1) {\n const middle = Math.floor((left + right) / 2);\n if (offsetAt(middle) === before) left = middle;\n else right = middle;\n }\n found.push(right);\n }\n low = high;\n before = after;\n }\n return found;\n};\n\n/**\n * This function gives the first instant at which the wall clock of `zone` shows `wall` or a later\n * wall-clock time. The wall-clock time is in milliseconds with the arithmetic of UTC, as for\n * `instantsOf`. Thus a time on the wall, for example the start of a day, always has an instant.\n *\n * - A wall-clock time that occurs one time gives its instant.\n * - A wall-clock time in the hour of a change back gives the first of its two instants.\n * - A wall-clock time in the gap of a change forward gives the instant of the change: the end of the gap.\n * - A name that is not a time zone, or a wall-clock time that is not a date, gives `undefined`.\n *\n * The search reads the offset one day before and one day after `wall`, as `instantsOf` does. A gap\n * that is not in these 2 days also gives `undefined`.\n */\nexport function firstInstantOf(wall: number, zone: string): number | undefined {\n const instants = instantsOf(wall, zone);\n if (instants === undefined) return undefined;\n if (instants.length > 0) return instants[0];\n const whole = Math.floor(wall / 1000) * 1000;\n const offsets: number[] = [];\n for (const probe of [whole - DAY_MS, whole, whole + DAY_MS]) {\n const local = localTime(probe, zone);\n if (local !== undefined) offsets.push(Math.round(local.offset * MINUTE_MS));\n }\n // A change at the instant c, from the offset o1 to the larger offset o2, skips the wall-clock times\n // from c + o1 to c + o2, without the end. Thus c is after wall - o2, and at or before wall - o1.\n const from = wall - Math.max(...offsets);\n const to = wall - Math.min(...offsets);\n const offsetAt = (instant: number): number | undefined => {\n const local = localTime(instant, zone);\n return local === undefined ? undefined : Math.round(local.offset * MINUTE_MS);\n };\n for (const change of changesOf(from, to, zone)) {\n const before = offsetAt(change - 1);\n const after = offsetAt(change);\n if (before !== undefined && after !== undefined && change + before <= wall && wall < change + after) return change;\n }\n return undefined;\n}\n\n/**\n * This function gives the next change of the window after `instant`: the first later instant at\n * which the window opens or closes. A timer can wait for it in closed form. It gives `undefined`\n * for a bad window, and when the window does not change in the 9 days after `instant`. A window\n * with no day and a full-day window on each day do not change.\n */\nexport function nextBoundary(instant: number, window: TimeWindow): WindowBoundary | undefined {\n const valid = checked(window);\n const local = valid === undefined ? undefined : localTime(instant, window.zone);\n if (valid === undefined || local === undefined) return undefined;\n const inside = within(valid, local);\n const horizon = instant + 9 * DAY_MS;\n // The state changes only where the wall clock shows the start or the end, or where the offset changes.\n const candidates = changesOf(instant, horizon, window.zone);\n const midnight = wallOf(local.year, local.month, local.day, 0, 0, 0);\n for (let day = -1; day <= 10; day += 1) {\n for (const minutes of [valid.start, valid.end]) candidates.push(...(instantsOf(midnight + day * DAY_MS + minutes * MINUTE_MS, window.zone) ?? []));\n }\n candidates.sort((a, b) => a - b);\n for (const at of candidates) {\n if (at <= instant || at > horizon) continue;\n const there = localTime(at, window.zone);\n if (there !== undefined && within(valid, there) !== inside) return { at, opens: !inside };\n }\n return undefined;\n}\n\n/** This function gives the problems of a window. With a problem, `inWindow` gives `false` and `nextBoundary` gives `undefined`. */\nexport function windowProblems(window: TimeWindow): string[] {\n const problems: string[] = [];\n if (zoneFormat(window.zone) === undefined) problems.push(`\"${window.zone}\" is not the IANA name of a time zone.`);\n if (minutesOf(window.start) === undefined) problems.push(`The start \"${window.start}\" is not a local time HH:MM from 00:00 to 23:59.`);\n if (minutesOf(window.end) === undefined) problems.push(`The end \"${window.end}\" is not a local time HH:MM from 00:00 to 23:59.`);\n for (const day of window.days ?? []) {\n if (!isDay(day)) problems.push(`The day ${day} is not a day of the week from 0 (Sunday) to 6.`);\n }\n if (window.days !== undefined && window.days.length === 0) problems.push(\"The window has no day, thus it does not open.\");\n return problems;\n}\n"],"mappings":";;AAgEA,MAAM,kBAA0B;CAC9B,MAAM,cAAe,WAAmD;CACxE,OAAO,gBAAgB,KAAA,IAAY,KAAK,IAAI,IAAI,YAAY,IAAI;AAClE;;AAGA,MAAM,gBAAgB;;AAGtB,MAAM,WAAW,YAA0C;CACzD,MAAM,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OAAO,IAAI;CAC1D,MAAM,WAAW,OAAO,MAAM,MAAM,MAAM,OAAO,MAAM,KAAK,GAAG,GAAG,CAAC;CACnE,KAAK,IAAI,MAAM,IAAI,OAAO,IAAI,OAAO,GACnC,KAAK,MAAM,WAAW,CAAC,MAAM,OAAO,MAAM,GAAG,GAAG,WAAW,KAAK,GAAI,WAAW,WAAW,MAAM,SAAS,UAAU,WAAW,OAAO,IAAI,KAAK,CAAC,CAAE;CAEnJ,WAAW,MAAM,GAAG,MAAM,IAAI,CAAC;CAC/B,KAAK,MAAM,MAAM,YAAY;EAC3B,IAAI,MAAM,WAAW,KAAK,SAAS;EACnC,MAAM,QAAQ,UAAU,IAAI,OAAO,IAAI;EACvC,IAAI,UAAU,KAAA,KAAa,OAAO,OAAO,KAAK,MAAM,QAAQ,OAAO;GAAE;GAAI,OAAO,CAAC;EAAO;CAC1F;AAEF;;AAGA,SAAgB,eAAe,QAA8B;CAC3D,MAAM,WAAqB,CAAC;CAC5B,IAAI,WAAW,OAAO,IAAI,MAAM,KAAA,GAAW,SAAS,KAAK,IAAI,OAAO,KAAK,uCAAuC;CAChH,IAAI,UAAU,OAAO,KAAK,MAAM,KAAA,GAAW,SAAS,KAAK,cAAc,OAAO,MAAM,iDAAiD;CACrI,IAAI,UAAU,OAAO,GAAG,MAAM,KAAA,GAAW,SAAS,KAAK,YAAY,OAAO,IAAI,iDAAiD;CAC/H,KAAK,MAAM,OAAO,OAAO,QAAQ,CAAC,GAChC,IAAI,CAAC,MAAM,GAAG,GAAG,SAAS,KAAK,WAAW,IAAI,gDAAgD;CAEhG,IAAI,OAAO,SAAS,KAAA,KAAa,OAAO,KAAK,WAAW,GAAG,SAAS,KAAK,+CAA+C;CACxH,OAAO;AACT"}
|
package/build/index.d.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import { a as Realization, c as Unit, d as machineProblems, f as readsFired, i as Over, l as Vantage, n as FIRED, o as Timer, r as Machine, s as TransitionDef, t as Expr, u as exprKnobs } from "./machine-yGpVFyfh.js";
|
|
2
2
|
import { i as replay, n as Replayable, r as Transition, t as ReplayOptions } from "./replay-DRTZc7Pw.js";
|
|
3
|
-
import { A as timerBand, C as parseExpr, D as recovery, E as realizationOf, M as timerUnder, N as transitionOn, O as stackedDetection, S as overValues, T as realizationKnobs, _ as detection, a as Detection, b as firings, c as KnobValues, d as Recovery, f as ScheduleOptions, g as algebraProblems, h as TimerBounds, i as Band, j as timerOf, k as synGiveUpSends, l as Manifestation, m as Situation, n as RunMachineOptions, o as Detector, p as Scheduled, r as runMachine, s as Firing, t as MachineRun, u as Node, v as errnoOf, w as probeTrain, x as modelSource, y as evaluate } from "./run-
|
|
3
|
+
import { A as timerBand, C as parseExpr, D as recovery, E as realizationOf, M as timerUnder, N as transitionOn, O as stackedDetection, S as overValues, T as realizationKnobs, _ as detection, a as Detection, b as firings, c as KnobValues, d as Recovery, f as ScheduleOptions, g as algebraProblems, h as TimerBounds, i as Band, j as timerOf, k as synGiveUpSends, l as Manifestation, m as Situation, n as RunMachineOptions, o as Detector, p as Scheduled, r as runMachine, s as Firing, t as MachineRun, u as Node, v as errnoOf, w as probeTrain, x as modelSource, y as evaluate } from "./run-BgUWHAcf.js";
|
|
4
4
|
/** This function gives one value or many values as an array. */
|
|
5
5
|
export declare const arr: <T>(value: T | readonly T[]) => readonly T[];
|
|
6
6
|
/** This function gives the states that a transition leaves. The state "*" is each state that is not final. */
|
|
7
7
|
export declare const fromStates: (m: Pick<Machine, "states">, from: string | readonly string[]) => string[];
|
|
8
|
+
/** This function gives the limit of the accept queue: the backlog of listen(2), clamped to `somaxconn`. */
|
|
9
|
+
export declare const acceptQueueLimit: (backlog: number, somaxconn: number) => number;
|
|
10
|
+
/** This function gives the connections that a full accept queue holds: its limit plus one. */
|
|
11
|
+
export declare const acceptQueueHeld: (backlog: number, somaxconn: number) => number;
|
|
8
12
|
/**
|
|
9
13
|
* This function gives the lowest count of one network namespace after one scan of the conntrack
|
|
10
14
|
* collector under pressure. Each entry of the table can go at that scan. The sources are Linux v7.0,
|
package/build/index.js
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
import { n as fromStates, t as arr } from "./states-DXQbSbfM.js";
|
|
2
|
-
import { C as readsFired, S as machineProblems, _ as timerOf, a as evaluate, b as FIRED, c as overValues, d as realizationKnobs, f as realizationOf, g as timerBand, h as synGiveUpSends, i as errnoOf, l as parseExpr, m as stackedDetection, n as algebraProblems, o as firings, p as recovery, r as detection, s as modelSource, t as runMachine, u as probeTrain, v as timerUnder, x as exprKnobs, y as transitionOn } from "./run-
|
|
2
|
+
import { C as readsFired, S as machineProblems, _ as timerOf, a as evaluate, b as FIRED, c as overValues, d as realizationKnobs, f as realizationOf, g as timerBand, h as synGiveUpSends, i as errnoOf, l as parseExpr, m as stackedDetection, n as algebraProblems, o as firings, p as recovery, r as detection, s as modelSource, t as runMachine, u as probeTrain, v as timerUnder, x as exprKnobs, y as transitionOn } from "./run-J6kGNoF8.js";
|
|
3
3
|
import { replay } from "./replay.js";
|
|
4
|
+
// src/accept-queue.ts
|
|
5
|
+
/**
|
|
6
|
+
* These functions give the counts of the accept queue of a TCP listener. The sources are Linux v6.6.
|
|
7
|
+
*
|
|
8
|
+
* - listen(2) clamps the backlog to `somaxconn` (`net/socket.c`, lines 1873-1879). The compare is
|
|
9
|
+
* unsigned, thus a negative backlog also gives `somaxconn`.
|
|
10
|
+
* - The queue is full when `sk_ack_backlog > sk_max_ack_backlog` (`include/net/sock.h`, lines
|
|
11
|
+
* 1033-1036). Thus the queue holds the limit plus one.
|
|
12
|
+
*
|
|
13
|
+
* The timers of a connection at a full queue are in the document of Linux TCP of
|
|
14
|
+
* `@mark1russell7/machines`: `synack_retransmit` and `synack_giveup`.
|
|
15
|
+
*/
|
|
16
|
+
const count = (value, what) => {
|
|
17
|
+
if (!Number.isSafeInteger(value)) throw new Error(`${what} is not a whole number: ${value}`);
|
|
18
|
+
return value;
|
|
19
|
+
};
|
|
20
|
+
/** This function gives the limit of the accept queue: the backlog of listen(2), clamped to `somaxconn`. */
|
|
21
|
+
const acceptQueueLimit = (backlog, somaxconn) => {
|
|
22
|
+
const max = count(somaxconn, "somaxconn");
|
|
23
|
+
if (max < 0) throw new Error(`somaxconn is less than 0: ${max}`);
|
|
24
|
+
const asked = count(backlog, "the backlog");
|
|
25
|
+
return asked < 0 || asked > max ? max : asked;
|
|
26
|
+
};
|
|
27
|
+
/** This function gives the connections that a full accept queue holds: its limit plus one. */
|
|
28
|
+
const acceptQueueHeld = (backlog, somaxconn) => acceptQueueLimit(backlog, somaxconn) + 1;
|
|
4
29
|
// src/conntrack.ts
|
|
5
30
|
/**
|
|
6
31
|
* This function gives the lowest count of one network namespace after one scan of the conntrack
|
|
@@ -22,6 +47,6 @@ const conntrackFloor = (max, hz, expired = 0) => {
|
|
|
22
47
|
const drops = Math.max(0, Math.floor(64e3 / hz) + 1 - expired);
|
|
23
48
|
return Math.max(Math.floor(max / 100) * 95 - 1, max - drops);
|
|
24
49
|
};
|
|
25
|
-
export { FIRED, algebraProblems, arr, conntrackFloor, detection, errnoOf, evaluate, exprKnobs, firings, fromStates, machineProblems, modelSource, overValues, parseExpr, probeTrain, readsFired, realizationKnobs, realizationOf, recovery, replay, runMachine, stackedDetection, synGiveUpSends, timerBand, timerOf, timerUnder, transitionOn };
|
|
50
|
+
export { FIRED, acceptQueueHeld, acceptQueueLimit, algebraProblems, arr, conntrackFloor, detection, errnoOf, evaluate, exprKnobs, firings, fromStates, machineProblems, modelSource, overValues, parseExpr, probeTrain, readsFired, realizationKnobs, realizationOf, recovery, replay, runMachine, stackedDetection, synGiveUpSends, timerBand, timerOf, timerUnder, transitionOn };
|
|
26
51
|
|
|
27
52
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/conntrack.ts"],"sourcesContent":["/**\n * This function gives the lowest count of one network namespace after one scan of the conntrack\n * collector under pressure. Each entry of the table can go at that scan. The sources are Linux v7.0,\n * `net/netfilter/nf_conntrack_core.c`.\n *\n * - The scan starts to drop at `nf_conntrack_max / 100 * 95`, in integer arithmetic (lines 1526-1527).\n * It drops an entry while the count is at that value or above it (lines 1605-1608). Thus this limit\n * stops the scan one entry below the value.\n * - A scan ends when its count of entries is more than `64000 / HZ` (line 97, lines 1561-1572). That end\n * clears the pressure (lines 1645-1646). Thus this limit stops the scan after `64000 / HZ + 1` entries.\n * - That count also holds each entry that expired by its own timeout, in any namespace (lines\n * 1575-1578). Thus `expired` such entries before the end take `expired` drops from the namespace.\n *\n * The limit that stops the scan first gives the floor. `expired` is 0 by default, which gives the\n * lowest floor. On a host with other flows, a scan can find some, and the floor is higher.\n */\nexport const conntrackFloor = (max: number, hz: number, expired = 0): number => {\n const drops = Math.max(0, Math.floor(64000 / hz) + 1 - expired);\n return Math.max(Math.floor(max / 100) * 95 - 1, max - drops);\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/accept-queue.ts","../src/conntrack.ts"],"sourcesContent":["/**\n * These functions give the counts of the accept queue of a TCP listener. The sources are Linux v6.6.\n *\n * - listen(2) clamps the backlog to `somaxconn` (`net/socket.c`, lines 1873-1879). The compare is\n * unsigned, thus a negative backlog also gives `somaxconn`.\n * - The queue is full when `sk_ack_backlog > sk_max_ack_backlog` (`include/net/sock.h`, lines\n * 1033-1036). Thus the queue holds the limit plus one.\n *\n * The timers of a connection at a full queue are in the document of Linux TCP of\n * `@mark1russell7/machines`: `synack_retransmit` and `synack_giveup`.\n */\n\nconst count = (value: number, what: string): number => {\n if (!Number.isSafeInteger(value)) throw new Error(`${what} is not a whole number: ${value}`);\n return value;\n};\n\n/** This function gives the limit of the accept queue: the backlog of listen(2), clamped to `somaxconn`. */\nexport const acceptQueueLimit = (backlog: number, somaxconn: number): number => {\n const max = count(somaxconn, \"somaxconn\");\n if (max < 0) throw new Error(`somaxconn is less than 0: ${max}`);\n const asked = count(backlog, \"the backlog\");\n return asked < 0 || asked > max ? max : asked;\n};\n\n/** This function gives the connections that a full accept queue holds: its limit plus one. */\nexport const acceptQueueHeld = (backlog: number, somaxconn: number): number => acceptQueueLimit(backlog, somaxconn) + 1;\n","/**\n * This function gives the lowest count of one network namespace after one scan of the conntrack\n * collector under pressure. Each entry of the table can go at that scan. The sources are Linux v7.0,\n * `net/netfilter/nf_conntrack_core.c`.\n *\n * - The scan starts to drop at `nf_conntrack_max / 100 * 95`, in integer arithmetic (lines 1526-1527).\n * It drops an entry while the count is at that value or above it (lines 1605-1608). Thus this limit\n * stops the scan one entry below the value.\n * - A scan ends when its count of entries is more than `64000 / HZ` (line 97, lines 1561-1572). That end\n * clears the pressure (lines 1645-1646). Thus this limit stops the scan after `64000 / HZ + 1` entries.\n * - That count also holds each entry that expired by its own timeout, in any namespace (lines\n * 1575-1578). Thus `expired` such entries before the end take `expired` drops from the namespace.\n *\n * The limit that stops the scan first gives the floor. `expired` is 0 by default, which gives the\n * lowest floor. On a host with other flows, a scan can find some, and the floor is higher.\n */\nexport const conntrackFloor = (max: number, hz: number, expired = 0): number => {\n const drops = Math.max(0, Math.floor(64000 / hz) + 1 - expired);\n return Math.max(Math.floor(max / 100) * 95 - 1, max - drops);\n};\n"],"mappings":";;;;;;;;;;;;;;;AAYA,MAAM,SAAS,OAAe,SAAyB;CACrD,IAAI,CAAC,OAAO,cAAc,KAAK,GAAG,MAAM,IAAI,MAAM,GAAG,KAAK,0BAA0B,OAAO;CAC3F,OAAO;AACT;;AAGA,MAAa,oBAAoB,SAAiB,cAA8B;CAC9E,MAAM,MAAM,MAAM,WAAW,WAAW;CACxC,IAAI,MAAM,GAAG,MAAM,IAAI,MAAM,6BAA6B,KAAK;CAC/D,MAAM,QAAQ,MAAM,SAAS,aAAa;CAC1C,OAAO,QAAQ,KAAK,QAAQ,MAAM,MAAM;AAC1C;;AAGA,MAAa,mBAAmB,SAAiB,cAA8B,iBAAiB,SAAS,SAAS,IAAI;;;;;;;;;;;;;;;;;;ACVtH,MAAa,kBAAkB,KAAa,IAAY,UAAU,MAAc;CAC9E,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,OAAQ,EAAE,IAAI,IAAI,OAAO;CAC9D,OAAO,KAAK,IAAI,KAAK,MAAM,MAAM,GAAG,IAAI,KAAK,GAAG,MAAM,KAAK;AAC7D"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as Machine, s as TransitionDef, t as Expr } from "./machine-yGpVFyfh.js";
|
|
2
|
-
import { n as Clock } from "./clock-
|
|
2
|
+
import { n as Clock } from "./clock-oJqrb5Q4.js";
|
|
3
3
|
import { r as Transition } from "./replay-DRTZc7Pw.js";
|
|
4
4
|
import { Extent, Quantity, Rational, Unknown } from "@mark1russell7/quantity";
|
|
5
5
|
/**
|
|
@@ -346,6 +346,19 @@ const synGiveUpEarly = (retries, linear, hz) => {
|
|
|
346
346
|
* `drop` of conntrack, and each retransmission to `TCPRetransFail`.
|
|
347
347
|
*/
|
|
348
348
|
const synGiveUpSends = (retries, linear) => synGiveUpWaits(BigInt(retries), BigInt(linear)).length;
|
|
349
|
+
/**
|
|
350
|
+
* This function gives the wait of the SYN-ACK of a listener after `fired` firings (`reqsk_timeout` in
|
|
351
|
+
* `include/net/inet_connection_sock.h`, lines 290-296 at v6.6). The timer of the request starts at
|
|
352
|
+
* `TCP_TIMEOUT_INIT`. Each firing that sends the SYN-ACK again doubles the wait, up to `TCP_RTO_MAX`.
|
|
353
|
+
*/
|
|
354
|
+
const synAckWait = (fired) => capped(TCP_TIMEOUT_INIT, fired, TCP_RTO_MAX);
|
|
355
|
+
/**
|
|
356
|
+
* This function gives each wait of the SYN-ACK of a listener, up to the expiry of the request
|
|
357
|
+
* (`reqsk_timer_handler` in `net/ipv4/inet_connection_sock.c` at v6.6). A firing sends the SYN-ACK again
|
|
358
|
+
* while `num_timeout` is less than `max_syn_ack_retries` (line 1022, `syn_ack_recalc` at line 858). The
|
|
359
|
+
* next firing drops the request. Thus `retries` + 1 waits come before the expiry: 63 s at the default 5.
|
|
360
|
+
*/
|
|
361
|
+
const synAckWaits = (retries) => Array.from({ length: Number(retries + 1n) }, (_, fired) => synAckWait(BigInt(fired)));
|
|
349
362
|
/** This function gives the whole jiffies of a time at HZ, rounded up, as `msecs_to_jiffies` and `usecs_to_jiffies` round. */
|
|
350
363
|
const jiffiesOf = (seconds, hz) => rationals.ceil(rationals.mul(seconds, hz)).n;
|
|
351
364
|
/**
|
|
@@ -567,6 +580,31 @@ const MODELS = {
|
|
|
567
580
|
seconds: ([fired, linear, hz]) => rationals.div(whole(granularity(jiffiesOf(synWait(integer(fired, FIRED), integer(linear, "tcp_syn_linear_timeouts")), hz))), hz),
|
|
568
581
|
source: "net/ipv4/tcp_timer.c tcp_retransmit_timer and kernel/time/timer.c calc_wheel_index at v6.6"
|
|
569
582
|
},
|
|
583
|
+
"linux.synack-wait": {
|
|
584
|
+
knobs: [null],
|
|
585
|
+
seconds: ([fired]) => synAckWait(integer(fired, FIRED)),
|
|
586
|
+
source: "include/net/inet_connection_sock.h reqsk_timeout (lines 290-296) and net/ipv4/inet_connection_sock.c reqsk_timer_handler (line 1062) at v6.6"
|
|
587
|
+
},
|
|
588
|
+
"linux.synack-wait-lateness": {
|
|
589
|
+
knobs: [null, "Hz"],
|
|
590
|
+
seconds: ([fired, hz]) => rationals.div(whole(granularity(jiffiesOf(synAckWait(integer(fired, FIRED)), hz))), hz),
|
|
591
|
+
source: "net/ipv4/inet_connection_sock.c reqsk_timer_handler and kernel/time/timer.c calc_wheel_index at v6.6"
|
|
592
|
+
},
|
|
593
|
+
"linux.synack-giveup": {
|
|
594
|
+
knobs: [null],
|
|
595
|
+
seconds: ([retries]) => synAckWaits(integer(retries, "tcp_synack_retries")).reduce((total, wait) => rationals.add(total, wait), whole(0n)),
|
|
596
|
+
source: "net/ipv4/inet_connection_sock.c reqsk_timer_handler at v6.6 (lines 1022, 1053-1062 and 1095-1096) and syn_ack_recalc (line 858)"
|
|
597
|
+
},
|
|
598
|
+
"linux.synack-giveup-lateness": {
|
|
599
|
+
knobs: [null, "Hz"],
|
|
600
|
+
seconds: ([retries, hz]) => rationals.div(whole(synAckWaits(integer(retries, "tcp_synack_retries")).reduce((total, wait) => total + granularity(jiffiesOf(wait, hz)), 0n)), hz),
|
|
601
|
+
source: "net/ipv4/inet_connection_sock.c reqsk_timer_handler and kernel/time/timer.c calc_wheel_index at v6.6"
|
|
602
|
+
},
|
|
603
|
+
"linux.synack-giveup-early": {
|
|
604
|
+
knobs: [null, "Hz"],
|
|
605
|
+
seconds: ([retries, hz]) => rationals.div(whole(integer(retries, "tcp_synack_retries") + 1n), hz),
|
|
606
|
+
source: "net/ipv4/inet_connection_sock.c reqsk_timer_handler (mod_timer from jiffies) at v6.6"
|
|
607
|
+
},
|
|
570
608
|
"ioredis.retry-base": {
|
|
571
609
|
knobs: [null],
|
|
572
610
|
seconds: ([fired]) => capped(rationals.fromDecimal("0.05"), integer(fired, FIRED), whole(5n)),
|
|
@@ -1139,4 +1177,4 @@ const runMachine = (doc, options) => {
|
|
|
1139
1177
|
};
|
|
1140
1178
|
export { readsFired as C, machineProblems as S, timerOf as _, evaluate as a, FIRED as b, overValues as c, realizationKnobs as d, realizationOf as f, timerBand as g, synGiveUpSends as h, errnoOf as i, parseExpr as l, stackedDetection as m, algebraProblems as n, firings as o, recovery as p, detection as r, modelSource as s, runMachine as t, probeTrain as u, timerUnder as v, exprKnobs as x, transitionOn as y };
|
|
1141
1179
|
|
|
1142
|
-
//# sourceMappingURL=run-
|
|
1180
|
+
//# sourceMappingURL=run-J6kGNoF8.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-J6kGNoF8.js","names":["r","r"],"sources":["../src/machine.ts","../src/algebra.ts","../src/run.ts"],"sourcesContent":["import { 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 pow ( ) */\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 no wait is shorter than the wait before it.\n * Examples are the retransmission timer of the kernel, its SYN timer 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 /** This value turns the knob's timers off: a time that reads the knob at it has no bound. */\n readonly off?: number | undefined;\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/** 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\", \"pow\"].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\" | \"pow\"; readonly args: readonly Node[] };\n\nconst FUNCTIONS = { min: 2, max: 2, floor: 1, ceil: 1, pow: 2 } as const;\n\n/** This count is the largest exponent that `pow` takes. A larger one is a mistake in a document, not a timer. */\nconst POW_LIMIT = 4096n;\n\n/**\n * This function gives a value to a whole power: `pow(a, n)`. The exponent must be an exact whole\n * number, for example the `fired` of a backoff. A negative exponent gives the reciprocal. No bound\n * to the power 0 is 1, and to a positive power it keeps its sign when the power is odd.\n */\nconst power = (a: Value, b: Value): Value => {\n if (b.kind !== \"exact\" || !r.isInteger(b.n)) return unknown(\"pow takes a whole exponent\");\n const k = b.n.n;\n if (k > POW_LIMIT || k < -POW_LIMIT) return unknown(`pow takes an exponent of ${POW_LIMIT} or less`);\n if (a.kind === \"infinite\") {\n if (k === 0n) return exact(r.ONE);\n if (k < 0n) return exact(r.ZERO);\n return k % 2n === 0n ? INFINITE : a;\n }\n if (a.kind !== \"exact\") return unknown(\"not an amount\");\n if (k < 0n && a.n.n === 0n) return unknown(\"a division by zero\");\n return exact(r.pow(a.n, Number(k)));\n};\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 // Only an own key is a function: `toString` is a knob, as each other name.\n if (Object.hasOwn(FUNCTIONS, token)) {\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 (node.op === \"pow\") return power(a, b);\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`\n * in `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/**\n * This function gives the wait of the SYN of a connect after `fired` firings, from 6.5\n * (`tcp_retransmit_timer` in `net/ipv4/tcp_timer.c`). Each firing sends the SYN again. The first\n * `tcp_syn_linear_timeouts` firings keep the initial RTO, thus the waits 0 to\n * `tcp_syn_linear_timeouts` are 1 s each. Then each firing doubles the wait, up to `TCP_RTO_MAX`.\n */\nconst synWait = (fired: bigint, linear: bigint): Rational =>\n fired <= linear ? TCP_TIMEOUT_INIT : capped(TCP_TIMEOUT_INIT, fired - linear, TCP_RTO_MAX);\n\n/**\n * This function gives each wait of the SYN of a connect, from 6.5: the waits 0 to\n * `tcp_syn_retries` + `tcp_syn_linear_timeouts` (`synWait`). The connect gives up at the end of the last wait.\n */\nconst synWaits = (retries: bigint, linear: bigint): Rational[] =>\n Array.from({ length: Number(linear + 1n + retries) }, (_, fired) => synWait(BigInt(fired), linear));\n\n/**\n * This function gives the waits of the SYN of a connect up to the firing that gives up, from 6.5\n * (`tcp_write_timeout` in `net/ipv4/tcp_timer.c` at v7.0, lines 242-284). A firing applies two tests.\n *\n * - The count test: the retransmissions before it are `tcp_syn_retries` + `tcp_syn_linear_timeouts`.\n * - The time test: `retransmits_timed_out` with the boundary `tcp_syn_retries` and no linear term. Its\n * budget is `tcp_model_timeout` from an RTO of 1 s, (2^(retries + 1) - 1) s, from the first SYN\n * (`tcp_connect` sets `retrans_stamp`, `tcp_output.c` line 4370). It needs one retransmission.\n *\n * The first firing that passes one test gives up. At the defaults both tests give 131 s. At\n * `tcp_syn_retries` 2 and 4 linear waits, the time test gives 7 s and the count test gives 11 s.\n */\nconst synGiveUpWaits = (retries: bigint, linear: bigint): Rational[] => {\n const budget = retransBudget(retries, TCP_TIMEOUT_INIT, TCP_RTO_MAX);\n const waits = synWaits(retries, linear);\n let at = whole(0n);\n for (let fired = 0; fired < waits.length; fired += 1) {\n at = r.add(at, waits[fired]!);\n // the firing after this wait has `fired` retransmissions before it, and the time test needs one\n if (fired >= 1 && r.cmp(at, budget) >= 0) return waits.slice(0, fired + 1);\n }\n return waits;\n};\n\n/**\n * This function gives how early the connect can give up, in seconds. The time test reads the real\n * time of a firing, and the wheel makes that time late. A firing before the nominal one can pass it when its\n * lateness takes it past the budget. With `tcp_usec_ts`, the test adds one jiffy (line 233).\n */\nconst synGiveUpEarly = (retries: bigint, linear: bigint, hz: Rational): Rational => {\n const budget = retransBudget(retries, TCP_TIMEOUT_INIT, TCP_RTO_MAX);\n const waits = synGiveUpWaits(retries, linear);\n const end = waits.reduce((total, wait) => r.add(total, wait), whole(0n));\n const jiffy = r.div(whole(1n), hz);\n let at = whole(0n);\n let late = whole(0n);\n for (let fired = 0; fired < waits.length - 1; fired += 1) {\n at = r.add(at, waits[fired]!);\n late = r.add(late, r.div(whole(granularity(jiffiesOf(waits[fired]!, hz))), hz));\n if (fired >= 1 && r.cmp(r.add(r.add(at, late), jiffy), budget) >= 0) {\n const low = r.sub(budget, jiffy);\n return r.sub(end, r.cmp(low, at) >= 0 ? low : at);\n }\n }\n return whole(0n);\n};\n\n/**\n * This function gives the SYNs that a connect sends before it gives up: the first SYN and each\n * retransmission (`synGiveUpWaits`). A connect whose SYN does not leave adds each of them to the field\n * `drop` of conntrack, and each retransmission to `TCPRetransFail`.\n */\nexport const synGiveUpSends = (retries: number, linear: number): number =>\n synGiveUpWaits(BigInt(retries), BigInt(linear)).length;\n\n/**\n * This function gives the wait of the SYN-ACK of a listener after `fired` firings (`reqsk_timeout` in\n * `include/net/inet_connection_sock.h`, lines 290-296 at v6.6). The timer of the request starts at\n * `TCP_TIMEOUT_INIT`. Each firing that sends the SYN-ACK again doubles the wait, up to `TCP_RTO_MAX`.\n */\nconst synAckWait = (fired: bigint): Rational => capped(TCP_TIMEOUT_INIT, fired, TCP_RTO_MAX);\n\n/**\n * This function gives each wait of the SYN-ACK of a listener, up to the expiry of the request\n * (`reqsk_timer_handler` in `net/ipv4/inet_connection_sock.c` at v6.6). A firing sends the SYN-ACK again\n * while `num_timeout` is less than `max_syn_ack_retries` (line 1022, `syn_ack_recalc` at line 858). The\n * next firing drops the request. Thus `retries` + 1 waits come before the expiry: 63 s at the default 5.\n */\nconst synAckWaits = (retries: bigint): Rational[] =>\n Array.from({ length: Number(retries + 1n) }, (_, fired) => synAckWait(BigInt(fired)));\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 the longest wait of the delayed ACK, in jiffies (`tcp_send_delayed_ack` in\n * `net/ipv4/tcp_output.c:4004-4054` at v6.6). The wait is the ACK timeout, `ato`. It is at least\n * `TCP_DELACK_MIN`, HZ/25. Above that, the smoothed round trip in whole jiffies bounds it, but not\n * below `TCP_DELACK_MIN`. The cap is `icsk_delack_max`, `TCP_DELACK_MAX` by default, HZ/5\n * (`include/net/tcp.h:133-136`, `net/ipv4/tcp.c:425`). Thus it is 40 ms on a fast path at each HZ, and\n * 200 ms at most.\n */\nconst delackWait = (rtt: Rational, hz: Rational): bigint => {\n const ticks = integer(hz, \"hz\");\n const least = ticks / 25n;\n const most = ticks / 5n;\n const srtt = jiffiesOf(rtt, hz);\n const bound = srtt > least ? srtt : least;\n return bound < most ? bound : most;\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\n * firing is the tail loss probe. For one segment, the probe waits two round trips plus\n * `TCP_RTO_MIN`, but not longer than the RTO. Thus it waits the RTO itself: the round trip plus\n * the minimum, in whole 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 // the longest wait of the delayed ACK: min(max(srtt, TCP_DELACK_MIN), TCP_DELACK_MAX), in jiffies\n \"linux.delack\": {\n knobs: [\"s\", \"Hz\"],\n seconds: ([rtt, hz]) => r.div(whole(delackWait(rtt!, hz!)), hz!),\n source:\n \"net/ipv4/tcp_output.c tcp_send_delayed_ack, include/net/tcp.h TCP_DELACK_MIN and TCP_DELACK_MAX at v6.6\",\n },\n // the rounding of that wait on the timer wheel: 1 jiffy at 40 ms, 8 at 200 ms at HZ 1000\n \"linux.delack-lateness\": {\n knobs: [\"s\", \"Hz\"],\n seconds: ([rtt, hz]) => r.div(whole(granularity(delackWait(rtt!, hz!))), hz!),\n source: \"net/ipv4/tcp_output.c tcp_send_delayed_ack and 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. The SYN gives up at the first firing after syn_retries + linear_timeouts\n // retransmissions, or after the budget of tcp_model_timeout for syn_retries, which comes first\n \"linux.syn-giveup\": {\n knobs: [null, null],\n seconds: ([retries, linear]) =>\n synGiveUpWaits(integer(retries!, \"tcp_syn_retries\"), integer(linear!, \"tcp_syn_linear_timeouts\")).reduce(\n (total, wait) => r.add(total, wait),\n whole(0n),\n ),\n source:\n \"net/ipv4/tcp_timer.c tcp_write_timeout, retransmits_timed_out and tcp_model_timeout at v7.0 (lines 187-284)\",\n },\n // the rounding of each of those waits on the timer wheel, at the level that its length puts it in:\n // 6.08 s at the defaults and HZ 1000, because the last wait of 64 s can be 4.096 s late\n \"linux.syn-giveup-lateness\": {\n knobs: [null, null, \"Hz\"],\n seconds: ([retries, linear, hz]) =>\n r.div(\n whole(\n synGiveUpWaits(integer(retries!, \"tcp_syn_retries\"), integer(linear!, \"tcp_syn_linear_timeouts\")).reduce(\n (total, wait) => total + granularity(jiffiesOf(wait, hz!)),\n 0n,\n ),\n ),\n hz!,\n ),\n source: \"net/ipv4/tcp_timer.c tcp_retransmit_timer and kernel/time/timer.c calc_wheel_index at v6.6\",\n },\n // how early the SYN can give up: a late firing before the nominal one can pass the time test.\n // 0 at the defaults and at syn_retries 2, because no such firing comes near the budget\n \"linux.syn-giveup-early\": {\n knobs: [null, null, \"Hz\"],\n seconds: ([retries, linear, hz]) =>\n synGiveUpEarly(integer(retries!, \"tcp_syn_retries\"), integer(linear!, \"tcp_syn_linear_timeouts\"), hz!),\n source: \"net/ipv4/tcp_timer.c retransmits_timed_out at v7.0 (lines 214-239) and kernel/time/timer.c calc_wheel_index\",\n },\n // one wait of the SYN of a connect, after `fired` firings: 1 s for the waits 0 to\n // tcp_syn_linear_timeouts, then doubled at each firing, up to TCP_RTO_MAX\n \"linux.syn-wait\": {\n knobs: [null, null],\n seconds: ([fired, linear]) => synWait(integer(fired!, FIRED), integer(linear!, \"tcp_syn_linear_timeouts\")),\n source:\n \"net/ipv4/tcp_timer.c tcp_retransmit_timer at v6.6 (lines 604 and 624-631) and at v6.17 (lines 448 and 671-678)\",\n },\n // the rounding of that wait on the timer wheel: 64 jiffies for a wait of 1 s at HZ 1000, 8 at HZ 250\n \"linux.syn-wait-lateness\": {\n knobs: [null, null, \"Hz\"],\n seconds: ([fired, linear, hz]) =>\n r.div(\n whole(granularity(jiffiesOf(synWait(integer(fired!, FIRED), integer(linear!, \"tcp_syn_linear_timeouts\")), hz!))),\n hz!,\n ),\n source: \"net/ipv4/tcp_timer.c tcp_retransmit_timer and kernel/time/timer.c calc_wheel_index at v6.6\",\n },\n // one wait of the SYN-ACK of a listener, after `fired` firings: 1 s doubled at each firing, up to\n // TCP_RTO_MAX. The young pruning of a crowded queue and TCP_DEFER_ACCEPT change the count of\n // firings, not the wait, and these models do not hold them\n \"linux.synack-wait\": {\n knobs: [null],\n seconds: ([fired]) => synAckWait(integer(fired!, FIRED)),\n source:\n \"include/net/inet_connection_sock.h reqsk_timeout (lines 290-296) and net/ipv4/inet_connection_sock.c reqsk_timer_handler (line 1062) at v6.6\",\n },\n // the rounding of that wait on the timer wheel: 64 jiffies for a wait of 1 s at HZ 1000\n \"linux.synack-wait-lateness\": {\n knobs: [null, \"Hz\"],\n seconds: ([fired, hz]) => r.div(whole(granularity(jiffiesOf(synAckWait(integer(fired!, FIRED)), hz!))), hz!),\n source: \"net/ipv4/inet_connection_sock.c reqsk_timer_handler and kernel/time/timer.c calc_wheel_index at v6.6\",\n },\n // the expiry of a request at a listener: the waits 0 to tcp_synack_retries, 63 s at the default 5.\n // The firing after the last wait drops the request, and a later segment of the client gets a reset\n \"linux.synack-giveup\": {\n knobs: [null],\n seconds: ([retries]) =>\n synAckWaits(integer(retries!, \"tcp_synack_retries\")).reduce((total, wait) => r.add(total, wait), whole(0n)),\n source:\n \"net/ipv4/inet_connection_sock.c reqsk_timer_handler at v6.6 (lines 1022, 1053-1062 and 1095-1096) and syn_ack_recalc (line 858)\",\n },\n // the rounding of each of those waits on the timer wheel: 1.728 s in all at the default 5 and HZ 1000\n \"linux.synack-giveup-lateness\": {\n knobs: [null, \"Hz\"],\n seconds: ([retries, hz]) =>\n r.div(\n whole(\n synAckWaits(integer(retries!, \"tcp_synack_retries\")).reduce(\n (total, wait) => total + granularity(jiffiesOf(wait, hz!)),\n 0n,\n ),\n ),\n hz!,\n ),\n source: \"net/ipv4/inet_connection_sock.c reqsk_timer_handler and kernel/time/timer.c calc_wheel_index at v6.6\",\n },\n // how early the expiry can come: each wait is a whole count of jiffies from the jiffy of its arming,\n // thus each one can end up to one jiffy early\n \"linux.synack-giveup-early\": {\n knobs: [null, \"Hz\"],\n seconds: ([retries, hz]) => r.div(whole(integer(retries!, \"tcp_synack_retries\") + 1n), hz!),\n source: \"net/ipv4/inet_connection_sock.c reqsk_timer_handler (mod_timer from jiffies) 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/** This function gives the model of a name, or undefined. Only an own key is a model: `toString` is not one. */\nconst modelOf = (name: string): Model | undefined => (Object.hasOwn(MODELS, name) ? MODELS[name] : undefined);\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 (!Object.hasOwn(doc.knobs, name)) 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 // a knob at its off value turns its timers off: a time that reads it has no bound\n const { off, unit: own } = doc.knobs[name]!;\n if (off !== undefined && own !== null && r.toNumber(convertExact(value, given.unit, own)) === off)\n return INFINITE;\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 = modelOf(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// the times on a timeline: the band of a timer, the firings of a backoff timer, a train of probes\n// ---------------------------------------------------------------------------------------------\n\n/** A band is the range of times in which a timer fires, from its arming. */\nexport interface Band {\n /** This time is the duration less how early the timer can fire. */\n readonly low: Extent;\n /** This time is the duration plus how late the timer can fire. */\n readonly high: Extent;\n}\n\n/** This function gives an amount as an exact value in seconds. Without an amount, it gives zero. */\nconst secondsOf = (extent: Extent | Unknown | undefined): Value => {\n if (extent === undefined) return exact(r.ZERO);\n if (\"unknown\" in extent) return unknown(extent.unknown);\n if (isUnbounded(extent)) return INFINITE;\n return exact(convertExact(r.fromNumber(extent.value), extent.unit, \"s\"));\n};\n\n/**\n * This function gives the band of a timer from its bounds, exactly, in `unit`. The band goes from\n * its duration less its early bound to its duration plus its lateness. A bound that the document\n * does not give is zero. A duration without an end gives a band without an end. A keepalive of 11 s, 4 ms early and 352 ms\n * late, gives 10.996 s to 11.352 s.\n */\nexport const timerBand = (bounds: TimerBounds, unit = \"s\"): Band | Unknown => {\n const duration = secondsOf(bounds.duration);\n const early = secondsOf(bounds.early);\n const late = secondsOf(bounds.lateness);\n const lost = unknownOf([duration, early, late]);\n if (lost !== undefined) return out(lost, unit) as Unknown;\n if (duration.kind !== \"exact\") return { low: unbounded(unit), high: unbounded(unit) };\n if (early.kind !== \"exact\") return { unknown: \"an early bound without an end\", unit };\n const low = r.sub(duration.n, early.n);\n const at = (n: Rational): Quantity => quantity(r.toNumber(convertExact(n, \"s\", unit)), unit);\n return { low: at(low), high: late.kind === \"exact\" ? at(r.add(duration.n, late.n)) : unbounded(unit) };\n};\n\n/** A scheduled firing is one firing of a backoff timer, and its time on the timeline. */\nexport interface Scheduled {\n /** This count is the wait that ends in this firing: the wait after `fired` firings. */\n readonly fired: number;\n /** This time is the sum of the waits to this firing, from the first wait of the schedule, in seconds. */\n readonly at: Quantity;\n}\n\n/** These options tell where the firings of a schedule start and stop. Each stop that they give applies. */\nexport interface ScheduleOptions {\n /** This count is the first wait of the schedule. The default is 0, the wait from the arming. */\n readonly from?: number | undefined;\n /** This count is the most firings to give. */\n readonly count?: number | undefined;\n /** This time stops the schedule: the schedule keeps no firing after it. */\n readonly until?: Extent | undefined;\n /** This time stops the schedule after the first firing at it or after it. That firing is in the schedule. */\n readonly reach?: Extent | undefined;\n}\n\n/**\n * This function gives the firings of a backoff timer on a timeline: the sum of its waits, exactly,\n * from the wait `from`. It stops at the first wait that is not a known amount, or at a stop of the\n * options, or after 4096 firings. Each time is the duration of the waits, without how early or\n * late each can fire.\n *\n * Two examples: the retransmission timer of Linux gives the send of each retransmission. The\n * retry of a call with a deadline gives the start of each try.\n */\nexport const firings = (\n doc: Machine,\n timer: string,\n values: KnobValues,\n options: ScheduleOptions,\n): Scheduled[] => {\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 (options.count === undefined && options.until === undefined && options.reach === undefined) {\n throw new Error(`the firings of ${timer} need a stop: a count, until or reach`);\n }\n const limit = (extent: Extent | undefined): Value | undefined => (extent === undefined ? undefined : secondsOf(extent));\n const until = limit(options.until);\n const reach = limit(options.reach);\n const from = options.from ?? 0;\n const count = Math.min(options.count ?? FIRINGS, FIRINGS);\n const result: Scheduled[] = [];\n let at = r.ZERO;\n for (let fired = from; result.length < count; fired += 1) {\n const wait = secondsOf(timerOf(doc, timer, values, fired).duration);\n if (wait.kind !== \"exact\") break;\n at = r.add(at, wait.n);\n if (until?.kind === \"exact\" && r.cmp(at, until.n) > 0) break;\n result.push({ fired, at: quantity(r.toNumber(at), \"s\") });\n if (reach?.kind === \"exact\" && r.cmp(at, reach.n) >= 0) break;\n }\n return result;\n};\n\n/**\n * This function gives the times of a train of probes, exactly, in seconds. The first probe is at\n * `first`, and each next probe is one `interval` later, `count` probes in all. A first time without\n * an end gives no probe. An interval without an end gives only the first probe. Keepalive at its\n * defaults sends its probes at 7200 s, 7275 s, and so on to 7800 s.\n */\nexport const probeTrain = (first: Extent, interval: Extent, count: number): Quantity[] => {\n const start = secondsOf(first);\n const step = secondsOf(interval);\n if (start.kind !== \"exact\" || count < 1) return [];\n const times = [quantity(r.toNumber(start.n), \"s\")];\n if (step.kind !== \"exact\") return times;\n for (let k = 1; k < count; k += 1) times.push(quantity(r.toNumber(r.add(start.n, r.mul(step.n, whole(BigInt(k))))), \"s\"));\n return times;\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 && modelOf(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 => modelOf(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","// @mark1russell7/algebra/run: a live instance of a machine document. The run takes the transitions\n// of the document on each event, and it operates the timers of the document on a clock. The entry\n// does not import zod or a `node:` module. Thus a client in a browser can run its own machines.\n\nimport type { Extent, Unknown } from \"@mark1russell7/quantity\";\nimport { convertExact, isUnbounded, quantity, rationals as r } from \"@mark1russell7/quantity\";\nimport type { KnobValues } from \"./algebra.ts\";\nimport { timerOf, transitionOn } from \"./algebra.ts\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { Machine, TransitionDef } from \"./machine.ts\";\nimport { machineProblems } from \"./machine.ts\";\nimport type { Transition } from \"./replay.ts\";\n\n/** These options start a run of a machine document. */\nexport interface RunMachineOptions {\n /** This clock gives the time of the run and operates its timers. A test gives `fakeClock()`. */\n readonly clock: Clock;\n /** This function gives the knob values for the durations of the timers. The default is the `default` of each knob. */\n readonly values?: KnobValues | undefined;\n /** This state is the start state. The default is the initial state of the document. */\n readonly state?: string | undefined;\n /** This name identifies the instance in each transition record. The default is the `id` of the document. */\n readonly instance?: string | undefined;\n /** This function gets each transition that the run takes, in the form that `replay` reads. */\n readonly onTransition?: ((transition: Transition) => void) | undefined;\n}\n\n/** A machine run is one live instance of a machine document. */\nexport interface MachineRun {\n /** This name is the state where the instance is. */\n readonly state: string;\n /**\n * This method gives one event to the instance. It gives the transition that the instance takes, or\n * undefined when the state has no transition on the event.\n */\n send(event: string): TransitionDef | undefined;\n /** This method stops each timer. After it, each send does nothing and gives undefined. */\n stop(): void;\n}\n\n/** This function gives the values of the knobs at their defaults. A knob without a default or without a unit has no value. */\nconst knobDefaults =\n (doc: Machine): KnobValues =>\n (name) => {\n const knob = Object.hasOwn(doc.knobs, name) ? doc.knobs[name] : undefined;\n if (knob === undefined || knob.unit === null || knob.default === null) return undefined;\n return quantity(knob.default, knob.unit);\n };\n\n/** This function gives the start state of a run: the state of the options, or the one initial state of the document. */\nconst startState = (doc: Machine, state: string | undefined): string => {\n if (state !== undefined) {\n if (!Object.hasOwn(doc.states, state)) throw new Error(`${doc.title} has no state ${state}`);\n return state;\n }\n const initial = Object.keys(doc.states).filter((name) => doc.states[name]!.initial === true);\n if (initial.length !== 1) {\n throw new Error(`${doc.title} has ${initial.length} initial states: give the start state in the options`);\n }\n return initial[0]!;\n};\n\n/**\n * This function starts a live instance of a machine document on a clock. It gives the run: its\n * state, `send` and `stop`. The run applies these rules:\n *\n * - The run refuses a document with problems (`machineProblems`), as each reader does. With a start\n * state in the options, a document with no initial state is correct.\n * - At the start, the instance enters its start state. The pseudo event `enter:<state>` operates\n * the timers, as after a transition.\n * - An event that the document does not name is an error. The run throws an `Error` that names it.\n * - `send` takes the transition of `transitionOn` from the state on the event. Then, in sequence,\n * these events operate the timers: the event itself, each event that the transition emits, and\n * `enter:<to>`. A transition to the state that it leaves also enters that state again.\n * - An event without a transition also operates the timers.\n * - For each timer, an event of `backoff.resets` first sets its count of firings to 0. Then an\n * event of `cancels` stops it, or else an event of `arms` starts it again from the full\n * duration. An event in `arms` and in `cancels` stops the timer, as in `detection`.\n * - The run reads the duration of each start from `timerOf`, with the values and the count of\n * firings of a backoff timer. It converts the duration to milliseconds exactly. It does not read\n * the lateness or the early bound. A duration with no bound does not start the timer.\n * - The run reads the first duration of each timer when it starts. Thus a knob without a value is an\n * error at the start, not in a callback of the clock.\n * - When a timer fires, its `fires` event goes through `send`. A backoff timer first adds 1 to its\n * count and starts again with its next wait. Thus its own `cancels` can stop it.\n * - The entry to a final state stops each timer. In a final state, `send` does nothing and gives undefined.\n * - The run gives each transition that it takes to `onTransition`, after the timers. The record has\n * the machine (the `id` of the document), the instance, the states, the event and the time of the clock.\n * - The `timer` of a transition is a note for the reader. The run does not read it.\n */\nexport const runMachine = (doc: Machine, options: RunMachineOptions): MachineRun => {\n const problems = machineProblems(doc).filter((problem) => options.state === undefined || problem !== \"no initial state\");\n if (problems.length > 0) throw new Error(`${doc.title} has problems: ${problems.join(\", \")}`);\n const clock = options.clock;\n const values = options.values ?? knobDefaults(doc);\n const instance = options.instance ?? doc.id;\n let state = startState(doc, options.state);\n let stopped = false;\n const timers = Object.entries(doc.timers).map(([name, def]) => ({\n name,\n def,\n fired: 0,\n cancel: undefined as Cancel | undefined,\n }));\n type Live = (typeof timers)[number];\n\n /** This function gives the wait of a timer in milliseconds, or undefined for a duration with no bound. */\n const waitOf = (timer: Live): number | undefined => {\n const duration: Extent | Unknown = timerOf(doc, timer.name, values, timer.def.backoff === undefined ? undefined : timer.fired).duration;\n if (\"unknown\" in duration) throw new Error(`${doc.title}'s ${timer.name} has no known duration: ${duration.unknown}`);\n if (isUnbounded(duration)) return undefined;\n return r.toNumber(convertExact(r.fromNumber(duration.value), duration.unit, \"ms\"));\n };\n const halt = (timer: Live): void => {\n timer.cancel?.();\n timer.cancel = undefined;\n };\n const begin = (timer: Live): void => {\n halt(timer);\n const ms = waitOf(timer);\n if (ms !== undefined) timer.cancel = clock.after(ms, () => fire(timer));\n };\n const fire = (timer: Live): void => {\n timer.cancel = undefined;\n if (stopped) return;\n if (timer.def.backoff !== undefined) {\n timer.fired += 1;\n begin(timer);\n }\n run.send(timer.def.fires);\n };\n /** This function operates each timer for one event. */\n const occur = (event: string): void => {\n for (const timer of timers) {\n if (timer.def.backoff?.resets.includes(event) === true) timer.fired = 0;\n if (timer.def.cancels?.includes(event) === true) halt(timer);\n else if (timer.def.arms.includes(event)) begin(timer);\n }\n };\n const isFinal = (name: string): boolean => doc.states[name]?.final === true;\n /** This function enters a state: `enter:<state>` operates the timers, and a final state stops each timer. */\n const enter = (to: string): void => {\n occur(`enter:${to}`);\n if (isFinal(to)) for (const timer of timers) halt(timer);\n };\n\n const run: MachineRun = {\n get state() {\n return state;\n },\n send(event) {\n if (!Object.hasOwn(doc.events, event)) throw new Error(`${doc.title} has no event ${event}`);\n if (stopped || isFinal(state)) return undefined;\n const from = state;\n const taken = transitionOn(doc, from, event);\n if (taken !== undefined) state = taken.to;\n occur(event);\n if (taken === undefined) return undefined;\n for (const sent of taken.emits ?? []) occur(sent);\n enter(taken.to);\n options.onTransition?.({ machine: doc.id, instance, from, on: event, to: taken.to, at: clock.now() });\n return taken;\n },\n stop() {\n stopped = true;\n for (const timer of timers) halt(timer);\n },\n };\n\n // a first duration that is not known stops the start, before a timer runs\n for (const timer of timers) waitOf(timer);\n enter(state);\n return run;\n};\n"],"mappings":";;;;;;;AA+CA,MAAa,QAAQ;;AA+HrB,MAAM,aAAa,MAAsB;CACvC,IAAI,UAAU,GAAG,OAAO,CAAC,EAAE,IAAI;CAC/B,IAAI,WAAW,GAAG,OAAO,CAAC,GAAG,EAAE,KAAK;CACpC,IAAI,UAAU,GACZ,QAAQ,EAAE,KAAK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;CACX,OAAO;AACT"}
|
package/build/run.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as RunMachineOptions, r as runMachine, t as MachineRun } from "./run-
|
|
1
|
+
import { n as RunMachineOptions, r as runMachine, t as MachineRun } from "./run-BgUWHAcf.js";
|
|
2
2
|
export { MachineRun, RunMachineOptions, runMachine };
|
package/build/run.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as runMachine } from "./run-
|
|
1
|
+
export { t as runMachine } from "./run-J6kGNoF8.js";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/algebra",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.9.1",
|
|
5
5
|
"description": "State machines as data, and the timer algebra over them: closed forms for a machine's timers in exact rationals, detection as the first live timer, recovery after a stall, and the replay of a trace.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"state-machine",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"node": ">=22.19"
|
|
61
61
|
},
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"@mark1russell7/quantity": "^0.4.
|
|
63
|
+
"@mark1russell7/quantity": "^0.4.1"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
66
|
"zod": "^4.1.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-DTmtHPlK.js","names":["r","r"],"sources":["../src/machine.ts","../src/algebra.ts","../src/run.ts"],"sourcesContent":["import { 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 pow ( ) */\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 no wait is shorter than the wait before it.\n * Examples are the retransmission timer of the kernel, its SYN timer 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 /** This value turns the knob's timers off: a time that reads the knob at it has no bound. */\n readonly off?: number | undefined;\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/** 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\", \"pow\"].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\" | \"pow\"; readonly args: readonly Node[] };\n\nconst FUNCTIONS = { min: 2, max: 2, floor: 1, ceil: 1, pow: 2 } as const;\n\n/** This count is the largest exponent that `pow` takes. A larger one is a mistake in a document, not a timer. */\nconst POW_LIMIT = 4096n;\n\n/**\n * This function gives a value to a whole power: `pow(a, n)`. The exponent must be an exact whole\n * number, for example the `fired` of a backoff. A negative exponent gives the reciprocal. No bound\n * to the power 0 is 1, and to a positive power it keeps its sign when the power is odd.\n */\nconst power = (a: Value, b: Value): Value => {\n if (b.kind !== \"exact\" || !r.isInteger(b.n)) return unknown(\"pow takes a whole exponent\");\n const k = b.n.n;\n if (k > POW_LIMIT || k < -POW_LIMIT) return unknown(`pow takes an exponent of ${POW_LIMIT} or less`);\n if (a.kind === \"infinite\") {\n if (k === 0n) return exact(r.ONE);\n if (k < 0n) return exact(r.ZERO);\n return k % 2n === 0n ? INFINITE : a;\n }\n if (a.kind !== \"exact\") return unknown(\"not an amount\");\n if (k < 0n && a.n.n === 0n) return unknown(\"a division by zero\");\n return exact(r.pow(a.n, Number(k)));\n};\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 // Only an own key is a function: `toString` is a knob, as each other name.\n if (Object.hasOwn(FUNCTIONS, token)) {\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 (node.op === \"pow\") return power(a, b);\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`\n * in `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/**\n * This function gives the wait of the SYN of a connect after `fired` firings, from 6.5\n * (`tcp_retransmit_timer` in `net/ipv4/tcp_timer.c`). Each firing sends the SYN again. The first\n * `tcp_syn_linear_timeouts` firings keep the initial RTO, thus the waits 0 to\n * `tcp_syn_linear_timeouts` are 1 s each. Then each firing doubles the wait, up to `TCP_RTO_MAX`.\n */\nconst synWait = (fired: bigint, linear: bigint): Rational =>\n fired <= linear ? TCP_TIMEOUT_INIT : capped(TCP_TIMEOUT_INIT, fired - linear, TCP_RTO_MAX);\n\n/**\n * This function gives each wait of the SYN of a connect, from 6.5: the waits 0 to\n * `tcp_syn_retries` + `tcp_syn_linear_timeouts` (`synWait`). The connect gives up at the end of the last wait.\n */\nconst synWaits = (retries: bigint, linear: bigint): Rational[] =>\n Array.from({ length: Number(linear + 1n + retries) }, (_, fired) => synWait(BigInt(fired), linear));\n\n/**\n * This function gives the waits of the SYN of a connect up to the firing that gives up, from 6.5\n * (`tcp_write_timeout` in `net/ipv4/tcp_timer.c` at v7.0, lines 242-284). A firing applies two tests.\n *\n * - The count test: the retransmissions before it are `tcp_syn_retries` + `tcp_syn_linear_timeouts`.\n * - The time test: `retransmits_timed_out` with the boundary `tcp_syn_retries` and no linear term. Its\n * budget is `tcp_model_timeout` from an RTO of 1 s, (2^(retries + 1) - 1) s, from the first SYN\n * (`tcp_connect` sets `retrans_stamp`, `tcp_output.c` line 4370). It needs one retransmission.\n *\n * The first firing that passes one test gives up. At the defaults both tests give 131 s. At\n * `tcp_syn_retries` 2 and 4 linear waits, the time test gives 7 s and the count test gives 11 s.\n */\nconst synGiveUpWaits = (retries: bigint, linear: bigint): Rational[] => {\n const budget = retransBudget(retries, TCP_TIMEOUT_INIT, TCP_RTO_MAX);\n const waits = synWaits(retries, linear);\n let at = whole(0n);\n for (let fired = 0; fired < waits.length; fired += 1) {\n at = r.add(at, waits[fired]!);\n // the firing after this wait has `fired` retransmissions before it, and the time test needs one\n if (fired >= 1 && r.cmp(at, budget) >= 0) return waits.slice(0, fired + 1);\n }\n return waits;\n};\n\n/**\n * This function gives how early the connect can give up, in seconds. The time test reads the real\n * time of a firing, and the wheel makes that time late. A firing before the nominal one can pass it when its\n * lateness takes it past the budget. With `tcp_usec_ts`, the test adds one jiffy (line 233).\n */\nconst synGiveUpEarly = (retries: bigint, linear: bigint, hz: Rational): Rational => {\n const budget = retransBudget(retries, TCP_TIMEOUT_INIT, TCP_RTO_MAX);\n const waits = synGiveUpWaits(retries, linear);\n const end = waits.reduce((total, wait) => r.add(total, wait), whole(0n));\n const jiffy = r.div(whole(1n), hz);\n let at = whole(0n);\n let late = whole(0n);\n for (let fired = 0; fired < waits.length - 1; fired += 1) {\n at = r.add(at, waits[fired]!);\n late = r.add(late, r.div(whole(granularity(jiffiesOf(waits[fired]!, hz))), hz));\n if (fired >= 1 && r.cmp(r.add(r.add(at, late), jiffy), budget) >= 0) {\n const low = r.sub(budget, jiffy);\n return r.sub(end, r.cmp(low, at) >= 0 ? low : at);\n }\n }\n return whole(0n);\n};\n\n/**\n * This function gives the SYNs that a connect sends before it gives up: the first SYN and each\n * retransmission (`synGiveUpWaits`). A connect whose SYN does not leave adds each of them to the field\n * `drop` of conntrack, and each retransmission to `TCPRetransFail`.\n */\nexport const synGiveUpSends = (retries: number, linear: number): number =>\n synGiveUpWaits(BigInt(retries), BigInt(linear)).length;\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 the longest wait of the delayed ACK, in jiffies (`tcp_send_delayed_ack` in\n * `net/ipv4/tcp_output.c:4004-4054` at v6.6). The wait is the ACK timeout, `ato`. It is at least\n * `TCP_DELACK_MIN`, HZ/25. Above that, the smoothed round trip in whole jiffies bounds it, but not\n * below `TCP_DELACK_MIN`. The cap is `icsk_delack_max`, `TCP_DELACK_MAX` by default, HZ/5\n * (`include/net/tcp.h:133-136`, `net/ipv4/tcp.c:425`). Thus it is 40 ms on a fast path at each HZ, and\n * 200 ms at most.\n */\nconst delackWait = (rtt: Rational, hz: Rational): bigint => {\n const ticks = integer(hz, \"hz\");\n const least = ticks / 25n;\n const most = ticks / 5n;\n const srtt = jiffiesOf(rtt, hz);\n const bound = srtt > least ? srtt : least;\n return bound < most ? bound : most;\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\n * firing is the tail loss probe. For one segment, the probe waits two round trips plus\n * `TCP_RTO_MIN`, but not longer than the RTO. Thus it waits the RTO itself: the round trip plus\n * the minimum, in whole 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 // the longest wait of the delayed ACK: min(max(srtt, TCP_DELACK_MIN), TCP_DELACK_MAX), in jiffies\n \"linux.delack\": {\n knobs: [\"s\", \"Hz\"],\n seconds: ([rtt, hz]) => r.div(whole(delackWait(rtt!, hz!)), hz!),\n source:\n \"net/ipv4/tcp_output.c tcp_send_delayed_ack, include/net/tcp.h TCP_DELACK_MIN and TCP_DELACK_MAX at v6.6\",\n },\n // the rounding of that wait on the timer wheel: 1 jiffy at 40 ms, 8 at 200 ms at HZ 1000\n \"linux.delack-lateness\": {\n knobs: [\"s\", \"Hz\"],\n seconds: ([rtt, hz]) => r.div(whole(granularity(delackWait(rtt!, hz!))), hz!),\n source: \"net/ipv4/tcp_output.c tcp_send_delayed_ack and 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. The SYN gives up at the first firing after syn_retries + linear_timeouts\n // retransmissions, or after the budget of tcp_model_timeout for syn_retries, which comes first\n \"linux.syn-giveup\": {\n knobs: [null, null],\n seconds: ([retries, linear]) =>\n synGiveUpWaits(integer(retries!, \"tcp_syn_retries\"), integer(linear!, \"tcp_syn_linear_timeouts\")).reduce(\n (total, wait) => r.add(total, wait),\n whole(0n),\n ),\n source:\n \"net/ipv4/tcp_timer.c tcp_write_timeout, retransmits_timed_out and tcp_model_timeout at v7.0 (lines 187-284)\",\n },\n // the rounding of each of those waits on the timer wheel, at the level that its length puts it in:\n // 6.08 s at the defaults and HZ 1000, because the last wait of 64 s can be 4.096 s late\n \"linux.syn-giveup-lateness\": {\n knobs: [null, null, \"Hz\"],\n seconds: ([retries, linear, hz]) =>\n r.div(\n whole(\n synGiveUpWaits(integer(retries!, \"tcp_syn_retries\"), integer(linear!, \"tcp_syn_linear_timeouts\")).reduce(\n (total, wait) => total + granularity(jiffiesOf(wait, hz!)),\n 0n,\n ),\n ),\n hz!,\n ),\n source: \"net/ipv4/tcp_timer.c tcp_retransmit_timer and kernel/time/timer.c calc_wheel_index at v6.6\",\n },\n // how early the SYN can give up: a late firing before the nominal one can pass the time test.\n // 0 at the defaults and at syn_retries 2, because no such firing comes near the budget\n \"linux.syn-giveup-early\": {\n knobs: [null, null, \"Hz\"],\n seconds: ([retries, linear, hz]) =>\n synGiveUpEarly(integer(retries!, \"tcp_syn_retries\"), integer(linear!, \"tcp_syn_linear_timeouts\"), hz!),\n source: \"net/ipv4/tcp_timer.c retransmits_timed_out at v7.0 (lines 214-239) and kernel/time/timer.c calc_wheel_index\",\n },\n // one wait of the SYN of a connect, after `fired` firings: 1 s for the waits 0 to\n // tcp_syn_linear_timeouts, then doubled at each firing, up to TCP_RTO_MAX\n \"linux.syn-wait\": {\n knobs: [null, null],\n seconds: ([fired, linear]) => synWait(integer(fired!, FIRED), integer(linear!, \"tcp_syn_linear_timeouts\")),\n source:\n \"net/ipv4/tcp_timer.c tcp_retransmit_timer at v6.6 (lines 604 and 624-631) and at v6.17 (lines 448 and 671-678)\",\n },\n // the rounding of that wait on the timer wheel: 64 jiffies for a wait of 1 s at HZ 1000, 8 at HZ 250\n \"linux.syn-wait-lateness\": {\n knobs: [null, null, \"Hz\"],\n seconds: ([fired, linear, hz]) =>\n r.div(\n whole(granularity(jiffiesOf(synWait(integer(fired!, FIRED), integer(linear!, \"tcp_syn_linear_timeouts\")), hz!))),\n hz!,\n ),\n source: \"net/ipv4/tcp_timer.c tcp_retransmit_timer and kernel/time/timer.c calc_wheel_index 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/** This function gives the model of a name, or undefined. Only an own key is a model: `toString` is not one. */\nconst modelOf = (name: string): Model | undefined => (Object.hasOwn(MODELS, name) ? MODELS[name] : undefined);\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 (!Object.hasOwn(doc.knobs, name)) 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 // a knob at its off value turns its timers off: a time that reads it has no bound\n const { off, unit: own } = doc.knobs[name]!;\n if (off !== undefined && own !== null && r.toNumber(convertExact(value, given.unit, own)) === off)\n return INFINITE;\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 = modelOf(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// the times on a timeline: the band of a timer, the firings of a backoff timer, a train of probes\n// ---------------------------------------------------------------------------------------------\n\n/** A band is the range of times in which a timer fires, from its arming. */\nexport interface Band {\n /** This time is the duration less how early the timer can fire. */\n readonly low: Extent;\n /** This time is the duration plus how late the timer can fire. */\n readonly high: Extent;\n}\n\n/** This function gives an amount as an exact value in seconds. Without an amount, it gives zero. */\nconst secondsOf = (extent: Extent | Unknown | undefined): Value => {\n if (extent === undefined) return exact(r.ZERO);\n if (\"unknown\" in extent) return unknown(extent.unknown);\n if (isUnbounded(extent)) return INFINITE;\n return exact(convertExact(r.fromNumber(extent.value), extent.unit, \"s\"));\n};\n\n/**\n * This function gives the band of a timer from its bounds, exactly, in `unit`. The band goes from\n * its duration less its early bound to its duration plus its lateness. A bound that the document\n * does not give is zero. A duration without an end gives a band without an end. A keepalive of 11 s, 4 ms early and 352 ms\n * late, gives 10.996 s to 11.352 s.\n */\nexport const timerBand = (bounds: TimerBounds, unit = \"s\"): Band | Unknown => {\n const duration = secondsOf(bounds.duration);\n const early = secondsOf(bounds.early);\n const late = secondsOf(bounds.lateness);\n const lost = unknownOf([duration, early, late]);\n if (lost !== undefined) return out(lost, unit) as Unknown;\n if (duration.kind !== \"exact\") return { low: unbounded(unit), high: unbounded(unit) };\n if (early.kind !== \"exact\") return { unknown: \"an early bound without an end\", unit };\n const low = r.sub(duration.n, early.n);\n const at = (n: Rational): Quantity => quantity(r.toNumber(convertExact(n, \"s\", unit)), unit);\n return { low: at(low), high: late.kind === \"exact\" ? at(r.add(duration.n, late.n)) : unbounded(unit) };\n};\n\n/** A scheduled firing is one firing of a backoff timer, and its time on the timeline. */\nexport interface Scheduled {\n /** This count is the wait that ends in this firing: the wait after `fired` firings. */\n readonly fired: number;\n /** This time is the sum of the waits to this firing, from the first wait of the schedule, in seconds. */\n readonly at: Quantity;\n}\n\n/** These options tell where the firings of a schedule start and stop. Each stop that they give applies. */\nexport interface ScheduleOptions {\n /** This count is the first wait of the schedule. The default is 0, the wait from the arming. */\n readonly from?: number | undefined;\n /** This count is the most firings to give. */\n readonly count?: number | undefined;\n /** This time stops the schedule: the schedule keeps no firing after it. */\n readonly until?: Extent | undefined;\n /** This time stops the schedule after the first firing at it or after it. That firing is in the schedule. */\n readonly reach?: Extent | undefined;\n}\n\n/**\n * This function gives the firings of a backoff timer on a timeline: the sum of its waits, exactly,\n * from the wait `from`. It stops at the first wait that is not a known amount, or at a stop of the\n * options, or after 4096 firings. Each time is the duration of the waits, without how early or\n * late each can fire.\n *\n * Two examples: the retransmission timer of Linux gives the send of each retransmission. The\n * retry of a call with a deadline gives the start of each try.\n */\nexport const firings = (\n doc: Machine,\n timer: string,\n values: KnobValues,\n options: ScheduleOptions,\n): Scheduled[] => {\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 (options.count === undefined && options.until === undefined && options.reach === undefined) {\n throw new Error(`the firings of ${timer} need a stop: a count, until or reach`);\n }\n const limit = (extent: Extent | undefined): Value | undefined => (extent === undefined ? undefined : secondsOf(extent));\n const until = limit(options.until);\n const reach = limit(options.reach);\n const from = options.from ?? 0;\n const count = Math.min(options.count ?? FIRINGS, FIRINGS);\n const result: Scheduled[] = [];\n let at = r.ZERO;\n for (let fired = from; result.length < count; fired += 1) {\n const wait = secondsOf(timerOf(doc, timer, values, fired).duration);\n if (wait.kind !== \"exact\") break;\n at = r.add(at, wait.n);\n if (until?.kind === \"exact\" && r.cmp(at, until.n) > 0) break;\n result.push({ fired, at: quantity(r.toNumber(at), \"s\") });\n if (reach?.kind === \"exact\" && r.cmp(at, reach.n) >= 0) break;\n }\n return result;\n};\n\n/**\n * This function gives the times of a train of probes, exactly, in seconds. The first probe is at\n * `first`, and each next probe is one `interval` later, `count` probes in all. A first time without\n * an end gives no probe. An interval without an end gives only the first probe. Keepalive at its\n * defaults sends its probes at 7200 s, 7275 s, and so on to 7800 s.\n */\nexport const probeTrain = (first: Extent, interval: Extent, count: number): Quantity[] => {\n const start = secondsOf(first);\n const step = secondsOf(interval);\n if (start.kind !== \"exact\" || count < 1) return [];\n const times = [quantity(r.toNumber(start.n), \"s\")];\n if (step.kind !== \"exact\") return times;\n for (let k = 1; k < count; k += 1) times.push(quantity(r.toNumber(r.add(start.n, r.mul(step.n, whole(BigInt(k))))), \"s\"));\n return times;\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 && modelOf(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 => modelOf(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","// @mark1russell7/algebra/run: a live instance of a machine document. The run takes the transitions\n// of the document on each event, and it operates the timers of the document on a clock. The entry\n// does not import zod or a `node:` module. Thus a client in a browser can run its own machines.\n\nimport type { Extent, Unknown } from \"@mark1russell7/quantity\";\nimport { convertExact, isUnbounded, quantity, rationals as r } from \"@mark1russell7/quantity\";\nimport type { KnobValues } from \"./algebra.ts\";\nimport { timerOf, transitionOn } from \"./algebra.ts\";\nimport type { Cancel, Clock } from \"./clock.ts\";\nimport type { Machine, TransitionDef } from \"./machine.ts\";\nimport { machineProblems } from \"./machine.ts\";\nimport type { Transition } from \"./replay.ts\";\n\n/** These options start a run of a machine document. */\nexport interface RunMachineOptions {\n /** This clock gives the time of the run and operates its timers. A test gives `fakeClock()`. */\n readonly clock: Clock;\n /** This function gives the knob values for the durations of the timers. The default is the `default` of each knob. */\n readonly values?: KnobValues | undefined;\n /** This state is the start state. The default is the initial state of the document. */\n readonly state?: string | undefined;\n /** This name identifies the instance in each transition record. The default is the `id` of the document. */\n readonly instance?: string | undefined;\n /** This function gets each transition that the run takes, in the form that `replay` reads. */\n readonly onTransition?: ((transition: Transition) => void) | undefined;\n}\n\n/** A machine run is one live instance of a machine document. */\nexport interface MachineRun {\n /** This name is the state where the instance is. */\n readonly state: string;\n /**\n * This method gives one event to the instance. It gives the transition that the instance takes, or\n * undefined when the state has no transition on the event.\n */\n send(event: string): TransitionDef | undefined;\n /** This method stops each timer. After it, each send does nothing and gives undefined. */\n stop(): void;\n}\n\n/** This function gives the values of the knobs at their defaults. A knob without a default or without a unit has no value. */\nconst knobDefaults =\n (doc: Machine): KnobValues =>\n (name) => {\n const knob = Object.hasOwn(doc.knobs, name) ? doc.knobs[name] : undefined;\n if (knob === undefined || knob.unit === null || knob.default === null) return undefined;\n return quantity(knob.default, knob.unit);\n };\n\n/** This function gives the start state of a run: the state of the options, or the one initial state of the document. */\nconst startState = (doc: Machine, state: string | undefined): string => {\n if (state !== undefined) {\n if (!Object.hasOwn(doc.states, state)) throw new Error(`${doc.title} has no state ${state}`);\n return state;\n }\n const initial = Object.keys(doc.states).filter((name) => doc.states[name]!.initial === true);\n if (initial.length !== 1) {\n throw new Error(`${doc.title} has ${initial.length} initial states: give the start state in the options`);\n }\n return initial[0]!;\n};\n\n/**\n * This function starts a live instance of a machine document on a clock. It gives the run: its\n * state, `send` and `stop`. The run applies these rules:\n *\n * - The run refuses a document with problems (`machineProblems`), as each reader does. With a start\n * state in the options, a document with no initial state is correct.\n * - At the start, the instance enters its start state. The pseudo event `enter:<state>` operates\n * the timers, as after a transition.\n * - An event that the document does not name is an error. The run throws an `Error` that names it.\n * - `send` takes the transition of `transitionOn` from the state on the event. Then, in sequence,\n * these events operate the timers: the event itself, each event that the transition emits, and\n * `enter:<to>`. A transition to the state that it leaves also enters that state again.\n * - An event without a transition also operates the timers.\n * - For each timer, an event of `backoff.resets` first sets its count of firings to 0. Then an\n * event of `cancels` stops it, or else an event of `arms` starts it again from the full\n * duration. An event in `arms` and in `cancels` stops the timer, as in `detection`.\n * - The run reads the duration of each start from `timerOf`, with the values and the count of\n * firings of a backoff timer. It converts the duration to milliseconds exactly. It does not read\n * the lateness or the early bound. A duration with no bound does not start the timer.\n * - The run reads the first duration of each timer when it starts. Thus a knob without a value is an\n * error at the start, not in a callback of the clock.\n * - When a timer fires, its `fires` event goes through `send`. A backoff timer first adds 1 to its\n * count and starts again with its next wait. Thus its own `cancels` can stop it.\n * - The entry to a final state stops each timer. In a final state, `send` does nothing and gives undefined.\n * - The run gives each transition that it takes to `onTransition`, after the timers. The record has\n * the machine (the `id` of the document), the instance, the states, the event and the time of the clock.\n * - The `timer` of a transition is a note for the reader. The run does not read it.\n */\nexport const runMachine = (doc: Machine, options: RunMachineOptions): MachineRun => {\n const problems = machineProblems(doc).filter((problem) => options.state === undefined || problem !== \"no initial state\");\n if (problems.length > 0) throw new Error(`${doc.title} has problems: ${problems.join(\", \")}`);\n const clock = options.clock;\n const values = options.values ?? knobDefaults(doc);\n const instance = options.instance ?? doc.id;\n let state = startState(doc, options.state);\n let stopped = false;\n const timers = Object.entries(doc.timers).map(([name, def]) => ({\n name,\n def,\n fired: 0,\n cancel: undefined as Cancel | undefined,\n }));\n type Live = (typeof timers)[number];\n\n /** This function gives the wait of a timer in milliseconds, or undefined for a duration with no bound. */\n const waitOf = (timer: Live): number | undefined => {\n const duration: Extent | Unknown = timerOf(doc, timer.name, values, timer.def.backoff === undefined ? undefined : timer.fired).duration;\n if (\"unknown\" in duration) throw new Error(`${doc.title}'s ${timer.name} has no known duration: ${duration.unknown}`);\n if (isUnbounded(duration)) return undefined;\n return r.toNumber(convertExact(r.fromNumber(duration.value), duration.unit, \"ms\"));\n };\n const halt = (timer: Live): void => {\n timer.cancel?.();\n timer.cancel = undefined;\n };\n const begin = (timer: Live): void => {\n halt(timer);\n const ms = waitOf(timer);\n if (ms !== undefined) timer.cancel = clock.after(ms, () => fire(timer));\n };\n const fire = (timer: Live): void => {\n timer.cancel = undefined;\n if (stopped) return;\n if (timer.def.backoff !== undefined) {\n timer.fired += 1;\n begin(timer);\n }\n run.send(timer.def.fires);\n };\n /** This function operates each timer for one event. */\n const occur = (event: string): void => {\n for (const timer of timers) {\n if (timer.def.backoff?.resets.includes(event) === true) timer.fired = 0;\n if (timer.def.cancels?.includes(event) === true) halt(timer);\n else if (timer.def.arms.includes(event)) begin(timer);\n }\n };\n const isFinal = (name: string): boolean => doc.states[name]?.final === true;\n /** This function enters a state: `enter:<state>` operates the timers, and a final state stops each timer. */\n const enter = (to: string): void => {\n occur(`enter:${to}`);\n if (isFinal(to)) for (const timer of timers) halt(timer);\n };\n\n const run: MachineRun = {\n get state() {\n return state;\n },\n send(event) {\n if (!Object.hasOwn(doc.events, event)) throw new Error(`${doc.title} has no event ${event}`);\n if (stopped || isFinal(state)) return undefined;\n const from = state;\n const taken = transitionOn(doc, from, event);\n if (taken !== undefined) state = taken.to;\n occur(event);\n if (taken === undefined) return undefined;\n for (const sent of taken.emits ?? []) occur(sent);\n enter(taken.to);\n options.onTransition?.({ machine: doc.id, instance, from, on: event, to: taken.to, at: clock.now() });\n return taken;\n },\n stop() {\n stopped = true;\n for (const timer of timers) halt(timer);\n },\n };\n\n // a first duration that is not known stops the start, before a timer runs\n for (const timer of timers) waitOf(timer);\n enter(state);\n return run;\n};\n"],"mappings":";;;;;;;AA+CA,MAAa,QAAQ;;AA+HrB,MAAM,aAAa,MAAsB;CACvC,IAAI,UAAU,GAAG,OAAO,CAAC,EAAE,IAAI;CAC/B,IAAI,WAAW,GAAG,OAAO,CAAC,GAAG,EAAE,KAAK;CACpC,IAAI,UAAU,GACZ,QAAQ,EAAE,KAAK,MAAM,0BAA0B,KAAK,CAAC,EAAA,CAAG,QACrD,SAAS,CAAC;EAAC;EAAO;EAAO;EAAS;EAAQ;CAAK,CAAC,CAAC,SAAS,IAAI,CACjE;CAEF,OAAO,CAAC;AACV;;AAGA,MAAa,aAAa,MAAsB,UAAU,CAAC,CAAC,CAAC,QAAQ,SAAS,SAAS,KAAK;;AAG5F,MAAa,cAAc,MAAqB,UAAU,CAAC,CAAC,CAAC,SAAS,KAAK;;;;;;AAO3E,MAAa,mBAAmB,MAAyB;CACvD,MAAM,WAAqB,CAAC;CAC5B,MAAM,SAAS,IAAI,IAAI,OAAO,KAAK,EAAE,MAAM,CAAC;CAC5C,IAAI,CAAC,OAAO,OAAO,EAAE,MAAM,CAAC,CAAC,MAAM,UAAU,MAAM,YAAY,IAAI,GACjE,SAAS,KAAK,kBAAkB;CAElC,KAAK,MAAM,KAAK,EAAE,aAAa;EAC7B,KAAK,MAAM,QAAQ,IAAI,EAAE,IAAI,GAC3B,IAAI,SAAS,OAAO,CAAC,OAAO,IAAI,IAAI,GAAG,SAAS,KAAK,GAAG,EAAE,GAAG,SAAS,MAAM;EAE9E,IAAI,CAAC,OAAO,IAAI,EAAE,EAAE,GAAG,SAAS,KAAK,GAAG,EAAE,GAAG,OAAO,EAAE,IAAI;EAC1D,KAAK,MAAM,SAAS,IAAI,EAAE,EAAE,GAC1B,IAAI,EAA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