@mark1russell7/capacity 0.0.0-stage → 0.1.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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1110 -2
  3. package/build/index.d.ts +858 -0
  4. package/build/index.d.ts.map +1 -0
  5. package/build/index.js +1713 -0
  6. package/build/index.js.map +1 -0
  7. package/build/instance-check-Bt-SI8va.js +1732 -0
  8. package/build/instance-check-Bt-SI8va.js.map +1 -0
  9. package/build/instance-sZmVOOvz.d.ts +801 -0
  10. package/build/instance-sZmVOOvz.d.ts.map +1 -0
  11. package/build/schema.d.ts +69 -0
  12. package/build/schema.d.ts.map +1 -0
  13. package/build/schema.js +325 -0
  14. package/build/schema.js.map +1 -0
  15. package/limits/alerts-routes.line.json +78 -0
  16. package/limits/alerts-scale.limits.json +10 -0
  17. package/limits/alerts-start-gate.limits.json +1149 -0
  18. package/limits/alerts-start-routes-limit-home.bracket.json +543 -0
  19. package/limits/alerts-start-routes-limit-mid.bracket.json +464 -0
  20. package/limits/alerts-start-routes-limit.bracket.json +579 -0
  21. package/limits/alerts-tail-gate.limits.json +610 -0
  22. package/package.json +85 -3
  23. package/src/app-check.ts +477 -0
  24. package/src/app-metrics.ts +105 -0
  25. package/src/app.ts +239 -0
  26. package/src/check.ts +253 -0
  27. package/src/composition.ts +680 -0
  28. package/src/demand.ts +312 -0
  29. package/src/fit.ts +153 -0
  30. package/src/forms.ts +358 -0
  31. package/src/gate.ts +237 -0
  32. package/src/index.ts +143 -0
  33. package/src/instance-check.ts +122 -0
  34. package/src/instance.ts +84 -0
  35. package/src/knee.ts +606 -0
  36. package/src/law.ts +236 -0
  37. package/src/limit.ts +112 -0
  38. package/src/names.ts +19 -0
  39. package/src/observe.ts +74 -0
  40. package/src/program.ts +74 -0
  41. package/src/scale.ts +617 -0
  42. package/src/schema.ts +263 -0
  43. package/src/value.ts +206 -0
  44. package/src/workload-check.ts +130 -0
  45. package/src/workload.ts +88 -0
package/src/forms.ts ADDED
@@ -0,0 +1,358 @@
1
+ import { err, ok, type Result } from "@mark1russell7/optional";
2
+ import { fitSeparable, SEPARABLE_MAX_COMBINATIONS, type SeparableFit, type SeparableModel } from "@mark1russell7/rigor-statistics";
3
+ import { app, let_, lit, ref, v, type Expr } from "@mark1russell7/vex";
4
+ import type { Constant, Form } from "./law.ts";
5
+ import { valuesOf } from "./program.ts";
6
+
7
+ /** This name is the name of the load variable in the programs of the catalog. A binding gives its id in a law. */
8
+ export const FORM_VARIABLE = "x";
9
+
10
+ /**
11
+ * A term is one part of a form: its constant times its basis. The basis and its slope read the
12
+ * variable and the shape constants of the form with `v(name)`. The slope is the change of the basis
13
+ * for each unit of the variable.
14
+ */
15
+ export interface Term {
16
+ readonly constant: string;
17
+ readonly basis: Expr;
18
+ readonly slope: Expr;
19
+ }
20
+
21
+ /**
22
+ * A grid gives the start candidates of one shape constant from the points of a fit.
23
+ *
24
+ * - `inside` gives each distinct value of the variable inside its range, and each middle of two
25
+ * values that follow. A knee starts at these values.
26
+ * - `scaled` gives each factor times the largest size of the variable to the `power`. With the power
27
+ * 0, the candidates are the factors.
28
+ */
29
+ export type Grid =
30
+ | { readonly kind: "inside" }
31
+ | { readonly kind: "scaled"; readonly factors: readonly number[]; readonly power: number };
32
+
33
+ /**
34
+ * The bounds tell where the refine of a fit can move a shape constant. They come from the points of the fit.
35
+ *
36
+ * - `range` is from the least value of the variable to its largest value. A knee is inside the range.
37
+ * - `size` is from the largest size of the variable up. The capacity of a queue is past each load.
38
+ * - `least` is from `value` up.
39
+ */
40
+ export type Bounds = { readonly kind: "range" } | { readonly kind: "size" } | { readonly kind: "least"; readonly value: number };
41
+
42
+ /**
43
+ * A shape constant changes the shape of a form, not its size. A fit starts it at each value of its grid. Then the fit
44
+ * refines it inside its bounds. A shape with no bounds has no limit.
45
+ */
46
+ export interface Shape {
47
+ readonly id: string;
48
+ readonly grid: Grid;
49
+ readonly bounds?: Bounds;
50
+ }
51
+
52
+ /**
53
+ * A catalog form is the math of a law of one variable, as data. Its value is the sum of its terms.
54
+ * Thus, with fixed shape constants, a fit of a form is linear in the constants of its terms.
55
+ */
56
+ export interface CatalogForm {
57
+ readonly id: string;
58
+ readonly title: string;
59
+ readonly terms: readonly Term[];
60
+ readonly shapes: readonly Shape[];
61
+ }
62
+
63
+ /**
64
+ * A binding puts a catalog form into a law. It gives the id of the variable in the law, and the id
65
+ * in the law of each constant. A constant with no entry keeps its id from the catalog.
66
+ */
67
+ export interface Binding {
68
+ readonly variable: string;
69
+ readonly constants?: Readonly<Record<string, string>>;
70
+ }
71
+
72
+ /** The points of a fit: the value of the variable and the measured value of each point, in the same order. */
73
+ export interface Points {
74
+ readonly x: readonly number[];
75
+ readonly y: readonly number[];
76
+ }
77
+
78
+ /** A start is the start values of the constants of a form, and the sum of the squared residuals at these values. */
79
+ export interface Start {
80
+ readonly constants: readonly Constant[];
81
+ readonly rss: number;
82
+ }
83
+
84
+ const x = v(FORM_VARIABLE);
85
+ const one = lit(1);
86
+ const zero = lit(0);
87
+ const add = (...parts: readonly Expr[]): Expr => parts.reduce((sum, part) => app("add", sum, part));
88
+ const times = (a: Expr, b: Expr): Expr => app("multiply", a, b);
89
+ const over = (a: Expr, b: Expr): Expr => app("divide", a, b);
90
+ const less = (a: Expr, b: Expr): Expr => app("subtract", a, b);
91
+ const square = (a: Expr): Expr => app("pow", a, lit(2));
92
+ const scaled = (factors: readonly number[], power: number): Grid => ({ kind: "scaled", factors, power });
93
+ const positive: Bounds = { kind: "least", value: 0 };
94
+
95
+ /** The base term: a constant amount. Its slope is 0. */
96
+ const base: Term = { constant: "base", basis: one, slope: zero };
97
+
98
+ /** The denominator of the scalability law: `1 + contention·(x − 1) + coherency·x·(x − 1)`. */
99
+ const contention = add(one, times(v("contention"), less(x, one)), times(times(v("coherency"), x), less(x, one)));
100
+
101
+ /**
102
+ * The catalog of the forms of a law, in the order of the roadmap. Each form is a sum of terms.
103
+ *
104
+ * - `constant`: `base`.
105
+ * - `linear`: `base + slope·x`.
106
+ * - `power`: `base + scale·x^exponent`.
107
+ * - `fall-power`: `base + excess / x + scale·x^exponent`. The term `excess / x` is a cost at a low load that falls as the load grows.
108
+ * - `logarithm`: `base + scale·ln(x)`.
109
+ * - `hinge`: `base + slope·x + bend·max(0, x − knee)`. After the knee the slope is `slope + bend`.
110
+ * - `queue`: `base + scale·capacity / (capacity − x)`. This is the delay of a queue. The form has no
111
+ * finite value at the capacity.
112
+ * - `scalability`: `unit·x / (1 + contention·(x − 1) + coherency·x·(x − 1))`. This is the
113
+ * universal scalability law of the throughput at a concurrency `x`.
114
+ * - `drift`: `base + drift·x + warm·(1 − e^(−x / settle))`. This is a measure over the age of a
115
+ * process: a warm-up that settles, and a steady drift.
116
+ */
117
+ export const FORMS: readonly CatalogForm[] = [
118
+ { id: "constant", title: "A constant", terms: [base], shapes: [] },
119
+ { id: "linear", title: "A line", terms: [base, { constant: "slope", basis: x, slope: one }], shapes: [] },
120
+ {
121
+ id: "power",
122
+ title: "A power of the variable",
123
+ terms: [
124
+ base,
125
+ {
126
+ constant: "scale",
127
+ basis: app("pow", x, v("exponent")),
128
+ slope: times(v("exponent"), app("pow", x, less(v("exponent"), one))),
129
+ },
130
+ ],
131
+ shapes: [{ id: "exponent", grid: scaled([-1, -0.5, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3], 0) }],
132
+ },
133
+ {
134
+ id: "fall-power",
135
+ title: "A fall at a low load, then a power of the variable",
136
+ terms: [
137
+ base,
138
+ { constant: "excess", basis: over(one, x), slope: app("negate", over(one, square(x))) },
139
+ {
140
+ constant: "scale",
141
+ basis: app("pow", x, v("exponent")),
142
+ slope: times(v("exponent"), app("pow", x, less(v("exponent"), one))),
143
+ },
144
+ ],
145
+ shapes: [{ id: "exponent", grid: scaled([0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 3], 0) }],
146
+ },
147
+ {
148
+ id: "logarithm",
149
+ title: "A logarithm of the variable",
150
+ terms: [base, { constant: "scale", basis: app("ln", x), slope: over(one, x) }],
151
+ shapes: [],
152
+ },
153
+ {
154
+ id: "hinge",
155
+ title: "Two lines that join at a knee",
156
+ terms: [
157
+ base,
158
+ { constant: "slope", basis: x, slope: one },
159
+ {
160
+ constant: "bend",
161
+ basis: app("max", zero, less(x, v("knee"))),
162
+ slope: app("if", app("gt", x, v("knee")), one, zero),
163
+ },
164
+ ],
165
+ shapes: [{ id: "knee", grid: { kind: "inside" }, bounds: { kind: "range" } }],
166
+ },
167
+ {
168
+ id: "queue",
169
+ title: "The delay of a queue",
170
+ terms: [
171
+ base,
172
+ {
173
+ constant: "scale",
174
+ basis: over(v("capacity"), less(v("capacity"), x)),
175
+ slope: over(v("capacity"), square(less(v("capacity"), x))),
176
+ },
177
+ ],
178
+ shapes: [{ id: "capacity", grid: scaled([1.02, 1.05, 1.1, 1.2, 1.5, 2, 3, 5, 10], 1), bounds: { kind: "size" } }],
179
+ },
180
+ {
181
+ id: "scalability",
182
+ title: "The universal scalability law",
183
+ terms: [
184
+ {
185
+ constant: "unit",
186
+ basis: over(x, contention),
187
+ // (D − x·D′) / D², with D′ = contention + coherency·(2x − 1): this is (1 − contention − coherency·x²) / D²
188
+ slope: over(less(less(one, v("contention")), times(v("coherency"), square(x))), square(contention)),
189
+ },
190
+ ],
191
+ shapes: [
192
+ { id: "contention", grid: scaled([0, 0.01, 0.03, 0.1, 0.2, 0.4, 0.7], 0), bounds: positive },
193
+ { id: "coherency", grid: scaled([0, 0.1, 0.3, 1, 3, 10], -2), bounds: positive },
194
+ ],
195
+ },
196
+ {
197
+ id: "drift",
198
+ title: "A warm-up and a drift with age",
199
+ terms: [
200
+ base,
201
+ { constant: "drift", basis: x, slope: one },
202
+ {
203
+ constant: "warm",
204
+ basis: less(one, app("exp", app("negate", over(x, v("settle"))))),
205
+ slope: over(app("exp", app("negate", over(x, v("settle")))), v("settle")),
206
+ },
207
+ ],
208
+ shapes: [{ id: "settle", grid: scaled([0.01, 0.03, 0.1, 0.3, 1, 3], 1), bounds: positive }],
209
+ },
210
+ ];
211
+
212
+ /** This function gives the form of the catalog with the id, or undefined. */
213
+ export const catalogForm = (id: string): CatalogForm | undefined => FORMS.find((form) => form.id === id);
214
+
215
+ /** This function gives the ids of the constants of a form: the constant of each term, then each shape constant. */
216
+ export const constantIdsOf = (form: CatalogForm): readonly string[] => [
217
+ ...form.terms.map((term) => term.constant),
218
+ ...form.shapes.map((shape) => shape.id),
219
+ ];
220
+
221
+ /** This function gives the sum of the terms of a form, with `part` for each term. A term of 0 does not count. */
222
+ const sumOf = (form: CatalogForm, part: (term: Term) => Expr): Expr => {
223
+ const parts = form.terms
224
+ .map((term) => ({ term, expr: part(term) }))
225
+ .filter(({ expr }) => !(expr.tag === "lit" && expr.value === 0))
226
+ .map(({ term, expr }) => (expr.tag === "lit" && expr.value === 1 ? v(term.constant) : times(v(term.constant), expr)));
227
+ return parts.length === 0 ? zero : add(...parts);
228
+ };
229
+
230
+ /** This function binds the names `ids` of a form and its variable to the reads of a law. */
231
+ const bind = (ids: readonly string[], binding: Binding, body: Expr): Expr =>
232
+ let_(Object.fromEntries([[FORM_VARIABLE, ref(binding.variable)], ...ids.map((id) => [id, ref(binding.constants?.[id] ?? id)])]), body);
233
+
234
+ /** This function binds each name of a form to the reads of a law: the variable and each constant. */
235
+ const bound = (form: CatalogForm, binding: Binding, body: Expr): Expr => bind(constantIdsOf(form), binding, body);
236
+
237
+ /** This function gives the program of the value of a form in a law. It reads the variable and each constant of the binding. */
238
+ export const programOf = (form: CatalogForm, binding: Binding): Expr => bound(form, binding, sumOf(form, (term) => term.basis));
239
+
240
+ /** This function gives the program of the slope of a form in a law: the change of its value for each unit of the variable. */
241
+ export const slopeOf = (form: CatalogForm, binding: Binding): Expr => bound(form, binding, sumOf(form, (term) => term.slope));
242
+
243
+ /** This function gives the form of a law from a form of the catalog. */
244
+ export const formOf = (form: CatalogForm, binding: Binding): Form => ({ id: form.id, program: programOf(form, binding) });
245
+
246
+ const records = (xs: readonly number[], constants: Readonly<Record<string, number>>): Readonly<Record<string, number>>[] =>
247
+ xs.map((value) => ({ ...constants, [FORM_VARIABLE]: value }));
248
+
249
+ /** This function gives the value of a form at each value of its variable, or the text of the first error. */
250
+ export const formValues = (
251
+ form: CatalogForm,
252
+ xs: readonly number[],
253
+ constants: Readonly<Record<string, number>>,
254
+ ): Result<readonly number[], string> => valuesOf(programOf(form, { variable: FORM_VARIABLE }), records(xs, constants));
255
+
256
+ /** This function gives the slope of a form at each value of its variable, or the text of the first error. */
257
+ export const formSlopes = (
258
+ form: CatalogForm,
259
+ xs: readonly number[],
260
+ constants: Readonly<Record<string, number>>,
261
+ ): Result<readonly number[], string> => valuesOf(slopeOf(form, { variable: FORM_VARIABLE }), records(xs, constants));
262
+
263
+ /** This function gives the largest size of the values of a variable. */
264
+ const sizeOf = (xs: readonly number[]): number => xs.reduce((most, value) => Math.max(most, Math.abs(value)), 0);
265
+
266
+ /** This function gives the candidates of a grid for the values of a variable. */
267
+ export const gridOf = (grid: Grid, xs: readonly number[]): readonly number[] => {
268
+ if (grid.kind === "scaled") {
269
+ const size = sizeOf(xs);
270
+ return grid.power === 0 ? grid.factors : size === 0 ? [] : grid.factors.map((factor) => factor * size ** grid.power);
271
+ }
272
+ const distinct = [...new Set(xs)].sort((a, b) => a - b);
273
+ const middles = distinct.slice(1).map((value, index) => (value + (distinct[index] as number)) / 2);
274
+ const low = distinct[0] ?? 0;
275
+ const high = distinct.at(-1) ?? 0;
276
+ return [...distinct, ...middles].filter((value) => value > low && value < high).sort((a, b) => a - b);
277
+ };
278
+
279
+ /** This function gives the bounds of the refine of a shape constant for the values of a variable. */
280
+ const boundsOf = (bounds: Bounds | undefined, xs: readonly number[]): { readonly min?: number; readonly max?: number } => {
281
+ if (bounds === undefined) return {};
282
+ if (bounds.kind === "least") return { min: bounds.value };
283
+ if (bounds.kind === "size") return { min: sizeOf(xs) };
284
+ return {
285
+ min: xs.reduce((least, value) => Math.min(least, value), Number.POSITIVE_INFINITY),
286
+ max: xs.reduce((most, value) => Math.max(most, value), Number.NEGATIVE_INFINITY),
287
+ };
288
+ };
289
+
290
+ /**
291
+ * This function gives a form of the catalog as a separable model of `@mark1russell7/rigor-statistics`. Each term is
292
+ * one column of the design: the basis of the term at each point. The candidates and the bounds of each shape constant
293
+ * come from the values `xs` of the variable. The design is null when a basis has no finite value at a point.
294
+ */
295
+ export const separableOf = (form: CatalogForm, xs: readonly number[]): SeparableModel<number> => {
296
+ const ids = form.shapes.map((shape) => shape.id);
297
+ // a basis reads the variable and the shape constants, not the constants of the terms
298
+ const bases = form.terms.map((term) => bind(ids, { variable: FORM_VARIABLE }, term.basis));
299
+ return {
300
+ terms: form.terms.map((term) => term.constant),
301
+ shapes: form.shapes.map((shape) => ({ id: shape.id, candidates: gridOf(shape.grid, xs), ...boundsOf(shape.bounds, xs) })),
302
+ design: (values, points) => {
303
+ const at = Object.fromEntries(ids.map((id, index) => [id, values[index] as number]));
304
+ const columns: (readonly number[])[] = [];
305
+ for (const basis of bases) {
306
+ const column = valuesOf(basis, records(points, at));
307
+ if (column.tag === "err") return null;
308
+ columns.push(column.value);
309
+ }
310
+ return points.map((_, row) => columns.map((column) => column[row] as number));
311
+ },
312
+ };
313
+ };
314
+
315
+ /** This function gives the constants of a form from a separable fit: the constant of each term, then each shape constant. */
316
+ export const constantsOf = (form: CatalogForm, fit: Pick<SeparableFit, "coefficients" | "shapes">): readonly Constant[] => [
317
+ ...form.terms.map((term, index) => ({ id: term.constant, value: fit.coefficients[index] as number })),
318
+ ...form.shapes.map((shape, index) => ({ id: shape.id, value: fit.shapes[index] as number })),
319
+ ];
320
+
321
+ /** This function gives the text of the first fault of the points of a fit, or undefined. */
322
+ export const pointsProblem = (points: Points): string | undefined => {
323
+ if (points.x.length === 0) return "The fit has no points.";
324
+ if (points.x.length !== points.y.length) return `The points have ${points.x.length} values of x and ${points.y.length} values of y.`;
325
+ if (![...points.x, ...points.y].every(Number.isFinite)) return "A point has a value that is not a finite number.";
326
+ return undefined;
327
+ };
328
+
329
+ /** This function gives the text of the reason that the model of a form has no start, or undefined. */
330
+ export const modelProblem = (form: CatalogForm, model: SeparableModel<number>): string | undefined => {
331
+ const empty = model.shapes.find((shape) => shape.candidates.length === 0);
332
+ if (empty !== undefined) return `The form "${form.id}" has no start value of its shape constant "${empty.id}" for these points.`;
333
+ const count = model.shapes.reduce((product, shape) => product * new Set(shape.candidates).size, 1);
334
+ if (count > SEPARABLE_MAX_COMBINATIONS) {
335
+ return `The form "${form.id}" has ${count} combinations of start values. The limit is ${SEPARABLE_MAX_COMBINATIONS}.`;
336
+ }
337
+ return undefined;
338
+ };
339
+
340
+ /**
341
+ * This function gives the least-squares fit of a form to some points, as the start values of its constants.
342
+ *
343
+ * The fit is `fitSeparable` of `@mark1russell7/rigor-statistics`. For each combination of the grids of the shape
344
+ * constants, the least-squares fit gives the constants of the terms. Then a golden-section search refines each shape
345
+ * constant inside its bounds. A form with no shape constant has one combination, thus its start is its least-squares fit.
346
+ *
347
+ * The function gives an error when no combination has a fit, for example with fewer points than terms.
348
+ */
349
+ export const startOf = (form: CatalogForm, points: Points): Result<Start, string> => {
350
+ const fault = pointsProblem(points);
351
+ if (fault !== undefined) return err(fault);
352
+ const model = separableOf(form, points.x);
353
+ const reason = modelProblem(form, model);
354
+ if (reason !== undefined) return err(reason);
355
+ const fit = fitSeparable(model, points.x, points.y);
356
+ if (fit === null) return err(`The form "${form.id}" has no least-squares fit to ${points.x.length} points.`);
357
+ return ok({ constants: constantsOf(form, fit), rss: fit.rss });
358
+ };
package/src/gate.ts ADDED
@@ -0,0 +1,237 @@
1
+ import { err, ok, type Result } from "@mark1russell7/optional";
2
+ import { gateOf, type Gate, type GateCaseOutcome, type LimitOutcome } from "@mark1russell7/rigor-bench";
3
+ import { binomialTest, holm, partialConjunction } from "@mark1russell7/rigor-statistics";
4
+ import { DEFAULT_LEVEL, type Law, type LawProblem } from "./law.ts";
5
+ import { lawValue, type LevelOptions, type LoadPoint, type Range } from "./value.ts";
6
+
7
+ /** This level is the level of the family of tests of a gate. It is the chance of one false block or more in one run of the gate. */
8
+ export const GATE_ALPHA = 0.01;
9
+
10
+ /**
11
+ * This count is the jobs that each must show the same side before the gate blocks. One job on a slow runner
12
+ * cannot block alone. It is the default of `jobs` of `notSlowerVerdict` of `@mark1russell7/rigor-bench`.
13
+ */
14
+ export const GATE_JOBS = 2;
15
+
16
+ /** The side of a measured value against the run range of its law. */
17
+ export type ReadSide = "within" | "high" | "low";
18
+
19
+ /** A law read tells where one measured value falls against the run range of its law at one load point. */
20
+ export interface LawRead {
21
+ readonly value: number;
22
+ /** This range is the range `run` of `lawValue`: where one measured run falls. */
23
+ readonly run: Range;
24
+ readonly side: ReadSide;
25
+ }
26
+
27
+ const problem = (code: LawProblem["code"], path: string, message: string): LawProblem => ({ code, path, message });
28
+
29
+ /**
30
+ * This function tells where one measured value falls against the run range of a law at a load point. The range is
31
+ * the range `run` of `lawValue`. A value above the range is `high`, and a value below it is `low`.
32
+ *
33
+ * The function gives a problem for a point outside the range of a variable, because there the law has no value to
34
+ * compare. It also gives each problem of `lawValue`, and a problem for a value that is not finite.
35
+ */
36
+ export const lawRead = (law: Law, point: LoadPoint, value: number, options: LevelOptions = {}): Result<LawRead, LawProblem> => {
37
+ if (!Number.isFinite(value)) return err(problem("value", "value", `The measured value ${value} is not finite.`));
38
+ const found = lawValue(law, point, options);
39
+ if (found.tag === "err") return found;
40
+ const [outside] = found.value.outside;
41
+ if (outside !== undefined) {
42
+ const variable = law.variables.find((each) => each.id === outside);
43
+ const range = variable === undefined ? "" : ` from ${variable.min} to ${variable.max}`;
44
+ return err(problem("point", outside, `The point is outside the range of the variable "${outside}"${range}. The law has no value there to compare.`));
45
+ }
46
+ const { run } = found.value;
47
+ return ok({ value, run, side: value > run.high ? "high" : value < run.low ? "low" : "within" });
48
+ };
49
+
50
+ /** A gate read is one measured value of one job at one load point. */
51
+ export interface GateRead {
52
+ readonly point: LoadPoint;
53
+ readonly value: number;
54
+ }
55
+
56
+ /**
57
+ * A gate job is the reads of one job for one law. A job with a reason in `noRead` gives no read, for example a job with a
58
+ * noise floor over its limit. The caller gives only the reads in the conditions of the law.
59
+ */
60
+ export interface GateJob {
61
+ /** This name is the name of the job, for example the address of its CI run and its start. */
62
+ readonly job: string;
63
+ readonly reads: readonly GateRead[];
64
+ readonly noRead?: string;
65
+ /** These texts tell each read that the caller left out, for example a point that the law leaves out. The counts do not use them. */
66
+ readonly unread?: readonly string[];
67
+ }
68
+
69
+ /** A gate case is one law and the jobs that measured its subject in its conditions. */
70
+ export interface GateCase {
71
+ readonly law: Law;
72
+ readonly jobs: readonly GateJob[];
73
+ }
74
+
75
+ /** These options set the level of the run range, the level of the family of tests and the count of jobs of a side. */
76
+ export interface LawGateOptions extends LevelOptions {
77
+ /** This level is the level of the family of tests. The default is `GATE_ALPHA`. */
78
+ readonly alpha?: number;
79
+ /** This count is the jobs that each must show a side. The default is `GATE_JOBS`. */
80
+ readonly jobs?: number;
81
+ }
82
+
83
+ /** A job count tells the reads of one job for one law, and the p of the count of each side. */
84
+ export interface JobCount {
85
+ readonly job: string;
86
+ /** This count is the reads in the range of the law. */
87
+ readonly reads: number;
88
+ readonly high: number;
89
+ readonly low: number;
90
+ /** This p is the p of the binomial test of the count `high`, with the chance of one side under the claim. */
91
+ readonly pHigh: number;
92
+ readonly pLow: number;
93
+ /** These texts tell each read that the caller left out (`GateJob.unread`), and each read that the law cannot compare. */
94
+ readonly unread: readonly string[];
95
+ }
96
+
97
+ /** A side test is the test of one side of one law over the jobs, after the Holm correction of the family. */
98
+ export interface SideTest {
99
+ readonly side: "high" | "low";
100
+ /** This p is the p of the claim "`jobs` jobs or more show this side" (`partialConjunction`). */
101
+ readonly p: number;
102
+ /** This p is the p after the Holm correction of the family. */
103
+ readonly adjusted: number;
104
+ readonly reject: boolean;
105
+ }
106
+
107
+ /** A job with no read tells the job and the reason. */
108
+ export interface NoReadJob {
109
+ readonly job: string;
110
+ readonly reason: string;
111
+ }
112
+
113
+ /** A law gate case is the outcome of one law, with the counts of each job and the test of each side. */
114
+ export interface LawGateCase extends GateCaseOutcome {
115
+ /** This name is the id of the law. */
116
+ readonly case: string;
117
+ readonly outcome: LimitOutcome;
118
+ /** This text tells the reason of the outcome, in one sentence. */
119
+ readonly reason: string;
120
+ readonly jobs: readonly JobCount[];
121
+ readonly noRead: readonly NoReadJob[];
122
+ /** These tests are the two sides, or an empty list for a case with too few jobs. */
123
+ readonly sides: readonly SideTest[];
124
+ }
125
+
126
+ /** A law gate is the gate of `@mark1russell7/rigor-bench` over the laws, with the facts that it uses. */
127
+ export interface LawGate extends Gate {
128
+ readonly level: number;
129
+ readonly alpha: number;
130
+ /** This count is the jobs that each must show a side. */
131
+ readonly need: number;
132
+ /** This chance is the chance of one side for one read of a job that agrees with its law: `(1 - level) / 2`. */
133
+ readonly share: number;
134
+ readonly cases: readonly LawGateCase[];
135
+ }
136
+
137
+ /** This function gives the text of a number with at most 3 significant digits. */
138
+ const short = (value: number): string => (Number.isInteger(value) ? String(value) : value.toPrecision(3));
139
+
140
+ /** This function gives the counts of one job for one law, or the reason that the job gives no read. */
141
+ const countOf = (law: Law, job: GateJob, level: number, share: number): JobCount | NoReadJob => {
142
+ if (job.noRead !== undefined) return { job: job.job, reason: job.noRead };
143
+ let high = 0;
144
+ let low = 0;
145
+ let reads = 0;
146
+ const unread: string[] = [...(job.unread ?? [])];
147
+ for (const each of job.reads) {
148
+ const found = lawRead(law, each.point, each.value, { level });
149
+ if (found.tag === "err") {
150
+ unread.push(`${JSON.stringify(each.point)}: ${found.error.message}`);
151
+ continue;
152
+ }
153
+ reads += 1;
154
+ if (found.value.side === "high") high += 1;
155
+ if (found.value.side === "low") low += 1;
156
+ }
157
+ if (reads === 0) return { job: job.job, reason: `The job has no read in the range of the law. ${unread[0] ?? "The job has no read."}` };
158
+ return { job: job.job, reads, high, low, pHigh: binomialTest(high, reads, share, "greater"), pLow: binomialTest(low, reads, share, "greater"), unread };
159
+ };
160
+
161
+ /** The counts of one case before the family test. */
162
+ interface Counted {
163
+ readonly law: Law;
164
+ readonly jobs: readonly JobCount[];
165
+ readonly noRead: readonly NoReadJob[];
166
+ }
167
+
168
+ /**
169
+ * This function gives the gate of some laws. For each law, it tells if the measured values of the jobs stay in the run
170
+ * range of the law. It is the rule of a gate of the laws of a subject, for example on a pull request.
171
+ *
172
+ * - **A read:** each value of a job falls `within`, `high` or `low` against the run range of its law (`lawRead`).
173
+ * A read of a job that agrees with its law falls on one side with a chance of `share`, `(1 - level) / 2`, or less.
174
+ * - **A job:** for each side, the binomial test of the count of reads on that side gives the p of the job.
175
+ * A job with `noRead`, or with no read in the range of the law, gives no read.
176
+ * - **A side:** `partialConjunction` joins the p of the jobs for the claim "`jobs` jobs or more show this side". Thus one
177
+ * job on an odd runner cannot block alone. The claim has no condition on how the reads of one job depend on each other.
178
+ * - **The family:** `holm` corrects the tests of the two sides of each law at the level `alpha`. A rejected side makes the
179
+ * case `beyond`. A low side is a block too: the law is no longer the law of the subject, and a new fit must replace it.
180
+ * - **No read:** a case with fewer than `jobs` jobs that read is `cannot decide`. So is a case whose reads are too few to
181
+ * reject a side, also with each read on that side. The gate of `@mark1russell7/rigor-bench` (`gateOf`) joins the cases.
182
+ * A gate with no case, or with a case that cannot decide and no block, is "no read". It does not pass.
183
+ *
184
+ * The function throws a `RangeError` for a level, an alpha or a count of jobs that is not valid.
185
+ */
186
+ export const lawGate = (cases: readonly GateCase[], options: LawGateOptions = {}): LawGate => {
187
+ const level = options.level ?? DEFAULT_LEVEL;
188
+ const alpha = options.alpha ?? GATE_ALPHA;
189
+ const need = options.jobs ?? GATE_JOBS;
190
+ if (!(level > 0 && level < 1)) throw new RangeError(`The level ${level} is not between 0 and 1.`);
191
+ if (!(alpha > 0 && alpha < 1)) throw new RangeError(`The alpha ${alpha} is not between 0 and 1.`);
192
+ if (!Number.isInteger(need) || need < 1) throw new RangeError(`The count of jobs ${need} is not a whole number above 0.`);
193
+ const share = (1 - level) / 2;
194
+
195
+ const counted: Counted[] = cases.map(({ law, jobs }) => {
196
+ const found = jobs.map((job) => countOf(law, job, level, share));
197
+ return { law, jobs: found.filter((each): each is JobCount => "reads" in each), noRead: found.filter((each): each is NoReadJob => "reason" in each) };
198
+ });
199
+ const decidable = counted.filter((each) => each.jobs.length >= need);
200
+ const tests = decidable.length * 2;
201
+ const pOf = (jobs: readonly JobCount[], side: "high" | "low"): number => partialConjunction(jobs.map((job) => (side === "high" ? job.pHigh : job.pLow)), need);
202
+ const corrected = holm(
203
+ decidable.flatMap((each) => [pOf(each.jobs, "high"), pOf(each.jobs, "low")]),
204
+ alpha,
205
+ );
206
+
207
+ let next = 0;
208
+ const outcomes: LawGateCase[] = counted.map(({ law, jobs, noRead }) => {
209
+ const base = { case: law.id, jobs, noRead };
210
+ if (jobs.length < need) {
211
+ const reason = `${jobs.length} jobs read the law. The gate needs ${need} jobs or more.${noRead.length > 0 ? ` ${noRead[0]!.reason}` : ""}`;
212
+ return { ...base, outcome: "cannot decide", reason, sides: [] };
213
+ }
214
+ const sides: SideTest[] = (["high", "low"] as const).map((side) => {
215
+ const test = corrected[next];
216
+ next += 1;
217
+ return { side, p: test?.p ?? 1, adjusted: test?.adjusted ?? 1, reject: test?.reject ?? false };
218
+ });
219
+ // The best p of a side is the p with each read on that side. Above the first step of Holm, no count can reject the side.
220
+ const best = partialConjunction(jobs.map((job) => binomialTest(job.reads, job.reads, share, "greater")), need);
221
+ const reads = jobs.reduce((sum, job) => sum + job.reads, 0);
222
+ const high = jobs.reduce((sum, job) => sum + job.high, 0);
223
+ const low = jobs.reduce((sum, job) => sum + job.low, 0);
224
+ const counts = `${high} of ${reads} reads in ${jobs.length} jobs are above the run range and ${low} are below`;
225
+ const rejected = sides.find((side) => side.reject);
226
+ if (rejected !== undefined) {
227
+ const what = rejected.side === "high" ? "The measure is above its law" : "The measure is below its law: the law is out of date, and a new fit must replace it";
228
+ return { ...base, outcome: "beyond", reason: `${what}. ${counts}. The adjusted p is ${short(rejected.adjusted)}, below ${alpha}.`, sides };
229
+ }
230
+ if (best > alpha / tests) {
231
+ const reason = `The reads are too few to reject a side: with each read on one side, the p is ${short(best)}, above ${short(alpha / tests)}.`;
232
+ return { ...base, outcome: "cannot decide", reason, sides };
233
+ }
234
+ return { ...base, outcome: "within", reason: `${counts}, as the chance ${short(share)} of each side gives.`, sides };
235
+ });
236
+ return { ...gateOf(outcomes), level, alpha, need, share, cases: outcomes };
237
+ };