@orkestrel/scaffold 0.0.138 → 0.0.139

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.
@@ -16,7 +16,7 @@
16
16
  // earlier light tickets' summed peaks with its own fit `slots` and each budget; the earliest light
17
17
  // ticket always fits. A light holder runs at below-normal priority, and its holder ends it and exits
18
18
  // 69 when a sample taken before the launcher exits passes the memory or process threshold; a sample
19
- // after the exit reads no member created after it and ends nothing.
19
+ // after the exit ends nothing, and on Windows reads no member created after it.
20
20
  // Directories: a run of the falsify skill's `mutate` script, `--restore` included, publishes
21
21
  // `edits` in its ticket, because it edits source in its working directory. Every ticket also waits
22
22
  // on the nearest earlier ticket that carries `edits` and shares its working directory, and a ticket
@@ -28,13 +28,18 @@
28
28
  // names an earlier ticket, so no cycle of waits forms, and each process derives from the earlier
29
29
  // tickets alone which light tickets the rule blocks.
30
30
  // Light reading: `<root>/limits.json` holds `slots`, the `budget` and the per-run `threshold`; while
31
- // it is absent or malformed, or on a host other than Windows, every ticket is heavy, no sampler runs,
32
- // and no record is written. Otherwise each run starts one PowerShell sampler at arrival, which readies
33
- // while the ticket waits, with no timer until its first sample, and exits when its stdin closes. The
34
- // holder starts its command after the sampler readies, or unmeasured once `READY_MS` passes, samples
35
- // the tree back to back through the command's first second and once a second after, and reads the
36
- // handover through one more sample; when that sample lists a member or no sampler answers, the
37
- // handover reads, kills, and reads again through fresh snapshots, each a second PowerShell. The
31
+ // it is absent or malformed, or on a host other than Windows and Linux, every ticket is heavy, no
32
+ // sampler runs, and no record is written. Otherwise each Windows run starts one PowerShell sampler at
33
+ // arrival, which readies while the ticket waits, with no timer until its first sample, and exits when
34
+ // its stdin closes; a Linux run reads the process table at `/proc` inside the lane process, each
35
+ // sample a `stat` read per entry for its parent, group, and CPU time and a `status` read per member
36
+ // for its `VmRSS`, and its tree is the launcher's process group with every process a parent link
37
+ // reaches from it. The holder starts its command after the sampler readies, or unmeasured after
38
+ // `READY_MS` passes, samples the tree through the command's first second, back to back on Windows and
39
+ // every `BURST_MS` on Linux, and once a second after, and reads the handover through one more sample.
40
+ // On Windows, when that sample lists a member or no sampler answers, the handover reads, kills, and
41
+ // reads again through fresh snapshots, each a second PowerShell; on Linux the handover reads the
42
+ // launcher's group, as an unmeasured run's does. The
38
43
  // holder writes one record per run under `<root>/history/<key>/`, keyed by the working directory and
39
44
  // the command, keeping the latest runs. A record that opens a key prunes the history after the
40
45
  // release, keeping only the keys written inside `HISTORY_AGE_MS` (7 days), and of those at most the
@@ -76,12 +81,37 @@
76
81
  // Only the holder kills, and only inside its own bounds.
77
82
  // - Process-identifier reuse, other hosts. A group id cannot be reused while the group has a member.
78
83
  // An empty group's id can be reused by a later group leader, so a reclaimer might refuse on a stale
79
- // run record. It never kills on one.
84
+ // run record. It never kills on one. A breach signals the launcher's group by the launcher's id,
85
+ // which the host keeps while the lane has not reaped the launcher. It signals any other group, and
86
+ // a member by its id, only after a read of the process table shows that member with the start
87
+ // ticks recorded for it. These reuses pass that check, and each needs the id space to wrap inside
88
+ // its window: an id given to another process inside the `CLOCK_TICK_MS` tick of the recorded
89
+ // start; an id given to another process between that read and the signal; and a parent id given
90
+ // to another process inside one reading, whose children then read as the member's. A reading also
91
+ // selects every member of a group the breach stopped, whose id the host holds while a stopped
92
+ // member lives; it reads another process there only after every member is killed from outside
93
+ // the lane and the id goes to another group inside one reading, a reuse of the second kind. On
94
+ // the Linux container measured 2026-11-16, `pid_max` is 32,768 and Node started 366 processes a
95
+ // second.
80
96
  // - A descendant that detached itself. A process that left the group, a run started through the WMI
81
97
  // detach of `.agents/platforms/windows.md`, and a Windows descendant whose parent exited before the
82
98
  // reading and is no recorded seed are all outside every reading. A background child of a `bash`
83
99
  // command can be that case, so pass a command directly rather than through `bash -c`. "No surviving
84
100
  // process tree" means the group, or the parent-link closure, and no more.
101
+ // A Linux census counts a process that left the group while its parent is a member, such as a
102
+ // browser a test runner starts. A breach sends `SIGSTOP` to the launcher's group and to the group
103
+ // of every counted member, reads the table again while each parent still lives, sends `SIGSTOP`
104
+ // to the group of every process a parent link then reaches from a counted member or from any
105
+ // member of a stopped group, and repeats until a reading adds no group or `KILL_BUDGET` readings
106
+ // have run. It then sends `SIGKILL` to every group and member it collected, the launcher's group
107
+ // last. These cases stay outside that kill: a process outside every stopped group whose parent
108
+ // exited before a reading could link it, such as a daemon that forks twice, which reads as a
109
+ // child of the host's init in a group and a session of its own; a process started after the last
110
+ // reading when the budget ended the readings, which a tree that keeps starting detached processes
111
+ // produces; a member the lane's account may not signal; and a member the host hides from
112
+ // `/proc`. A lane that ends between the stop and the kill leaves its tree stopped, and arrivals
113
+ // exit 75 until a person ends that tree. The handover reading reads the group alone, so
114
+ // a process outside the group that outlives a run that ended without a breach stays outside it.
85
115
  // - An owner ended alone mid-run. No event reports a foreign tree's end. Arrivals exit 75 until that
86
116
  // tree is gone, and the next arrival then reclaims.
87
117
  // - An owner ended between the run record and the launcher id. The tree cannot be identified. Arrivals
@@ -93,14 +123,22 @@
93
123
  // - Sampling. A process that lives between two samples goes uncounted, the CPU time of a member that
94
124
  // exits between samples is lost, and disk input and output are not measured. A command that ends
95
125
  // before one process query answers, about 140 ms on the Windows host measured 2026-11-12, can
96
- // record zero, so it counts nothing until a later run is read.
126
+ // record zero, so it counts nothing until a later run is read; a Linux census of 142 processes read
127
+ // in 1 to 3 ms on the Linux container measured 2026-11-16.
128
+ // - Linux readings. The census counts CPU time in ticks of `CLOCK_TICK_MS`, the `USER_HZ` of x86 and
129
+ // arm64, so a kernel with another `USER_HZ` misreads cores. It sums `VmRSS`, which counts a shared
130
+ // page once per member that maps it, so a Linux tree reads above the private bytes Windows sums, and
131
+ // a `limits.json` carries figures measured on its own host.
97
132
  // - Transition. A process of an earlier release reads no `edits` field: it does not wait on a mutation
98
133
  // of its directory, a `mutate` run it carries publishes no `edits`, so the directory rule cannot see
99
134
  // that run, and as a light ticket it counts a directory-blocked light ticket of this release as one
100
135
  // that has not held, so it queues behind it. Every checkout on an earlier `@orkestrel/scaffold`
101
136
  // keeps starting such processes on the shared root until that checkout adopts this release, so the
102
137
  // bound is the last adoption, not one process's exit. A mutation of this release does wait on an
103
- // earlier ticket of its directory, whichever release wrote it.
138
+ // earlier ticket of its directory, whichever release wrote it. A Linux process of 0.0.138 or earlier
139
+ // reads no limits, so its ticket is heavy and its run writes no record; it waits on the earlier
140
+ // heavy tickets and passes the light ones, as a heavy ticket of this release does, so both releases
141
+ // share one queue on one root.
104
142
  // - Heavy throughput. A heavy ticket that the directory rule blocks still keeps every later heavy
105
143
  // ticket out, from every directory, because passing it would let two heavy tickets hold at once.
106
144
  // - Light budget. A light ticket that the directory rule blocks is not one later light tickets wait to
@@ -112,9 +150,10 @@
112
150
  // - The ready wait. A holder waits for its sampler before it writes its run record and signals that
113
151
  // it holds, so later light tickets count it as one that has not held for up to `READY_MS` when its
114
152
  // sampler never reports ready.
115
- // - The idle sampler. Each queued measured ticket keeps its PowerShell sampler from arrival, about
116
- // 75 MB of private memory once ready on the Windows host measured 2026-11-13, and no budget counts
117
- // that memory, so a long queue of measured tickets costs that much per ticket.
153
+ // - The idle sampler. Each queued measured Windows ticket keeps its PowerShell sampler from arrival,
154
+ // about 75 MB of private memory after it readies on the Windows host measured 2026-11-13, and no budget
155
+ // counts that memory, so a long queue of measured tickets costs that much per ticket. A Linux
156
+ // census starts no process.
118
157
  // - A prune beside a write. A holder that writes a record to an existing key that is past a bound can
119
158
  // lose that record to another holder's prune, which removes the key with the record in it.
120
159
  // - An unreaped member. A group reads as ended when two readings of the process table at `/proc`,
@@ -134,8 +173,10 @@
134
173
  // - A denied root. A sandbox that refuses the root or the endpoint exits 75; no sandboxed bench exec
135
174
  // has run this script.
136
175
  // - Linux. The socket file, the process group, and the zombie reading were read on a Linux container
137
- // on 2026-11-14 (Node 22.23.5, an init that does not reap as a child ends); the signal handling is
138
- // unread on Linux.
176
+ // on 2026-11-14 (Node 22.23.5, an init that does not reap as a child ends), the census and the
177
+ // light lanes on 2026-11-16 (4 CPUs), and the breach kill's group stop, its fixpoint readings,
178
+ // and its kill order on the same container on 2026-11-16; the handling of a signal the lane
179
+ // process receives is unread on Linux.
139
180
  // Migration stop: a second queue does not see the first, so while a host's sessions run another
140
181
  // serializer, no caller moves. After a scaffold release carries this script and no command runs on the
141
182
  // host, move every caller in one step and delete the serializer this replaces.
@@ -168,6 +209,7 @@ import {
168
209
  sep,
169
210
  } from 'node:path'
170
211
  import { createInterface } from 'node:readline'
212
+ import { setImmediate as yieldTurn, setTimeout as wait } from 'node:timers/promises'
171
213
  import { fileURLToPath } from 'node:url'
172
214
  import { parseArgs } from 'node:util'
173
215
 
@@ -278,11 +320,14 @@ export const STOP_SIGNALS: readonly NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SI
278
320
  export const CLOCK_ALLOWANCE_MS = 16
279
321
 
280
322
  /**
281
- * Holds the kill attempts the handover reading makes before it stays held.
323
+ * Holds the kill attempts the handover reading makes before it stays held, and the readings a Linux
324
+ * breach kill takes toward a fixpoint.
282
325
  *
283
326
  * @remarks
284
327
  * Each attempt on Windows is a synchronous `taskkill` per member and a process snapshot. A member
285
328
  * that outlives this many forced kills is a defect a person reads rather than a wait the queue absorbs.
329
+ * A breach kill of a Chromium launch and of a tree of 41 to 46 processes settled in 1 or 2 readings
330
+ * of 1 to 4 ms each on the Linux container measured 2026-11-16.
286
331
  */
287
332
  export const KILL_BUDGET = 5
288
333
 
@@ -349,6 +394,30 @@ export const HANDOVER_MS = 5000
349
394
  /** Holds the pause in milliseconds between two samples of a holder's tree. */
350
395
  export const SAMPLE_MS = 1000
351
396
 
397
+ /**
398
+ * Holds the pause in milliseconds between two samples of a Linux holder's first second.
399
+ *
400
+ * @remarks
401
+ * A Linux sample reads the process table inside the lane process in a few milliseconds, so a burst
402
+ * paced back to back, as the Windows sampler's is, would hold a core for that second.
403
+ */
404
+ export const BURST_MS = 50
405
+
406
+ /**
407
+ * Holds the milliseconds of one clock tick in the Linux process table.
408
+ *
409
+ * @remarks
410
+ * The table counts CPU time and a start time in `USER_HZ` ticks, which the kernel fixes at 100 per
411
+ * second on x86 and arm64; Node exposes no `sysconf` to read it.
412
+ */
413
+ export const CLOCK_TICK_MS = 10
414
+
415
+ /** Matches the boot-time line of the Linux `/proc/stat`, in whole seconds since the epoch. */
416
+ export const BOOT_PATTERN = /^btime (\d+)$/u
417
+
418
+ /** Matches the resident-memory line of a Linux `/proc/<pid>/status`, in kibibytes. */
419
+ export const RESIDENT_PATTERN = /^VmRSS:\s+(\d+) kB$/u
420
+
352
421
  /** Holds the exit code of a light run its holder ended at a threshold. */
353
422
  export const BREACH_CODE = 69
354
423
 
@@ -545,6 +614,18 @@ export interface Gauge extends Row {
545
614
  readonly memory: number
546
615
  }
547
616
 
617
+ /**
618
+ * Describes one Linux process-table entry a census reads: a gauge whose creation date is the boot
619
+ * second plus its start ticks, whose memory is its resident bytes, with its process group, its
620
+ * state, and its start ticks since boot (the twenty-second `stat` field), which a kill compares to
621
+ * confirm the process it signals is the one the census counted.
622
+ */
623
+ export interface Member extends Gauge {
624
+ readonly group: number
625
+ readonly state: string
626
+ readonly start: number
627
+ }
628
+
548
629
  /** Describes what a history prune did: the keys it removed and the names it skipped. */
549
630
  export interface Prune {
550
631
  readonly removed: readonly string[]
@@ -643,6 +724,28 @@ export interface Sweep {
643
724
  readonly members: readonly number[]
644
725
  }
645
726
 
727
+ /**
728
+ * Describes what the readings of a breach kill collected: the launcher's group, every group sent
729
+ * `SIGSTOP` in order with the launcher's first, the members the last reading selected, and whether
730
+ * a reading added no group.
731
+ */
732
+ export interface Collection {
733
+ readonly group: number
734
+ readonly groups: readonly number[]
735
+ readonly members: readonly Member[]
736
+ readonly settled: boolean
737
+ }
738
+
739
+ /**
740
+ * Describes what a breach kill signalled: whether its readings settled, each group sent `SIGKILL`
741
+ * in order with the launcher's last, and each member sent `SIGKILL` by its id.
742
+ */
743
+ export interface Kill {
744
+ readonly settled: boolean
745
+ readonly groups: readonly number[]
746
+ readonly members: readonly number[]
747
+ }
748
+
646
749
  /** Describes one ticket as `--status` reports it; `edits` marks a `mutate` run, and `holding` a live ticket with a run record. */
647
750
  export interface StatusRow {
648
751
  readonly sequence: number
@@ -2179,6 +2282,316 @@ export function readGroup(
2179
2282
  return second !== undefined && matchesEnded(first, second) ? [] : [group]
2180
2283
  }
2181
2284
 
2285
+ /**
2286
+ * Parses one Linux process-table `stat` line into a census member with no memory read yet.
2287
+ *
2288
+ * @remarks
2289
+ * The fields are read after the last `)`, as {@link parseStat} reads them: the state, the parent,
2290
+ * and the group open them, `utime` and `stime` are the twelfth and thirteenth, and the start time is
2291
+ * the twentieth.
2292
+ *
2293
+ * @param text - The content of `/proc/<pid>/stat`.
2294
+ * @param boot - The boot time in epoch milliseconds, which the start ticks count from.
2295
+ * @returns The member with its memory at 0, or undefined when the text does not have that form.
2296
+ */
2297
+ export function parseMember(text: string, boot: number): Member | undefined {
2298
+ const open = text.indexOf(' (')
2299
+ const close = text.lastIndexOf(')')
2300
+ if (open === -1 || close < open) return undefined
2301
+ const pid = text.slice(0, open)
2302
+ const fields = text.slice(close + 2).split(' ')
2303
+ const [state, parent, group] = fields
2304
+ const [user, system, start] = [fields[11], fields[12], fields[19]]
2305
+ const numbers = [pid, parent, group, user, system, start]
2306
+ if (state === undefined || state === '') return undefined
2307
+ if (!numbers.every((value) => value !== undefined && /^\d+$/u.test(value))) return undefined
2308
+ return {
2309
+ pid: Number(pid),
2310
+ parent: Number(parent),
2311
+ group: Number(group),
2312
+ state,
2313
+ created: boot + Number(start) * CLOCK_TICK_MS,
2314
+ cpu: (Number(user) + Number(system)) * CLOCK_TICK_MS,
2315
+ memory: 0,
2316
+ start: Number(start),
2317
+ }
2318
+ }
2319
+
2320
+ /**
2321
+ * Parses the resident memory of one Linux `/proc/<pid>/status` text.
2322
+ *
2323
+ * @param text - The content of `/proc/<pid>/status`.
2324
+ * @returns The `VmRSS` value in bytes, or undefined when the text holds no such line, as a kernel
2325
+ * thread's does.
2326
+ */
2327
+ export function parseResident(text: string): number | undefined {
2328
+ const match = text
2329
+ .split(/\r\n|\n/u)
2330
+ .map((line) => RESIDENT_PATTERN.exec(line.trim()))
2331
+ .find((item) => item !== null)
2332
+ return match?.[1] === undefined ? undefined : Number(match[1]) * 1024
2333
+ }
2334
+
2335
+ /**
2336
+ * Reads the Linux boot time from the process table.
2337
+ *
2338
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
2339
+ * @returns The `btime` line of `stat` in epoch milliseconds, or undefined when the file cannot be
2340
+ * read or holds no such line.
2341
+ */
2342
+ export function readBoot(table = PROCESS_TABLE): number | undefined {
2343
+ try {
2344
+ const match = readFileSync(join(table, 'stat'), 'utf8')
2345
+ .split(/\r\n|\n/u)
2346
+ .map((line) => BOOT_PATTERN.exec(line.trim()))
2347
+ .find((item) => item !== null)
2348
+ return match?.[1] === undefined ? undefined : Number(match[1]) * 1000
2349
+ } catch {
2350
+ return undefined
2351
+ }
2352
+ }
2353
+
2354
+ /**
2355
+ * Reads every live process of the Linux process table.
2356
+ *
2357
+ * @remarks
2358
+ * An entry whose `stat` is gone, unreadable, or malformed, and an entry that has exited
2359
+ * ({@link ENDED_STATES}), is skipped: an exited member holds no CPU or memory.
2360
+ *
2361
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
2362
+ * @returns One member per live process with its memory at 0, or undefined when the boot time or the
2363
+ * listing cannot be read.
2364
+ */
2365
+ export function readMembers(table = PROCESS_TABLE): readonly Member[] | undefined {
2366
+ const boot = readBoot(table)
2367
+ const names = readListing(table)
2368
+ if (boot === undefined || names === undefined) return undefined
2369
+ return names
2370
+ .filter((name) => /^\d+$/u.test(name))
2371
+ .flatMap((name) => {
2372
+ try {
2373
+ const member = parseMember(readFileSync(join(table, name, 'stat'), 'utf8'), boot)
2374
+ return member === undefined || ENDED_STATES.includes(member.state) ? [] : [member]
2375
+ } catch {
2376
+ return []
2377
+ }
2378
+ })
2379
+ }
2380
+
2381
+ /**
2382
+ * Reads the resident memory of one Linux process.
2383
+ *
2384
+ * @param pid - The process id.
2385
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
2386
+ * @returns The `VmRSS` value in bytes; 0 when the entry is gone, unreadable, or holds no such line.
2387
+ */
2388
+ export function readResident(pid: number, table = PROCESS_TABLE): number {
2389
+ try {
2390
+ return parseResident(readFileSync(join(table, String(pid), 'status'), 'utf8')) ?? 0
2391
+ } catch {
2392
+ return 0
2393
+ }
2394
+ }
2395
+
2396
+ /**
2397
+ * Selects the members of one run's process tree from a Linux census.
2398
+ *
2399
+ * @remarks
2400
+ * A member of the launcher's process group counts, and so does a known member the census still
2401
+ * shows with its start ticks, and every process a parent link reaches from a counted one, such as a
2402
+ * browser a test runner starts in a group of its own. A group id cannot be reused while the group
2403
+ * has a member, so a member never names an unrelated process.
2404
+ *
2405
+ * @param members - The census.
2406
+ * @param group - The launcher's id, which is its group's id.
2407
+ * @param known - Members an earlier reading counted. Default: none.
2408
+ * @returns The members.
2409
+ */
2410
+ export function selectGroup(
2411
+ members: readonly Member[],
2412
+ group: number,
2413
+ known: readonly Member[] = [],
2414
+ ): readonly Member[] {
2415
+ const starts = new Map(known.map((member) => [member.pid, member.start]))
2416
+ const reached = new Map(
2417
+ members
2418
+ .filter((member) => member.group === group || starts.get(member.pid) === member.start)
2419
+ .map((member) => [member.pid, member]),
2420
+ )
2421
+ for (const member of reached.values()) {
2422
+ for (const row of members) {
2423
+ if (row.parent === member.pid && !reached.has(row.pid)) reached.set(row.pid, row)
2424
+ }
2425
+ }
2426
+ return [...reached.values()]
2427
+ }
2428
+
2429
+ /**
2430
+ * Checks whether a tally passes a light run's threshold.
2431
+ *
2432
+ * @param tally - What the samples read so far.
2433
+ * @param threshold - The light run's threshold.
2434
+ * @returns True when the peak memory or the peak process count is past its threshold; false
2435
+ * otherwise.
2436
+ */
2437
+ export function exceedsThreshold(tally: Tally, threshold: Usage): boolean {
2438
+ return tally.memory > threshold.memory || tally.processes > threshold.processes
2439
+ }
2440
+
2441
+ /**
2442
+ * Reads one Linux process from the process table, with no memory read.
2443
+ *
2444
+ * @param pid - The process id.
2445
+ * @param table - The process table's root. Default: {@link PROCESS_TABLE}.
2446
+ * @returns The member its `stat` shows, its creation date counted from 0, or undefined when the
2447
+ * entry is gone, unreadable, or malformed.
2448
+ */
2449
+ export function readProcess(pid: number, table = PROCESS_TABLE): Member | undefined {
2450
+ try {
2451
+ return parseMember(readFileSync(join(table, String(pid), 'stat'), 'utf8'), 0)
2452
+ } catch {
2453
+ return undefined
2454
+ }
2455
+ }
2456
+
2457
+ /**
2458
+ * Sends one signal to a process id, or to a group when the target is negative.
2459
+ *
2460
+ * @param target - The process id, or the negated group id.
2461
+ * @param signal - The signal.
2462
+ */
2463
+ export function sendSignal(target: number, signal: NodeJS.Signals): void {
2464
+ try {
2465
+ process.kill(target, signal)
2466
+ } catch {}
2467
+ }
2468
+
2469
+ /**
2470
+ * Takes one reading of the process table, and reads a thrown error as a failed reading.
2471
+ *
2472
+ * @param read - Takes the reading; undefined means it could not read the table.
2473
+ * @returns The members the reading listed, or undefined when it failed or threw.
2474
+ */
2475
+ export function takeReading(
2476
+ read: () => readonly Member[] | undefined,
2477
+ ): readonly Member[] | undefined {
2478
+ try {
2479
+ return read()
2480
+ } catch {
2481
+ return undefined
2482
+ }
2483
+ }
2484
+
2485
+ /**
2486
+ * Collects a breaching tree to a fixpoint: each reading selects the launcher's group, every member
2487
+ * of a group collected so far, the members collected so far that it still shows with their start
2488
+ * ticks, and every process a parent link reaches from those, and sends `SIGSTOP` to each selected
2489
+ * member's group that has received none.
2490
+ *
2491
+ * @remarks
2492
+ * A stopped parent keeps its children's parent field, so the next reading reaches what an earlier
2493
+ * one missed, and a group-directed signal reaches the child of a fork in flight. The collection
2494
+ * settles when a reading adds no group, and ends unsettled when a reading fails or the budget ends.
2495
+ *
2496
+ * @param read - Takes one reading of the process table; undefined means it could not read it.
2497
+ * @param signal - Sends a signal to a process id, or to a group when the target is negative.
2498
+ * @param collection - What the earlier readings collected.
2499
+ * @param budget - The readings left.
2500
+ * @returns What the readings collected.
2501
+ */
2502
+ export function collectTree(
2503
+ read: () => readonly Member[] | undefined,
2504
+ signal: (target: number, signal: NodeJS.Signals) => void,
2505
+ collection: Collection,
2506
+ budget: number,
2507
+ ): Collection {
2508
+ const members = budget > 0 ? takeReading(read) : undefined
2509
+ if (members === undefined) return collection
2510
+ const known = new Set(collection.groups)
2511
+ const selected = selectGroup(members, collection.group, [
2512
+ ...collection.members,
2513
+ ...members.filter((member) => known.has(member.group)),
2514
+ ])
2515
+ const added = [...new Set(selected.map((member) => member.group))].filter(
2516
+ (group) => !known.has(group),
2517
+ )
2518
+ for (const group of added) signal(-group, 'SIGSTOP')
2519
+ const next = { ...collection, groups: [...collection.groups, ...added], members: selected }
2520
+ return added.length === 0
2521
+ ? { ...next, settled: true }
2522
+ : collectTree(read, signal, next, budget - 1)
2523
+ }
2524
+
2525
+ /**
2526
+ * Kills what a breach collected: each collected group other than the launcher's, in reverse order
2527
+ * of collection; each collected member outside the launcher's group by its id; and the launcher's
2528
+ * group last.
2529
+ *
2530
+ * @remarks
2531
+ * A child group ends before the group of its parent, because the exit that orphans a group with
2532
+ * stopped members of the same session sends that group `SIGHUP` and `SIGCONT`. The by-id signal
2533
+ * reaches a member that left its group after the last reading. The launcher's group ends through
2534
+ * {@link killMembers}, which pauses after it. `SIGKILL` ends a stopped process, so nothing is left
2535
+ * stopped.
2536
+ *
2537
+ * @param collection - What the readings collected.
2538
+ * @param signal - Sends a signal, for a proof. Default: {@link sendSignal}.
2539
+ * @returns What the kill signalled, and whether the readings settled.
2540
+ */
2541
+ export function killTree(
2542
+ collection: Collection,
2543
+ signal: (target: number, signal: NodeJS.Signals) => void = sendSignal,
2544
+ ): Kill {
2545
+ const { group } = collection
2546
+ const others = collection.groups.filter((id) => id !== group).toReversed()
2547
+ for (const id of others) signal(-id, 'SIGKILL')
2548
+ const outside = collection.members
2549
+ .filter((member) => member.group !== group)
2550
+ .map((member) => member.pid)
2551
+ for (const pid of outside) signal(pid, 'SIGKILL')
2552
+ killMembers([group], signal)
2553
+ return { settled: collection.settled, groups: [...others, group], members: outside }
2554
+ }
2555
+
2556
+ /**
2557
+ * Ends the tree one Linux census sample breached: it stops the launcher's group and each counted
2558
+ * member's group, collects the tree to a fixpoint, and kills what it collected.
2559
+ *
2560
+ * @remarks
2561
+ * The launcher's group takes `SIGSTOP` first. A counted member outside it is a seed only while a
2562
+ * fresh read of its `stat` shows the start ticks the census sampled, and its group, as that read
2563
+ * shows it, takes `SIGSTOP` next. {@link collectTree} then reads up to {@link KILL_BUDGET} times,
2564
+ * and every path, a failed reading included, ends in {@link killTree}.
2565
+ *
2566
+ * @param group - The launcher's id, which is its group's id.
2567
+ * @param members - The members the breaching sample selected per {@link selectGroup}.
2568
+ * @param table - The process table's root, for a proof. Default: {@link PROCESS_TABLE}.
2569
+ * @param signal - Sends a signal, for a proof. Default: {@link sendSignal}.
2570
+ * @returns What the kill signalled, and whether its readings settled.
2571
+ */
2572
+ export function killCensus(
2573
+ group: number,
2574
+ members: readonly Member[],
2575
+ table = PROCESS_TABLE,
2576
+ signal: (target: number, signal: NodeJS.Signals) => void = sendSignal,
2577
+ ): Kill {
2578
+ signal(-group, 'SIGSTOP')
2579
+ const seeds = members.flatMap((member) => {
2580
+ if (member.group === group) return []
2581
+ const fresh = readProcess(member.pid, table)
2582
+ return fresh?.start === member.start ? [fresh] : []
2583
+ })
2584
+ const groups = [...new Set(seeds.map((member) => member.group))].filter((id) => id !== group)
2585
+ for (const id of groups) signal(-id, 'SIGSTOP')
2586
+ const collection = collectTree(
2587
+ () => readMembers(table),
2588
+ signal,
2589
+ { group, groups: [group, ...groups], members: seeds, settled: false },
2590
+ KILL_BUDGET,
2591
+ )
2592
+ return killTree(collection, signal)
2593
+ }
2594
+
2182
2595
  /**
2183
2596
  * Reads the members of one run's process tree.
2184
2597
  *
@@ -2228,8 +2641,13 @@ export function selectTree(
2228
2641
  * group, and a pause follows, because no event reports the end of a foreign group.
2229
2642
  *
2230
2643
  * @param members - The ids a reading returned.
2644
+ * @param signal - Sends a signal on a host other than Windows, for a proof. Default:
2645
+ * {@link sendSignal}.
2231
2646
  */
2232
- export function killMembers(members: readonly number[]): void {
2647
+ export function killMembers(
2648
+ members: readonly number[],
2649
+ signal: (target: number, signal: NodeJS.Signals) => void = sendSignal,
2650
+ ): void {
2233
2651
  for (const member of members) {
2234
2652
  if (process.platform === 'win32') {
2235
2653
  spawnSync('taskkill', ['/pid', String(member), '/T', '/F'], {
@@ -2237,9 +2655,7 @@ export function killMembers(members: readonly number[]): void {
2237
2655
  windowsHide: true,
2238
2656
  })
2239
2657
  } else {
2240
- try {
2241
- process.kill(-member, 'SIGKILL')
2242
- } catch {}
2658
+ signal(-member, 'SIGKILL')
2243
2659
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, KILL_PAUSE_MS)
2244
2660
  }
2245
2661
  }
@@ -2889,7 +3305,7 @@ export class Sampler {
2889
3305
  threshold === undefined ||
2890
3306
  this.#ceiling !== undefined ||
2891
3307
  this.#breached ||
2892
- (this.#tally.memory <= threshold.memory && this.#tally.processes <= threshold.processes)
3308
+ !exceedsThreshold(this.#tally, threshold)
2893
3309
  ) {
2894
3310
  return
2895
3311
  }
@@ -2900,18 +3316,176 @@ export class Sampler {
2900
3316
  }
2901
3317
  }
2902
3318
 
3319
+ /**
3320
+ * Samples one holder's process tree from the Linux process table, inside the lane process.
3321
+ *
3322
+ * @remarks
3323
+ * A sample reads each entry's `stat` for its parent, group, state, start, and CPU time, selects the
3324
+ * tree per {@link selectGroup}, and reads each member's `VmRSS` from its `status`. The census starts
3325
+ * no process and readies at once when the table reads. A {@link Census.sample} call reads after one
3326
+ * turn of the event loop; after the first, a timer also samples every {@link SAMPLE_MS} until
3327
+ * {@link Census.stop}. A threshold, given for a light run, calls the breach handler once with the
3328
+ * launcher's id and the members that sample selected, on the first sample before
3329
+ * {@link Census.seal} whose memory or process count passes it. The holder passes {@link killCensus},
3330
+ * which stops those members' groups and collects what they started after the sample before it
3331
+ * kills.
3332
+ */
3333
+ export class Census {
3334
+ readonly #table: string
3335
+ readonly #threshold: Usage | undefined
3336
+ readonly #breach: (launcher: number, members: readonly Member[]) => void
3337
+ #group: number | undefined
3338
+ #sealed = false
3339
+ #tally: Tally = { cpu: new Map(), memory: 0, processes: 0 }
3340
+ #breached = false
3341
+ #timer: NodeJS.Timeout | undefined
3342
+ #stopped = false
3343
+
3344
+ /**
3345
+ * Creates the census.
3346
+ *
3347
+ * @param threshold - The light run's threshold, or undefined for a heavy run.
3348
+ * @param breach - Called once with the launcher's id and the members the sample selected when a
3349
+ * sample passes the threshold.
3350
+ * @param table - The process table's root, for a proof. Default: {@link PROCESS_TABLE}.
3351
+ */
3352
+ constructor(
3353
+ threshold: Usage | undefined,
3354
+ breach: (launcher: number, members: readonly Member[]) => void,
3355
+ table = PROCESS_TABLE,
3356
+ ) {
3357
+ this.#threshold = threshold
3358
+ this.#breach = breach
3359
+ this.#table = table
3360
+ }
3361
+
3362
+ /** Holds what the samples read so far. */
3363
+ get tally(): Tally {
3364
+ return this.#tally
3365
+ }
3366
+
3367
+ /** Holds whether a sample passed the threshold. */
3368
+ get breached(): boolean {
3369
+ return this.#breached
3370
+ }
3371
+
3372
+ /**
3373
+ * Checks that the process table reads.
3374
+ *
3375
+ * @param _budget - Unused: the census starts no process to wait for.
3376
+ * @returns A promise of true when the table reads and the census has not stopped; false otherwise.
3377
+ */
3378
+ async ready(_budget: number): Promise<boolean> {
3379
+ return !this.#stopped && readMembers(this.#table) !== undefined
3380
+ }
3381
+
3382
+ /**
3383
+ * Names the launcher whose group later samples read.
3384
+ *
3385
+ * @param seeds - The launcher id and, when known, the command id; the launcher's id is its group's.
3386
+ * @param _floor - Unused: a group needs no creation bound.
3387
+ */
3388
+ seed(seeds: readonly number[], _floor: number): void {
3389
+ const [launcher] = seeds
3390
+ this.#group = launcher
3391
+ }
3392
+
3393
+ /**
3394
+ * Marks the launcher's exit: a later sample triggers no breach.
3395
+ *
3396
+ * @param _ceiling - Unused: a group id is not reused while the group has a member.
3397
+ */
3398
+ seal(_ceiling: number): void {
3399
+ this.#sealed = true
3400
+ }
3401
+
3402
+ /**
3403
+ * Reads one sample after one turn of the event loop, and starts the timer on the first call.
3404
+ *
3405
+ * @param _budget - Unused: the read answers inside this process.
3406
+ * @returns A promise of the members the sample selected, empty before a seed; undefined after a
3407
+ * stop or when the table cannot be read.
3408
+ */
3409
+ async sample(_budget?: number): Promise<readonly Gauge[] | undefined> {
3410
+ await yieldTurn()
3411
+ if (this.#stopped) return undefined
3412
+ this.#timer ??= setInterval(() => this.#read(), SAMPLE_MS).unref()
3413
+ return this.#read()
3414
+ }
3415
+
3416
+ /**
3417
+ * Samples every {@link BURST_MS} until a time or an abort.
3418
+ *
3419
+ * @param until - The epoch millisecond after which no further sample starts.
3420
+ * @param signal - Ends the burst after the sample in flight.
3421
+ * @returns A promise that resolves when the burst ends.
3422
+ */
3423
+ async burst(until: number, signal: AbortSignal): Promise<void> {
3424
+ const rows = await this.sample()
3425
+ if (rows === undefined || signal.aborted || Date.now() >= until) return
3426
+ await wait(BURST_MS)
3427
+ await this.burst(until, signal)
3428
+ }
3429
+
3430
+ /**
3431
+ * Stops the timer; a later sample reads nothing.
3432
+ *
3433
+ * @returns A promise that resolves at once.
3434
+ */
3435
+ async stop(): Promise<void> {
3436
+ this.#stopped = true
3437
+ clearInterval(this.#timer)
3438
+ }
3439
+
3440
+ /**
3441
+ * Stops the timer at once, as {@link Census.stop} does, for the holder's unmeasured path.
3442
+ *
3443
+ * @returns A promise that resolves at once.
3444
+ */
3445
+ async destroy(): Promise<void> {
3446
+ this.#stopped = true
3447
+ clearInterval(this.#timer)
3448
+ }
3449
+
3450
+ #read(): readonly Gauge[] | undefined {
3451
+ const members = readMembers(this.#table)
3452
+ const group = this.#group
3453
+ if (members === undefined) return undefined
3454
+ if (group === undefined) return []
3455
+ const selected = selectGroup(members, group).map((member) => ({
3456
+ ...member,
3457
+ memory: readResident(member.pid, this.#table),
3458
+ }))
3459
+ this.#tally = tallySample(this.#tally, selected)
3460
+ const threshold = this.#threshold
3461
+ if (
3462
+ threshold === undefined ||
3463
+ this.#sealed ||
3464
+ this.#breached ||
3465
+ !exceedsThreshold(this.#tally, threshold)
3466
+ ) {
3467
+ return selected
3468
+ }
3469
+ this.#breached = true
3470
+ this.#breach(group, selected)
3471
+ return selected
3472
+ }
3473
+ }
3474
+
2903
3475
  /**
2904
3476
  * Runs the command as the holder, reads the tree at handover, and releases.
2905
3477
  *
2906
3478
  * @remarks
2907
- * A measured holder starts its command after its sampler readies, samples the tree back to back
2908
- * through the command's first {@link SAMPLE_MS} and once every {@link SAMPLE_MS} after, reads the
2909
- * handover through one more sample, and writes the run's record before it releases, so the command's
2910
- * next arrival reads it. When that sample lists a member, the handover reads, kills, and reads again
2911
- * through fresh snapshots, each a second PowerShell. A sampler that does not ready within
2912
- * {@link READY_MS} is destroyed, and the command runs unmeasured and records nothing. A record that
2913
- * opened a key prunes the history after the release. A light holder lowers its own priority before
2914
- * the spawn, and ends its tree when a sample passes the threshold.
3479
+ * A measured holder starts its command after its sampler readies, samples the tree through the
3480
+ * command's first {@link SAMPLE_MS}, back to back on Windows and every {@link BURST_MS} on Linux, and
3481
+ * once every {@link SAMPLE_MS} after, reads the handover through one more sample, and writes the
3482
+ * run's record before it releases, so the command's next arrival reads it. On Windows, when that
3483
+ * sample lists a member, the handover reads, kills, and reads again through fresh snapshots, each a
3484
+ * second PowerShell; on Linux the handover reads the launcher's group, as an unmeasured run's does.
3485
+ * A sampler that does not ready within {@link READY_MS} is destroyed, and the command runs
3486
+ * unmeasured and records nothing. A record that opened a key prunes the history after the release. A
3487
+ * light holder lowers its own priority before the spawn, and ends its tree when a sample passes the
3488
+ * threshold.
2915
3489
  *
2916
3490
  * @param options - The run.
2917
3491
  * @param launcher - The launcher's path.
@@ -2919,7 +3493,8 @@ export class Sampler {
2919
3493
  * @param measure - What a measured holder needs, or undefined when no limits apply.
2920
3494
  * @param token - This process's endpoint, which holds after the run record exists and leaves before
2921
3495
  * the run record is removed.
2922
- * @param sampler - The measured holder's sampler, started at arrival; the caller stops it.
3496
+ * @param sampler - The measured holder's sampler, a Windows {@link Sampler} started at arrival or a
3497
+ * Linux {@link Census}; the caller stops it.
2923
3498
  * @returns The launcher's code; 1 when a signal ended it; 69 when a light run passed its threshold;
2924
3499
  * 70 when the tree still reads as present or the ticket could not be removed; 75 when the launcher
2925
3500
  * could not start, the priority could not be lowered, or the run record could not be written.
@@ -2930,7 +3505,7 @@ export async function runHolder(
2930
3505
  sequence: number,
2931
3506
  measure?: Measure,
2932
3507
  token?: Token,
2933
- sampler?: Sampler,
3508
+ sampler?: Sampler | Census,
2934
3509
  ): Promise<number> {
2935
3510
  const { root } = options
2936
3511
  if (measure?.light !== undefined && !lowerPriority(process.pid)) {
@@ -2998,8 +3573,11 @@ export async function runHolder(
2998
3573
  `lane: the sampler did not answer the handover within ${String(HANDOVER_MS)} ms; ${quote(options.label)} records nothing`,
2999
3574
  )
3000
3575
  }
3576
+ // A Linux census row carries no creation date the Windows tree selection can bound.
3001
3577
  const quick =
3002
- rows !== undefined && typeof run === 'object' ? selectTree(rows, run, ended) : undefined
3578
+ process.platform === 'win32' && rows !== undefined && typeof run === 'object'
3579
+ ? selectTree(rows, run, ended)
3580
+ : undefined
3003
3581
  const sweep =
3004
3582
  typeof run !== 'object'
3005
3583
  ? { gone: false, members: [] }
@@ -3051,10 +3629,11 @@ export async function runHolder(
3051
3629
  * Reads what a run measures at arrival: the limits, the command's key, and its light footprint.
3052
3630
  *
3053
3631
  * @remarks
3054
- * A host other than Windows has no sampler, so it measures nothing and every ticket there is heavy.
3055
- * A `--solo` run is heavy whatever its command reads. A `mutate` run is keyed without its edits
3056
- * file and seeded by its wrapped command; {@link decideDirectory} keeps it apart from the tickets of
3057
- * its working directory.
3632
+ * The sampler is platform-defined: Windows has a PowerShell {@link Sampler} and Linux a
3633
+ * {@link Census} of its process table, and any other host has none, so it measures nothing and every
3634
+ * ticket there is heavy. A `--solo` run is heavy whatever its command reads. A `mutate` run is keyed
3635
+ * without its edits file and seeded by its wrapped command; {@link decideDirectory} keeps it apart
3636
+ * from the tickets of its working directory.
3058
3637
  *
3059
3638
  * @param options - The run.
3060
3639
  * @param token - This process's token.
@@ -3062,7 +3641,7 @@ export async function runHolder(
3062
3641
  * host has no sampler.
3063
3642
  */
3064
3643
  export function readMeasure(options: LaneOptions, token: string): Measure | undefined {
3065
- if (process.platform !== 'win32') return undefined
3644
+ if (process.platform !== 'win32' && process.platform !== 'linux') return undefined
3066
3645
  const limits = readLimits(options.root)
3067
3646
  if (limits === 'unread') {
3068
3647
  console.error(
@@ -3097,12 +3676,20 @@ export async function enterLane(
3097
3676
  try {
3098
3677
  mkdirSync(root, { recursive: true })
3099
3678
  const measure = readMeasure(options, tokenId)
3679
+ const threshold = measure?.light === undefined ? undefined : measure.limits.threshold
3100
3680
  const sampler =
3101
3681
  measure === undefined
3102
3682
  ? undefined
3103
- : new Sampler(measure.light === undefined ? undefined : measure.limits.threshold, (pid) =>
3104
- killMembers([pid]),
3105
- )
3683
+ : process.platform === 'win32'
3684
+ ? new Sampler(threshold, (pid) => killMembers([pid]))
3685
+ : new Census(threshold, (group, members) => {
3686
+ const kill = killCensus(group, members)
3687
+ if (!kill.settled) {
3688
+ console.error(
3689
+ `lane: the breach readings of ${quote(options.label)} ended unsettled, at ${String(KILL_BUDGET)} readings or on a failed reading; the lane killed the groups ${kill.groups.join(', ')} and the members ${kill.members.join(', ') || 'none'} it collected`,
3690
+ )
3691
+ }
3692
+ })
3106
3693
  try {
3107
3694
  await token.listen(renderEndpoint(root, tokenId))
3108
3695
  const edits =