@mark1russell7/algebra 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.js ADDED
@@ -0,0 +1,843 @@
1
+ import { convertExact, isUnbounded, quantity, rationals, unbounded, unitSchema } from "@mark1russell7/quantity";
2
+ import { z } from "zod";
3
+ //#region src/machine.ts
4
+ /**
5
+ * This name is what the waits of a backoff timer read for the number of times that it fired after
6
+ * a reset, from 0. It is not a knob, because nothing sets it. It is the count of the timer itself.
7
+ */
8
+ const FIRED = "fired";
9
+ const unit = unitSchema(["time", "count"]);
10
+ const knobUnit = unitSchema([
11
+ "time",
12
+ "count",
13
+ "frequency"
14
+ ]);
15
+ const expr = z.union([
16
+ z.strictObject({
17
+ const: z.number(),
18
+ unit
19
+ }),
20
+ z.strictObject({
21
+ knob: z.string(),
22
+ unit
23
+ }),
24
+ z.strictObject({
25
+ expr: z.string(),
26
+ unit
27
+ }),
28
+ z.strictObject({
29
+ model: z.string(),
30
+ knobs: z.array(z.string()),
31
+ unit
32
+ })
33
+ ]);
34
+ const timer = z.strictObject({
35
+ duration: expr,
36
+ /** This expression is how late the timer can fire, a tolerance on one side. */
37
+ lateness: expr.optional(),
38
+ /** This expression is how early the timer can fire, for example one jiffy. */
39
+ early: expr.optional(),
40
+ /** These are the events, or "enter:<STATE>", that start the timer or start it again. */
41
+ arms: z.array(z.string()),
42
+ cancels: z.array(z.string()).optional(),
43
+ /** This event is the event that the timer raises. */
44
+ fires: z.string(),
45
+ /** A backoff timer starts again after it fires, and its waits read `fired`. */
46
+ backoff: z.strictObject({ resets: z.array(z.string()) }).optional(),
47
+ note: z.string().optional()
48
+ });
49
+ const realization = z.union([z.strictObject({ timer: z.string() }), z.strictObject({
50
+ duration: expr,
51
+ lateness: expr.optional(),
52
+ early: expr.optional(),
53
+ note: z.string().optional()
54
+ })]);
55
+ const oneOrMany = z.union([z.string(), z.array(z.string())]);
56
+ const transition = z.strictObject({
57
+ id: z.string(),
58
+ /** The state "*" is each state that is not final. */
59
+ from: oneOrMany,
60
+ to: z.string(),
61
+ on: oneOrMany,
62
+ guard: z.string().optional(),
63
+ timer: z.string().optional(),
64
+ emits: z.array(z.string()).optional(),
65
+ errno: z.string().optional(),
66
+ note: z.string().optional(),
67
+ /** This text is the file and line, or the section of a specification, that the transition comes from. */
68
+ source: z.string().optional()
69
+ });
70
+ /** This schema accepts a machine document. */
71
+ const machineSchema = z.strictObject({
72
+ format: z.literal("mark1russell7.machine/1"),
73
+ id: z.string(),
74
+ title: z.string(),
75
+ layer: z.enum([
76
+ "wire",
77
+ "kernel",
78
+ "middlebox",
79
+ "proxy",
80
+ "driver",
81
+ "server",
82
+ "canary",
83
+ "injector",
84
+ "self"
85
+ ]),
86
+ version: z.string(),
87
+ /** These are the conditions where the machine holds: a range of kernels, an architecture. */
88
+ conditions: z.record(z.string(), z.string()).optional(),
89
+ sources: z.array(z.strictObject({
90
+ ref: z.string(),
91
+ rung: z.enum([
92
+ "normative",
93
+ "implemented",
94
+ "documented",
95
+ "observed",
96
+ "derived"
97
+ ]),
98
+ note: z.string().optional()
99
+ })),
100
+ states: z.record(z.string(), z.strictObject({
101
+ initial: z.boolean().optional(),
102
+ final: z.boolean().optional(),
103
+ pseudo: z.boolean().optional(),
104
+ note: z.string().optional()
105
+ })),
106
+ events: z.record(z.string(), z.strictObject({
107
+ kind: z.enum([
108
+ "rx",
109
+ "tx",
110
+ "app",
111
+ "timer",
112
+ "local",
113
+ "packet",
114
+ "peer"
115
+ ]),
116
+ note: z.string().optional()
117
+ })),
118
+ /**
119
+ * These are the names of the machine for the knobs that its timers and guards read. Each has
120
+ * its key in its system, as a knob in a corpus has.
121
+ */
122
+ knobs: z.record(z.string(), z.strictObject({
123
+ key: z.string(),
124
+ scope: z.string(),
125
+ /** The unit is null for a switch or a choice (nf_conntrack_tcp_loose), whose default is its code. */
126
+ unit: knobUnit.nullable(),
127
+ default: z.number().nullable(),
128
+ note: z.string().optional()
129
+ })),
130
+ timers: z.record(z.string(), timer),
131
+ realizes: z.record(z.string(), realization).optional(),
132
+ over: z.strictObject({
133
+ machine: z.string(),
134
+ states: z.record(z.string(), z.string()),
135
+ sets: z.record(z.string(), expr),
136
+ ends: z.string(),
137
+ note: z.string().optional()
138
+ }).optional(),
139
+ transitions: z.array(transition),
140
+ /** This map tells what a source shows of the machine: its states as the source names them, and what it hides. */
141
+ observe: z.record(z.string(), z.strictObject({
142
+ states: z.record(z.string(), z.string()),
143
+ hides: z.array(z.string()).optional(),
144
+ fidelity: z.enum([
145
+ "complete",
146
+ "sampled",
147
+ "lossy",
148
+ "derived"
149
+ ]),
150
+ note: z.string().optional()
151
+ })).optional(),
152
+ generated: z.strictObject({
153
+ from: z.string(),
154
+ by: z.string()
155
+ }).optional()
156
+ });
157
+ /** This function gives one value or many values as an array. */
158
+ const arr = (value) => Array.isArray(value) ? value : [value];
159
+ /** This function gives the names that a duration reads: its knobs, by the names of the machine, and `fired`. */
160
+ const exprNames = (e) => {
161
+ if ("knob" in e) return [e.knob];
162
+ if ("model" in e) return [...e.knobs];
163
+ if ("expr" in e) return (e.expr.match(/[A-Za-z_][A-Za-z0-9_.]*/g) ?? []).filter((word) => ![
164
+ "min",
165
+ "max",
166
+ "floor",
167
+ "ceil"
168
+ ].includes(word));
169
+ return [];
170
+ };
171
+ /** This function gives the knobs that a duration reads, by the names of the machine for them. */
172
+ const exprKnobs = (e) => exprNames(e).filter((name) => name !== FIRED);
173
+ /** This function tells if a duration reads the number of times that its timer fired, as the waits of a backoff do. */
174
+ const readsFired = (e) => exprNames(e).includes(FIRED);
175
+ /** This function gives the states that a transition leaves. The state "*" is each state that is not final. */
176
+ const fromStates = (m, from) => {
177
+ const out = /* @__PURE__ */ new Set();
178
+ for (const state of arr(from)) if (state !== "*") out.add(state);
179
+ else for (const [name, def] of Object.entries(m.states)) if (def.final !== true) out.add(name);
180
+ return [...out];
181
+ };
182
+ /**
183
+ * This function gives the problems in the consistency of a document. Each state, event, timer and
184
+ * knob that it refers to must exist, and it must have an initial state. A reader refuses a
185
+ * machine with problems, and does not draw half of it.
186
+ */
187
+ const machineProblems = (m) => {
188
+ const problems = [];
189
+ const states = new Set(Object.keys(m.states));
190
+ if (!Object.values(m.states).some((state) => state.initial === true)) problems.push("no initial state");
191
+ for (const t of m.transitions) {
192
+ for (const from of arr(t.from)) if (from !== "*" && !states.has(from)) problems.push(`${t.id}: from ${from}`);
193
+ if (!states.has(t.to)) problems.push(`${t.id}: to ${t.to}`);
194
+ for (const event of arr(t.on)) if (m.events[event] === void 0) problems.push(`${t.id}: event ${event}`);
195
+ if (t.timer !== void 0 && m.timers[t.timer] === void 0) problems.push(`${t.id}: timer ${t.timer}`);
196
+ }
197
+ if (m.knobs["fired"] !== void 0) problems.push(`knob ${FIRED}: the name is a backoff timer's count of its firings`);
198
+ for (const [id, tm] of Object.entries(m.timers)) {
199
+ if (m.events[tm.fires] === void 0) problems.push(`timer ${id}: fires ${tm.fires}`);
200
+ for (const knob of exprKnobs(tm.duration)) {
201
+ const def = m.knobs[knob];
202
+ if (def === void 0) problems.push(`timer ${id}: knob ${knob}`);
203
+ else if (def.unit === null) problems.push(`timer ${id}: knob ${knob} is not an amount`);
204
+ }
205
+ if ([
206
+ tm.duration,
207
+ tm.lateness,
208
+ tm.early
209
+ ].some((e) => e !== void 0 && readsFired(e)) && tm.backoff === void 0) problems.push(`timer ${id}: reads ${FIRED}, but has no backoff`);
210
+ for (const event of tm.backoff?.resets ?? []) if (!event.startsWith("enter:") && m.events[event] === void 0) problems.push(`timer ${id}: backoff resets on ${event}`);
211
+ }
212
+ for (const [mechanism, how] of Object.entries(m.realizes ?? {})) {
213
+ if ("timer" in how) {
214
+ if (m.timers[how.timer] === void 0 && m.over === void 0) problems.push(`realizes ${mechanism}: timer ${how.timer}`);
215
+ continue;
216
+ }
217
+ if ([
218
+ how.duration,
219
+ how.lateness,
220
+ how.early
221
+ ].some((e) => e !== void 0 && readsFired(e))) problems.push(`realizes ${mechanism}: reads ${FIRED}, which only a backoff timer counts`);
222
+ for (const knob of exprKnobs(how.duration)) {
223
+ const def = m.knobs[knob];
224
+ if (def === void 0) problems.push(`realizes ${mechanism}: knob ${knob}`);
225
+ else if (def.unit === null) problems.push(`realizes ${mechanism}: knob ${knob} is not an amount`);
226
+ }
227
+ }
228
+ if (m.over !== void 0) {
229
+ for (const state of Object.keys(m.over.states)) if (!states.has(state)) problems.push(`over: state ${state}`);
230
+ if (m.events[m.over.ends] === void 0) problems.push(`over: ends ${m.over.ends}`);
231
+ for (const [lower, set] of Object.entries(m.over.sets)) {
232
+ if (readsFired(set)) problems.push(`over: sets ${lower} from ${FIRED}, which is no knob`);
233
+ for (const knob of exprKnobs(set)) {
234
+ const def = m.knobs[knob];
235
+ if (def === void 0) problems.push(`over: sets ${lower} from knob ${knob}`);
236
+ else if (def.unit === null) problems.push(`over: sets ${lower} from ${knob}, no amount`);
237
+ }
238
+ }
239
+ }
240
+ for (const [source, view] of Object.entries(m.observe ?? {})) for (const state of Object.values(view.states)) if (!states.has(state)) problems.push(`observe ${source}: ${state}`);
241
+ const ids = m.transitions.map((t) => t.id);
242
+ for (const id of new Set(ids)) if (ids.filter((other) => other === id).length > 1) problems.push(`transition ${id} twice`);
243
+ return problems;
244
+ };
245
+ //#endregion
246
+ //#region src/algebra.ts
247
+ const exact = (n) => ({
248
+ kind: "exact",
249
+ n
250
+ });
251
+ const INFINITE = { kind: "infinite" };
252
+ const unknown = (why) => ({
253
+ kind: "unknown",
254
+ why
255
+ });
256
+ const whole = (n) => rationals.rational(n);
257
+ /** This function gives the first unknown among some values. An operation over them gets it. */
258
+ const unknownOf = (values) => values.find((value) => value.kind === "unknown");
259
+ const FUNCTIONS = {
260
+ min: 2,
261
+ max: 2,
262
+ floor: 1,
263
+ ceil: 1
264
+ };
265
+ /** This function parses the arithmetic of a document, or it throws an error that tells where the text stops making sense. */
266
+ const parseExpr = (text) => {
267
+ const tokens = text.match(/\d+(?:\.\d+)?|[A-Za-z_][A-Za-z0-9_.]*|[-+*/(),]|\S/g) ?? [];
268
+ let at = 0;
269
+ const peek = () => tokens[at];
270
+ const take = (expected) => {
271
+ const token = tokens[at];
272
+ if (token === void 0 || expected !== void 0 && token !== expected) throw new Error(`"${text}": expected ${expected ?? "more"} at ${token ?? "the end"}`);
273
+ at += 1;
274
+ return token;
275
+ };
276
+ const expr = () => {
277
+ let node = term();
278
+ while (peek() === "+" || peek() === "-") node = {
279
+ op: take(),
280
+ a: node,
281
+ b: term()
282
+ };
283
+ return node;
284
+ };
285
+ const term = () => {
286
+ let node = factor();
287
+ while (peek() === "*" || peek() === "/") node = {
288
+ op: take(),
289
+ a: node,
290
+ b: factor()
291
+ };
292
+ return node;
293
+ };
294
+ const factor = () => {
295
+ const token = take();
296
+ if (token === "(") {
297
+ const inner = expr();
298
+ take(")");
299
+ return inner;
300
+ }
301
+ if (token === "-") return {
302
+ op: "neg",
303
+ a: factor()
304
+ };
305
+ if (/^\d/.test(token)) return {
306
+ op: "num",
307
+ n: rationals.fromDecimal(token)
308
+ };
309
+ if (!/^[A-Za-z_]/.test(token)) throw new Error(`"${text}": ${token} is not a term`);
310
+ if (token in FUNCTIONS) {
311
+ const name = token;
312
+ take("(");
313
+ const args = [expr()];
314
+ while (peek() === ",") {
315
+ take(",");
316
+ args.push(expr());
317
+ }
318
+ take(")");
319
+ if (args.length !== FUNCTIONS[name]) throw new Error(`"${text}": ${name} takes ${FUNCTIONS[name]}, not ${args.length}`);
320
+ return {
321
+ op: name,
322
+ args
323
+ };
324
+ }
325
+ return {
326
+ op: "knob",
327
+ name: token
328
+ };
329
+ };
330
+ const node = expr();
331
+ if (at < tokens.length) throw new Error(`"${text}": ${tokens[at]} after the end`);
332
+ return node;
333
+ };
334
+ const run = (node, valueOf) => {
335
+ if (node.op === "num") return exact(node.n);
336
+ if (node.op === "knob") return valueOf(node.name);
337
+ if (node.op === "neg") {
338
+ const a = run(node.a, valueOf);
339
+ return a.kind === "exact" ? exact(rationals.neg(a.n)) : a.kind === "infinite" ? unknown("a negative unbounded time") : a;
340
+ }
341
+ if ("args" in node) {
342
+ const args = node.args.map((arg) => run(arg, valueOf));
343
+ const lost = unknownOf(args);
344
+ if (lost !== void 0) return lost;
345
+ if (node.op === "floor" || node.op === "ceil") {
346
+ const [a] = args;
347
+ return a.kind === "exact" ? exact(node.op === "floor" ? rationals.floor(a.n) : rationals.ceil(a.n)) : a;
348
+ }
349
+ const [a, b] = args;
350
+ if (a.kind === "infinite" || b.kind === "infinite") return node.op === "max" ? INFINITE : a.kind === "infinite" ? b : a;
351
+ if (a.kind !== "exact" || b.kind !== "exact") return unknown("not an amount");
352
+ const aFirst = rationals.cmp(a.n, b.n) <= 0;
353
+ if (node.op === "min") return aFirst ? a : b;
354
+ return aFirst ? b : a;
355
+ }
356
+ const a = run(node.a, valueOf);
357
+ const b = run(node.b, valueOf);
358
+ const lost = unknownOf([a, b]);
359
+ if (lost !== void 0) return lost;
360
+ if (a.kind === "exact" && b.kind === "exact") {
361
+ if (node.op === "/" && b.n.n === 0n) return unknown("a division by zero");
362
+ const op = {
363
+ "+": rationals.add,
364
+ "-": rationals.sub,
365
+ "*": rationals.mul,
366
+ "/": rationals.div
367
+ }[node.op];
368
+ return exact(op(a.n, b.n));
369
+ }
370
+ const zero = (value) => value.kind === "exact" && value.n.n === 0n;
371
+ if (node.op === "+") return INFINITE;
372
+ if (node.op === "*") return zero(a) || zero(b) ? unknown("zero times no bound") : INFINITE;
373
+ if (node.op === "-") return a.kind === "infinite" && b.kind !== "infinite" ? INFINITE : unknown("no bound less no bound");
374
+ return a.kind === "infinite" ? b.kind === "infinite" ? unknown("no bound over no bound") : INFINITE : exact(rationals.ZERO);
375
+ };
376
+ const integer = (value, what) => {
377
+ if (!rationals.isInteger(value) || value.n < 0n) throw new Error(`${what} is not a whole count: ${rationals.toNumber(value)}`);
378
+ return value.n;
379
+ };
380
+ /** This function gives min(base × 2^k, cap), exactly. */
381
+ const capped = (base, k, cap) => {
382
+ const doubled = rationals.mul(base, whole(2n ** k));
383
+ return rationals.cmp(doubled, cap) <= 0 ? doubled : cap;
384
+ };
385
+ /**
386
+ * This function gives the hypothetical retransmission timeout of the kernel, tcp_model_timeout in
387
+ * net/ipv4/tcp_timer.c. The waits double from the minimum RTO until a step is more than the
388
+ * maximum, and then the waits are capped. For tcp_retries2 = 15, it is 0.2 s × (2^10 − 1) +
389
+ * 6 × 120 s = 924.6 s.
390
+ */
391
+ const retransBudget = (retries, min, max) => {
392
+ let thresh = 0n;
393
+ while (rationals.cmp(rationals.mul(min, whole(2n ** (thresh + 1n))), max) <= 0) thresh += 1n;
394
+ if (retries <= thresh) return rationals.mul(min, whole(2n ** (retries + 1n) - 1n));
395
+ return rationals.add(rationals.mul(min, whole(2n ** (thresh + 1n) - 1n)), rationals.mul(whole(retries - thresh), max));
396
+ };
397
+ /** These are TCP_TIMEOUT_INIT and TCP_RTO_MAX in include/net/tcp.h at v6.6: the first SYN RTO and the cap. */
398
+ const TCP_TIMEOUT_INIT = whole(1n);
399
+ const TCP_RTO_MAX = whole(120n);
400
+ /** This function gives the whole jiffies of a time at HZ, rounded up, as msecs_to_jiffies and usecs_to_jiffies round. */
401
+ const jiffiesOf = (seconds, hz) => rationals.ceil(rationals.mul(seconds, hz)).n;
402
+ /**
403
+ * This function gives how late the timer wheel can fire a timer that is due in `jiffies`
404
+ * (calc_wheel_index in kernel/time/timer.c at v6.6). Level 0 holds the timers due in 63 jiffies
405
+ * or less. Each level above holds eight times as long, at eight times the granularity. The wheel
406
+ * rounds a timer up to the next boundary of its level, thus it fires up to one granularity late.
407
+ * At HZ 250, a 2 h timer can be up to 131 s late.
408
+ */
409
+ const granularity = (jiffies) => {
410
+ let level = 0n;
411
+ while (level < 8n && jiffies >= 63n << 3n * level) level += 1n;
412
+ return 8n ** level;
413
+ };
414
+ /**
415
+ * This function gives the lateness of the retransmission give-up after its budget. The first
416
+ * retransmission sets the RTO to the round trip plus the minimum, rounded up to a jiffy
417
+ * (tcp_set_rto). On a Docker network at HZ 250, that is 204 ms, not 200.
418
+ *
419
+ * Each firing doubles the RTO, up to the cap. The budget ends in the firing after the last one
420
+ * that is short of it. Thus the give-up comes one step late at most, plus the rounding of each
421
+ * firing on the wheel. The model assumes a steady path, whose variance stays below the minimum RTO.
422
+ */
423
+ const retransLateness = (retries, min, max, rtt, hz) => {
424
+ const base = jiffiesOf(rationals.add(min, rtt), hz);
425
+ const cap = jiffiesOf(max, hz);
426
+ let step = base;
427
+ let wheel = 0n;
428
+ for (let k = 1n; k <= retries + 1n; k += 1n) {
429
+ step = base * 2n ** k < cap ? base * 2n ** k : cap;
430
+ wheel += granularity(step);
431
+ }
432
+ return rationals.div(whole(step + wheel), hz);
433
+ };
434
+ /**
435
+ * This function gives one wait of the retransmission timer with one segment in flight, in jiffies
436
+ * (net/ipv4/tcp_timer.c, and tcp_schedule_loss_probe in tcp_output.c, at v6.6). Its first firing
437
+ * is the tail loss probe. For one segment, the probe waits two round trips plus TCP_RTO_MIN, but
438
+ * not longer than the RTO. Thus it waits the RTO itself: the round trip plus the minimum, in whole
439
+ * jiffies.
440
+ *
441
+ * The probe arms the RTO again, and each RTO firing doubles it, up to the cap. Thus the
442
+ * firing k comes 2^k RTOs after the send: 0.204, 0.408, 0.816 s on a Docker network at HZ 250.
443
+ * With more than one segment in flight, the probe waits two round trips plus 2 jiffies.
444
+ */
445
+ const rtoWait = (fired, min, max, rtt, hz) => {
446
+ const base = jiffiesOf(rationals.add(min, rtt), hz);
447
+ const cap = jiffiesOf(max, hz);
448
+ if (fired === 0n) return base;
449
+ const doubled = base * 2n ** (fired - 1n);
450
+ return doubled < cap ? doubled : cap;
451
+ };
452
+ /**
453
+ * This function gives the lateness of keepalive. It adds the idle timer and the interval of each
454
+ * probe, each rounded up on the wheel at its own level. Linux arms the idle timer, then one probe
455
+ * interval for each probe without an answer.
456
+ */
457
+ const keepaliveLateness = (idle, interval, probes, hz) => {
458
+ const late = (time) => whole(granularity(jiffiesOf(time, hz)));
459
+ return rationals.div(rationals.add(late(idle), rationals.mul(whole(probes), late(interval))), hz);
460
+ };
461
+ const MODELS = {
462
+ "linux.retrans-budget": {
463
+ knobs: [
464
+ null,
465
+ "s",
466
+ "s"
467
+ ],
468
+ seconds: ([retries, min, max]) => retransBudget(integer(retries, "tcp_retries2"), min, max),
469
+ source: "net/ipv4/tcp_timer.c tcp_model_timeout at v6.6"
470
+ },
471
+ "linux.retrans-step": {
472
+ knobs: [
473
+ null,
474
+ "s",
475
+ "s",
476
+ "s",
477
+ "Hz"
478
+ ],
479
+ seconds: ([retries, min, max, rtt, hz]) => retransLateness(integer(retries, "tcp_retries2"), min, max, rtt, hz),
480
+ source: "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)"
481
+ },
482
+ "linux.rto-wait": {
483
+ knobs: [
484
+ null,
485
+ "s",
486
+ "s",
487
+ "s",
488
+ "Hz"
489
+ ],
490
+ seconds: ([fired, min, max, rtt, hz]) => rationals.div(whole(rtoWait(integer(fired, FIRED), min, max, rtt, hz)), hz),
491
+ source: "net/ipv4/tcp_timer.c tcp_retransmit_timer and tcp_output.c tcp_schedule_loss_probe at v6.6 (measured by @mark1russell7/harness, 2026-10-12)"
492
+ },
493
+ "linux.rto-wait-lateness": {
494
+ knobs: [
495
+ null,
496
+ "s",
497
+ "s",
498
+ "s",
499
+ "Hz"
500
+ ],
501
+ seconds: ([fired, min, max, rtt, hz]) => rationals.div(whole(granularity(rtoWait(integer(fired, FIRED), min, max, rtt, hz))), hz),
502
+ source: "kernel/time/timer.c calc_wheel_index at v6.6"
503
+ },
504
+ "linux.keepalive-lateness": {
505
+ knobs: [
506
+ "s",
507
+ "s",
508
+ null,
509
+ "Hz"
510
+ ],
511
+ seconds: ([idle, interval, probes, hz]) => keepaliveLateness(idle, interval, integer(probes, "keepcnt"), hz),
512
+ source: "net/ipv4/tcp_timer.c tcp_keepalive_timer and kernel/time/timer.c at v6.6"
513
+ },
514
+ "linux.wheel": {
515
+ knobs: ["s", "Hz"],
516
+ seconds: ([time, hz]) => rationals.div(whole(granularity(jiffiesOf(time, hz))), hz),
517
+ source: "kernel/time/timer.c calc_wheel_index at v6.6"
518
+ },
519
+ "linux.jiffy": {
520
+ knobs: ["Hz"],
521
+ seconds: ([hz]) => rationals.div(whole(1n), hz),
522
+ source: "include/linux/jiffies.h"
523
+ },
524
+ "linux.syn-giveup": {
525
+ knobs: [null, null],
526
+ seconds: ([retries, linear]) => {
527
+ const n = integer(retries, "tcp_syn_retries");
528
+ let total = rationals.mul(whole(integer(linear, "tcp_syn_linear_timeouts") + 1n), TCP_TIMEOUT_INIT);
529
+ for (let i = 1n; i <= n; i += 1n) total = rationals.add(total, capped(TCP_TIMEOUT_INIT, i, TCP_RTO_MAX));
530
+ return total;
531
+ },
532
+ source: "net/ipv4/tcp_timer.c tcp_write_timeout and Documentation/networking/ip-sysctl.rst at v6.6"
533
+ },
534
+ "ioredis.retry-base": {
535
+ knobs: [null],
536
+ seconds: ([fired]) => capped(rationals.fromDecimal("0.05"), integer(fired, FIRED), whole(5n)),
537
+ source: "ioredis 6.0.0 built/redis/RedisOptions.js retryStrategy and built/redis/event_handler.js"
538
+ }
539
+ };
540
+ /**
541
+ * This function gives the value of a knob in the unit that the document gives it (or as a count
542
+ * when it is a count). For `fired`, it gives which wait of a backoff timer it is.
543
+ */
544
+ const knobIn = (doc, name, unit, values, fired) => {
545
+ if (name === "fired") return fired === void 0 ? unknown("one wait of a timer with a backoff: say which, by how many times it has fired") : exact(rationals.fromNumber(fired));
546
+ if (doc.knobs[name] === void 0) return unknown(`the machine names no knob ${name}`);
547
+ const given = values(name);
548
+ if (given === void 0) return unknown(`nothing gives ${name}'s value`);
549
+ if ("unknown" in given) return unknown(`${name}: ${given.unknown}`);
550
+ if (given.value === "infinite") return INFINITE;
551
+ const value = rationals.fromNumber(given.value);
552
+ return exact(unit === null ? convertExact(value, given.unit, given.unit) : convertExact(value, given.unit, unit));
553
+ };
554
+ const out = (value, unit) => value.kind === "exact" ? quantity(rationals.toNumber(value.n), unit) : value.kind === "infinite" ? unbounded(unit) : {
555
+ unknown: value.why,
556
+ unit
557
+ };
558
+ /**
559
+ * This function evaluates one duration of a timer of a machine, in the unit that its document
560
+ * gives it. The waits of a backoff timer read `fired`, which tells which wait.
561
+ */
562
+ const evaluate = (doc, expr, values, fired) => {
563
+ if ("const" in expr) return quantity(expr.const, expr.unit);
564
+ if ("knob" in expr) return out(knobIn(doc, expr.knob, expr.unit, values, fired), expr.unit);
565
+ if ("expr" in expr) {
566
+ const tree = parseExpr(expr.expr);
567
+ const value = run(tree, (name) => knobIn(doc, name, doc.knobs[name]?.unit ?? null, values, fired));
568
+ return out(value, expr.unit);
569
+ }
570
+ const model = MODELS[expr.model];
571
+ if (model === void 0) return {
572
+ unknown: `no model ${expr.model}`,
573
+ unit: expr.unit
574
+ };
575
+ if (model.knobs.length !== expr.knobs.length) return {
576
+ unknown: `${expr.model} reads ${model.knobs.length} knobs, not ${expr.knobs.length}`,
577
+ unit: expr.unit
578
+ };
579
+ const args = expr.knobs.map((name, index) => knobIn(doc, name, model.knobs[index] ?? null, values, fired));
580
+ const lost = unknownOf(args);
581
+ if (lost !== void 0) return out(lost, expr.unit);
582
+ if (args.some((arg) => arg.kind === "infinite")) return unbounded(expr.unit);
583
+ const seconds = model.seconds(args.map((arg) => arg.n));
584
+ return quantity(rationals.toNumber(convertExact(seconds, "s", expr.unit)), expr.unit);
585
+ };
586
+ /**
587
+ * This function gives the bounds of a timer of a machine: how long it operates, how late it can
588
+ * fire, how early. For a backoff timer, it gives one of its waits: the wait after `fired` firings.
589
+ */
590
+ const timerOf = (doc, timer, values, fired) => {
591
+ const def = doc.timers[timer];
592
+ if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
593
+ return {
594
+ duration: evaluate(doc, def.duration, values, fired),
595
+ ...def.lateness !== void 0 ? { lateness: evaluate(doc, def.lateness, values, fired) } : {},
596
+ ...def.early !== void 0 ? { early: evaluate(doc, def.early, values, fired) } : {}
597
+ };
598
+ };
599
+ /** This count is the most firings that `recovery` examines before it tells that the stall is longer than them. */
600
+ const FIRINGS = 4096;
601
+ /**
602
+ * This function gives the recovery from a stall. A backoff timer continues to fire through a
603
+ * stall, and what each firing sends gets through only after the stall ends. Thus the connection
604
+ * moves again at the first firing at the end or after it. That firing can be most of a wait after
605
+ * the end. A stall that stops immediately after one firing costs almost all of the next, longer
606
+ * wait.
607
+ *
608
+ * The stall counts from the arming of the timer, which is the send that the stall first lost. The
609
+ * waits add, and so do how early and how late each can fire.
610
+ */
611
+ const recovery = (doc, timer, values, stall) => {
612
+ const def = doc.timers[timer];
613
+ if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
614
+ if (def.backoff === void 0) throw new Error(`${doc.title}'s ${timer} has no backoff`);
615
+ if (isUnbounded(stall)) return {
616
+ unknown: "a stall that never ends: nothing recovers from it",
617
+ unit: "s"
618
+ };
619
+ const end = convertExact(rationals.fromNumber(stall.value), stall.unit, "s");
620
+ const inSeconds = (extent, what) => {
621
+ if (extent === void 0) return rationals.ZERO;
622
+ if ("unknown" in extent) return `${what}: ${extent.unknown}`;
623
+ if (isUnbounded(extent)) return `${what} has no bound, so the timer never fires again`;
624
+ return convertExact(rationals.fromNumber(extent.value), extent.unit, "s");
625
+ };
626
+ const s = (value) => quantity(rationals.toNumber(value), "s");
627
+ const sums = [];
628
+ let low = rationals.ZERO;
629
+ let high = rationals.ZERO;
630
+ for (let fired = 0; fired < FIRINGS; fired += 1) {
631
+ const bounds = timerOf(doc, timer, values, fired);
632
+ const wait = inSeconds(bounds.duration, `wait ${fired}`);
633
+ const early = inSeconds(bounds.early, `wait ${fired}'s early bound`);
634
+ const late = inSeconds(bounds.lateness, `wait ${fired}'s lateness`);
635
+ if (typeof wait === "string") return {
636
+ unknown: wait,
637
+ unit: "s"
638
+ };
639
+ if (typeof early === "string") return {
640
+ unknown: early,
641
+ unit: "s"
642
+ };
643
+ if (typeof late === "string") return {
644
+ unknown: late,
645
+ unit: "s"
646
+ };
647
+ low = rationals.add(low, rationals.sub(wait, early));
648
+ high = rationals.add(high, rationals.add(wait, late));
649
+ sums.push({
650
+ fired,
651
+ low,
652
+ high
653
+ });
654
+ if (rationals.cmp(low, end) < 0) continue;
655
+ const first = sums.filter((f) => rationals.cmp(f.high, end) >= 0);
656
+ const earliest = first[0].low;
657
+ return {
658
+ firings: sums.map((f) => ({
659
+ fired: f.fired,
660
+ low: s(f.low),
661
+ high: s(f.high)
662
+ })),
663
+ first: first.map((f) => f.fired),
664
+ low: s(rationals.cmp(earliest, end) >= 0 ? earliest : end),
665
+ high: s(first.at(-1).high)
666
+ };
667
+ }
668
+ return {
669
+ unknown: `${FIRINGS} firings do not outlast the stall`,
670
+ unit: "s"
671
+ };
672
+ };
673
+ /**
674
+ * This function gives how long a mechanism takes where a machine operates, from the realization
675
+ * of its document. The realization is one of its timers, whole, or its own duration, lateness and
676
+ * early bound over the knobs of the machine. It gives undefined when the document does not realize the mechanism.
677
+ */
678
+ const realizationOf = (doc, mechanism, values) => {
679
+ const how = doc.realizes?.[mechanism];
680
+ if (how === void 0) return void 0;
681
+ if ("timer" in how) return timerOf(doc, how.timer, values);
682
+ return {
683
+ duration: evaluate(doc, how.duration, values),
684
+ ...how.lateness !== void 0 ? { lateness: evaluate(doc, how.lateness, values) } : {},
685
+ ...how.early !== void 0 ? { early: evaluate(doc, how.early, values) } : {}
686
+ };
687
+ };
688
+ /** This function gives the knobs that a realization reads, by the names of the machine for them. */
689
+ const realizationKnobs = (doc, mechanism) => {
690
+ const how = doc.realizes?.[mechanism];
691
+ if (how === void 0) return [];
692
+ const def = "timer" in how ? doc.timers[how.timer] : how;
693
+ if (def === void 0) return [];
694
+ return [...new Set([
695
+ def.duration,
696
+ def.lateness,
697
+ def.early
698
+ ].flatMap((e) => e === void 0 ? [] : exprKnobs(e)))];
699
+ };
700
+ /** This function gives what in a document the algebra cannot read: arithmetic that does not parse, or a model that it does not have. */
701
+ const algebraProblems = (doc) => {
702
+ const problems = [];
703
+ const read = (where, exprs) => {
704
+ for (const expr of exprs) {
705
+ if (expr === void 0) continue;
706
+ if ("expr" in expr) try {
707
+ parseExpr(expr.expr);
708
+ } catch (error) {
709
+ problems.push(`${where}: ${error.message}`);
710
+ }
711
+ if ("model" in expr && MODELS[expr.model] === void 0) problems.push(`${where}: no model ${expr.model}`);
712
+ }
713
+ };
714
+ for (const [id, def] of Object.entries(doc.timers)) read(`timer ${id}`, [
715
+ def.duration,
716
+ def.lateness,
717
+ def.early
718
+ ]);
719
+ for (const [mechanism, how] of Object.entries(doc.realizes ?? {})) if (!("timer" in how)) read(`realizes ${mechanism}`, [
720
+ how.duration,
721
+ how.lateness,
722
+ how.early
723
+ ]);
724
+ for (const [lower, set] of Object.entries(doc.over?.sets ?? {})) read(`over sets ${lower}`, [set]);
725
+ return problems;
726
+ };
727
+ /** This function gives the source of the formula of a named model, for a reader of a result. */
728
+ const modelSource = (name) => MODELS[name]?.source;
729
+ const soonest = (a, b) => {
730
+ const rank = (d) => "unknown" in d.duration ? 2 : d.duration.value === "infinite" ? 1 : 0;
731
+ if (rank(a) !== rank(b)) return rank(a) - rank(b);
732
+ if (rank(a) !== 0) return a.timer.localeCompare(b.timer);
733
+ const seconds = (d) => {
734
+ const value = d.duration;
735
+ return rationals.toNumber(convertExact(rationals.fromNumber(value.value), value.unit, "s"));
736
+ };
737
+ return seconds(a) - seconds(b) || a.timer.localeCompare(b.timer);
738
+ };
739
+ /**
740
+ * This function gives the detection: the minimum over the detectors that are live in the
741
+ * situation. The entry to the state arms a timer, and so does what the failure causes: data in
742
+ * flight without an acknowledgment gets a retransmission. An event that occurs cancels a timer.
743
+ *
744
+ * An event that arms the timer again, and that the failure continues to let through, stops it
745
+ * before it fires. For example, the kernel of a frozen process answers each keepalive probe.
746
+ * Without a live detector, the failure is silent at the level of this machine. Only something
747
+ * above it, the timeout of an application or a heartbeat, can find it. The result is only as good
748
+ * as the events that the document names.
749
+ */
750
+ const detection = (doc, situation, manifestation, values) => {
751
+ const passes = new Set(manifestation.passes);
752
+ const happened = /* @__PURE__ */ new Set([`enter:${situation.state}`]);
753
+ if (situation.inFlight && !passes.has("rx.ack")) happened.add("tx.retransmit.first");
754
+ const occurs = (event) => happened.has(event) || passes.has(event);
755
+ const detectors = [];
756
+ const held = [];
757
+ for (const [timer, def] of Object.entries(doc.timers)) {
758
+ if (def.backoff !== void 0) continue;
759
+ if (!def.arms.some(occurs)) continue;
760
+ const cancelled = (def.cancels ?? []).find(occurs);
761
+ if (cancelled !== void 0) {
762
+ held.push({
763
+ timer,
764
+ why: `${cancelled} cancels it`
765
+ });
766
+ continue;
767
+ }
768
+ const rearmed = def.arms.find((event) => passes.has(event));
769
+ if (rearmed !== void 0) {
770
+ held.push({
771
+ timer,
772
+ why: `${rearmed} keeps arriving and re-arms it`
773
+ });
774
+ continue;
775
+ }
776
+ detectors.push({
777
+ timer,
778
+ fires: def.fires,
779
+ duration: evaluate(doc, def.duration, values)
780
+ });
781
+ }
782
+ detectors.sort(soonest);
783
+ const [earliest] = detectors;
784
+ return {
785
+ detectors,
786
+ first: earliest !== void 0 && !("unknown" in earliest.duration) && earliest.duration.value !== "infinite" ? earliest : null,
787
+ unsettled: detectors.filter((d) => "unknown" in d.duration).map((d) => d.timer),
788
+ held
789
+ };
790
+ };
791
+ /** This function gives the transition that a machine takes from a state on an event, by its document. */
792
+ const transitionOn = (doc, state, event) => doc.transitions.find((t) => fromStates(doc, t.from).includes(state) && arr(t.on).includes(event));
793
+ /**
794
+ * This function gives the values of a machine for the machine that it operates on. These are the
795
+ * knobs that it sets, evaluated over its own knobs, and the other knobs of the lower machine. The
796
+ * keepAlive of ioredis at 5000 ms is the keepidle of the kernel at 5 s.
797
+ */
798
+ const overValues = (upper, upperValues, lowerValues) => (name) => {
799
+ const set = upper.over?.sets[name];
800
+ return set === void 0 ? lowerValues(name) : evaluate(upper, set, upperValues);
801
+ };
802
+ /**
803
+ * This function gives the detection through the machine that a machine operates on. The detectors
804
+ * of the lower machine are live in the state below the state of this machine. They use the knobs
805
+ * that this machine sets.
806
+ *
807
+ * Each one reaches this machine as the event that the end of the lower
808
+ * machine gives. They are beside the timers of this machine, and the first of all of them is the
809
+ * first detection. A failure lets nothing new through to a machine above the socket, only the end
810
+ * of the socket. Thus the timers of this machine see only what its state arms.
811
+ */
812
+ const stackedDetection = (upper, lower, situation, manifestation, upperValues, lowerValues) => {
813
+ const over = upper.over;
814
+ if (over === void 0) throw new Error(`${upper.title} runs on no other machine`);
815
+ const sitsOn = over.states[situation.state];
816
+ if (sitsOn === void 0) throw new Error(`${upper.title}'s ${situation.state} sits on no state of ${lower.title}`);
817
+ const own = detection(upper, situation, {
818
+ name: manifestation.name,
819
+ passes: []
820
+ }, upperValues);
821
+ const below = detection(lower, {
822
+ ...situation,
823
+ state: sitsOn
824
+ }, manifestation, overValues(upper, upperValues, lowerValues));
825
+ const detectors = [...own.detectors, ...below.detectors.map((d) => ({
826
+ ...d,
827
+ beneath: over.machine
828
+ }))].sort(soonest);
829
+ const [earliest] = detectors;
830
+ return {
831
+ detectors,
832
+ first: earliest !== void 0 && !("unknown" in earliest.duration) && earliest.duration.value !== "infinite" ? earliest : null,
833
+ unsettled: detectors.filter((d) => "unknown" in d.duration).map((d) => d.timer),
834
+ held: [...own.held, ...below.held.map((h) => ({
835
+ ...h,
836
+ why: `${h.why}, beneath`
837
+ }))]
838
+ };
839
+ };
840
+ //#endregion
841
+ export { FIRED, algebraProblems, arr, detection, evaluate, exprKnobs, fromStates, machineProblems, machineSchema, modelSource, overValues, parseExpr, readsFired, realizationKnobs, realizationOf, recovery, stackedDetection, timerOf, transitionOn };
842
+
843
+ //# sourceMappingURL=index.js.map