@mark1russell7/harness 0.16.17 → 0.16.19

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.
@@ -1,4 +1,7 @@
1
- import { valueIn } from "@mark1russell7/quantity";
1
+ import { quantity, valueIn } from "@mark1russell7/quantity";
2
+ import { rungVerdict } from "@mark1russell7/rigor-bench";
3
+ import { closedLoopPlan, measureLoad, schedule, scheduleHeld } from "@mark1russell7/rigor-chaos";
4
+ import { quantile } from "@mark1russell7/rigor-statistics";
2
5
  import { setTimeout } from "node:timers/promises";
3
6
  import { createHash } from "node:crypto";
4
7
  import { execFile } from "node:child_process";
@@ -9,6 +12,686 @@ import { createRequire } from "node:module";
9
12
  import { fileURLToPath } from "node:url";
10
13
  import { isDeepStrictEqual } from "node:util";
11
14
  import semver from "semver";
15
+ // src/load.ts
16
+ /**
17
+ * The measure and the verdict of an open-loop cell (SYS-68). A client on a schedule sends each
18
+ * arrival at its time, thus a stall counts in each arrival that it delayed. The package rigor-chaos
19
+ * counts each latency from the planned time. The package rigor-bench judges a quantile by a
20
+ * distribution-free interval.
21
+ */
22
+ /** This path is where the client of an open-loop cell finds its schedule. */
23
+ const SCHEDULE_PATH = "/tmp/schedule.json";
24
+ /** This function gives the time of a line of the client, in ms from the start of the schedule. */
25
+ const fromStart = (start, t) => (t - start) / 1e6;
26
+ /**
27
+ * This function gives the measure of one run of a schedule from the lines of its client. It gives
28
+ * null when the client did not start the schedule. The first `sent` line of a client is its request
29
+ * before `ready`, and it names no arrival. The end of the run is its last line.
30
+ */
31
+ const loadOf = (events, plan) => {
32
+ const start = events.find((event) => event.ev === "scheduled")?.t;
33
+ if (start === void 0) return null;
34
+ return measureOf(events, start, plan, void 0);
35
+ };
36
+ /** This function tells if a status of a reply is a failure: a number outside 200 to 299. */
37
+ const failedStatus = (status) => typeof status === "number" && (status < 200 || status > 299);
38
+ /**
39
+ * This function gives the measure of the arrivals of one stream: the lines with the key `key`, or
40
+ * each line for no key. A `sent` line of a pool or of a fresh stream gives the time that its arrival
41
+ * waited for a connection, in ns (`wait`). The lag of such an arrival does not count that wait, but
42
+ * its latency still counts from its planned time.
43
+ */
44
+ const measureOf = (events, start, plan, key) => {
45
+ const sent = /* @__PURE__ */ new Map();
46
+ const done = /* @__PURE__ */ new Map();
47
+ const waits = /* @__PURE__ */ new Map();
48
+ let failed = 0;
49
+ for (const event of events) {
50
+ const index = event["i"];
51
+ if (typeof index !== "number" || key !== void 0 && event["k"] !== key) continue;
52
+ if (event.ev === "sent") {
53
+ sent.set(index, fromStart(start, event.t));
54
+ const wait = event["wait"];
55
+ if (typeof wait === "number" && wait > 0) waits.set(index, wait / 1e6);
56
+ }
57
+ if (event.ev === "replied") {
58
+ done.set(index, fromStart(start, event.t));
59
+ if (failedStatus(event["status"])) failed += 1;
60
+ }
61
+ }
62
+ const completions = [...sent].map(([index, at]) => ({
63
+ index,
64
+ sent: at,
65
+ done: done.get(index) ?? null
66
+ }));
67
+ const end = events.reduce((latest, event) => Math.max(latest, fromStart(start, event.t)), 0);
68
+ const measure = measureLoad(plan, completions, end);
69
+ if (waits.size === 0) return {
70
+ ...measure,
71
+ failed
72
+ };
73
+ const lag = plan.times.flatMap((planned, index) => {
74
+ const at = sent.get(index);
75
+ return at === void 0 ? [] : [at - (waits.get(index) ?? 0) - planned];
76
+ });
77
+ return {
78
+ ...measure,
79
+ lag,
80
+ failed
81
+ };
82
+ };
83
+ /** This path is where the client `load` finds its plan. */
84
+ const LOAD_PATH = "/tmp/load.json";
85
+ /** This text is the format of the plan of the client `load`. */
86
+ const LOAD_FORMAT = "systems-load/1";
87
+ /** This count is the most connections of the pool of one stream of the client `load`. */
88
+ const LOAD_POOL_LIMIT = 1024;
89
+ /**
90
+ * This function gives each problem of the connections of one load stream. An empty list means that
91
+ * the client `load` can use them. The size of a pool is a whole number from 1 to `LOAD_POOL_LIMIT`.
92
+ */
93
+ const connectionsProblems = (connections) => {
94
+ const fields = connections;
95
+ const mode = fields["mode"];
96
+ if (mode === "pipeline" || mode === "fresh") return [];
97
+ if (mode !== "pool") return [`the connections have the mode ${String(mode)}: the mode is pipeline, pool or fresh`];
98
+ const size = fields["size"];
99
+ return typeof size === "number" && Number.isInteger(size) && size >= 1 && size <= 1024 ? [] : [`the pool has the size ${String(size)}: a whole number from 1 to ${LOAD_POOL_LIMIT}`];
100
+ };
101
+ /**
102
+ * This function gives the lines that end the wait of a run for the client `load` or `schedule`.
103
+ * Without streams, the end of the one connection ends the run.
104
+ * With streams, the client `load` writes `done` when each stream can do no more, also after an error.
105
+ * The end of one connection does not end the other streams, thus only `done`, `deadline` and `fail` end the wait.
106
+ */
107
+ const loadEnds = (streams) => streams === void 0 || streams.length === 0 ? [
108
+ "done",
109
+ "error",
110
+ "eof",
111
+ "deadline"
112
+ ] : [
113
+ "done",
114
+ "deadline",
115
+ "fail"
116
+ ];
117
+ /**
118
+ * This function gives the schedule of each stream of a cell, and the text of the plan of the client
119
+ * `load`. It throws for no stream, for two streams with one key and for a stream with no request.
120
+ * It also throws for a bad value of the connections of a stream. A stream with no connections has
121
+ * no such field in the plan.
122
+ */
123
+ const loadPlanOf = (streams) => {
124
+ if (streams.length === 0) throw new RangeError("a plan of the client load has no stream");
125
+ const keys = /* @__PURE__ */ new Set();
126
+ for (const stream of streams) {
127
+ if (keys.has(stream.key)) throw new RangeError(`two streams have the key ${stream.key}`);
128
+ if (stream.requests.length === 0) throw new RangeError(`the stream ${stream.key} has no request`);
129
+ const problem = stream.connections === void 0 ? void 0 : connectionsProblems(stream.connections)[0];
130
+ if (problem !== void 0) throw new RangeError(`the stream ${stream.key}: ${problem}`);
131
+ keys.add(stream.key);
132
+ }
133
+ const scheduled = streams.map((stream) => ({
134
+ key: stream.key,
135
+ schedule: schedule(stream.plan.profile, stream.plan.options),
136
+ requests: stream.requests,
137
+ ...stream.connections === void 0 ? {} : { connections: stream.connections }
138
+ }));
139
+ return {
140
+ streams: scheduled.map(({ key, schedule: each }) => ({
141
+ key,
142
+ schedule: each
143
+ })),
144
+ content: JSON.stringify({
145
+ format: LOAD_FORMAT,
146
+ streams: scheduled
147
+ })
148
+ };
149
+ };
150
+ /**
151
+ * This function gives the measure of each stream of a run of the client `load`, and their pool. Each
152
+ * stream counts its arrivals from 0, thus the lines of a stream are the lines with its key. The pool
153
+ * sums the counts and joins the times, in the order of the streams. It gives null when the client did
154
+ * not start its schedule.
155
+ */
156
+ const streamsLoadOf = (events, streams) => {
157
+ const start = events.find((event) => event.ev === "scheduled")?.t;
158
+ if (start === void 0) return null;
159
+ const each = streams.map((stream) => [stream.key, measureOf(events, start, stream.schedule, stream.key)]);
160
+ return {
161
+ pool: poolOf(each.map(([, measure]) => measure)),
162
+ streams: Object.fromEntries(each)
163
+ };
164
+ };
165
+ /** This function gives the pool of some measures: it sums the counts and joins the times, in the order of the measures. */
166
+ const poolOf = (measures) => {
167
+ const sum = (count) => measures.reduce((total, measure) => total + count(measure), 0);
168
+ const join = (times) => measures.flatMap(times);
169
+ return {
170
+ planned: sum((measure) => measure.planned),
171
+ unsent: sum((measure) => measure.unsent),
172
+ unfinished: sum((measure) => measure.unfinished),
173
+ failed: sum((measure) => measure.failed ?? 0),
174
+ latency: join((measure) => measure.latency),
175
+ service: join((measure) => measure.service),
176
+ lag: join((measure) => measure.lag),
177
+ censored: join((measure) => measure.censored)
178
+ };
179
+ };
180
+ /**
181
+ * This time is the tolerance of a closed-loop estimate, in ms. A send later than its expected time
182
+ * by more than this tolerance is a pause of the client: a driver gap.
183
+ */
184
+ const CLOSED_TOLERANCE = 5;
185
+ /**
186
+ * This function gives the estimate of one closed-loop stream from its requests, in the order of their
187
+ * sends. Each time is a time of a line of the client. The client waits `interval` ms after each reply,
188
+ * thus the interval is also the pause of the driver. The function gives undefined for no request, and
189
+ * for a request with no reply before the last request.
190
+ */
191
+ const estimateOf = (requests, end, interval) => {
192
+ const start = requests[0]?.sent;
193
+ if (start === void 0 || requests.slice(0, -1).some((request) => request.done === null)) return void 0;
194
+ const loop = requests.map((request) => ({
195
+ sent: fromStart(start, request.sent),
196
+ done: request.done === null ? null : fromStart(start, request.done)
197
+ }));
198
+ const stop = Math.max(fromStart(start, end), ...loop.map((request) => request.done ?? request.sent), interval);
199
+ const run = closedLoopPlan(loop, {
200
+ interval,
201
+ end: stop,
202
+ tolerance: 5,
203
+ pause: interval
204
+ });
205
+ return {
206
+ ...measureLoad(run.plan, run.completions, stop),
207
+ hidden: run.hidden,
208
+ driverGaps: run.driverGaps,
209
+ driverGapTotal: run.driverGapTotal
210
+ };
211
+ };
212
+ /** This function gives the spread of a list of times in ms, or null for no time. */
213
+ const spreadOf = (values) => values.length === 0 ? null : {
214
+ p50: quantity(quantile(values, .5, "nearest-rank"), "ms"),
215
+ p99: quantity(quantile(values, .99, "nearest-rank"), "ms"),
216
+ max: quantity(values.reduce((most, value) => Math.max(most, value), 0), "ms")
217
+ };
218
+ /** This time is the date of the record of a band and the date of its verdict. The record has no age, because it comes from this run. */
219
+ const NOW = "2026-01-01T00:00:00.000Z";
220
+ /**
221
+ * This function judges one band of the latency over the pooled arrivals of the counted runs. The
222
+ * top of the band reads the interval of rigor-bench: the band holds only if the interval is under its top.
223
+ * The latencies of one run can follow each other, thus the width of the interval is an estimate.
224
+ * The bottom of the band reads the quantile itself. It gives the text of the verdict, and if it holds.
225
+ */
226
+ const bandVerdict = (band, values, censored) => {
227
+ const high = valueIn(band.high, "ms");
228
+ const rung = {
229
+ name: "band",
230
+ at: {},
231
+ budgets: [{
232
+ kind: "quantile",
233
+ measure: "latency",
234
+ unit: "ms",
235
+ quantile: band.quantile,
236
+ limit: high
237
+ }],
238
+ test: "the cell"
239
+ };
240
+ const top = rungVerdict(rung, {
241
+ rung: "band",
242
+ commit: "the cell",
243
+ at: NOW,
244
+ real: ["the counted runs"],
245
+ synthetic: [],
246
+ evidence: [{
247
+ kind: "quantile",
248
+ measure: "latency",
249
+ values,
250
+ censored
251
+ }]
252
+ }, { now: NOW });
253
+ const read = values.length + censored.length === 0 ? null : quantile([...values, ...censored], band.quantile, "nearest-rank");
254
+ const low = band.low === void 0 ? null : valueIn(band.low, "ms");
255
+ const above = low === null || read !== null && read >= low;
256
+ const place = low === null ? `under ${high} ms` : `in [${low}, ${high}] ms`;
257
+ const outcome = top.outcome === "within" && !above ? "under the bottom of the band" : top.outcome;
258
+ return {
259
+ holds: top.outcome === "within" && above,
260
+ words: `p${band.quantile * 100} of the latency ${read === null ? "has no value" : `is ${read} ms`}, wanted ${place}: ${outcome}. ${top.reason}`
261
+ };
262
+ };
263
+ /**
264
+ * This function judges the share of failed arrivals over the counted runs against a limit. Each
265
+ * planned arrival is a trial. An arrival fails if the client did not send it. It also fails with no
266
+ * reply at the end of its run, or with the status of a failure. The rate budget of rigor-bench
267
+ * reads the upper end of the Wilson interval at 0.95. Thus 381 arrivals with no failure hold a limit
268
+ * of 1 %, and fewer arrivals cannot decide.
269
+ */
270
+ const failuresVerdict = (limit, failures, trials) => {
271
+ const verdict = rungVerdict({
272
+ name: "failures",
273
+ at: {},
274
+ budgets: [{
275
+ kind: "rate",
276
+ measure: "failures",
277
+ limit
278
+ }],
279
+ test: "the cell"
280
+ }, {
281
+ rung: "failures",
282
+ commit: "the cell",
283
+ at: NOW,
284
+ real: ["the counted runs"],
285
+ synthetic: [],
286
+ evidence: [{
287
+ kind: "rate",
288
+ measure: "failures",
289
+ failures,
290
+ trials
291
+ }]
292
+ }, { now: NOW });
293
+ return {
294
+ holds: verdict.outcome === "within",
295
+ words: `${failures} of ${trials} arrivals failed, wanted a share under ${limit * 100} %: ${verdict.outcome}. ${verdict.reason}`
296
+ };
297
+ };
298
+ /**
299
+ * This function judges the load of an open-loop cell over its counted runs. A run that did not keep
300
+ * its schedule measures its driver, not the target, thus it is a finding of that run. Each
301
+ * band reads all the arrivals of the counted runs.
302
+ */
303
+ const loadVerdict = (prediction, runs) => {
304
+ const limit = valueIn(prediction.lag, "ms");
305
+ const outside = runs.flatMap((run) => {
306
+ if (run.load === void 0) return [{
307
+ run: run.name,
308
+ why: "the client never started its schedule"
309
+ }];
310
+ const check = scheduleHeld(run.load, limit);
311
+ return check.held ? [] : [{
312
+ run: run.name,
313
+ why: check.reason
314
+ }];
315
+ });
316
+ const measures = runs.flatMap((run) => run.load === void 0 ? [] : [run.load]);
317
+ const latency = measures.flatMap((measure) => measure.latency);
318
+ const censored = measures.flatMap((measure) => measure.censored);
319
+ const bands = prediction.bands.map((band) => bandVerdict(band, latency, censored));
320
+ const total = (count) => measures.reduce((sum, measure) => sum + count(measure), 0);
321
+ const planned = total((measure) => measure.planned);
322
+ const unsent = total((measure) => measure.unsent);
323
+ const unfinished = total((measure) => measure.unfinished);
324
+ const failed = total((measure) => measure.failed ?? 0);
325
+ const failures = prediction.failures === void 0 ? void 0 : failuresVerdict(prediction.failures, unsent + unfinished + failed, planned);
326
+ return {
327
+ holds: runs.length > 0 && outside.length === 0 && bands.every((band) => band.holds) && (failures?.holds ?? true),
328
+ outside,
329
+ load: {
330
+ planned,
331
+ unsent,
332
+ unfinished,
333
+ failed,
334
+ latency: spreadOf([...latency, ...censored]),
335
+ service: spreadOf(measures.flatMap((measure) => measure.service)),
336
+ lag: spreadOf(measures.flatMap((measure) => measure.lag.map((lag) => Math.abs(lag)))),
337
+ bands: bands.map((band) => band.words),
338
+ ...failures === void 0 ? {} : { failures: failures.words }
339
+ }
340
+ };
341
+ };
342
+ /** This function gives the estimate verdict of the counted runs, or undefined when no run has an estimate. */
343
+ const estimateVerdict = (estimates) => {
344
+ const runs = estimates.filter((estimate) => estimate !== void 0);
345
+ if (runs.length === 0) return void 0;
346
+ const pool = poolOf(runs);
347
+ const total = (count) => runs.reduce((sum, estimate) => sum + count(estimate), 0);
348
+ const hidden = total((estimate) => estimate.hidden);
349
+ const driverGaps = total((estimate) => estimate.driverGaps);
350
+ const driverGapTotal = total((estimate) => estimate.driverGapTotal);
351
+ const latency = spreadOf([...pool.latency, ...pool.censored]);
352
+ const seconds = (time) => (valueIn(time, "ms") / 1e3).toFixed(3);
353
+ const spread = latency === null ? "no latency" : `median ${seconds(latency.p50)} s, p99 ${seconds(latency.p99)} s, slowest ${seconds(latency.max)} s`;
354
+ const gaps = driverGaps === 0 ? "no pause of the client" : `${driverGaps} pauses of the client, ${Math.round(driverGapTotal)} ms in all`;
355
+ return {
356
+ planned: pool.planned,
357
+ hidden,
358
+ driverGaps,
359
+ driverGapTotal: quantity(driverGapTotal, "ms"),
360
+ latency,
361
+ words: `The estimate of the open loop puts back ${hidden} hidden sends, with ${gaps}: ${spread}.`
362
+ };
363
+ };
364
+ // src/resources.ts
365
+ /**
366
+ * The resources that one container of a lab used. A reader in a sidecar reads the files of the
367
+ * cgroup of the container and the devices of its network namespace (`RESOURCES_PROGRAM`). It
368
+ * writes the text of each file in one JSON line, with a stamp on CLOCK_MONOTONIC. This module reads
369
+ * each file from that line, and it gives the change between two readings.
370
+ *
371
+ * A file that the reader cannot read gives null: no read. It does not give a zero.
372
+ */
373
+ /** This name is the event of a line of the reader. */
374
+ const RESOURCES_EVENT = "resources";
375
+ /** This path is the reader of the resources, in the image of the harness. */
376
+ const RESOURCES_PROGRAM = "/opt/harness/resources";
377
+ /** This count is the smallest CPU limit that Docker takes, in CPUs. */
378
+ const LEAST_CPUS = .01;
379
+ /** This amount is the smallest memory limit that Docker takes, in bytes: 6 MiB. */
380
+ const LEAST_MEMORY = 6291456;
381
+ /** This function gives the bytes of a memory limit, or null for an amount that is not a count of bytes. */
382
+ const bytesOf = (memory) => {
383
+ try {
384
+ const bytes = Math.round(valueIn(memory, "B"));
385
+ return Number.isSafeInteger(bytes) ? bytes : null;
386
+ } catch {
387
+ return null;
388
+ }
389
+ };
390
+ /** This function tells that a text is a list of CPUs, as `cpuset.cpus` takes it: `0`, `2-3` or `0,2`. */
391
+ const isCpuList = (text) => /^\d+(-\d+)?(,\d+(-\d+)?)*$/.test(text) && text.split(",").every((range) => {
392
+ const [first, last] = range.split("-").map(Number);
393
+ return last === void 0 || first <= last;
394
+ });
395
+ /** This function gives the problems of the limits of a container, each as a sentence. Limits with no problem give an empty list. */
396
+ const limitsProblems = (limits) => {
397
+ const problems = [];
398
+ const { cpus, cpuset, memory } = limits;
399
+ if (cpus !== void 0 && !(Number.isFinite(cpus) && cpus >= LEAST_CPUS)) problems.push(`cpus is ${cpus}: Docker takes ${LEAST_CPUS} CPUs or more`);
400
+ if (cpuset !== void 0 && !isCpuList(cpuset)) problems.push(`cpuset is "${cpuset}": write a list of CPUs, for example 0, 2-3 or 0,2`);
401
+ if (memory !== void 0) {
402
+ const bytes = bytesOf(memory);
403
+ if (bytes === null) problems.push(`memory is ${memory.value} ${memory.unit}: write an amount of data, for example 512 MiB`);
404
+ else if (bytes < LEAST_MEMORY) problems.push(`memory is ${bytes} B: Docker takes 6 MiB or more`);
405
+ }
406
+ return problems;
407
+ };
408
+ /**
409
+ * This function gives the limits of a container as Docker takes them: the CPU quota, the CPUs and
410
+ * the memory, with no swap. It throws for limits that have a problem (`limitsProblems`).
411
+ */
412
+ const hostLimitsOf = (limits) => {
413
+ const problems = limitsProblems(limits);
414
+ if (problems.length > 0) throw new RangeError(`the limits of a container: ${problems.join("; ")}`);
415
+ const bytes = limits.memory === void 0 ? null : bytesOf(limits.memory);
416
+ return {
417
+ ...limits.cpus === void 0 ? {} : { NanoCpus: Math.round(limits.cpus * 1e9) },
418
+ ...limits.cpuset === void 0 ? {} : { CpusetCpus: limits.cpuset },
419
+ ...bytes === null ? {} : {
420
+ Memory: bytes,
421
+ MemorySwap: bytes
422
+ }
423
+ };
424
+ };
425
+ /**
426
+ * This function gives the argv of the reader: one reading, or a series with a period. Each folder
427
+ * is a place where the cgroup of the container can be. The reader takes the first one that is there.
428
+ */
429
+ const resourceArgs = (dirs, period) => {
430
+ if (period === void 0) return [
431
+ RESOURCES_PROGRAM,
432
+ "read",
433
+ ...dirs
434
+ ];
435
+ const ms = Math.round(valueIn(period, "ms"));
436
+ if (!(ms >= 1)) throw new RangeError(`resourceArgs: the period of a series is ${ms} ms, and the reader takes 1 ms or more`);
437
+ return [
438
+ RESOURCES_PROGRAM,
439
+ "watch",
440
+ "--period-ms",
441
+ String(ms),
442
+ ...dirs
443
+ ];
444
+ };
445
+ /** This function gives a count from its digits, or null for another text and for a count that a number cannot hold. */
446
+ const countOf = (text) => {
447
+ if (text === void 0 || !/^\d+$/.test(text)) return null;
448
+ const count = Number(text);
449
+ return Number.isSafeInteger(count) ? count : null;
450
+ };
451
+ /** This function gives the count of a file of a cgroup that holds one count, as `memory.current` does. Another text gives null. */
452
+ const cgroupNumber = (text) => countOf(text.trim());
453
+ /** This function gives a limit of a cgroup, as `memory.max` prints it: its count, or `max` for no limit. Another text gives null. */
454
+ const cgroupLimit = (text) => text.trim() === "max" ? "max" : cgroupNumber(text);
455
+ /**
456
+ * This function gives the counts of a flat keyed file of a cgroup: one key and one count on each
457
+ * line. `cpu.stat` and `memory.stat` are such files. It skips each other line.
458
+ */
459
+ const cgroupKeyed = (text) => Object.fromEntries(text.split("\n").flatMap((line) => {
460
+ const parts = line.trim().split(/\s+/);
461
+ const count = parts.length === 2 ? countOf(parts[1]) : null;
462
+ return count === null ? [] : [[parts[0], count]];
463
+ }));
464
+ /** This function gives one count of a flat keyed file, or null for a key that the file does not have. */
465
+ const keyOf = (counts, key) => Object.hasOwn(counts, key) ? counts[key] : null;
466
+ /** This function reads `cpu.stat`. It gives null for a text with no usage. */
467
+ const cpuStatOf = (text) => {
468
+ const counts = cgroupKeyed(text);
469
+ const [usage, user, system] = [
470
+ keyOf(counts, "usage_usec"),
471
+ keyOf(counts, "user_usec"),
472
+ keyOf(counts, "system_usec")
473
+ ];
474
+ if (usage === null || user === null || system === null) return null;
475
+ return {
476
+ usage,
477
+ user,
478
+ system,
479
+ periods: keyOf(counts, "nr_periods"),
480
+ throttled: keyOf(counts, "nr_throttled"),
481
+ throttledTime: keyOf(counts, "throttled_usec")
482
+ };
483
+ };
484
+ /** This function reads `memory.stat`: the amounts of `anon`, `file`, `kernel` and `sock`, each null without its key. */
485
+ const memoryStatOf = (text) => {
486
+ const counts = cgroupKeyed(text);
487
+ const [stack, slab] = [keyOf(counts, "kernel_stack"), keyOf(counts, "slab")];
488
+ return {
489
+ anon: keyOf(counts, "anon"),
490
+ file: keyOf(counts, "file"),
491
+ kernel: keyOf(counts, "kernel") ?? (stack === null || slab === null ? null : stack + slab),
492
+ sock: keyOf(counts, "sock")
493
+ };
494
+ };
495
+ /** This function reads `cpu.max`: the quota and the period, as `50000 100000` or `max 100000`. Another text gives null. */
496
+ const cpuMaxOf = (text) => {
497
+ const parts = text.trim().split(/\s+/);
498
+ const quota = parts[0] === "max" ? "max" : countOf(parts[0]);
499
+ const period = countOf(parts[1]);
500
+ return parts.length !== 2 || quota === null || period === null ? null : {
501
+ quota,
502
+ period
503
+ };
504
+ };
505
+ const NO_TRAFFIC = {
506
+ bytes: 0,
507
+ packets: 0
508
+ };
509
+ const sumOf = (devices, side) => devices.reduce((sum, device) => ({
510
+ bytes: sum.bytes + device[side].bytes,
511
+ packets: sum.packets + device[side].packets
512
+ }), NO_TRAFFIC);
513
+ /** This function gives the network of some devices: the devices in the order of their names, and their sums. */
514
+ const networkWith = (devices) => {
515
+ const sorted = [...devices].sort((one, other) => one.name < other.name ? -1 : one.name > other.name ? 1 : 0);
516
+ return {
517
+ devices: sorted,
518
+ rx: sumOf(sorted, "rx"),
519
+ tx: sumOf(sorted, "tx")
520
+ };
521
+ };
522
+ /**
523
+ * This function reads `/proc/net/dev`: the bytes and the packets of each device, without `lo`. It
524
+ * gives null for a text that is not that file, and for a line of a device that it cannot read.
525
+ */
526
+ const networkOf = (text) => {
527
+ if (!text.includes("|bytes")) return null;
528
+ const devices = [];
529
+ for (const line of text.split("\n")) {
530
+ const colon = line.lastIndexOf(":");
531
+ if (colon < 0) continue;
532
+ const name = line.slice(0, colon).trim();
533
+ const counts = line.slice(colon + 1).trim().split(/\s+/).map(countOf);
534
+ if (name === "" || counts.length < 16 || counts.includes(null)) return null;
535
+ if (name === "lo") continue;
536
+ devices.push({
537
+ name,
538
+ rx: {
539
+ bytes: counts[0],
540
+ packets: counts[1]
541
+ },
542
+ tx: {
543
+ bytes: counts[8],
544
+ packets: counts[9]
545
+ }
546
+ });
547
+ }
548
+ return networkWith(devices);
549
+ };
550
+ /** This function gives the text of one file of a line of the reader, or null for no read. */
551
+ const textOf$1 = (files, name) => {
552
+ if (typeof files !== "object" || files === null || !Object.hasOwn(files, name)) return null;
553
+ const text = files[name];
554
+ return typeof text === "string" ? text : null;
555
+ };
556
+ /** This function reads a text with `read`, and gives null for no text. */
557
+ const readWith = (text, read) => text === null ? null : read(text);
558
+ /**
559
+ * This function gives the reading of one line of the reader (`RESOURCES_EVENT`). It gives null for
560
+ * another line, and for a line with no stamps.
561
+ */
562
+ const resourceReadingOf = (line) => {
563
+ const { t, t1, cgroup, files, net } = line;
564
+ if (line.ev !== "resources" || typeof t !== "number" || typeof t1 !== "number" || typeof cgroup !== "string") return null;
565
+ const file = (name) => textOf$1(files, name);
566
+ const stat = readWith(file("memory.stat"), memoryStatOf) ?? {
567
+ anon: null,
568
+ file: null,
569
+ kernel: null,
570
+ sock: null
571
+ };
572
+ const cpuset = file("cpuset.cpus.effective")?.trim();
573
+ return {
574
+ t0: t,
575
+ t1,
576
+ cgroup,
577
+ cpu: readWith(file("cpu.stat"), cpuStatOf),
578
+ memory: {
579
+ current: readWith(file("memory.current"), cgroupNumber),
580
+ peak: readWith(file("memory.peak"), cgroupNumber),
581
+ ...stat,
582
+ events: readWith(file("memory.events"), cgroupKeyed)
583
+ },
584
+ pids: readWith(file("pids.current"), cgroupNumber),
585
+ network: typeof net === "string" ? networkOf(net) : null,
586
+ limits: {
587
+ cpu: readWith(file("cpu.max"), cpuMaxOf),
588
+ memory: readWith(file("memory.max"), cgroupLimit),
589
+ cpuset: cpuset === void 0 || cpuset === "" ? null : cpuset
590
+ }
591
+ };
592
+ };
593
+ /**
594
+ * This function gives the reading of the output of one read of the reader. It throws for a text
595
+ * that is not a line of a reading.
596
+ */
597
+ const resourceReadingIn = (output) => {
598
+ let line = null;
599
+ try {
600
+ line = JSON.parse(output);
601
+ } catch {}
602
+ const reading = typeof line === "object" && line !== null && typeof line.ev === "string" ? resourceReadingOf(line) : null;
603
+ if (reading === null) throw new Error(`the reader of the resources gave no reading: ${output.slice(0, 200)}`);
604
+ return reading;
605
+ };
606
+ /** This function gives a time from its microseconds. */
607
+ const fromMicroseconds = (time) => quantity(time / 1e6, "s");
608
+ /**
609
+ * This function gives what a container used between two readings. It gives its CPU time, the time
610
+ * that its CPU limit stopped it, the traffic of each device, and its last memory. A counter that
611
+ * went down is in `resets`, and its part is null. It throws when the second reading is the earlier one.
612
+ */
613
+ const resourceChange = (before, after) => {
614
+ if (after.t0 < before.t0) throw new RangeError(`resourceChange: the second reading is ${before.t0 - after.t0} ns before the first`);
615
+ const resets = [];
616
+ /** This function gives the rise of a counter. It gives null for a counter that went down, and names it. */
617
+ const rise = (name, from, to) => {
618
+ if (to >= from) return to - from;
619
+ resets.push(name);
620
+ return null;
621
+ };
622
+ /** This function gives the rise of a counter that can have no read. */
623
+ const riseOf = (name, from, to) => from === null || to === null ? null : rise(name, from, to);
624
+ const same = before.cgroup === after.cgroup;
625
+ if (!same) resets.push("cgroup");
626
+ const cpu = (() => {
627
+ if (!same || before.cpu === null || after.cpu === null) return null;
628
+ const [total, user, system] = [
629
+ rise("cpu.usage", before.cpu.usage, after.cpu.usage),
630
+ rise("cpu.user", before.cpu.user, after.cpu.user),
631
+ rise("cpu.system", before.cpu.system, after.cpu.system)
632
+ ];
633
+ const periods = riseOf("cpu.periods", before.cpu.periods, after.cpu.periods);
634
+ const throttledPeriods = riseOf("cpu.throttled", before.cpu.throttled, after.cpu.throttled);
635
+ const throttled = riseOf("cpu.throttledTime", before.cpu.throttledTime, after.cpu.throttledTime);
636
+ if (total === null || user === null || system === null) return null;
637
+ return {
638
+ total: fromMicroseconds(total),
639
+ user: fromMicroseconds(user),
640
+ system: fromMicroseconds(system),
641
+ throttled: throttled === null ? null : fromMicroseconds(throttled),
642
+ periods,
643
+ throttledPeriods
644
+ };
645
+ })();
646
+ const network = (() => {
647
+ if (before.network === null || after.network === null) return null;
648
+ const earlier = new Map(before.network.devices.map((device) => [device.name, device]));
649
+ const devices = [];
650
+ let whole = true;
651
+ for (const device of after.network.devices) {
652
+ const from = earlier.get(device.name) ?? {
653
+ name: device.name,
654
+ rx: NO_TRAFFIC,
655
+ tx: NO_TRAFFIC
656
+ };
657
+ earlier.delete(device.name);
658
+ const each = ["rx", "tx"].map((side) => ({
659
+ bytes: rise(`network.${device.name}.${side}.bytes`, from[side].bytes, device[side].bytes),
660
+ packets: rise(`network.${device.name}.${side}.packets`, from[side].packets, device[side].packets)
661
+ }));
662
+ const [rx, tx] = [each[0], each[1]];
663
+ if (rx.bytes === null || rx.packets === null || tx.bytes === null || tx.packets === null) whole = false;
664
+ else devices.push({
665
+ name: device.name,
666
+ rx: {
667
+ bytes: rx.bytes,
668
+ packets: rx.packets
669
+ },
670
+ tx: {
671
+ bytes: tx.bytes,
672
+ packets: tx.packets
673
+ }
674
+ });
675
+ }
676
+ for (const name of earlier.keys()) {
677
+ resets.push(`network.${name}`);
678
+ whole = false;
679
+ }
680
+ return whole ? networkWith(devices) : null;
681
+ })();
682
+ const [peakBefore, peakAfter] = [before.memory.peak, after.memory.peak];
683
+ return {
684
+ elapsed: quantity((after.t0 - before.t0) / 1e9, "s"),
685
+ cpu,
686
+ memory: {
687
+ last: after.memory.current,
688
+ peak: peakAfter,
689
+ peakBetween: !same || peakBefore === null || peakAfter === null ? null : peakAfter > peakBefore
690
+ },
691
+ network,
692
+ resets
693
+ };
694
+ };
12
695
  // src/cell.ts
13
696
  /** These are the capabilities that a client image can get. */
14
697
  const CLIENT_CAPABILITIES = [
@@ -23,8 +706,14 @@ const isHopPlace = (place) => typeof place === "object" && "hop" in place;
23
706
  * environments of the cell can operate. A value of the host is the same for each environment of the
24
707
  * host. Thus a cell with sysctls of the host operates one environment at a time. Otherwise, a lab
25
708
  * reads the value of a different lab as its value before, and the restore does not give back the host.
709
+ * A bad value of the connections of a load stream is also a problem, before a lab opens.
26
710
  */
27
- const environmentProblems = (cell) => (cell.hostSysctls?.length ?? 0) > 0 && (cell.concurrency ?? 1) > 1 ? [`${cell.name}: a cell with sysctls of the host operates one environment at a time, not ${cell.concurrency}`] : [];
711
+ const environmentProblems = (cell) => [
712
+ ...(cell.hostSysctls?.length ?? 0) > 0 && (cell.concurrency ?? 1) > 1 ? [`${cell.name}: a cell with sysctls of the host operates one environment at a time, not ${cell.concurrency}`] : [],
713
+ ...cell.target.limits === void 0 ? [] : limitsProblems(cell.target.limits).map((problem) => `${cell.name}: the target: ${problem}`),
714
+ ...cell.clientLimits === void 0 ? [] : limitsProblems(cell.clientLimits).map((problem) => `${cell.name}: the client: ${problem}`),
715
+ ...(cell.probe.streams ?? []).flatMap((stream) => stream.connections === void 0 ? [] : connectionsProblems(stream.connections).map((problem) => `${cell.name}: the stream ${stream.key}: ${problem}`))
716
+ ];
28
717
  /**
29
718
  * This function tells if the request of a client goes before the fault of its cell. That is so for a
30
719
  * hop event that comes while the request is in flight (`HopEvent.inFlight`). Then a request after the fault is void.
@@ -754,6 +1443,6 @@ const grpcClientImage = () => imageOf(shipped("grpc"));
754
1443
  const targetSourceOf = (target) => target.subject ?? target.image;
755
1444
  /** This function gives the image that a target operates: the image of its subject, or its stock image. */
756
1445
  const targetImageOf = (target) => imageOf(targetSourceOf(target));
757
- export { targetSourceOf as A, versionsOf as B, programOf as C, subjectClient as D, sources as E, goVersions as F, requestFirst as G, environmentProblems as H, jarVersions as I, locksOf as L, unpinnedBases as M, LOCK_NAMES as N, subjectProblems as O, cargoVersions as P, npmDrift as R, planOf as S, shippedSource as T, isHopPlace as U, CLIENT_CAPABILITIES as V, latestEndOf as W, kafkaClientImage as _, SHIPPED_NAMES as a, nodeHttpImage as b, buildRecordOf as c, harnessImage as d, harnessVersion as f, inContext as g, imageProblems as h, SHIPPED_CLIENTS as i, unlockedManifests as j, targetImageOf as k, goHttpImage as l, imageOf as m, PINNED as n, amqpClientImage as o, hikariClientImage as p, REPOSITORY as r, basesOf as s, CLIENT_NAMES as t, grpcClientImage as u, mongoClientImage as v, routerImage as w, pgClientImage as x, nodeClientImage as y, npmVersions as z };
1446
+ export { hostLimitsOf as $, targetSourceOf as A, versionsOf as B, programOf as C, subjectClient as D, sources as E, goVersions as F, requestFirst as G, environmentProblems as H, jarVersions as I, cgroupKeyed as J, RESOURCES_EVENT as K, locksOf as L, unpinnedBases as M, LOCK_NAMES as N, subjectProblems as O, cargoVersions as P, cpuStatOf as Q, npmDrift as R, planOf as S, shippedSource as T, isHopPlace as U, CLIENT_CAPABILITIES as V, latestEndOf as W, cgroupNumber as X, cgroupLimit as Y, cpuMaxOf as Z, kafkaClientImage as _, loadPlanOf as _t, SHIPPED_NAMES as a, resourceReadingIn as at, nodeHttpImage as b, streamsLoadOf as bt, buildRecordOf as c, LOAD_FORMAT as ct, harnessImage as d, SCHEDULE_PATH as dt, limitsProblems as et, harnessVersion as f, connectionsProblems as ft, inContext as g, loadOf as gt, imageProblems as h, loadEnds as ht, SHIPPED_CLIENTS as i, resourceChange as it, unlockedManifests as j, targetImageOf as k, goHttpImage as l, LOAD_PATH as lt, imageOf as m, estimateVerdict as mt, PINNED as n, networkOf as nt, amqpClientImage as o, resourceReadingOf as ot, hikariClientImage as p, estimateOf as pt, RESOURCES_PROGRAM as q, REPOSITORY as r, resourceArgs as rt, basesOf as s, CLOSED_TOLERANCE as st, CLIENT_NAMES as t, memoryStatOf as tt, grpcClientImage as u, LOAD_POOL_LIMIT as ut, mongoClientImage as v, loadVerdict as vt, routerImage as w, pgClientImage as x, nodeClientImage as y, poolOf as yt, npmVersions as z };
758
1447
 
759
- //# sourceMappingURL=image-BE9H5gIv.js.map
1448
+ //# sourceMappingURL=image-S18_TQfQ.js.map