@mark1russell7/algebra 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +67 -2
- package/build/index.d.ts +386 -0
- package/build/index.js +916 -0
- package/build/index.js.map +1 -0
- package/package.json +66 -3
package/build/index.js
ADDED
|
@@ -0,0 +1,916 @@
|
|
|
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
|
+
/**
|
|
458
|
+
* This function gives the lateness of the retransmission give-up after its budget, under an ICMP
|
|
459
|
+
* host or net unreachable for each RTO retransmission. Each ICMP reverts one doubling of the backoff
|
|
460
|
+
* (tcp_ld_RTO_revert in net/ipv4/tcp_ipv4.c at v6.6, RFC 6069). Then each wait after the first RTO
|
|
461
|
+
* firing is one RTO again, thus the give-up comes at most one RTO after the budget. Each firing up
|
|
462
|
+
* to it can fire up to the granularity of its level of the wheel late.
|
|
463
|
+
*/
|
|
464
|
+
const retransLatenessReverted = (retries, min, max, rtt, hz) => {
|
|
465
|
+
const base = jiffiesOf(rationals.add(min, rtt), hz);
|
|
466
|
+
const firings = (jiffiesOf(retransBudget(retries, min, max), hz) + base - 1n) / base + 1n;
|
|
467
|
+
return rationals.div(whole(base + firings * granularity(base)), hz);
|
|
468
|
+
};
|
|
469
|
+
const keepaliveLateness = (idle, interval, probes, hz) => {
|
|
470
|
+
const late = (time) => whole(granularity(jiffiesOf(time, hz)));
|
|
471
|
+
return rationals.div(rationals.add(late(idle), rationals.mul(whole(probes), late(interval))), hz);
|
|
472
|
+
};
|
|
473
|
+
const MODELS = {
|
|
474
|
+
"linux.retrans-budget": {
|
|
475
|
+
knobs: [
|
|
476
|
+
null,
|
|
477
|
+
"s",
|
|
478
|
+
"s"
|
|
479
|
+
],
|
|
480
|
+
seconds: ([retries, min, max]) => retransBudget(integer(retries, "tcp_retries2"), min, max),
|
|
481
|
+
source: "net/ipv4/tcp_timer.c tcp_model_timeout at v6.6"
|
|
482
|
+
},
|
|
483
|
+
"linux.retrans-step": {
|
|
484
|
+
knobs: [
|
|
485
|
+
null,
|
|
486
|
+
"s",
|
|
487
|
+
"s",
|
|
488
|
+
"s",
|
|
489
|
+
"Hz"
|
|
490
|
+
],
|
|
491
|
+
seconds: ([retries, min, max, rtt, hz]) => retransLateness(integer(retries, "tcp_retries2"), min, max, rtt, hz),
|
|
492
|
+
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)"
|
|
493
|
+
},
|
|
494
|
+
"linux.rto-wait": {
|
|
495
|
+
knobs: [
|
|
496
|
+
null,
|
|
497
|
+
"s",
|
|
498
|
+
"s",
|
|
499
|
+
"s",
|
|
500
|
+
"Hz"
|
|
501
|
+
],
|
|
502
|
+
seconds: ([fired, min, max, rtt, hz]) => rationals.div(whole(rtoWait(integer(fired, FIRED), min, max, rtt, hz)), hz),
|
|
503
|
+
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)"
|
|
504
|
+
},
|
|
505
|
+
"linux.rto-wait-reverted": {
|
|
506
|
+
knobs: [
|
|
507
|
+
null,
|
|
508
|
+
"s",
|
|
509
|
+
"s",
|
|
510
|
+
"s",
|
|
511
|
+
"Hz"
|
|
512
|
+
],
|
|
513
|
+
seconds: ([, min, , rtt, hz]) => rationals.div(whole(jiffiesOf(rationals.add(min, rtt), hz)), hz),
|
|
514
|
+
source: "net/ipv4/tcp_ipv4.c tcp_v4_err and tcp_ld_RTO_revert at v6.6 (RFC 6069)"
|
|
515
|
+
},
|
|
516
|
+
"linux.retrans-step-reverted": {
|
|
517
|
+
knobs: [
|
|
518
|
+
null,
|
|
519
|
+
"s",
|
|
520
|
+
"s",
|
|
521
|
+
"s",
|
|
522
|
+
"Hz"
|
|
523
|
+
],
|
|
524
|
+
seconds: ([retries, min, max, rtt, hz]) => retransLatenessReverted(integer(retries, "tcp_retries2"), min, max, rtt, hz),
|
|
525
|
+
source: "net/ipv4/tcp_ipv4.c tcp_ld_RTO_revert and net/ipv4/tcp_timer.c retransmits_timed_out at v6.6 (RFC 6069)"
|
|
526
|
+
},
|
|
527
|
+
"linux.rto-wait-lateness": {
|
|
528
|
+
knobs: [
|
|
529
|
+
null,
|
|
530
|
+
"s",
|
|
531
|
+
"s",
|
|
532
|
+
"s",
|
|
533
|
+
"Hz"
|
|
534
|
+
],
|
|
535
|
+
seconds: ([fired, min, max, rtt, hz]) => rationals.div(whole(granularity(rtoWait(integer(fired, FIRED), min, max, rtt, hz))), hz),
|
|
536
|
+
source: "kernel/time/timer.c calc_wheel_index at v6.6"
|
|
537
|
+
},
|
|
538
|
+
"linux.keepalive-lateness": {
|
|
539
|
+
knobs: [
|
|
540
|
+
"s",
|
|
541
|
+
"s",
|
|
542
|
+
null,
|
|
543
|
+
"Hz"
|
|
544
|
+
],
|
|
545
|
+
seconds: ([idle, interval, probes, hz]) => keepaliveLateness(idle, interval, integer(probes, "keepcnt"), hz),
|
|
546
|
+
source: "net/ipv4/tcp_timer.c tcp_keepalive_timer and kernel/time/timer.c at v6.6"
|
|
547
|
+
},
|
|
548
|
+
"linux.wheel": {
|
|
549
|
+
knobs: ["s", "Hz"],
|
|
550
|
+
seconds: ([time, hz]) => rationals.div(whole(granularity(jiffiesOf(time, hz))), hz),
|
|
551
|
+
source: "kernel/time/timer.c calc_wheel_index at v6.6"
|
|
552
|
+
},
|
|
553
|
+
"linux.jiffy": {
|
|
554
|
+
knobs: ["Hz"],
|
|
555
|
+
seconds: ([hz]) => rationals.div(whole(1n), hz),
|
|
556
|
+
source: "include/linux/jiffies.h"
|
|
557
|
+
},
|
|
558
|
+
"linux.syn-giveup": {
|
|
559
|
+
knobs: [null, null],
|
|
560
|
+
seconds: ([retries, linear]) => {
|
|
561
|
+
const n = integer(retries, "tcp_syn_retries");
|
|
562
|
+
let total = rationals.mul(whole(integer(linear, "tcp_syn_linear_timeouts") + 1n), TCP_TIMEOUT_INIT);
|
|
563
|
+
for (let i = 1n; i <= n; i += 1n) total = rationals.add(total, capped(TCP_TIMEOUT_INIT, i, TCP_RTO_MAX));
|
|
564
|
+
return total;
|
|
565
|
+
},
|
|
566
|
+
source: "net/ipv4/tcp_timer.c tcp_write_timeout and Documentation/networking/ip-sysctl.rst at v6.6"
|
|
567
|
+
},
|
|
568
|
+
"ioredis.retry-base": {
|
|
569
|
+
knobs: [null],
|
|
570
|
+
seconds: ([fired]) => capped(rationals.fromDecimal("0.05"), integer(fired, FIRED), whole(5n)),
|
|
571
|
+
source: "ioredis 6.0.0 built/redis/RedisOptions.js retryStrategy and built/redis/event_handler.js"
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
/**
|
|
575
|
+
* This function gives the value of a knob in the unit that the document gives it (or as a count
|
|
576
|
+
* when it is a count). For `fired`, it gives which wait of a backoff timer it is.
|
|
577
|
+
*/
|
|
578
|
+
const knobIn = (doc, name, unit, values, fired) => {
|
|
579
|
+
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));
|
|
580
|
+
if (doc.knobs[name] === void 0) return unknown(`the machine names no knob ${name}`);
|
|
581
|
+
const given = values(name);
|
|
582
|
+
if (given === void 0) return unknown(`nothing gives ${name}'s value`);
|
|
583
|
+
if ("unknown" in given) return unknown(`${name}: ${given.unknown}`);
|
|
584
|
+
if (given.value === "infinite") return INFINITE;
|
|
585
|
+
const value = rationals.fromNumber(given.value);
|
|
586
|
+
return exact(unit === null ? convertExact(value, given.unit, given.unit) : convertExact(value, given.unit, unit));
|
|
587
|
+
};
|
|
588
|
+
const out = (value, unit) => value.kind === "exact" ? quantity(rationals.toNumber(value.n), unit) : value.kind === "infinite" ? unbounded(unit) : {
|
|
589
|
+
unknown: value.why,
|
|
590
|
+
unit
|
|
591
|
+
};
|
|
592
|
+
/**
|
|
593
|
+
* This function evaluates one duration of a timer of a machine, in the unit that its document
|
|
594
|
+
* gives it. The waits of a backoff timer read `fired`, which tells which wait.
|
|
595
|
+
*/
|
|
596
|
+
const evaluate = (doc, expr, values, fired) => {
|
|
597
|
+
if ("const" in expr) return quantity(expr.const, expr.unit);
|
|
598
|
+
if ("knob" in expr) return out(knobIn(doc, expr.knob, expr.unit, values, fired), expr.unit);
|
|
599
|
+
if ("expr" in expr) {
|
|
600
|
+
const tree = parseExpr(expr.expr);
|
|
601
|
+
const value = run(tree, (name) => knobIn(doc, name, doc.knobs[name]?.unit ?? null, values, fired));
|
|
602
|
+
return out(value, expr.unit);
|
|
603
|
+
}
|
|
604
|
+
const model = MODELS[expr.model];
|
|
605
|
+
if (model === void 0) return {
|
|
606
|
+
unknown: `no model ${expr.model}`,
|
|
607
|
+
unit: expr.unit
|
|
608
|
+
};
|
|
609
|
+
if (model.knobs.length !== expr.knobs.length) return {
|
|
610
|
+
unknown: `${expr.model} reads ${model.knobs.length} knobs, not ${expr.knobs.length}`,
|
|
611
|
+
unit: expr.unit
|
|
612
|
+
};
|
|
613
|
+
const args = expr.knobs.map((name, index) => knobIn(doc, name, model.knobs[index] ?? null, values, fired));
|
|
614
|
+
const lost = unknownOf(args);
|
|
615
|
+
if (lost !== void 0) return out(lost, expr.unit);
|
|
616
|
+
if (args.some((arg) => arg.kind === "infinite")) return unbounded(expr.unit);
|
|
617
|
+
const seconds = model.seconds(args.map((arg) => arg.n));
|
|
618
|
+
return quantity(rationals.toNumber(convertExact(seconds, "s", expr.unit)), expr.unit);
|
|
619
|
+
};
|
|
620
|
+
/**
|
|
621
|
+
* This function gives the bounds of a timer of a machine: how long it operates, how late it can
|
|
622
|
+
* fire, how early. For a backoff timer, it gives one of its waits: the wait after `fired` firings.
|
|
623
|
+
*/
|
|
624
|
+
const timerOf = (doc, timer, values, fired) => {
|
|
625
|
+
const def = doc.timers[timer];
|
|
626
|
+
if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
|
|
627
|
+
return {
|
|
628
|
+
duration: evaluate(doc, def.duration, values, fired),
|
|
629
|
+
...def.lateness !== void 0 ? { lateness: evaluate(doc, def.lateness, values, fired) } : {},
|
|
630
|
+
...def.early !== void 0 ? { early: evaluate(doc, def.early, values, fired) } : {}
|
|
631
|
+
};
|
|
632
|
+
};
|
|
633
|
+
/** This count is the most firings that `recovery` examines before it tells that the stall is longer than them. */
|
|
634
|
+
const FIRINGS = 4096;
|
|
635
|
+
/**
|
|
636
|
+
* This function gives the recovery from a stall. A backoff timer continues to fire through a
|
|
637
|
+
* stall, and what each firing sends gets through only after the stall ends. Thus the connection
|
|
638
|
+
* moves again at the first firing at the end or after it. That firing can be most of a wait after
|
|
639
|
+
* the end. A stall that stops immediately after one firing costs almost all of the next, longer
|
|
640
|
+
* wait.
|
|
641
|
+
*
|
|
642
|
+
* The stall counts from the arming of the timer, which is the send that the stall first lost. The
|
|
643
|
+
* waits add, and so do how early and how late each can fire.
|
|
644
|
+
*/
|
|
645
|
+
const recovery = (doc, timer, values, stall) => {
|
|
646
|
+
const def = doc.timers[timer];
|
|
647
|
+
if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
|
|
648
|
+
if (def.backoff === void 0) throw new Error(`${doc.title}'s ${timer} has no backoff`);
|
|
649
|
+
if (isUnbounded(stall)) return {
|
|
650
|
+
unknown: "a stall that never ends: nothing recovers from it",
|
|
651
|
+
unit: "s"
|
|
652
|
+
};
|
|
653
|
+
const end = convertExact(rationals.fromNumber(stall.value), stall.unit, "s");
|
|
654
|
+
const inSeconds = (extent, what) => {
|
|
655
|
+
if (extent === void 0) return rationals.ZERO;
|
|
656
|
+
if ("unknown" in extent) return `${what}: ${extent.unknown}`;
|
|
657
|
+
if (isUnbounded(extent)) return `${what} has no bound, so the timer never fires again`;
|
|
658
|
+
return convertExact(rationals.fromNumber(extent.value), extent.unit, "s");
|
|
659
|
+
};
|
|
660
|
+
const s = (value) => quantity(rationals.toNumber(value), "s");
|
|
661
|
+
const sums = [];
|
|
662
|
+
let low = rationals.ZERO;
|
|
663
|
+
let high = rationals.ZERO;
|
|
664
|
+
for (let fired = 0; fired < FIRINGS; fired += 1) {
|
|
665
|
+
const bounds = timerOf(doc, timer, values, fired);
|
|
666
|
+
const wait = inSeconds(bounds.duration, `wait ${fired}`);
|
|
667
|
+
const early = inSeconds(bounds.early, `wait ${fired}'s early bound`);
|
|
668
|
+
const late = inSeconds(bounds.lateness, `wait ${fired}'s lateness`);
|
|
669
|
+
if (typeof wait === "string") return {
|
|
670
|
+
unknown: wait,
|
|
671
|
+
unit: "s"
|
|
672
|
+
};
|
|
673
|
+
if (typeof early === "string") return {
|
|
674
|
+
unknown: early,
|
|
675
|
+
unit: "s"
|
|
676
|
+
};
|
|
677
|
+
if (typeof late === "string") return {
|
|
678
|
+
unknown: late,
|
|
679
|
+
unit: "s"
|
|
680
|
+
};
|
|
681
|
+
low = rationals.add(low, rationals.sub(wait, early));
|
|
682
|
+
high = rationals.add(high, rationals.add(wait, late));
|
|
683
|
+
sums.push({
|
|
684
|
+
fired,
|
|
685
|
+
low,
|
|
686
|
+
high
|
|
687
|
+
});
|
|
688
|
+
if (rationals.cmp(low, end) < 0) continue;
|
|
689
|
+
const first = sums.filter((f) => rationals.cmp(f.high, end) >= 0);
|
|
690
|
+
const earliest = first[0].low;
|
|
691
|
+
return {
|
|
692
|
+
firings: sums.map((f) => ({
|
|
693
|
+
fired: f.fired,
|
|
694
|
+
low: s(f.low),
|
|
695
|
+
high: s(f.high)
|
|
696
|
+
})),
|
|
697
|
+
first: first.map((f) => f.fired),
|
|
698
|
+
low: s(rationals.cmp(earliest, end) >= 0 ? earliest : end),
|
|
699
|
+
high: s(first.at(-1).high)
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
return {
|
|
703
|
+
unknown: `${FIRINGS} firings do not outlast the stall`,
|
|
704
|
+
unit: "s"
|
|
705
|
+
};
|
|
706
|
+
};
|
|
707
|
+
/**
|
|
708
|
+
* This function gives how long a mechanism takes where a machine operates, from the realization
|
|
709
|
+
* of its document. The realization is one of its timers, whole, or its own duration, lateness and
|
|
710
|
+
* early bound over the knobs of the machine. It gives undefined when the document does not realize the mechanism.
|
|
711
|
+
*/
|
|
712
|
+
const realizationOf = (doc, mechanism, values) => {
|
|
713
|
+
const how = doc.realizes?.[mechanism];
|
|
714
|
+
if (how === void 0) return void 0;
|
|
715
|
+
if ("timer" in how) return timerOf(doc, how.timer, values);
|
|
716
|
+
return {
|
|
717
|
+
duration: evaluate(doc, how.duration, values),
|
|
718
|
+
...how.lateness !== void 0 ? { lateness: evaluate(doc, how.lateness, values) } : {},
|
|
719
|
+
...how.early !== void 0 ? { early: evaluate(doc, how.early, values) } : {}
|
|
720
|
+
};
|
|
721
|
+
};
|
|
722
|
+
/** This function gives the knobs that a realization reads, by the names of the machine for them. */
|
|
723
|
+
const realizationKnobs = (doc, mechanism) => {
|
|
724
|
+
const how = doc.realizes?.[mechanism];
|
|
725
|
+
if (how === void 0) return [];
|
|
726
|
+
const def = "timer" in how ? doc.timers[how.timer] : how;
|
|
727
|
+
if (def === void 0) return [];
|
|
728
|
+
return [...new Set([
|
|
729
|
+
def.duration,
|
|
730
|
+
def.lateness,
|
|
731
|
+
def.early
|
|
732
|
+
].flatMap((e) => e === void 0 ? [] : exprKnobs(e)))];
|
|
733
|
+
};
|
|
734
|
+
/** This function gives what in a document the algebra cannot read: arithmetic that does not parse, or a model that it does not have. */
|
|
735
|
+
const algebraProblems = (doc) => {
|
|
736
|
+
const problems = [];
|
|
737
|
+
const read = (where, exprs) => {
|
|
738
|
+
for (const expr of exprs) {
|
|
739
|
+
if (expr === void 0) continue;
|
|
740
|
+
if ("expr" in expr) try {
|
|
741
|
+
parseExpr(expr.expr);
|
|
742
|
+
} catch (error) {
|
|
743
|
+
problems.push(`${where}: ${error.message}`);
|
|
744
|
+
}
|
|
745
|
+
if ("model" in expr && MODELS[expr.model] === void 0) problems.push(`${where}: no model ${expr.model}`);
|
|
746
|
+
}
|
|
747
|
+
};
|
|
748
|
+
for (const [id, def] of Object.entries(doc.timers)) read(`timer ${id}`, [
|
|
749
|
+
def.duration,
|
|
750
|
+
def.lateness,
|
|
751
|
+
def.early
|
|
752
|
+
]);
|
|
753
|
+
for (const [mechanism, how] of Object.entries(doc.realizes ?? {})) if (!("timer" in how)) read(`realizes ${mechanism}`, [
|
|
754
|
+
how.duration,
|
|
755
|
+
how.lateness,
|
|
756
|
+
how.early
|
|
757
|
+
]);
|
|
758
|
+
for (const [lower, set] of Object.entries(doc.over?.sets ?? {})) read(`over sets ${lower}`, [set]);
|
|
759
|
+
return problems;
|
|
760
|
+
};
|
|
761
|
+
/** This function gives the source of the formula of a named model, for a reader of a result. */
|
|
762
|
+
const modelSource = (name) => MODELS[name]?.source;
|
|
763
|
+
const soonest = (a, b) => {
|
|
764
|
+
const rank = (d) => "unknown" in d.duration ? 2 : d.duration.value === "infinite" ? 1 : 0;
|
|
765
|
+
if (rank(a) !== rank(b)) return rank(a) - rank(b);
|
|
766
|
+
if (rank(a) !== 0) return a.timer.localeCompare(b.timer);
|
|
767
|
+
const seconds = (d) => {
|
|
768
|
+
const value = d.duration;
|
|
769
|
+
return rationals.toNumber(convertExact(rationals.fromNumber(value.value), value.unit, "s"));
|
|
770
|
+
};
|
|
771
|
+
return seconds(a) - seconds(b) || a.timer.localeCompare(b.timer);
|
|
772
|
+
};
|
|
773
|
+
/**
|
|
774
|
+
* This function gives the detection: the minimum over the detectors that are live in the
|
|
775
|
+
* situation. The entry to the state arms a timer, and so does what the failure causes: data in
|
|
776
|
+
* flight without an acknowledgment gets a retransmission. An event that occurs cancels a timer.
|
|
777
|
+
*
|
|
778
|
+
* An event that arms the timer again, and that the failure continues to let through, stops it
|
|
779
|
+
* before it fires. For example, the kernel of a frozen process answers each keepalive probe.
|
|
780
|
+
* Without a live detector, the failure is silent at the level of this machine. Only something
|
|
781
|
+
* above it, the timeout of an application or a heartbeat, can find it. The result is only as good
|
|
782
|
+
* as the events that the document names.
|
|
783
|
+
*/
|
|
784
|
+
const detection = (doc, situation, manifestation, values) => {
|
|
785
|
+
const passes = new Set(manifestation.passes);
|
|
786
|
+
const happened = /* @__PURE__ */ new Set([`enter:${situation.state}`]);
|
|
787
|
+
if (situation.inFlight && !passes.has("rx.ack")) happened.add("tx.retransmit.first");
|
|
788
|
+
const occurs = (event) => happened.has(event) || passes.has(event);
|
|
789
|
+
const detectors = [];
|
|
790
|
+
const held = [];
|
|
791
|
+
for (const [timer, def] of Object.entries(doc.timers)) {
|
|
792
|
+
if (def.backoff !== void 0) continue;
|
|
793
|
+
if (!def.arms.some(occurs)) continue;
|
|
794
|
+
const cancelled = (def.cancels ?? []).find(occurs);
|
|
795
|
+
if (cancelled !== void 0) {
|
|
796
|
+
held.push({
|
|
797
|
+
timer,
|
|
798
|
+
why: `${cancelled} cancels it`
|
|
799
|
+
});
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
const rearmed = def.arms.find((event) => passes.has(event));
|
|
803
|
+
if (rearmed !== void 0) {
|
|
804
|
+
held.push({
|
|
805
|
+
timer,
|
|
806
|
+
why: `${rearmed} keeps arriving and re-arms it`
|
|
807
|
+
});
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
const duration = manifestation.replaces?.[timer]?.duration ?? def.duration;
|
|
811
|
+
detectors.push({
|
|
812
|
+
timer,
|
|
813
|
+
fires: def.fires,
|
|
814
|
+
duration: evaluate(doc, duration, values)
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
detectors.sort(soonest);
|
|
818
|
+
const [earliest] = detectors;
|
|
819
|
+
const finite = earliest !== void 0 && !("unknown" in earliest.duration) && earliest.duration.value !== "infinite";
|
|
820
|
+
const delivered = (manifestation.delivers ?? []).flatMap((event) => {
|
|
821
|
+
const taken = transitionOn(doc, situation.state, event);
|
|
822
|
+
return taken === void 0 ? [] : [{
|
|
823
|
+
event,
|
|
824
|
+
to: taken.to,
|
|
825
|
+
errno: taken.errno ?? null
|
|
826
|
+
}];
|
|
827
|
+
});
|
|
828
|
+
return {
|
|
829
|
+
detectors,
|
|
830
|
+
first: finite ? earliest : null,
|
|
831
|
+
unsettled: detectors.filter((d) => "unknown" in d.duration).map((d) => d.timer),
|
|
832
|
+
held,
|
|
833
|
+
delivered
|
|
834
|
+
};
|
|
835
|
+
};
|
|
836
|
+
/**
|
|
837
|
+
* This function gives the bounds of a timer of a machine under a failure: its own bounds, with each
|
|
838
|
+
* duration that the manifestation replaces.
|
|
839
|
+
*/
|
|
840
|
+
const timerUnder = (doc, timer, values, manifestation, fired) => {
|
|
841
|
+
const def = doc.timers[timer];
|
|
842
|
+
if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
|
|
843
|
+
const replaced = manifestation.replaces?.[timer];
|
|
844
|
+
const duration = replaced?.duration ?? def.duration;
|
|
845
|
+
const lateness = replaced?.lateness ?? def.lateness;
|
|
846
|
+
const early = replaced?.early ?? def.early;
|
|
847
|
+
return {
|
|
848
|
+
duration: evaluate(doc, duration, values, fired),
|
|
849
|
+
...lateness !== void 0 ? { lateness: evaluate(doc, lateness, values, fired) } : {},
|
|
850
|
+
...early !== void 0 ? { early: evaluate(doc, early, values, fired) } : {}
|
|
851
|
+
};
|
|
852
|
+
};
|
|
853
|
+
/**
|
|
854
|
+
* This function gives the errno of a detection by a timer: the errno of the transition that its
|
|
855
|
+
* event takes from the state. A soft error of the manifestation replaces ETIMEDOUT, but only for
|
|
856
|
+
* the timers whose segments its ICMP quotes in the window.
|
|
857
|
+
*/
|
|
858
|
+
const errnoOf = (doc, state, detector, manifestation) => {
|
|
859
|
+
const errno = transitionOn(doc, state, detector.fires)?.errno ?? null;
|
|
860
|
+
const soft = manifestation.errno;
|
|
861
|
+
return errno === "ETIMEDOUT" && soft !== void 0 && soft.timers.includes(detector.timer) ? soft.errno : errno;
|
|
862
|
+
};
|
|
863
|
+
/** This function gives the transition that a machine takes from a state on an event, by its document. */
|
|
864
|
+
const transitionOn = (doc, state, event) => doc.transitions.find((t) => fromStates(doc, t.from).includes(state) && arr(t.on).includes(event));
|
|
865
|
+
/**
|
|
866
|
+
* This function gives the values of a machine for the machine that it operates on. These are the
|
|
867
|
+
* knobs that it sets, evaluated over its own knobs, and the other knobs of the lower machine. The
|
|
868
|
+
* keepAlive of ioredis at 5000 ms is the keepidle of the kernel at 5 s.
|
|
869
|
+
*/
|
|
870
|
+
const overValues = (upper, upperValues, lowerValues) => (name) => {
|
|
871
|
+
const set = upper.over?.sets[name];
|
|
872
|
+
return set === void 0 ? lowerValues(name) : evaluate(upper, set, upperValues);
|
|
873
|
+
};
|
|
874
|
+
/**
|
|
875
|
+
* This function gives the detection through the machine that a machine operates on. The detectors
|
|
876
|
+
* of the lower machine are live in the state below the state of this machine. They use the knobs
|
|
877
|
+
* that this machine sets.
|
|
878
|
+
*
|
|
879
|
+
* Each one reaches this machine as the event that the end of the lower
|
|
880
|
+
* machine gives. They are beside the timers of this machine, and the first of all of them is the
|
|
881
|
+
* first detection. A failure lets nothing new through to a machine above the socket, only the end
|
|
882
|
+
* of the socket. Thus the timers of this machine see only what its state arms.
|
|
883
|
+
*/
|
|
884
|
+
const stackedDetection = (upper, lower, situation, manifestation, upperValues, lowerValues) => {
|
|
885
|
+
const over = upper.over;
|
|
886
|
+
if (over === void 0) throw new Error(`${upper.title} runs on no other machine`);
|
|
887
|
+
const sitsOn = over.states[situation.state];
|
|
888
|
+
if (sitsOn === void 0) throw new Error(`${upper.title}'s ${situation.state} sits on no state of ${lower.title}`);
|
|
889
|
+
const own = detection(upper, situation, {
|
|
890
|
+
name: manifestation.name,
|
|
891
|
+
passes: []
|
|
892
|
+
}, upperValues);
|
|
893
|
+
const below = detection(lower, {
|
|
894
|
+
...situation,
|
|
895
|
+
state: sitsOn
|
|
896
|
+
}, manifestation, overValues(upper, upperValues, lowerValues));
|
|
897
|
+
const detectors = [...own.detectors, ...below.detectors.map((d) => ({
|
|
898
|
+
...d,
|
|
899
|
+
beneath: over.machine
|
|
900
|
+
}))].sort(soonest);
|
|
901
|
+
const [earliest] = detectors;
|
|
902
|
+
return {
|
|
903
|
+
detectors,
|
|
904
|
+
first: earliest !== void 0 && !("unknown" in earliest.duration) && earliest.duration.value !== "infinite" ? earliest : null,
|
|
905
|
+
unsettled: detectors.filter((d) => "unknown" in d.duration).map((d) => d.timer),
|
|
906
|
+
held: [...own.held, ...below.held.map((h) => ({
|
|
907
|
+
...h,
|
|
908
|
+
why: `${h.why}, beneath`
|
|
909
|
+
}))],
|
|
910
|
+
delivered: below.delivered
|
|
911
|
+
};
|
|
912
|
+
};
|
|
913
|
+
//#endregion
|
|
914
|
+
export { FIRED, algebraProblems, arr, detection, errnoOf, evaluate, exprKnobs, fromStates, machineProblems, machineSchema, modelSource, overValues, parseExpr, readsFired, realizationKnobs, realizationOf, recovery, stackedDetection, timerOf, timerUnder, transitionOn };
|
|
915
|
+
|
|
916
|
+
//# sourceMappingURL=index.js.map
|