@mark1russell7/capacity 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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1108 -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-0n6WhJzF.d.ts +782 -0
  8. package/build/instance-0n6WhJzF.d.ts.map +1 -0
  9. package/build/instance-check-CAuD9L4Z.js +1711 -0
  10. package/build/instance-check-CAuD9L4Z.js.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 +315 -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 +228 -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 +142 -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 +215 -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 +260 -0
  43. package/src/value.ts +206 -0
  44. package/src/workload-check.ts +130 -0
  45. package/src/workload.ts +88 -0
package/build/index.js ADDED
@@ -0,0 +1,1713 @@
1
+ import { $ as isUtc, A as placeholdersOf, B as WORKLOAD_FORMAT, C as shareOf, D as fillPlaceholders, E as checkApp, F as checkWorkload, G as checkLaw, H as intervalOf, I as demandProblems, J as valuesAt, L as workloadProblem, M as APP_FILE, N as APP_FORMAT, O as isHttps, P as APP_LINE_KINDS, Q as finite, R as NO_DEMAND, S as scaleDemand, T as appWorkloadProblems, U as lawValue, V as constantIntervals, W as levelProblem, X as NAME, Y as valuesOf, Z as SLUG, _ as rowValuesOf, a as limitProblems, at as leastCount, b as mergeDemands, c as RESOURCE_UNITS, d as compositionValue, et as repeated, f as flatPartsOf, g as rowValueOf, h as preparedOf, i as limitProblem, it as bootstrapDraws, j as requestPath, k as metricsGaps, l as COMPOSITION_FORMAT, m as partsOutside, n as checkLimits, nt as LAW_FORMAT, o as INSTANCE_FORMAT, ot as leastGroups, p as isLawTerm, q as recordOf, r as instanceProblems, rt as MAX_VARIABLES, s as LIMITS_FORMAT, t as checkInstance, tt as DEFAULT_LEVEL, u as checkComposition, v as instancePointOf, w as totalRate, x as portionOf, y as loadPointOf, z as RATE } from "./instance-check-CAuD9L4Z.js";
2
+ import { convertible, factorOf, isCanonicalUnit, isQuantity, kindOf, quantity, scale, valueIn, whyNotConvertible } from "@mark1russell7/quantity";
3
+ import { app, let_, lit, ref, v } from "@mark1russell7/vex";
4
+ import { err, ok } from "@mark1russell7/optional";
5
+ import { SEPARABLE_BOOTSTRAP_RUNS, SEPARABLE_MAX_COMBINATIONS, binomialTest, bootstrapSeparable, fitSeparable, heldOutSeparable, holm, mean, partialConjunction, rankSeparable } from "@mark1russell7/rigor-statistics";
6
+ import { gateOf } from "@mark1russell7/rigor-bench";
7
+ // src/forms.ts
8
+ /** This name is the name of the load variable in the programs of the catalog. A binding gives its id in a law. */
9
+ const FORM_VARIABLE = "x";
10
+ const x = v("x");
11
+ const one = lit(1);
12
+ const zero = lit(0);
13
+ const add = (...parts) => parts.reduce((sum, part) => app("add", sum, part));
14
+ const times = (a, b) => app("multiply", a, b);
15
+ const over = (a, b) => app("divide", a, b);
16
+ const less = (a, b) => app("subtract", a, b);
17
+ const square = (a) => app("pow", a, lit(2));
18
+ const scaled = (factors, power) => ({
19
+ kind: "scaled",
20
+ factors,
21
+ power
22
+ });
23
+ const positive = {
24
+ kind: "least",
25
+ value: 0
26
+ };
27
+ /** The base term: a constant amount. Its slope is 0. */
28
+ const base = {
29
+ constant: "base",
30
+ basis: one,
31
+ slope: zero
32
+ };
33
+ /** The denominator of the scalability law: `1 + contention·(x − 1) + coherency·x·(x − 1)`. */
34
+ const contention = add(one, times(v("contention"), less(x, one)), times(times(v("coherency"), x), less(x, one)));
35
+ /**
36
+ * The catalog of the forms of a law, in the order of the roadmap. Each form is a sum of terms.
37
+ *
38
+ * - `constant`: `base`.
39
+ * - `linear`: `base + slope·x`.
40
+ * - `power`: `base + scale·x^exponent`.
41
+ * - `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.
42
+ * - `logarithm`: `base + scale·ln(x)`.
43
+ * - `hinge`: `base + slope·x + bend·max(0, x − knee)`. After the knee the slope is `slope + bend`.
44
+ * - `queue`: `base + scale·capacity / (capacity − x)`. This is the delay of a queue. The form has no
45
+ * finite value at the capacity.
46
+ * - `scalability`: `unit·x / (1 + contention·(x − 1) + coherency·x·(x − 1))`. This is the
47
+ * universal scalability law of the throughput at a concurrency `x`.
48
+ * - `drift`: `base + drift·x + warm·(1 − e^(−x / settle))`. This is a measure over the age of a
49
+ * process: a warm-up that settles, and a steady drift.
50
+ */
51
+ const FORMS = [
52
+ {
53
+ id: "constant",
54
+ title: "A constant",
55
+ terms: [base],
56
+ shapes: []
57
+ },
58
+ {
59
+ id: "linear",
60
+ title: "A line",
61
+ terms: [base, {
62
+ constant: "slope",
63
+ basis: x,
64
+ slope: one
65
+ }],
66
+ shapes: []
67
+ },
68
+ {
69
+ id: "power",
70
+ title: "A power of the variable",
71
+ terms: [base, {
72
+ constant: "scale",
73
+ basis: app("pow", x, v("exponent")),
74
+ slope: times(v("exponent"), app("pow", x, less(v("exponent"), one)))
75
+ }],
76
+ shapes: [{
77
+ id: "exponent",
78
+ grid: scaled([
79
+ -1,
80
+ -.5,
81
+ .25,
82
+ .5,
83
+ .75,
84
+ 1,
85
+ 1.25,
86
+ 1.5,
87
+ 2,
88
+ 3
89
+ ], 0)
90
+ }]
91
+ },
92
+ {
93
+ id: "fall-power",
94
+ title: "A fall at a low load, then a power of the variable",
95
+ terms: [
96
+ base,
97
+ {
98
+ constant: "excess",
99
+ basis: over(one, x),
100
+ slope: app("negate", over(one, square(x)))
101
+ },
102
+ {
103
+ constant: "scale",
104
+ basis: app("pow", x, v("exponent")),
105
+ slope: times(v("exponent"), app("pow", x, less(v("exponent"), one)))
106
+ }
107
+ ],
108
+ shapes: [{
109
+ id: "exponent",
110
+ grid: scaled([
111
+ .25,
112
+ .5,
113
+ .75,
114
+ 1,
115
+ 1.25,
116
+ 1.5,
117
+ 2,
118
+ 3
119
+ ], 0)
120
+ }]
121
+ },
122
+ {
123
+ id: "logarithm",
124
+ title: "A logarithm of the variable",
125
+ terms: [base, {
126
+ constant: "scale",
127
+ basis: app("ln", x),
128
+ slope: over(one, x)
129
+ }],
130
+ shapes: []
131
+ },
132
+ {
133
+ id: "hinge",
134
+ title: "Two lines that join at a knee",
135
+ terms: [
136
+ base,
137
+ {
138
+ constant: "slope",
139
+ basis: x,
140
+ slope: one
141
+ },
142
+ {
143
+ constant: "bend",
144
+ basis: app("max", zero, less(x, v("knee"))),
145
+ slope: app("if", app("gt", x, v("knee")), one, zero)
146
+ }
147
+ ],
148
+ shapes: [{
149
+ id: "knee",
150
+ grid: { kind: "inside" },
151
+ bounds: { kind: "range" }
152
+ }]
153
+ },
154
+ {
155
+ id: "queue",
156
+ title: "The delay of a queue",
157
+ terms: [base, {
158
+ constant: "scale",
159
+ basis: over(v("capacity"), less(v("capacity"), x)),
160
+ slope: over(v("capacity"), square(less(v("capacity"), x)))
161
+ }],
162
+ shapes: [{
163
+ id: "capacity",
164
+ grid: scaled([
165
+ 1.02,
166
+ 1.05,
167
+ 1.1,
168
+ 1.2,
169
+ 1.5,
170
+ 2,
171
+ 3,
172
+ 5,
173
+ 10
174
+ ], 1),
175
+ bounds: { kind: "size" }
176
+ }]
177
+ },
178
+ {
179
+ id: "scalability",
180
+ title: "The universal scalability law",
181
+ terms: [{
182
+ constant: "unit",
183
+ basis: over(x, contention),
184
+ slope: over(less(less(one, v("contention")), times(v("coherency"), square(x))), square(contention))
185
+ }],
186
+ shapes: [{
187
+ id: "contention",
188
+ grid: scaled([
189
+ 0,
190
+ .01,
191
+ .03,
192
+ .1,
193
+ .2,
194
+ .4,
195
+ .7
196
+ ], 0),
197
+ bounds: positive
198
+ }, {
199
+ id: "coherency",
200
+ grid: scaled([
201
+ 0,
202
+ .1,
203
+ .3,
204
+ 1,
205
+ 3,
206
+ 10
207
+ ], -2),
208
+ bounds: positive
209
+ }]
210
+ },
211
+ {
212
+ id: "drift",
213
+ title: "A warm-up and a drift with age",
214
+ terms: [
215
+ base,
216
+ {
217
+ constant: "drift",
218
+ basis: x,
219
+ slope: one
220
+ },
221
+ {
222
+ constant: "warm",
223
+ basis: less(one, app("exp", app("negate", over(x, v("settle"))))),
224
+ slope: over(app("exp", app("negate", over(x, v("settle")))), v("settle"))
225
+ }
226
+ ],
227
+ shapes: [{
228
+ id: "settle",
229
+ grid: scaled([
230
+ .01,
231
+ .03,
232
+ .1,
233
+ .3,
234
+ 1,
235
+ 3
236
+ ], 1),
237
+ bounds: positive
238
+ }]
239
+ }
240
+ ];
241
+ /** This function gives the form of the catalog with the id, or undefined. */
242
+ const catalogForm = (id) => FORMS.find((form) => form.id === id);
243
+ /** This function gives the ids of the constants of a form: the constant of each term, then each shape constant. */
244
+ const constantIdsOf = (form) => [...form.terms.map((term) => term.constant), ...form.shapes.map((shape) => shape.id)];
245
+ /** This function gives the sum of the terms of a form, with `part` for each term. A term of 0 does not count. */
246
+ const sumOf = (form, part) => {
247
+ const parts = form.terms.map((term) => ({
248
+ term,
249
+ expr: part(term)
250
+ })).filter(({ expr }) => !(expr.tag === "lit" && expr.value === 0)).map(({ term, expr }) => expr.tag === "lit" && expr.value === 1 ? v(term.constant) : times(v(term.constant), expr));
251
+ return parts.length === 0 ? zero : add(...parts);
252
+ };
253
+ /** This function binds the names `ids` of a form and its variable to the reads of a law. */
254
+ const bind = (ids, binding, body) => let_(Object.fromEntries([["x", ref(binding.variable)], ...ids.map((id) => [id, ref(binding.constants?.[id] ?? id)])]), body);
255
+ /** This function binds each name of a form to the reads of a law: the variable and each constant. */
256
+ const bound = (form, binding, body) => bind(constantIdsOf(form), binding, body);
257
+ /** This function gives the program of the value of a form in a law. It reads the variable and each constant of the binding. */
258
+ const programOf = (form, binding) => bound(form, binding, sumOf(form, (term) => term.basis));
259
+ /** 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. */
260
+ const slopeOf = (form, binding) => bound(form, binding, sumOf(form, (term) => term.slope));
261
+ /** This function gives the form of a law from a form of the catalog. */
262
+ const formOf = (form, binding) => ({
263
+ id: form.id,
264
+ program: programOf(form, binding)
265
+ });
266
+ const records = (xs, constants) => xs.map((value) => ({
267
+ ...constants,
268
+ ["x"]: value
269
+ }));
270
+ /** This function gives the value of a form at each value of its variable, or the text of the first error. */
271
+ const formValues = (form, xs, constants) => valuesOf(programOf(form, { variable: "x" }), records(xs, constants));
272
+ /** This function gives the slope of a form at each value of its variable, or the text of the first error. */
273
+ const formSlopes = (form, xs, constants) => valuesOf(slopeOf(form, { variable: "x" }), records(xs, constants));
274
+ /** This function gives the largest size of the values of a variable. */
275
+ const sizeOf = (xs) => xs.reduce((most, value) => Math.max(most, Math.abs(value)), 0);
276
+ /** This function gives the candidates of a grid for the values of a variable. */
277
+ const gridOf = (grid, xs) => {
278
+ if (grid.kind === "scaled") {
279
+ const size = sizeOf(xs);
280
+ return grid.power === 0 ? grid.factors : size === 0 ? [] : grid.factors.map((factor) => factor * size ** grid.power);
281
+ }
282
+ const distinct = [...new Set(xs)].sort((a, b) => a - b);
283
+ const middles = distinct.slice(1).map((value, index) => (value + distinct[index]) / 2);
284
+ const low = distinct[0] ?? 0;
285
+ const high = distinct.at(-1) ?? 0;
286
+ return [...distinct, ...middles].filter((value) => value > low && value < high).sort((a, b) => a - b);
287
+ };
288
+ /** This function gives the bounds of the refine of a shape constant for the values of a variable. */
289
+ const boundsOf = (bounds, xs) => {
290
+ if (bounds === void 0) return {};
291
+ if (bounds.kind === "least") return { min: bounds.value };
292
+ if (bounds.kind === "size") return { min: sizeOf(xs) };
293
+ return {
294
+ min: xs.reduce((least, value) => Math.min(least, value), Number.POSITIVE_INFINITY),
295
+ max: xs.reduce((most, value) => Math.max(most, value), Number.NEGATIVE_INFINITY)
296
+ };
297
+ };
298
+ /**
299
+ * This function gives a form of the catalog as a separable model of `@mark1russell7/rigor-statistics`. Each term is
300
+ * one column of the design: the basis of the term at each point. The candidates and the bounds of each shape constant
301
+ * come from the values `xs` of the variable. The design is null when a basis has no finite value at a point.
302
+ */
303
+ const separableOf = (form, xs) => {
304
+ const ids = form.shapes.map((shape) => shape.id);
305
+ const bases = form.terms.map((term) => bind(ids, { variable: "x" }, term.basis));
306
+ return {
307
+ terms: form.terms.map((term) => term.constant),
308
+ shapes: form.shapes.map((shape) => ({
309
+ id: shape.id,
310
+ candidates: gridOf(shape.grid, xs),
311
+ ...boundsOf(shape.bounds, xs)
312
+ })),
313
+ design: (values, points) => {
314
+ const at = Object.fromEntries(ids.map((id, index) => [id, values[index]]));
315
+ const columns = [];
316
+ for (const basis of bases) {
317
+ const column = valuesOf(basis, records(points, at));
318
+ if (column.tag === "err") return null;
319
+ columns.push(column.value);
320
+ }
321
+ return points.map((_, row) => columns.map((column) => column[row]));
322
+ }
323
+ };
324
+ };
325
+ /** This function gives the constants of a form from a separable fit: the constant of each term, then each shape constant. */
326
+ const constantsOf = (form, fit) => [...form.terms.map((term, index) => ({
327
+ id: term.constant,
328
+ value: fit.coefficients[index]
329
+ })), ...form.shapes.map((shape, index) => ({
330
+ id: shape.id,
331
+ value: fit.shapes[index]
332
+ }))];
333
+ /** This function gives the text of the first fault of the points of a fit, or undefined. */
334
+ const pointsProblem = (points) => {
335
+ if (points.x.length === 0) return "The fit has no points.";
336
+ if (points.x.length !== points.y.length) return `The points have ${points.x.length} values of x and ${points.y.length} values of y.`;
337
+ if (![...points.x, ...points.y].every(Number.isFinite)) return "A point has a value that is not a finite number.";
338
+ };
339
+ /** This function gives the text of the reason that the model of a form has no start, or undefined. */
340
+ const modelProblem = (form, model) => {
341
+ const empty = model.shapes.find((shape) => shape.candidates.length === 0);
342
+ if (empty !== void 0) return `The form "${form.id}" has no start value of its shape constant "${empty.id}" for these points.`;
343
+ const count = model.shapes.reduce((product, shape) => product * new Set(shape.candidates).size, 1);
344
+ if (count > SEPARABLE_MAX_COMBINATIONS) return `The form "${form.id}" has ${count} combinations of start values. The limit is ${SEPARABLE_MAX_COMBINATIONS}.`;
345
+ };
346
+ /**
347
+ * This function gives the least-squares fit of a form to some points, as the start values of its constants.
348
+ *
349
+ * The fit is `fitSeparable` of `@mark1russell7/rigor-statistics`. For each combination of the grids of the shape
350
+ * constants, the least-squares fit gives the constants of the terms. Then a golden-section search refines each shape
351
+ * constant inside its bounds. A form with no shape constant has one combination, thus its start is its least-squares fit.
352
+ *
353
+ * The function gives an error when no combination has a fit, for example with fewer points than terms.
354
+ */
355
+ const startOf = (form, points) => {
356
+ const fault = pointsProblem(points);
357
+ if (fault !== void 0) return err(fault);
358
+ const model = separableOf(form, points.x);
359
+ const reason = modelProblem(form, model);
360
+ if (reason !== void 0) return err(reason);
361
+ const fit = fitSeparable(model, points.x, points.y);
362
+ if (fit === null) return err(`The form "${form.id}" has no least-squares fit to ${points.x.length} points.`);
363
+ return ok({
364
+ constants: constantsOf(form, fit),
365
+ rss: fit.rss
366
+ });
367
+ };
368
+ // src/fit.ts
369
+ /**
370
+ * This function fits a law of one variable to its points. Each form competes, and the form with the smallest root mean
371
+ * square of its held-out residuals wins. A form with a point that has no held-out prediction ranks after each form with
372
+ * a prediction at each point.
373
+ *
374
+ * The fit of each form is `fitSeparable` of `@mark1russell7/rigor-statistics`. Each held-out residual comes from a fit of
375
+ * the other groups. The replicates of the winner come from a bootstrap of the whole groups of `bootstrapGroups`. The losers of the record are
376
+ * the other forms with a held-out prediction at each point.
377
+ *
378
+ * The function gives an error for points that a fit cannot use, and when no form has a held-out prediction at each point.
379
+ * It gives an error for fewer groups of the bootstrap than `leastGroups` of the level 0.95, because their draws are too few for an interval.
380
+ */
381
+ const fitLaw = (points, options = {}) => {
382
+ const fault = pointsProblem(points);
383
+ if (fault !== void 0) return err(fault);
384
+ const n = points.x.length;
385
+ const forms = options.forms ?? FORMS;
386
+ if (forms.length === 0) return err("The fit has no form.");
387
+ const twice = forms.find((form, index) => forms.findIndex((other) => other.id === form.id) !== index);
388
+ if (twice !== void 0) return err(`The form "${twice.id}" is in the list of forms two times.`);
389
+ const residual = options.residual ?? "absolute";
390
+ if (residual === "relative" && points.y.some((y) => y === 0)) return err("A relative fit needs values that are not 0.");
391
+ const groups = options.groups ?? points.x;
392
+ if (groups.length !== n) return err(`The fit has ${groups.length} groups for ${n} points.`);
393
+ const groupCount = new Set(groups).size;
394
+ if (groupCount < 2) return err("The fit needs two groups or more, because the held-out fit holds out one group.");
395
+ const bootstrapGroups = options.bootstrapGroups ?? groups;
396
+ if (bootstrapGroups.length !== n) return err(`The fit has ${bootstrapGroups.length} groups of the bootstrap for ${n} points.`);
397
+ const bootstrapCount = new Set(bootstrapGroups).size;
398
+ const leastBootstrap = leastGroups(DEFAULT_LEVEL);
399
+ if (bootstrapCount < leastBootstrap) return err(`The bootstrap draws whole groups, and the fit has ${bootstrapCount} of them. Thus the count of different draws is ${bootstrapDraws(bootstrapCount)}. The level ${DEFAULT_LEVEL} needs ${leastCount(DEFAULT_LEVEL)}, thus ${leastBootstrap} groups or more.`);
400
+ const weighted = residual === "relative" ? { weights: points.y.map((y) => 1 / (y * y)) } : {};
401
+ const models = {};
402
+ const skipped = [];
403
+ for (const form of forms) {
404
+ const model = separableOf(form, points.x);
405
+ const reason = modelProblem(form, model);
406
+ if (reason === void 0) models[form.id] = model;
407
+ else skipped.push({
408
+ form: form.id,
409
+ error: {
410
+ mae: NaN,
411
+ rmse: NaN
412
+ },
413
+ missing: n,
414
+ reason
415
+ });
416
+ }
417
+ const ranked = rankSeparable(models, points.x, points.y, {
418
+ groups,
419
+ residual,
420
+ ...weighted
421
+ });
422
+ const ranks = [...ranked.map((rank) => ({
423
+ form: rank.id,
424
+ error: {
425
+ mae: rank.error.mae,
426
+ rmse: rank.error.rmse
427
+ },
428
+ missing: rank.error.missing,
429
+ ...rank.fit === null ? { reason: `The form "${rank.id}" has no least-squares fit to ${n} points.` } : {}
430
+ })), ...skipped];
431
+ const best = ranked[0];
432
+ if (best === void 0 || best.fit === null || best.error.missing > 0) return err(`No form of ${forms.length} has a held-out prediction at each of the ${n} points.`);
433
+ const winner = forms.find((form) => form.id === best.id);
434
+ const model = models[best.id];
435
+ const held = heldOutSeparable(model, points.x, points.y, {
436
+ groups,
437
+ residual,
438
+ ...weighted
439
+ });
440
+ const boot = bootstrapSeparable(model, points.x, points.y, {
441
+ groups: bootstrapGroups,
442
+ ...weighted,
443
+ runs: options.runs ?? SEPARABLE_BOOTSTRAP_RUNS,
444
+ seed: options.seed ?? 1
445
+ });
446
+ if (boot === null) return err(`The form "${winner.id}" has no fit for the bootstrap.`);
447
+ const least = leastCount(DEFAULT_LEVEL);
448
+ if (boot.replicates.length < least) return err(`The bootstrap gave ${boot.replicates.length} fits in ${boot.runs} runs. The level ${DEFAULT_LEVEL} needs ${least}.`);
449
+ const binding = options.binding ?? { variable: "x" };
450
+ const values = [...best.fit.coefficients, ...best.fit.shapes];
451
+ const constants = constantIdsOf(winner).map((id, index) => ({
452
+ id: binding.constants?.[id] ?? id,
453
+ value: values[index]
454
+ }));
455
+ const losers = ranks.slice(1).filter((rank) => rank.missing === 0 && rank.reason === void 0).map((rank) => ({
456
+ form: rank.form,
457
+ error: rank.error
458
+ }));
459
+ const method = `separable least squares: ${Object.keys(models).length} forms ranked by the rmse of the held-out residuals of ${groupCount} groups, ${boot.replicates.length} fits in ${boot.runs} bootstrap runs of ${bootstrapCount} whole groups (seed ${boot.seed})`;
460
+ return ok({
461
+ form: formOf(winner, binding),
462
+ constants,
463
+ replicates: boot.replicates,
464
+ fit: {
465
+ method,
466
+ residual,
467
+ residuals: held.residuals,
468
+ losers
469
+ },
470
+ ranks
471
+ });
472
+ };
473
+ // src/knee.ts
474
+ /** This number is the count of steps of the grid of a knee search when the options give none. */
475
+ const KNEE_STEPS = 64;
476
+ /** This number is the largest count of steps of the grid of a knee search. It sets a limit on the work of one search. */
477
+ const MAX_STEPS = 4096;
478
+ /** This number sets the farthest distance from a peak where the pole test reads the size of the law. It is a share of the width of the bracket. */
479
+ const NEAR = 1e-6;
480
+ /** Each distance of the pole test is this share of the distance before it. */
481
+ const CLOSER = .001;
482
+ /** At a pole, the gain of size in the second step nearer is at least this share of the gain in the first step. */
483
+ const POLE_GAIN = .9;
484
+ /** A gain of size less than this share of the size is the noise of the floats, not a pole. */
485
+ const NOISE = 1e-9;
486
+ /** The step of a difference quotient, for each unit of the load. */
487
+ const STEP = 1e-7;
488
+ /** The most rounds of a bisection or of a golden-section search. Each search stops before, when its bracket has no middle. */
489
+ const ROUNDS = 400;
490
+ const INVERSE_PHI = (Math.sqrt(5) - 1) / 2;
491
+ const problem$2 = (code, path, message) => ({
492
+ code,
493
+ path,
494
+ message
495
+ });
496
+ /** This function gives the value of a curve at one load. */
497
+ const valueOf = (curve, load) => curve([load])[0];
498
+ /**
499
+ * This function gives the load where a test changes from false to true, with a bisection. The test
500
+ * is false at `low` and true at `high`. The function gives the end of the last bracket where the test is true.
501
+ */
502
+ const crossingOf = (test, low, high) => {
503
+ let [a, b] = [low, high];
504
+ for (let round = 0; round < ROUNDS; round += 1) {
505
+ const middle = a + (b - a) / 2;
506
+ if (middle <= a || middle >= b) break;
507
+ if (test(middle)) b = middle;
508
+ else a = middle;
509
+ }
510
+ return b;
511
+ };
512
+ /** This function gives the load of the largest size in a bracket, with a golden-section search. */
513
+ const peakOf = (size, low, high) => {
514
+ let [a, b] = [low, high];
515
+ let c = b - INVERSE_PHI * (b - a);
516
+ let d = a + INVERSE_PHI * (b - a);
517
+ let [sizeC, sizeD] = [size(c), size(d)];
518
+ for (let round = 0; round < ROUNDS && a < c && c < d && d < b; round += 1) if (sizeC >= sizeD) {
519
+ [b, d, sizeD] = [
520
+ d,
521
+ c,
522
+ sizeC
523
+ ];
524
+ c = b - INVERSE_PHI * (b - a);
525
+ sizeC = size(c);
526
+ } else {
527
+ [a, c, sizeC] = [
528
+ c,
529
+ d,
530
+ sizeD
531
+ ];
532
+ d = a + INVERSE_PHI * (b - a);
533
+ sizeD = size(d);
534
+ }
535
+ return sizeC >= sizeD ? c : d;
536
+ };
537
+ /**
538
+ * This function tells if the size of a law grows with no bound near the top of a peak. It reads the
539
+ * size at three distances from the top, each 1000 times nearer than the distance before it.
540
+ *
541
+ * At a pole, each step nearer adds as much size as the step before, or more. A power pole adds more,
542
+ * and a logarithm pole adds the same. Near a finite peak, the second step adds about a millionth of
543
+ * the first. A load with no value at one of the distances is an edge near the top.
544
+ */
545
+ const diverges = (size, top, near) => {
546
+ const sizeAt = (distance) => Math.max(size(top - distance), size(top + distance));
547
+ const [far, middle, close] = [
548
+ near,
549
+ near * CLOSER,
550
+ near * CLOSER * CLOSER
551
+ ].map(sizeAt);
552
+ if (!Number.isFinite(close) || !Number.isFinite(middle) || !Number.isFinite(far)) return true;
553
+ const first = middle - far;
554
+ return first > NOISE * middle && close - middle >= POLE_GAIN * first;
555
+ };
556
+ /**
557
+ * This function gives the edge of one row of a law: the first load of the grid where the law has
558
+ * no finite value. It gives Infinity when the law has a finite value on all of the grid.
559
+ *
560
+ * The size of a law at a load is the distance of its value from the start value. A load with no
561
+ * value has an infinite size. The search examines each peak of the size on the grid, in order. A
562
+ * golden-section search finds the top of the peak, and the pole test examines it. A peak with no
563
+ * value at its top starts a region with no value.
564
+ */
565
+ const edgeOf = (curve, grid, values, start) => {
566
+ const sizeOf = (value) => value === void 0 ? 1e400 : Math.abs(value - start);
567
+ const size = (load) => sizeOf(valueOf(curve, load));
568
+ const noValue = (load) => valueOf(curve, load) === void 0;
569
+ const sizes = values.map(sizeOf);
570
+ const last = grid.length - 1;
571
+ for (let index = 1; index <= last; index += 1) {
572
+ const here = sizes[index];
573
+ const missing = values[index] === void 0;
574
+ if (!(here > sizes[index - 1] && (index === last || missing || here >= sizes[index + 1]))) continue;
575
+ const low = grid[index - 1];
576
+ const high = grid[missing ? index : Math.min(index + 1, last)];
577
+ const top = peakOf(size, low, high);
578
+ if (noValue(top)) return crossingOf(noValue, low, top);
579
+ if (diverges(size, top, NEAR * (high - low))) return top;
580
+ if (missing) return crossingOf(noValue, low, grid[index]);
581
+ }
582
+ return 1e400;
583
+ };
584
+ /** This function gives the step of a difference quotient at a load. The unit is the width of the search on a linear scale, and 0 on a log scale. */
585
+ const stepAt = (load, unit) => STEP * Math.max(Math.abs(load), unit);
586
+ /**
587
+ * This function gives the first load before the edge where the test holds. It gives Infinity when
588
+ * the test does not hold before the edge or the end of the grid.
589
+ *
590
+ * The search tests the loads of the grid before the edge, and one load near the edge. A bisection
591
+ * then finds the load between the last load that fails the test and the first load that passes it.
592
+ */
593
+ const firstHolds = (holds, grid, values, edge) => {
594
+ const loads = grid.map((load, index) => ({
595
+ load,
596
+ value: values[index]
597
+ })).filter(({ load }) => load < edge);
598
+ if (Number.isFinite(edge)) {
599
+ const before = loads.at(-1)?.load ?? grid[0];
600
+ loads.push({
601
+ load: edge - NEAR * (edge - before),
602
+ value: void 0
603
+ });
604
+ }
605
+ let previous;
606
+ for (const { load, value } of loads) {
607
+ if (holds(load, value)) return previous === void 0 ? load : crossingOf((x) => holds(x), previous, load);
608
+ previous = load;
609
+ }
610
+ return 1e400;
611
+ };
612
+ /** This function gives the first load where one row passes its test, and the edge of the row. The text `what` names the owner of the row in a problem. */
613
+ const rowOf = (curve, path, testOf, grid, unit, what = "law") => {
614
+ const values = curve(grid);
615
+ const start = values[0];
616
+ const from = grid[0];
617
+ if (start === void 0) return err(problem$2("value", path, `The ${what} has no value at the start of the search, ${from}.`));
618
+ const edge = edgeOf(curve, grid, values, start);
619
+ const test = testOf({
620
+ curve,
621
+ start,
622
+ path,
623
+ from,
624
+ unit,
625
+ grid,
626
+ values,
627
+ edge
628
+ });
629
+ if (test.tag === "err") return test;
630
+ return ok({
631
+ crossing: test.value === void 0 ? void 0 : firstHolds(test.value, grid, values, edge),
632
+ edge
633
+ });
634
+ };
635
+ /** This function gives the test of a knee rule: the value or the slope is above its mark from the start of the search. */
636
+ const ruleTest = (rule) => ({ curve, start, path, from, unit }) => {
637
+ if (rule.kind === "rise") {
638
+ if (!(start > 0)) return err(problem$2("knee", path, `The rule "rise" needs a value above 0 at the start of the search. The value is ${start}.`));
639
+ const limit = (1 + rule.share) * start;
640
+ return ok((load, value = valueOf(curve, load)) => value !== void 0 && value > limit);
641
+ }
642
+ const slopeAt = (load, value) => {
643
+ const step = stepAt(load, unit);
644
+ const before = valueOf(curve, load - step);
645
+ return value === void 0 || before === void 0 ? void 0 : (value - before) / step;
646
+ };
647
+ const step = stepAt(from, unit);
648
+ const after = valueOf(curve, from + step);
649
+ const first = after === void 0 ? void 0 : (after - start) / step;
650
+ if (first === void 0 || !(first > 0)) return err(problem$2("knee", path, `The rule "slope" needs a slope above 0 at the start of the search. The slope is ${String(first)}.`));
651
+ const limit = rule.factor * first;
652
+ return ok((load, value) => {
653
+ const slope = slopeAt(load, value ?? valueOf(curve, load));
654
+ return slope !== void 0 && slope > limit;
655
+ });
656
+ };
657
+ /** This function gives the test of an amount: the value is above the amount. */
658
+ const amountTest = (amount) => ({ curve }) => ok((load, value = valueOf(curve, load)) => value !== void 0 && value > amount);
659
+ /** These kinds name the knee rules. */
660
+ const KNEE_KINDS = [
661
+ "rise",
662
+ "slope",
663
+ "floor"
664
+ ];
665
+ /**
666
+ * This function gives the problem of a knee rule, or undefined for a correct rule. The rule can come
667
+ * from data, thus the function also examines its shape. The path of a problem starts with `path`.
668
+ */
669
+ const kneeRuleProblem = (rule, path = "rule") => {
670
+ if (typeof rule !== "object" || rule === null || Array.isArray(rule)) return problem$2("knee", path, "The rule is not a record.");
671
+ const { kind, share, factor } = rule;
672
+ if (kind === "rise" || kind === "floor") {
673
+ if (typeof share === "number" && Number.isFinite(share) && share > 0) return void 0;
674
+ return problem$2("knee", `${path}.share`, `The share of the rule "${kind}" is ${String(share)}. It must be a finite number above 0.`);
675
+ }
676
+ if (kind === "slope") {
677
+ if (typeof factor === "number" && Number.isFinite(factor) && factor > 1) return void 0;
678
+ return problem$2("knee", `${path}.factor`, `The factor of the rule "slope" is ${String(factor)}. It must be a finite number above 1.`);
679
+ }
680
+ return problem$2("knee", `${path}.kind`, `The kind of the rule is ${JSON.stringify(kind) ?? "undefined"}. It must be one of ${KNEE_KINDS.join(", ")}.`);
681
+ };
682
+ /**
683
+ * This function gives the open value of the values of the rows. The first value is the value of the
684
+ * estimate. A value past `end` is past the end of the search, and an infinite value is too.
685
+ */
686
+ const openValueOf = (values, level, end) => {
687
+ const [value, ...spread] = values.map((entry) => Number.isFinite(entry) ? entry : Number.MAX_VALUE);
688
+ const interval = intervalOf(value, spread, level);
689
+ const open = (entry) => entry > end ? null : entry;
690
+ return {
691
+ value: open(value),
692
+ interval: {
693
+ low: open(interval.low),
694
+ high: open(interval.high)
695
+ }
696
+ };
697
+ };
698
+ /** This function gives the crossing of the values of the rows. The flag `outside` tells that the value is outside `range`. */
699
+ const crossingFrom = (values, level, range, end) => {
700
+ const found = openValueOf(values, level, end);
701
+ return {
702
+ ...found,
703
+ outside: found.value !== null && (found.value < range.low || found.value > range.high)
704
+ };
705
+ };
706
+ /**
707
+ * This function gives the grid of a search from `from` to `to` in `steps` steps, or its problem. A
708
+ * grid on the scale `log` starts above 0. The text `owner` names the variable of the search in a problem.
709
+ */
710
+ const searchGrid = (from, to, steps, log, owner) => {
711
+ if (!(Number.isFinite(from) && Number.isFinite(to) && from < to)) return err(problem$2("range", "from", `The search goes from ${from} to ${to}. It must go from a finite number to a larger finite number.`));
712
+ if (log && !(from > 0)) return err(problem$2("range", "from", `${owner} has the scale "log", thus the search starts above 0.`));
713
+ if (!(Number.isInteger(steps) && steps >= 2 && steps <= 4096)) return err(problem$2("knee", "steps", `The search has ${steps} steps. It must have a whole number of steps from 2 to ${MAX_STEPS}.`));
714
+ return ok(Array.from({ length: steps + 1 }, (_, index) => index === steps ? to : log ? from * (to / from) ** (index / steps) : from + (to - from) * index / steps));
715
+ };
716
+ /**
717
+ * This function gives the setup of a search along one variable of a law, or its problem. The function
718
+ * `check` gives the problem of the test before the setup.
719
+ */
720
+ const searchOf = (law, variable, options, check) => {
721
+ const level = options.level ?? .95;
722
+ const noLevel = levelProblem(law, level, false);
723
+ if (noLevel !== void 0) return err(noLevel);
724
+ const target = law.variables.find((entry) => entry.id === variable);
725
+ if (target === void 0) return err(problem$2("point", "variable", `The law has no variable "${variable}".`));
726
+ const badTest = check();
727
+ if (badTest !== void 0) return err(badTest);
728
+ const at = options.at ?? {};
729
+ for (const name of Object.keys(at)) {
730
+ if (name === variable) return err(problem$2("point", `at.${name}`, `The point "at" gives "${name}", the variable of the search.`));
731
+ if (!law.variables.some((entry) => entry.id === name)) return err(problem$2("point", `at.${name}`, `The law has no variable "${name}".`));
732
+ }
733
+ const base = {};
734
+ for (const other of law.variables) {
735
+ if (other.id === variable) continue;
736
+ const value = at[other.id];
737
+ if (typeof value !== "number" || !Number.isFinite(value)) return err(problem$2("point", `at.${other.id}`, `The point "at" gives no finite value for the variable "${other.id}".`));
738
+ base[other.id] = value;
739
+ }
740
+ const from = options.from ?? target.min;
741
+ const to = options.to ?? target.max;
742
+ const log = target.scale === "log";
743
+ const grid = searchGrid(from, to, options.steps ?? 64, log, `The variable "${variable}"`);
744
+ if (grid.tag === "err") return grid;
745
+ const names = law.constants.map((constant) => constant.id);
746
+ const program = law.form.program;
747
+ const curveOf = (values) => (loads) => valuesAt(program, loads.map((load) => recordOf(names, values, {
748
+ ...base,
749
+ [variable]: load
750
+ })));
751
+ const outside = law.variables.filter((entry) => entry.id !== variable && (base[entry.id] < entry.min || base[entry.id] > entry.max)).map((entry) => entry.id);
752
+ return ok({
753
+ target,
754
+ level,
755
+ search: {
756
+ low: from,
757
+ high: to
758
+ },
759
+ grid: grid.value,
760
+ unit: log ? 0 : to - from,
761
+ curveOf,
762
+ outside
763
+ });
764
+ };
765
+ /** This function searches a law for the first load that passes a test, in the constants and in each replicate. */
766
+ const along = (law, setup, testOf) => {
767
+ const rows = [{
768
+ path: "constants",
769
+ values: law.constants.map((constant) => constant.value)
770
+ }, ...law.replicates.map((row, index) => ({
771
+ path: `replicates[${index}]`,
772
+ values: row
773
+ }))];
774
+ const crossings = [];
775
+ const edges = [];
776
+ let skipped = 0;
777
+ for (const row of rows) {
778
+ const result = rowOf(setup.curveOf(row.values), row.path, testOf, setup.grid, setup.unit);
779
+ if (result.tag === "err") return result;
780
+ edges.push(result.value.edge);
781
+ const { crossing } = result.value;
782
+ if (crossing === void 0) {
783
+ if (row.path === "constants") return err(problem$2("knee", row.path, "The rule cannot apply to the constants of the law."));
784
+ skipped += 1;
785
+ } else crossings.push(crossing);
786
+ }
787
+ const range = {
788
+ low: setup.target.min,
789
+ high: setup.target.max
790
+ };
791
+ return ok({
792
+ crossing: crossingFrom(crossings, setup.level, range, setup.search.high),
793
+ edge: crossingFrom(edges, setup.level, range, setup.search.high),
794
+ skipped
795
+ });
796
+ };
797
+ /** This function gives the floor of one row: its least value on the grid, at the loads before its edge. */
798
+ const rowFloor = (grid, values, edge, start) => {
799
+ let floor = {
800
+ load: grid[0],
801
+ value: start
802
+ };
803
+ grid.forEach((load, index) => {
804
+ const value = values[index];
805
+ if (load < edge && value !== void 0 && value < floor.value) floor = {
806
+ load,
807
+ value
808
+ };
809
+ });
810
+ return floor;
811
+ };
812
+ /**
813
+ * This function gives the floor of a law on the grid of a search. The floor is the least value of the
814
+ * law with its constants, at the loads before its edge. The rule `floor` needs a floor above 0.
815
+ */
816
+ const floorOf = (law, setup) => {
817
+ const curve = setup.curveOf(law.constants.map((constant) => constant.value));
818
+ const values = curve(setup.grid);
819
+ const start = values[0];
820
+ if (start === void 0) return err(problem$2("value", "constants", `The law has no value at the start of the search, ${setup.grid[0]}.`));
821
+ const floor = rowFloor(setup.grid, values, edgeOf(curve, setup.grid, values, start), start);
822
+ if (!(floor.value > 0)) return err(problem$2("knee", "constants", `The rule "floor" needs a floor above 0. The floor is ${floor.value} at ${floor.load}.`));
823
+ return ok(floor);
824
+ };
825
+ /**
826
+ * This function gives the test of the rule `floor` for one row. From the load of the floor of the
827
+ * row, the value is above `1 + share` times that floor. A row with no floor above 0 has no test.
828
+ */
829
+ const floorTest = (share) => ({ curve, start, grid, values, edge }) => {
830
+ const floor = rowFloor(grid, values, edge, start);
831
+ if (!(floor.value > 0)) return ok(void 0);
832
+ const limit = (1 + share) * floor.value;
833
+ return ok((load, value = valueOf(curve, load)) => load >= floor.load && value !== void 0 && value > limit);
834
+ };
835
+ /**
836
+ * This function gives the largest count of replicates that a knee interval can leave out. The count is
837
+ * at most the replicates of one tail of the level, and at least `leastCount` replicates stay.
838
+ */
839
+ const mostSkipped = (replicates, level) => Math.min(Math.floor(replicates * (1 - level) / 2 + 1e-9), replicates - leastCount(level));
840
+ /**
841
+ * This function gives the knee of a law along one variable, with an interval. It also gives the
842
+ * edge: the first load where the law has no finite value.
843
+ *
844
+ * The point `at` of the options gives each other variable of the law. The function evaluates the
845
+ * law with its constants, then with each replicate. The interval of the knee and of the edge is the
846
+ * share `level` of the values of the replicates, made wider to hold the value.
847
+ *
848
+ * The search tests a grid of loads, then a bisection finds each crossing. A crossing between two
849
+ * loads of the grid is found. Two edges in one step of the grid can hide the first edge.
850
+ *
851
+ * The rule `floor` gives each row its own floor. Thus the knee of a row is always after its floor,
852
+ * and the uncertainty of the floor is in the interval. A replicate with no floor above 0 has no knee:
853
+ * the field `noFloor` counts these replicates, and the interval leaves them out. When they are more
854
+ * than one tail of the level, the function gives a problem.
855
+ *
856
+ * The function gives a problem for a variable or a point that the law cannot read. A bad search
857
+ * range, rule or count of steps, and a level that the law cannot show, also give a problem. The last
858
+ * problems are a law with no value at the start of the search, and a rule that cannot apply there.
859
+ */
860
+ const lawKnee = (law, variable, rule, options = {}) => {
861
+ const setup = searchOf(law, variable, options, () => kneeRuleProblem(rule));
862
+ if (setup.tag === "err") return setup;
863
+ let floor;
864
+ if (rule.kind === "floor") {
865
+ const least = floorOf(law, setup.value);
866
+ if (least.tag === "err") return least;
867
+ floor = least.value;
868
+ }
869
+ const found = along(law, setup.value, rule.kind === "floor" ? floorTest(rule.share) : ruleTest(rule));
870
+ if (found.tag === "err") return found;
871
+ const { target, level, search, outside } = setup.value;
872
+ const knee = {
873
+ variable,
874
+ unit: target.unit,
875
+ rule,
876
+ level,
877
+ search,
878
+ knee: found.value.crossing,
879
+ edge: found.value.edge,
880
+ outside
881
+ };
882
+ if (floor === void 0) return ok(knee);
883
+ const { skipped } = found.value;
884
+ const most = mostSkipped(law.replicates.length, level);
885
+ if (skipped > most) {
886
+ const message = `The rule "floor" needs a floor above 0. ${skipped} of ${law.replicates.length} replicates have a floor of 0 or less. The interval of the level ${level} can leave out at most ${most}.`;
887
+ return err(problem$2("knee", "replicates", message));
888
+ }
889
+ return ok({
890
+ ...knee,
891
+ floor,
892
+ noFloor: skipped
893
+ });
894
+ };
895
+ /**
896
+ * This function gives the first load along one variable where a law is above an amount, with an
897
+ * interval. This is the inverse query of one law: the largest load that one limit holds.
898
+ *
899
+ * The options are the options of `lawKnee`. When the law is above the amount at the start of the
900
+ * search, the crossing is the start. When the law holds the amount on all of the search, the
901
+ * crossing is null. A pole is above each amount, so the crossing is before the pole.
902
+ *
903
+ * The function gives each problem of `lawKnee` that is not about a rule. An amount that is not finite
904
+ * gives a problem. An amount that does not convert to the unit of the measure also gives a problem.
905
+ */
906
+ const lawReach = (law, variable, amount, options = {}) => {
907
+ if (!isQuantity(amount) || !Number.isFinite(amount.value)) return err(problem$2("value", "amount", "The amount is not a finite quantity."));
908
+ if (!convertible(amount.unit, law.measure.unit)) {
909
+ const why = whyNotConvertible(amount.unit, law.measure.unit) ?? "the units are different";
910
+ return err(problem$2("unit", "amount", `The amount is in "${amount.unit}", and the measure of the law is in "${law.measure.unit}": ${why}.`));
911
+ }
912
+ const value = valueIn(amount, law.measure.unit);
913
+ const setup = searchOf(law, variable, options, () => void 0);
914
+ if (setup.tag === "err") return setup;
915
+ const found = along(law, setup.value, amountTest(value));
916
+ if (found.tag === "err") return found;
917
+ const { target, level, search, outside } = setup.value;
918
+ return ok({
919
+ variable,
920
+ unit: target.unit,
921
+ amount: value,
922
+ level,
923
+ search,
924
+ crossing: found.value.crossing,
925
+ edge: found.value.edge,
926
+ outside
927
+ });
928
+ };
929
+ // src/gate.ts
930
+ /** 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. */
931
+ const GATE_ALPHA = .01;
932
+ /**
933
+ * This count is the jobs that each must show the same side before the gate blocks. One job on a slow runner
934
+ * cannot block alone. It is the default of `jobs` of `notSlowerVerdict` of `@mark1russell7/rigor-bench`.
935
+ */
936
+ const GATE_JOBS = 2;
937
+ const problem$1 = (code, path, message) => ({
938
+ code,
939
+ path,
940
+ message
941
+ });
942
+ /**
943
+ * This function tells where one measured value falls against the run range of a law at a load point. The range is
944
+ * the range `run` of `lawValue`. A value above the range is `high`, and a value below it is `low`.
945
+ *
946
+ * The function gives a problem for a point outside the range of a variable, because there the law has no value to
947
+ * compare. It also gives each problem of `lawValue`, and a problem for a value that is not finite.
948
+ */
949
+ const lawRead = (law, point, value, options = {}) => {
950
+ if (!Number.isFinite(value)) return err(problem$1("value", "value", `The measured value ${value} is not finite.`));
951
+ const found = lawValue(law, point, options);
952
+ if (found.tag === "err") return found;
953
+ const [outside] = found.value.outside;
954
+ if (outside !== void 0) {
955
+ const variable = law.variables.find((each) => each.id === outside);
956
+ const range = variable === void 0 ? "" : ` from ${variable.min} to ${variable.max}`;
957
+ return err(problem$1("point", outside, `The point is outside the range of the variable "${outside}"${range}. The law has no value there to compare.`));
958
+ }
959
+ const { run } = found.value;
960
+ return ok({
961
+ value,
962
+ run,
963
+ side: value > run.high ? "high" : value < run.low ? "low" : "within"
964
+ });
965
+ };
966
+ /** This function gives the text of a number with at most 3 significant digits. */
967
+ const short = (value) => Number.isInteger(value) ? String(value) : value.toPrecision(3);
968
+ /** This function gives the counts of one job for one law, or the reason that the job gives no read. */
969
+ const countOf = (law, job, level, share) => {
970
+ if (job.noRead !== void 0) return {
971
+ job: job.job,
972
+ reason: job.noRead
973
+ };
974
+ let high = 0;
975
+ let low = 0;
976
+ let reads = 0;
977
+ const unread = [...job.unread ?? []];
978
+ for (const each of job.reads) {
979
+ const found = lawRead(law, each.point, each.value, { level });
980
+ if (found.tag === "err") {
981
+ unread.push(`${JSON.stringify(each.point)}: ${found.error.message}`);
982
+ continue;
983
+ }
984
+ reads += 1;
985
+ if (found.value.side === "high") high += 1;
986
+ if (found.value.side === "low") low += 1;
987
+ }
988
+ if (reads === 0) return {
989
+ job: job.job,
990
+ reason: `The job has no read in the range of the law. ${unread[0] ?? "The job has no read."}`
991
+ };
992
+ return {
993
+ job: job.job,
994
+ reads,
995
+ high,
996
+ low,
997
+ pHigh: binomialTest(high, reads, share, "greater"),
998
+ pLow: binomialTest(low, reads, share, "greater"),
999
+ unread
1000
+ };
1001
+ };
1002
+ /**
1003
+ * This function gives the gate of some laws. For each law, it tells if the measured values of the jobs stay in the run
1004
+ * range of the law. It is the rule of a gate of the laws of a subject, for example on a pull request.
1005
+ *
1006
+ * - **A read:** each value of a job falls `within`, `high` or `low` against the run range of its law (`lawRead`).
1007
+ * A read of a job that agrees with its law falls on one side with a chance of `share`, `(1 - level) / 2`, or less.
1008
+ * - **A job:** for each side, the binomial test of the count of reads on that side gives the p of the job.
1009
+ * A job with `noRead`, or with no read in the range of the law, gives no read.
1010
+ * - **A side:** `partialConjunction` joins the p of the jobs for the claim "`jobs` jobs or more show this side". Thus one
1011
+ * job on an odd runner cannot block alone. The claim has no condition on how the reads of one job depend on each other.
1012
+ * - **The family:** `holm` corrects the tests of the two sides of each law at the level `alpha`. A rejected side makes the
1013
+ * 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.
1014
+ * - **No read:** a case with fewer than `jobs` jobs that read is `cannot decide`. So is a case whose reads are too few to
1015
+ * reject a side, also with each read on that side. The gate of `@mark1russell7/rigor-bench` (`gateOf`) joins the cases.
1016
+ * A gate with no case, or with a case that cannot decide and no block, is "no read". It does not pass.
1017
+ *
1018
+ * The function throws a `RangeError` for a level, an alpha or a count of jobs that is not valid.
1019
+ */
1020
+ const lawGate = (cases, options = {}) => {
1021
+ const level = options.level ?? .95;
1022
+ const alpha = options.alpha ?? .01;
1023
+ const need = options.jobs ?? 2;
1024
+ if (!(level > 0 && level < 1)) throw new RangeError(`The level ${level} is not between 0 and 1.`);
1025
+ if (!(alpha > 0 && alpha < 1)) throw new RangeError(`The alpha ${alpha} is not between 0 and 1.`);
1026
+ if (!Number.isInteger(need) || need < 1) throw new RangeError(`The count of jobs ${need} is not a whole number above 0.`);
1027
+ const share = (1 - level) / 2;
1028
+ const counted = cases.map(({ law, jobs }) => {
1029
+ const found = jobs.map((job) => countOf(law, job, level, share));
1030
+ return {
1031
+ law,
1032
+ jobs: found.filter((each) => "reads" in each),
1033
+ noRead: found.filter((each) => "reason" in each)
1034
+ };
1035
+ });
1036
+ const decidable = counted.filter((each) => each.jobs.length >= need);
1037
+ const tests = decidable.length * 2;
1038
+ const pOf = (jobs, side) => partialConjunction(jobs.map((job) => side === "high" ? job.pHigh : job.pLow), need);
1039
+ const corrected = holm(decidable.flatMap((each) => [pOf(each.jobs, "high"), pOf(each.jobs, "low")]), alpha);
1040
+ let next = 0;
1041
+ const outcomes = counted.map(({ law, jobs, noRead }) => {
1042
+ const base = {
1043
+ case: law.id,
1044
+ jobs,
1045
+ noRead
1046
+ };
1047
+ if (jobs.length < need) {
1048
+ const reason = `${jobs.length} jobs read the law. The gate needs ${need} jobs or more.${noRead.length > 0 ? ` ${noRead[0].reason}` : ""}`;
1049
+ return {
1050
+ ...base,
1051
+ outcome: "cannot decide",
1052
+ reason,
1053
+ sides: []
1054
+ };
1055
+ }
1056
+ const sides = ["high", "low"].map((side) => {
1057
+ const test = corrected[next];
1058
+ next += 1;
1059
+ return {
1060
+ side,
1061
+ p: test?.p ?? 1,
1062
+ adjusted: test?.adjusted ?? 1,
1063
+ reject: test?.reject ?? false
1064
+ };
1065
+ });
1066
+ const best = partialConjunction(jobs.map((job) => binomialTest(job.reads, job.reads, share, "greater")), need);
1067
+ const reads = jobs.reduce((sum, job) => sum + job.reads, 0);
1068
+ const high = jobs.reduce((sum, job) => sum + job.high, 0);
1069
+ const low = jobs.reduce((sum, job) => sum + job.low, 0);
1070
+ const counts = `${high} of ${reads} reads in ${jobs.length} jobs are above the run range and ${low} are below`;
1071
+ const rejected = sides.find((side) => side.reject);
1072
+ if (rejected !== void 0) {
1073
+ 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";
1074
+ return {
1075
+ ...base,
1076
+ outcome: "beyond",
1077
+ reason: `${what}. ${counts}. The adjusted p is ${short(rejected.adjusted)}, below ${alpha}.`,
1078
+ sides
1079
+ };
1080
+ }
1081
+ if (best > alpha / tests) {
1082
+ 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)}.`;
1083
+ return {
1084
+ ...base,
1085
+ outcome: "cannot decide",
1086
+ reason,
1087
+ sides
1088
+ };
1089
+ }
1090
+ return {
1091
+ ...base,
1092
+ outcome: "within",
1093
+ reason: `${counts}, as the chance ${short(share)} of each side gives.`,
1094
+ sides
1095
+ };
1096
+ });
1097
+ return {
1098
+ ...gateOf(outcomes),
1099
+ level,
1100
+ alpha,
1101
+ need,
1102
+ share,
1103
+ cases: outcomes
1104
+ };
1105
+ };
1106
+ // src/app-metrics.ts
1107
+ /**
1108
+ * This function gives the increase of a counter from its values in the order of their times. A value below
1109
+ * the value before it is a new start of the process. The counter starts again at 0, thus the increase adds
1110
+ * the whole value.
1111
+ */
1112
+ const counterIncrease = (values) => values.reduce((total, value, index) => {
1113
+ if (index === 0) return total;
1114
+ const before = values[index - 1] ?? 0;
1115
+ return total + (value >= before ? value - before : value);
1116
+ }, 0);
1117
+ /** This function makes a problem of the readings of an app. */
1118
+ const readingProblem = (path, message) => ({
1119
+ code: "series",
1120
+ path,
1121
+ message
1122
+ });
1123
+ /**
1124
+ * This function gives the observation of an app in a window. The observation has the count of the requests of
1125
+ * each class, the mean of each request variable and each level. It reads only the readings in the window.
1126
+ *
1127
+ * - The count of a class is the increase of its counter. A class with no request in the window is not in the observation.
1128
+ * - The mean of a request variable is the increase of the counter of its total, over the count of its class.
1129
+ * - A level is the mean of the readings of its gauge, with the same weight for each reading. Item CAP-63 adds a weight for the time of each reading.
1130
+ *
1131
+ * It gives a problem for each gap of the metrics of the app (`metricsGaps`). It also gives a problem for a
1132
+ * counter with fewer than 2 readings, and for a gauge with no reading. `observedWorkload` gives the workload
1133
+ * of the observation.
1134
+ */
1135
+ const observationOf = (app, window, readings) => {
1136
+ const { origin, from, to } = window;
1137
+ if (!isUtc(from) || !isUtc(to) || !(Date.parse(from) < Date.parse(to))) return err([readingProblem("window", "The window does not go from a UTC time to a later UTC time.")]);
1138
+ const problems = metricsGaps(app).map((gap) => readingProblem("metrics", gap.message));
1139
+ const start = Date.parse(from);
1140
+ const end = Date.parse(to);
1141
+ /** This function gives the values of a series in the window, in the order of their times. */
1142
+ const valuesOf = (series) => readings.filter((reading) => reading.series === series.id && isUtc(reading.at) && Date.parse(reading.at) >= start && Date.parse(reading.at) <= end).sort((a, b) => Date.parse(a.at) - Date.parse(b.at)).map((reading) => reading.value).filter((value) => Number.isFinite(value));
1143
+ /** This function gives the increase of a counter in the window, in the unit of the series, or a problem. */
1144
+ const increaseOf = (series) => {
1145
+ const values = valuesOf(series);
1146
+ if (values.length >= 2) return counterIncrease(values);
1147
+ problems.push(readingProblem(`readings.${series.id}`, `The counter "${series.id}" has ${values.length} readings in the window. Its increase needs 2 or more.`));
1148
+ };
1149
+ const classes = [];
1150
+ for (const entry of app.classes) {
1151
+ const counter = app.metrics.find((series) => "rate" in series.of && series.of.rate === entry.id);
1152
+ if (counter === void 0) continue;
1153
+ const count = increaseOf(counter);
1154
+ if (count === void 0 || count === 0) continue;
1155
+ const request = {};
1156
+ for (const name of entry.request) {
1157
+ const total = app.metrics.find((series) => "total" in series.of && series.of.total === name && series.of.class === entry.id);
1158
+ const variable = app.variables.find((each) => each.id === name);
1159
+ if (total === void 0 || variable === void 0) continue;
1160
+ const sum = increaseOf(total);
1161
+ if (sum !== void 0) request[name] = quantity(valueIn(quantity(sum, total.unit), variable.unit) / count, variable.unit);
1162
+ }
1163
+ classes.push({
1164
+ id: entry.id,
1165
+ count: quantity(count, counter.unit),
1166
+ request
1167
+ });
1168
+ }
1169
+ const levels = {};
1170
+ for (const variable of app.variables) {
1171
+ if (variable.kind !== "level") continue;
1172
+ const gauge = app.metrics.find((series) => "level" in series.of && series.of.level === variable.id);
1173
+ if (gauge === void 0) continue;
1174
+ const values = valuesOf(gauge);
1175
+ if (values.length === 0) {
1176
+ problems.push(readingProblem(`readings.${gauge.id}`, `The gauge "${gauge.id}" has no reading in the window.`));
1177
+ continue;
1178
+ }
1179
+ levels[variable.id] = quantity(valueIn(quantity(mean(values), gauge.unit), variable.unit), variable.unit);
1180
+ }
1181
+ return problems.length > 0 ? err(problems) : ok({
1182
+ origin,
1183
+ from,
1184
+ to,
1185
+ classes,
1186
+ levels
1187
+ });
1188
+ };
1189
+ // src/observe.ts
1190
+ /**
1191
+ * This function gives the workload of an observation. The rate of a class is its count, divided by
1192
+ * the seconds of the window. Thus the rate is the mean rate of the window. For the load at a peak,
1193
+ * give the window of the peak.
1194
+ *
1195
+ * It gives each problem of an observation that is not correct, and each problem of the workload.
1196
+ */
1197
+ const observedWorkload = (observation, name) => {
1198
+ const { origin, from, to } = observation;
1199
+ const seconds = isUtc(from) && isUtc(to) ? (Date.parse(to) - Date.parse(from)) / 1e3 : NaN;
1200
+ if (!(seconds > 0)) return err([workloadProblem("source", "source", "The window does not go from a UTC time to a later UTC time.")]);
1201
+ const problems = [];
1202
+ const classes = [];
1203
+ observation.classes.forEach((entry, index) => {
1204
+ const { count } = entry;
1205
+ const unit = isQuantity(count) && kindOf(count.unit) === "count" ? `${count.unit}/s` : void 0;
1206
+ if (unit === void 0 || !isCanonicalUnit(unit) || kindOf(unit) !== "frequency" || count.value < 0) {
1207
+ problems.push(workloadProblem("rate", `classes[${index}].count`, `The count of the class "${entry.id}" is not a count of 0 or more, for example in "{request}".`));
1208
+ return;
1209
+ }
1210
+ classes.push({
1211
+ id: entry.id,
1212
+ rate: quantity(count.value / seconds, unit),
1213
+ request: entry.request
1214
+ });
1215
+ });
1216
+ if (problems.length > 0) return err(problems);
1217
+ const workload = {
1218
+ format: WORKLOAD_FORMAT,
1219
+ id: name.id,
1220
+ title: name.title,
1221
+ classes,
1222
+ levels: observation.levels,
1223
+ source: {
1224
+ kind: "metrics",
1225
+ origin,
1226
+ from,
1227
+ to
1228
+ }
1229
+ };
1230
+ const found = checkWorkload(workload);
1231
+ return found.length > 0 ? err(found) : ok(workload);
1232
+ };
1233
+ // src/limit.ts
1234
+ /** This function gives the amount of a limit at the path `at`, or the problem that stops it. */
1235
+ const amountAt = (limit, instance, at) => {
1236
+ const bad = limitProblems(limit, at)[0];
1237
+ if (bad !== void 0) return err(bad);
1238
+ let ceiling;
1239
+ if (limit.ceiling.kind === "amount") ceiling = limit.ceiling.amount;
1240
+ else {
1241
+ const name = limit.ceiling.resource;
1242
+ if (!Object.hasOwn(instance.resources, name)) return err(limitProblem("resource", `resources.${name}`, `The instance has no resource "${name}" for the limit "${limit.id}".`));
1243
+ const resource = instance.resources[name];
1244
+ if (!isQuantity(resource) || !(resource.value > 0)) return err(limitProblem("resource", `resources.${name}`, `The resource "${name}" of the instance is not a finite amount above 0.`));
1245
+ ceiling = resource;
1246
+ }
1247
+ const amount = scale(ceiling, 1 - limit.headroom);
1248
+ if (!(amount.value > 0) || !finite(amount.value)) {
1249
+ const field = at === "" ? "ceiling" : `${at}.ceiling`;
1250
+ return err(limitProblem("amount", field, `The ceiling of the limit "${limit.id}", less its headroom, is not a finite amount above 0.`));
1251
+ }
1252
+ return ok(amount);
1253
+ };
1254
+ /** This function gives the use of a limit, with the path of the limit and the path of the value for a problem. */
1255
+ const useAt = (limit, instance, value, at, valuePath) => {
1256
+ const amount = amountAt(limit, instance, at);
1257
+ if (amount.tag === "err") return amount;
1258
+ if (!isQuantity(value) || value.value < 0) return err(limitProblem("amount", valuePath, `The value of the measure "${limit.measure}" is not a finite amount of 0 or more.`));
1259
+ if (!convertible(value.unit, amount.value.unit)) {
1260
+ const why = whyNotConvertible(value.unit, amount.value.unit) ?? "the units are different";
1261
+ return err(limitProblem("unit", valuePath, `The measure "${limit.measure}" is in "${value.unit}", and the ceiling of the limit "${limit.id}" is in "${amount.value.unit}": ${why}.`));
1262
+ }
1263
+ const use = valueIn(value, amount.value.unit) / amount.value.value;
1264
+ if (!finite(use)) return err(limitProblem("amount", valuePath, `The value of the measure "${limit.measure}" has no finite use.`));
1265
+ return ok({
1266
+ limit: limit.id,
1267
+ measure: limit.measure,
1268
+ value,
1269
+ amount: amount.value,
1270
+ use,
1271
+ holds: use <= 1
1272
+ });
1273
+ };
1274
+ /**
1275
+ * This function gives the amount of a limit on an instance: the ceiling, less the headroom. It is
1276
+ * the largest value of the measure that holds the limit, in the unit of the ceiling.
1277
+ *
1278
+ * It gives a problem for a limit that is not correct. It gives a problem for a ceiling that names
1279
+ * a resource when the instance does not have that resource.
1280
+ */
1281
+ const limitAmount = (limit, instance) => amountAt(limit, instance, "");
1282
+ /**
1283
+ * This function gives the use of a limit on an instance by one value of its measure. The use is
1284
+ * the value, divided by the amount of the limit. Thus a use of 1 is exactly at the limit.
1285
+ *
1286
+ * It gives each problem of `limitAmount`. It gives a problem for a value that is not a finite
1287
+ * amount of 0 or more. It gives a problem for a value that does not convert to the unit of the ceiling.
1288
+ */
1289
+ const limitUse = (limit, instance, value) => useAt(limit, instance, value, "", "value");
1290
+ /**
1291
+ * This function gives the use of each limit on an instance. The `values` give the value of each
1292
+ * measure, by the id of the measure. The uses go from the largest to the smallest. Thus the first
1293
+ * use is the limit that binds.
1294
+ *
1295
+ * A limit with no value is a problem, and not a limit that holds. The function also gives a
1296
+ * problem for two limits with one id, and each problem of `limitUse`.
1297
+ */
1298
+ const limitUses = (limits, instance, values) => {
1299
+ const twice = repeated(limits.map((limit) => limit.id));
1300
+ if (twice !== void 0) return err(limitProblem("id", "limits", `Two limits have the id "${twice}".`));
1301
+ const uses = [];
1302
+ for (const [index, limit] of limits.entries()) {
1303
+ const at = `limits[${index}]`;
1304
+ if (!Object.hasOwn(values, limit.measure)) return err(limitProblem("measure", `${at}.measure`, `The values give no amount for the measure "${limit.measure}" of the limit "${limit.id}".`));
1305
+ const use = useAt(limit, instance, values[limit.measure], at, `values.${limit.measure}`);
1306
+ if (use.tag === "err") return use;
1307
+ uses.push(use.value);
1308
+ }
1309
+ return ok(uses.sort((a, b) => b.use - a.use));
1310
+ };
1311
+ // src/scale.ts
1312
+ /** This number is the largest count of instances of a scale search when the options give none: 2 to the power 20. */
1313
+ const SCALE_MOST = 2 ** 20;
1314
+ /** This number is the count of steps of the grid of a scale search when the options give none. */
1315
+ const SCALE_STEPS = 128;
1316
+ const problem = (code, path, message) => ({
1317
+ code,
1318
+ path,
1319
+ message
1320
+ });
1321
+ /** This function gives a problem with `owner` in front of its path. */
1322
+ const under = (found, owner) => ({
1323
+ code: found.code,
1324
+ path: `${owner}.${found.path}`,
1325
+ message: found.message
1326
+ });
1327
+ /**
1328
+ * This function gives a problem of a composition of the model, with the path in the model. A path of
1329
+ * the catalog starts with `laws` or `compositions`, and each other path is in the composition.
1330
+ */
1331
+ const inComposition = (found, at) => under(found, /^(laws|compositions)\./.test(found.path) ? "catalog" : `compositions[${at}]`);
1332
+ /** This function gives the setup of a scale query, or the first problem of the model, the demand or the options. */
1333
+ const setupOf = (model, demand, options) => {
1334
+ const level = options.level ?? .95;
1335
+ const most = options.most ?? SCALE_MOST;
1336
+ if (!Number.isSafeInteger(most) || most < 2) return err(problem("factor", "most", `The largest count of the search, ${most}, is not a whole number of 2 or more.`));
1337
+ const badDemand = demandProblems(demand)[0];
1338
+ if (badDemand !== void 0) return err(under(badDemand, "demand"));
1339
+ const whole = options.whole ?? [];
1340
+ const unknown = whole.find((name) => !Object.hasOwn(demand.levels, name));
1341
+ if (unknown !== void 0) return err(problem("variable", "whole", `The demand has no level "${unknown}".`));
1342
+ if (model.limits.length === 0) return err(problem("measure", "limits", "The model has no limit."));
1343
+ const twice = repeated(model.limits.map((limit) => limit.id));
1344
+ if (twice !== void 0) return err(problem("id", "limits", `Two limits have the id "${twice}".`));
1345
+ const byMeasure = /* @__PURE__ */ new Map();
1346
+ for (const [index, composition] of model.compositions.entries()) {
1347
+ const measure = composition.measure.id;
1348
+ if (byMeasure.has(measure)) return err(problem("measure", `compositions[${index}].measure.id`, `Two compositions give the measure "${measure}".`));
1349
+ byMeasure.set(measure, index);
1350
+ }
1351
+ const prepared = /* @__PURE__ */ new Map();
1352
+ const limits = [];
1353
+ for (const [index, limit] of model.limits.entries()) {
1354
+ const path = `limits[${index}]`;
1355
+ const amount = limitAmount(limit, model.instance);
1356
+ if (amount.tag === "err") return err(under(amount.error, amount.error.path.startsWith("resources.") ? "instance" : path));
1357
+ const at = byMeasure.get(limit.measure);
1358
+ if (at === void 0) return err(problem("measure", `${path}.measure`, `The model has no composition of the measure "${limit.measure}" of the limit "${limit.id}".`));
1359
+ const composition = model.compositions[at];
1360
+ let ready = prepared.get(at);
1361
+ if (ready === void 0) {
1362
+ const found = preparedOf(composition, model.catalog, level);
1363
+ if (found.tag === "err") return err(inComposition(found.error, at));
1364
+ ready = found.value;
1365
+ prepared.set(at, ready);
1366
+ }
1367
+ const unit = composition.measure.unit;
1368
+ const ceiling = amount.value;
1369
+ if (!convertible(unit, ceiling.unit)) {
1370
+ const why = whyNotConvertible(unit, ceiling.unit) ?? "the units are different";
1371
+ const message = `The composition of the limit "${limit.id}" gives "${unit}", and the ceiling of the limit is in "${ceiling.unit}": ${why}.`;
1372
+ return err(problem("unit", `compositions[${at}].measure.unit`, message));
1373
+ }
1374
+ limits.push({
1375
+ limit,
1376
+ path,
1377
+ at,
1378
+ prepared: ready,
1379
+ per: factorOf(unit, ceiling.unit) / ceiling.value
1380
+ });
1381
+ }
1382
+ const rows = Math.min(...limits.map((each) => each.prepared.rows));
1383
+ return ok({
1384
+ limits,
1385
+ rows,
1386
+ level,
1387
+ given: options.given ?? {},
1388
+ whole,
1389
+ most,
1390
+ steps: options.steps ?? 128,
1391
+ demand
1392
+ });
1393
+ };
1394
+ /** This function gives the flat parts of the composition of a limit at one load of a path, or undefined when the load has none. */
1395
+ const partsAt = (setup, each, demandAt, load) => {
1396
+ const demand = demandAt(load);
1397
+ if (demand === void 0) return void 0;
1398
+ const parts = flatPartsOf(each.prepared, demand, setup.given);
1399
+ return parts.tag === "ok" ? parts.value : void 0;
1400
+ };
1401
+ /**
1402
+ * This function searches each limit along a path of demands. For each row of each limit, it gives the first load
1403
+ * where the use of the limit is above 1. A load where the composition has no value also breaks the row.
1404
+ * Infinity tells that the row holds the limit on all of the grid.
1405
+ *
1406
+ * A problem of the composition at the start of the search is a problem of the model, and not an edge.
1407
+ */
1408
+ const breaksOf = (setup, grid, demandAt) => {
1409
+ const found = [];
1410
+ const start = grid[0];
1411
+ for (const each of setup.limits) {
1412
+ const demand = demandAt(start);
1413
+ if (demand !== void 0) {
1414
+ const first = flatPartsOf(each.prepared, demand, setup.given);
1415
+ if (first.tag === "err") return err(inComposition(first.error, each.at));
1416
+ }
1417
+ const known = /* @__PURE__ */ new Map();
1418
+ const cached = (load) => {
1419
+ if (!known.has(load)) known.set(load, partsAt(setup, each, demandAt, load));
1420
+ return known.get(load);
1421
+ };
1422
+ const onGrid = new Set(grid);
1423
+ const gridRows = /* @__PURE__ */ new Map();
1424
+ const valueAt = (load, row) => {
1425
+ if (onGrid.has(load)) {
1426
+ if (!gridRows.has(load)) {
1427
+ const parts = cached(load);
1428
+ gridRows.set(load, parts === void 0 ? void 0 : rowValuesOf(parts, 0, setup.rows));
1429
+ }
1430
+ return gridRows.get(load)?.[row];
1431
+ }
1432
+ const parts = cached(load);
1433
+ return parts === void 0 ? void 0 : rowValueOf(parts, row);
1434
+ };
1435
+ const rows = [];
1436
+ let edge = false;
1437
+ for (let row = 0; row <= setup.rows; row += 1) {
1438
+ const curve = (loads) => loads.map((load) => {
1439
+ const value = valueAt(load, row);
1440
+ return value === void 0 ? void 0 : each.per * value;
1441
+ });
1442
+ const result = rowOf(curve, `${each.path}.rows[${row}]`, amountTest(1), grid, 0, "composition");
1443
+ if (result.tag === "err") return result;
1444
+ const crossing = result.value.crossing ?? 1e400;
1445
+ if (row === 0) edge = result.value.edge <= crossing && Number.isFinite(result.value.edge);
1446
+ rows.push(Math.min(crossing, result.value.edge));
1447
+ }
1448
+ found.push({
1449
+ rows,
1450
+ edge
1451
+ });
1452
+ }
1453
+ return ok(found);
1454
+ };
1455
+ /** This function gives the index of the least finite value, the first on a tie, or null when no value is finite. */
1456
+ const leastOf = (values) => {
1457
+ let best = null;
1458
+ for (const [index, value] of values.entries()) if (Number.isFinite(value) && (best === null || value < values[best])) best = index;
1459
+ return best;
1460
+ };
1461
+ /** This function joins the rows of the limits. Each row breaks at the first load where one of its limits breaks. */
1462
+ const summaryOf = (breaks, rows) => {
1463
+ const joined = [];
1464
+ const counts = new Array(breaks.length).fill(0);
1465
+ for (let row = 0; row <= rows; row += 1) {
1466
+ const loads = breaks.map((each) => each.rows[row]);
1467
+ const first = leastOf(loads);
1468
+ joined.push(first === null ? 1e400 : loads[first]);
1469
+ if (row > 0 && first !== null) counts[first] = counts[first] + 1;
1470
+ }
1471
+ const estimate = breaks.map((each) => each.rows[0]);
1472
+ const order = estimate.map((_, index) => index).sort((a, b) => estimate[a] - estimate[b] || a - b);
1473
+ return {
1474
+ rows: joined,
1475
+ binding: leastOf(estimate),
1476
+ binds: counts.map((count) => count / rows),
1477
+ order
1478
+ };
1479
+ };
1480
+ /** This function tells if a law of the composition of a limit reads a variable outside its range at one load of a path. */
1481
+ const outsideAt = (setup, each, demandAt, load) => {
1482
+ const parts = partsAt(setup, each, demandAt, load);
1483
+ return parts !== void 0 && partsOutside(parts);
1484
+ };
1485
+ /** This function gives the reach of a count of instances from the breaks of each limit along the factor of the demand. */
1486
+ const reachFrom = (setup, count, breaks, outside) => {
1487
+ const { most, level } = setup;
1488
+ const summary = summaryOf(breaks, setup.rows);
1489
+ const at = (value) => value ?? most;
1490
+ const limits = summary.order.map((index) => {
1491
+ const each = setup.limits[index];
1492
+ const found = breaks[index];
1493
+ const factor = openValueOf(found.rows, level, most);
1494
+ return {
1495
+ limit: each.limit.id,
1496
+ measure: each.limit.measure,
1497
+ factor,
1498
+ binds: summary.binds[index],
1499
+ edge: found.edge,
1500
+ extrapolated: outside(each, at(factor.value))
1501
+ };
1502
+ });
1503
+ const factor = openValueOf(summary.rows, level, most);
1504
+ return {
1505
+ count,
1506
+ level,
1507
+ search: {
1508
+ low: 1 / most,
1509
+ high: most
1510
+ },
1511
+ factor,
1512
+ binding: summary.binding === null ? null : setup.limits[summary.binding].limit.id,
1513
+ extrapolated: setup.limits.some((each) => outside(each, at(factor.value))),
1514
+ limits
1515
+ };
1516
+ };
1517
+ /** This function gives the reach of a count of instances, from a correct setup. */
1518
+ const reachOf = (setup, count) => {
1519
+ const { most, whole } = setup;
1520
+ const grid = searchGrid(1 / most, most, setup.steps, true, "The factor of the demand");
1521
+ if (grid.tag === "err") return grid;
1522
+ const demandAt = (factor) => {
1523
+ const portion = portionOf(setup.demand, factor / count, factor, whole);
1524
+ return portion.tag === "ok" ? portion.value : void 0;
1525
+ };
1526
+ const breaks = breaksOf(setup, grid.value, demandAt);
1527
+ if (breaks.tag === "err") return breaks;
1528
+ return ok(reachFrom(setup, count, breaks.value, (each, factor) => outsideAt(setup, each, demandAt, factor)));
1529
+ };
1530
+ /**
1531
+ * This function gives the highest load that a count of instances holds, as a factor of the demand,
1532
+ * with an interval. Thus it is the inverse query of the scale rule. The demand divides between the
1533
+ * instances, as in `shareOf`, and the levels in `options.whole` do not divide.
1534
+ *
1535
+ * Each row of the doubt of the laws has its own search. Row `i` of each limit reads row `i` of each
1536
+ * law, thus the rows of the limits pair. The factor of a row is the first factor where one limit
1537
+ * of the row breaks, or where a composition has no value. The interval is the share `level` of the
1538
+ * factors of the replicates, made wider to hold the factor of the estimate.
1539
+ *
1540
+ * The search tests a grid of factors, then a bisection finds each crossing. A crossing between two
1541
+ * loads of the grid is found. Two crossings in one step of the grid can hide the first.
1542
+ *
1543
+ * The function gives a problem for a model, a demand or options that are not correct. It gives a
1544
+ * problem for a count that is not a whole number of 1 or more. It also gives a problem when a
1545
+ * composition has no value at the start of the search.
1546
+ */
1547
+ const countReach = (model, count, demand, options = {}) => {
1548
+ const setup = setupOf(model, demand, options);
1549
+ if (setup.tag === "err") return setup;
1550
+ if (!Number.isSafeInteger(count) || count < 1) return err(problem("factor", "count", `The count of instances ${count} is not a whole number of 1 or more.`));
1551
+ return reachOf(setup.value, count);
1552
+ };
1553
+ /** This function gives the lowest count of instances for a share of one instance where a limit breaks. A null count is more than `most`. */
1554
+ const countAt = (share, most) => {
1555
+ if (share === null) return 1;
1556
+ const count = Math.floor(1 / share) + 1;
1557
+ return count > most ? null : count;
1558
+ };
1559
+ /** This function changes an open value of the share of one instance to an open value of the count. The ends change places. */
1560
+ const countsOf = (share, most) => ({
1561
+ value: countAt(share.value, most),
1562
+ interval: {
1563
+ low: countAt(share.interval.high, most),
1564
+ high: countAt(share.interval.low, most)
1565
+ }
1566
+ });
1567
+ /**
1568
+ * This function gives the scale rule of a service at a load: the lowest count of instances that
1569
+ * holds each limit, with an interval. It also gives the limit that binds first, and the load of the
1570
+ * next step: the highest load of that count, from `countReach`.
1571
+ *
1572
+ * The search goes along the share of the demand on one instance: the share of `n` instances is
1573
+ * `1 / n`. It starts at the share of `most` instances and goes up to the share of one instance. The
1574
+ * count of a row comes from the first share where one limit of the row breaks. Thus the count holds
1575
+ * each limit, and each larger count also holds each limit. A level in `options.whole` does not divide.
1576
+ *
1577
+ * Each row of the doubt of the laws has its own search, and the rows of the limits pair, as in
1578
+ * `countReach`. The interval of the count is the share `level` of the counts of the replicates, made
1579
+ * wider to hold the count of the estimate. The field `binds` of each limit is the share of the
1580
+ * replicates where that limit sets the count.
1581
+ *
1582
+ * The function gives each problem of `countReach` that is not about a count.
1583
+ */
1584
+ const scaleRule = (model, demand, options = {}) => {
1585
+ const setup = setupOf(model, demand, options);
1586
+ if (setup.tag === "err") return setup;
1587
+ const { most, whole } = setup.value;
1588
+ const grid = searchGrid(1 / most, 1, setup.value.steps, true, "The share of one instance");
1589
+ if (grid.tag === "err") return grid;
1590
+ const demandAt = (share) => {
1591
+ const portion = portionOf(setup.value.demand, share, 1, whole);
1592
+ return portion.tag === "ok" ? portion.value : void 0;
1593
+ };
1594
+ const breaks = breaksOf(setup.value, grid.value, demandAt);
1595
+ if (breaks.tag === "err") return breaks;
1596
+ return ruleFrom(setup.value, breaks.value, (each, share) => outsideAt(setup.value, each, demandAt, share), (count) => reachOf(setup.value, count));
1597
+ };
1598
+ /** This function gives the scale rule from the breaks of each limit along the share of one instance, and the reach of a count. */
1599
+ const ruleFrom = (setup, breaks, outside, reachAt) => {
1600
+ const { most, level } = setup;
1601
+ const summary = summaryOf(breaks, setup.rows);
1602
+ const shareOfCount = (count) => 1 / (count ?? most);
1603
+ const limits = summary.order.map((index) => {
1604
+ const each = setup.limits[index];
1605
+ const found = breaks[index];
1606
+ const count = countsOf(openValueOf(found.rows, level, 1), most);
1607
+ return {
1608
+ limit: each.limit.id,
1609
+ measure: each.limit.measure,
1610
+ count,
1611
+ binds: summary.binds[index],
1612
+ edge: found.edge,
1613
+ extrapolated: outside(each, shareOfCount(count.value))
1614
+ };
1615
+ });
1616
+ const count = countsOf(openValueOf(summary.rows, level, 1), most);
1617
+ let next = null;
1618
+ if (count.value !== null) {
1619
+ const reach = reachAt(count.value);
1620
+ if (reach.tag === "err") return reach;
1621
+ next = reach.value;
1622
+ }
1623
+ return ok({
1624
+ level,
1625
+ most,
1626
+ count,
1627
+ binding: summary.binding === null ? null : setup.limits[summary.binding].limit.id,
1628
+ extrapolated: setup.limits.some((each) => outside(each, shareOfCount(count.value))),
1629
+ limits,
1630
+ next
1631
+ });
1632
+ };
1633
+ /**
1634
+ * This function changes the loads on one instance of a ladder to the loads of a search from `low` to `high`. A load
1635
+ * past `high` holds on all of that search, and a load before `low` breaks at its start, as in `rowOf`.
1636
+ */
1637
+ const loadsIn = (rows, times, low, high) => rows.map((load) => {
1638
+ const found = load * times;
1639
+ return found > high ? 1e400 : Math.max(found, low);
1640
+ });
1641
+ /**
1642
+ * This function gives the scale ladder of a service over the factors of the demand from `range.low` to `range.high`.
1643
+ * The search covers the loads on one instance that `scaleRule` and `countReach` read at each factor of the range: from
1644
+ * `range.low / most` to `range.high * most`. Its grid has the density of the grid of `scaleRule`, up to the largest
1645
+ * count of steps.
1646
+ *
1647
+ * The values of the ladder agree with `scaleRule` and `countReach` to the precision of their bisections. They can differ
1648
+ * when two crossings are in one step of a grid, because the grids are different.
1649
+ *
1650
+ * The function gives each problem of `scaleRule`. It also gives a problem for a level in `options.whole`. With such a level,
1651
+ * the demand on one instance does not depend only on the load over the count. It gives a problem for a range that does not
1652
+ * go from a number above 0 to a larger finite number.
1653
+ */
1654
+ const scaleLadder = (model, demand, range, options = {}) => {
1655
+ const found = setupOf(model, demand, options);
1656
+ if (found.tag === "err") return found;
1657
+ const setup = found.value;
1658
+ if (setup.whole.length > 0) return err(problem("variable", "whole", "A ladder needs a demand that divides between the instances. Use scaleRule for a level in whole."));
1659
+ if (!(range.low > 0 && Number.isFinite(range.high) && range.low < range.high)) return err(problem("factor", "range", `The range goes from ${range.low} to ${range.high}. It must go from a number above 0 to a larger finite number.`));
1660
+ const { most, level } = setup;
1661
+ const search = {
1662
+ low: range.low / most,
1663
+ high: range.high * most
1664
+ };
1665
+ const steps = Math.min(MAX_STEPS, Math.max(setup.steps, Math.ceil(setup.steps * Math.log(search.high / search.low) / Math.log(most))));
1666
+ const grid = searchGrid(search.low, search.high, steps, true, "The load on one instance");
1667
+ if (grid.tag === "err") return grid;
1668
+ const demandAt = (load) => {
1669
+ const portion = portionOf(setup.demand, load, load, []);
1670
+ return portion.tag === "ok" ? portion.value : void 0;
1671
+ };
1672
+ const breaks = breaksOf(setup, grid.value, demandAt);
1673
+ if (breaks.tag === "err") return breaks;
1674
+ const ladder = breaks.value;
1675
+ const outsideOn = (each, load) => outsideAt(setup, each, demandAt, load);
1676
+ const inRange = (factor) => factor >= range.low && factor <= range.high ? ok(factor) : err(problem("factor", "factor", `The factor ${factor} is outside the range of the ladder, from ${range.low} to ${range.high}.`));
1677
+ /** This function gives the breaks of each limit along the factor of a search from `low` to `high`. The load on one instance is `times` the factor. */
1678
+ const breaksIn = (times, low, high) => ladder.map((each) => {
1679
+ const rows = loadsIn(each.rows, 1 / times, low, high);
1680
+ return {
1681
+ rows,
1682
+ edge: each.edge && Number.isFinite(rows[0])
1683
+ };
1684
+ });
1685
+ const reachIn = (count, factor) => reachFrom(setup, count, breaksIn(factor / count, 1 / most, most), (each, at) => outsideOn(each, factor * at / count));
1686
+ const reachAt = (count, factor) => {
1687
+ if (!Number.isSafeInteger(count) || count < 1) return err(problem("factor", "count", `The count of instances ${count} is not a whole number of 1 or more.`));
1688
+ const at = inRange(factor);
1689
+ return at.tag === "err" ? at : ok(reachIn(count, factor));
1690
+ };
1691
+ const ruleAt = (factor) => {
1692
+ const at = inRange(factor);
1693
+ if (at.tag === "err") return at;
1694
+ return ruleFrom(setup, breaksIn(factor, 1 / most, 1), (each, share) => outsideOn(each, factor * share), (count) => ok(reachIn(count, factor)));
1695
+ };
1696
+ const limits = setup.limits.map((each, index) => ({
1697
+ limit: each.limit.id,
1698
+ measure: each.limit.measure,
1699
+ ...ladder[index]
1700
+ }));
1701
+ return ok({
1702
+ level,
1703
+ most,
1704
+ range,
1705
+ search,
1706
+ limits,
1707
+ ruleAt,
1708
+ reachAt
1709
+ });
1710
+ };
1711
+ export { APP_FILE, APP_FORMAT, APP_LINE_KINDS, COMPOSITION_FORMAT, DEFAULT_LEVEL, FORMS, FORM_VARIABLE, GATE_ALPHA, GATE_JOBS, INSTANCE_FORMAT, KNEE_STEPS, LAW_FORMAT, LIMITS_FORMAT, MAX_VARIABLES, NAME, NO_DEMAND, RATE, RESOURCE_UNITS, SCALE_MOST, SCALE_STEPS, SLUG, WORKLOAD_FORMAT, appWorkloadProblems, bootstrapDraws, catalogForm, checkApp, checkComposition, checkInstance, checkLaw, checkLimits, checkWorkload, compositionValue, constantIdsOf, constantIntervals, countReach, counterIncrease, demandProblems, fillPlaceholders, fitLaw, formOf, formSlopes, formValues, gridOf, instancePointOf, instanceProblems, isHttps, isLawTerm, kneeRuleProblem, lawGate, lawKnee, lawReach, lawRead, lawValue, leastCount, leastGroups, limitAmount, limitProblems, limitUse, limitUses, loadPointOf, mergeDemands, metricsGaps, observationOf, observedWorkload, placeholdersOf, programOf, requestPath, scaleDemand, scaleLadder, scaleRule, separableOf, shareOf, slopeOf, startOf, totalRate };
1712
+
1713
+ //# sourceMappingURL=index.js.map