@isentinel/machine-budget 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,675 @@
1
+ import { c as costKey, i as openSharedLedger, l as learnedCost, n as formatGb, o as treeProbe, r as nodePlatform, s as isLedgerLocked, t as describeRun } from "./run-text-1kRifnCt.mjs";
2
+ import process from "node:process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { doNothing } from "remeda";
5
+ // src/admission.ts
6
+ const BYTES_PER_GB = 2 ** 30;
7
+ const MAIN_MEMORY_SHARE = .5;
8
+ const RESERVE_SHARE = .15;
9
+ const LANE_MEMORY_SHARE = .15;
10
+ const LANE_THREADS = 2;
11
+ const SMALL_REQUEST_BYTES = 2 * BYTES_PER_GB;
12
+ const AGING_MS = 6e4;
13
+ /**
14
+ * Whether a request takes the small-job lane when the main lane is full.
15
+ *
16
+ * @param request - The worker range and the memory of one worker.
17
+ * @returns True when the minimum workers need 2 GiB or less.
18
+ */
19
+ function isSmallRequest(request) {
20
+ return request.minWorkers * request.memoryPerWorker <= SMALL_REQUEST_BYTES;
21
+ }
22
+ /**
23
+ * The oldest big request that has waited past the aging limit and started
24
+ * before this one, which every younger request waits behind.
25
+ *
26
+ * @param input - The time, this request's waiter id, and every waiter.
27
+ * @returns The aged waiter, or undefined when none blocks this request.
28
+ */
29
+ function olderAgedWaiter({ now, waiterId, waiters }) {
30
+ const since = waiters.find((waiter) => waiter.id === waiterId)?.since ?? now;
31
+ return waiters.filter((waiter) => waiter.isBig && waiter.since < since && now - waiter.since > AGING_MS).toSorted((a, b) => a.since - b.since)[0];
32
+ }
33
+ /**
34
+ * Decides one request: the largest worker count that fits, or why it waits.
35
+ *
36
+ * @param input - The machine, the leases and waiters, and the request.
37
+ * @returns A grant with its lane and workers, or the reason to wait.
38
+ */
39
+ function admit(input) {
40
+ const { leases, machine, request } = input;
41
+ const isBig = !isSmallRequest(request);
42
+ const isBehindAged = olderAgedWaiter(input) !== void 0;
43
+ const mainLeases = leases.filter((lease) => lease.lane === "main");
44
+ if (isBig && machine.pressure !== "normal" && mainLeases.length > 0) return {
45
+ kind: "wait",
46
+ reason: "memory pressure"
47
+ };
48
+ const headroom = machine.availableMemory - machine.totalMemory * RESERVE_SHARE;
49
+ const main = isBehindAged ? {
50
+ kind: "blocked",
51
+ reason: "older request"
52
+ } : fitWorkers(request, mainFit(input, headroom));
53
+ if (main.kind === "fit") return {
54
+ kind: "grant",
55
+ lane: "main",
56
+ workers: main.workers
57
+ };
58
+ if (!isBehindAged && mainLeases.length === 0) return {
59
+ kind: "grant",
60
+ lane: "main",
61
+ workers: request.minWorkers
62
+ };
63
+ const lane = isBig || request.isMainLaneOnly === true ? main : fitWorkers(request, laneFit(input, headroom));
64
+ return lane.kind === "fit" ? {
65
+ kind: "grant",
66
+ lane: "small",
67
+ workers: lane.workers
68
+ } : {
69
+ kind: "wait",
70
+ reason: main.reason
71
+ };
72
+ }
73
+ /**
74
+ * The most workers of a request that the run cap lets one run hold now, its
75
+ * own leases included.
76
+ *
77
+ * @param input - The machine, the leases and waiters, and the request.
78
+ * @returns The worker count, at most the maximum of the request.
79
+ */
80
+ function runCapWorkers(input) {
81
+ const { machine, request } = input;
82
+ const limit = mainLimit(machine);
83
+ const runs = activeRuns(input);
84
+ const byMemory = Math.floor(limit.memory / runs / request.memoryPerWorker);
85
+ return Math.min(request.maxWorkers, byMemory, Math.floor(limit.threads / runs));
86
+ }
87
+ function activeRuns({ leases, session, waiters }) {
88
+ const sessions = /* @__PURE__ */ new Set([session]);
89
+ for (const lease of leases) if (lease.lane === "main") sessions.add(lease.session);
90
+ for (const waiter of waiters) sessions.add(waiter.session);
91
+ return sessions.size;
92
+ }
93
+ function sum(leases) {
94
+ return leases.reduce((total, lease) => {
95
+ return {
96
+ memory: total.memory + lease.memory,
97
+ threads: total.threads + lease.threads
98
+ };
99
+ }, {
100
+ memory: 0,
101
+ threads: 0
102
+ });
103
+ }
104
+ function mainUsage(input) {
105
+ const mainLeases = input.leases.filter((lease) => lease.lane === "main");
106
+ const runLeases = mainLeases.filter((lease) => lease.session === input.session);
107
+ return {
108
+ machine: sum(mainLeases),
109
+ run: sum(runLeases)
110
+ };
111
+ }
112
+ function mainLimit(machine) {
113
+ return {
114
+ memory: machine.totalMemory * MAIN_MEMORY_SHARE,
115
+ threads: Math.max(1, machine.threads - LANE_THREADS)
116
+ };
117
+ }
118
+ function mainFit(input, headroom) {
119
+ const limit = mainLimit(input.machine);
120
+ const usage = mainUsage(input);
121
+ const runs = activeRuns(input);
122
+ return {
123
+ free: {
124
+ memory: limit.memory - usage.machine.memory,
125
+ threads: limit.threads - usage.machine.threads
126
+ },
127
+ headroom,
128
+ runFree: {
129
+ memory: limit.memory / runs - usage.run.memory,
130
+ threads: Math.floor(limit.threads / runs) - usage.run.threads
131
+ }
132
+ };
133
+ }
134
+ function laneFit({ leases, machine }, headroom) {
135
+ const used = sum(leases.filter((lease) => lease.lane === "small"));
136
+ return {
137
+ free: {
138
+ memory: machine.totalMemory * LANE_MEMORY_SHARE - used.memory,
139
+ threads: LANE_THREADS - used.threads
140
+ },
141
+ headroom,
142
+ runFree: void 0
143
+ };
144
+ }
145
+ function fitsPool(pool, demand) {
146
+ return demand.memory <= pool.memory && demand.threads <= pool.threads;
147
+ }
148
+ function failure(fit, demand) {
149
+ if (demand.memory > fit.free.memory) return "memory limit";
150
+ if (demand.threads > fit.free.threads) return "thread limit";
151
+ if (fit.runFree !== void 0 && !fitsPool(fit.runFree, demand)) return "run cap";
152
+ return demand.memory > fit.headroom ? "available memory" : void 0;
153
+ }
154
+ function demandOf(request, workers) {
155
+ return {
156
+ memory: workers * request.memoryPerWorker,
157
+ threads: workers
158
+ };
159
+ }
160
+ function fitWorkers(request, fit) {
161
+ const reason = failure(fit, demandOf(request, request.minWorkers));
162
+ if (reason !== void 0) return {
163
+ kind: "blocked",
164
+ reason
165
+ };
166
+ let workers = request.maxWorkers;
167
+ while (failure(fit, demandOf(request, workers)) !== void 0) workers -= 1;
168
+ return {
169
+ kind: "fit",
170
+ workers
171
+ };
172
+ }
173
+ // src/reclaim.ts
174
+ /** How often a live session stamps its heartbeat. */
175
+ const HEARTBEAT_INTERVAL_MS = 5e3;
176
+ const SUSPECT_MS = 3 * HEARTBEAT_INTERVAL_MS;
177
+ const STALE_MS = 6e4;
178
+ const CLOCK_JUMP_MS = 3e4;
179
+ const START_TOLERANCE_MS = 1e4;
180
+ /**
181
+ * Finds the sessions whose runs are gone.
182
+ *
183
+ * @param input - The sessions, the clock and a process probe.
184
+ * @returns The dead session ids.
185
+ */
186
+ function findDeadSessions(input) {
187
+ const { lastSeenAt, now } = input;
188
+ const isHeartbeatSkipped = lastSeenAt !== void 0 && (now - lastSeenAt > CLOCK_JUMP_MS || now < lastSeenAt);
189
+ return {
190
+ dead: input.sessions.filter((session) => {
191
+ return session.id !== input.self && isDead({
192
+ ...input,
193
+ isHeartbeatSkipped,
194
+ session
195
+ });
196
+ }).map((session) => session.id),
197
+ isHeartbeatSkipped
198
+ };
199
+ }
200
+ function isDead({ isHeartbeatSkipped, now, probe, session }) {
201
+ if (!probe.isAlive(session.pid)) return true;
202
+ const age = now - session.heartbeatAt;
203
+ if (age < SUSPECT_MS && age >= 0) return false;
204
+ const startedAt = probe.startTime(session.pid);
205
+ if (startedAt !== void 0 && Math.abs(startedAt - session.startedAt) > START_TOLERANCE_MS) return true;
206
+ return !isHeartbeatSkipped && age >= STALE_MS;
207
+ }
208
+ // src/prune.ts
209
+ /**
210
+ * Reads the sessions with no write lock, then probes their processes with no
211
+ * transaction open, so a slow probe never holds the ledger lock.
212
+ *
213
+ * @param surveyor - The session that surveys.
214
+ * @returns The sessions and the dead among them.
215
+ */
216
+ function surveySessions({ id, ledger, options }) {
217
+ const { platform } = options;
218
+ const { lastSeenAt, sessions } = ledger.read((reader) => {
219
+ return {
220
+ lastSeenAt: reader.lastSeenAt(),
221
+ sessions: reader.sessions()
222
+ };
223
+ });
224
+ const now = platform.now();
225
+ return {
226
+ ...findDeadSessions({
227
+ lastSeenAt,
228
+ now,
229
+ probe: platform.probe,
230
+ self: id,
231
+ sessions
232
+ }),
233
+ now,
234
+ sessions
235
+ };
236
+ }
237
+ /**
238
+ * Removes the dead sessions of a survey that no run changed since, and marks
239
+ * the ledger seen.
240
+ *
241
+ * @param transaction - The open write transaction.
242
+ * @param pruning - The survey and the time to write.
243
+ */
244
+ function prune(transaction, { now, survey }) {
245
+ const { dead, isHeartbeatSkipped, sessions } = survey;
246
+ const current = new Map(transaction.sessions().map((record) => [record.id, record]));
247
+ const unchanged = sessions.filter((record) => {
248
+ const stored = current.get(record.id);
249
+ return dead.includes(record.id) && stored !== void 0 && isSameSession(record, stored);
250
+ });
251
+ transaction.removeSessions(unchanged.map((record) => record.id));
252
+ if (isHeartbeatSkipped) transaction.refreshHeartbeats(now);
253
+ transaction.markSeen(now);
254
+ }
255
+ /**
256
+ * Prunes, then puts the session and its leases back with a fresh heartbeat.
257
+ *
258
+ * @param transaction - The open write transaction.
259
+ * @param restorer - The session and its survey.
260
+ * @returns The time of the writes.
261
+ */
262
+ function restore(transaction, { session, survey }) {
263
+ const { platform } = session.options;
264
+ const now = platform.now();
265
+ prune(transaction, {
266
+ now,
267
+ survey
268
+ });
269
+ transaction.upsertSession({
270
+ id: session.id,
271
+ heartbeatAt: now,
272
+ pid: platform.pid,
273
+ startedAt: platform.startedAt,
274
+ worktree: session.options.workspaceRoot
275
+ });
276
+ for (const lease of session.held.values()) transaction.addLease(lease);
277
+ return now;
278
+ }
279
+ /**
280
+ * Surveys the sessions, then restores the session in one write transaction.
281
+ *
282
+ * @param session - The session to restore.
283
+ */
284
+ function restoreSession(session) {
285
+ const survey = surveySessions(session);
286
+ session.ledger.transact((transaction) => restore(transaction, {
287
+ session,
288
+ survey
289
+ }));
290
+ }
291
+ function isSameSession(left, right) {
292
+ return left.heartbeatAt === right.heartbeatAt && left.pid === right.pid && left.startedAt === right.startedAt;
293
+ }
294
+ // src/wait-line.ts
295
+ /**
296
+ * Writes the line of a waiting request: its size, its reason, and the runs in
297
+ * its way. Behind an older request, that is the run of the aged request;
298
+ * otherwise each other run that holds leases, the largest first.
299
+ *
300
+ * @param notice - The request, the reason and the ledger rows.
301
+ * @returns The line and its reprint key.
302
+ */
303
+ function waitLine(notice) {
304
+ const { reason, request } = notice;
305
+ const need = formatGb(request.minWorkers * request.memoryPerWorker);
306
+ const { cause, runs } = causeOf(notice);
307
+ return {
308
+ line: `machine budget: waiting for ${need} and ${request.minWorkers} threads (${reason}); ${cause}; machine-budget-status prints the ledger`,
309
+ reprintKey: [reason, ...runs.toSorted()].join(" ")
310
+ };
311
+ }
312
+ function holdersOf({ leases, session: own, sessions }) {
313
+ return sessions.filter((session) => session.id !== own).map((session) => {
314
+ const owned = leases.filter((lease) => lease.session === session.id);
315
+ return {
316
+ memory: owned.reduce((total, lease) => total + lease.memory, 0),
317
+ session,
318
+ threads: owned.reduce((total, lease) => total + lease.threads, 0)
319
+ };
320
+ }).filter(({ threads }) => threads > 0).toSorted((a, b) => b.memory - a.memory);
321
+ }
322
+ function causeOf(notice) {
323
+ const { reason, sessions, waiters } = notice;
324
+ const aged = reason === "older request" ? olderAgedWaiter(notice) : void 0;
325
+ const blocker = waiters.find((waiter) => waiter.id === aged?.id);
326
+ if (blocker !== void 0) return {
327
+ cause: `behind ${describeRun(sessions.find((session) => session.id === blocker.session))} (${formatGb(blocker.memory)}, ${blocker.threads} threads)`,
328
+ runs: [blocker.id]
329
+ };
330
+ const holders = holdersOf(notice);
331
+ const parts = holders.map(({ memory, session, threads }) => {
332
+ return `${describeRun(session)} (${formatGb(memory)}, ${threads} threads)`;
333
+ });
334
+ return {
335
+ cause: parts.length === 0 ? "no run holds a lease" : `held by ${parts.join(", ")}`,
336
+ runs: holders.map(({ session }) => session.id)
337
+ };
338
+ }
339
+ // src/budget.ts
340
+ const FIRST_RETRY_MS = 250;
341
+ const LAST_RETRY_MS = 2e3;
342
+ /**
343
+ * Joins the machine budget. Each lease is one row in the shared ledger until
344
+ * it is released, the run closes, or a later run finds the run dead.
345
+ *
346
+ * @param options - The ledger, the platform and the logger.
347
+ * @returns The budget of this run.
348
+ */
349
+ function openBudget(options) {
350
+ if (isBudgetOff(options.environment)) return unlimitedBudget;
351
+ return sharedBudget(joinSession(options));
352
+ }
353
+ function heartbeat(session) {
354
+ try {
355
+ restoreSession(session);
356
+ } catch (err) {
357
+ session.options.log(`machine budget: heartbeat failed: ${String(err)}`);
358
+ }
359
+ }
360
+ function sharedBudget(session) {
361
+ const stop = session.options.platform.every(HEARTBEAT_INTERVAL_MS, () => {
362
+ heartbeat(session);
363
+ });
364
+ let isClosed = false;
365
+ return {
366
+ close: () => {
367
+ if (isClosed) return;
368
+ isClosed = true;
369
+ stop();
370
+ leaveSession(session);
371
+ },
372
+ isShared: true,
373
+ leaseAsync: async (request) => {
374
+ assertRequest(request);
375
+ return leaseAsync(session, request);
376
+ },
377
+ runCapWorkers: (request) => {
378
+ assertRequest(request);
379
+ return readRunCap(session, request);
380
+ },
381
+ tryLease: (request) => {
382
+ assertRequest(request);
383
+ const outcome = attempt({
384
+ isWaiting: false,
385
+ request,
386
+ session,
387
+ waiterId: randomUUID()
388
+ });
389
+ return outcome.kind === "grant" ? toLease({
390
+ outcome,
391
+ request,
392
+ session
393
+ }) : void 0;
394
+ }
395
+ };
396
+ }
397
+ function isBudgetOff(environment) {
398
+ const ci = environment["CI"];
399
+ return environment["MACHINE_BUDGET"] === "off" || ci !== void 0 && ci !== "false";
400
+ }
401
+ function unlimitedLease(request) {
402
+ assertRequest(request);
403
+ const { maxWorkers, memoryPerWorker } = request;
404
+ return {
405
+ memoryPerWorker,
406
+ release: doNothing(),
407
+ workers: maxWorkers
408
+ };
409
+ }
410
+ const unlimitedBudget = {
411
+ close: doNothing(),
412
+ isShared: false,
413
+ leaseAsync: async (request) => Promise.try(() => unlimitedLease(request)),
414
+ runCapWorkers: (request) => unlimitedLease(request).workers,
415
+ tryLease: unlimitedLease
416
+ };
417
+ function assertRequest({ maxWorkers, memoryPerWorker, minWorkers }) {
418
+ if (!Number.isSafeInteger(minWorkers) || minWorkers < 1 || maxWorkers < minWorkers) throw new RangeError(`a lease needs 1 <= minWorkers <= maxWorkers, got ${minWorkers} and ${maxWorkers}`);
419
+ if (!Number.isSafeInteger(maxWorkers) || !Number.isFinite(memoryPerWorker) || memoryPerWorker <= 0) throw new RangeError(`a lease needs a whole maxWorkers and memoryPerWorker above 0, got ${maxWorkers} and ${memoryPerWorker}`);
420
+ }
421
+ function joinSession(options) {
422
+ const session = {
423
+ id: randomUUID(),
424
+ held: /* @__PURE__ */ new Map(),
425
+ ledger: options.openLedger(),
426
+ options,
427
+ repository: options.platform.gitCommonDirectory(options.workspaceRoot)
428
+ };
429
+ restoreSession(session);
430
+ return session;
431
+ }
432
+ function leaveSession(session) {
433
+ session.ledger.transact((transaction) => {
434
+ transaction.removeSessions([session.id]);
435
+ });
436
+ session.ledger.close();
437
+ }
438
+ function workerMemory({ request, session, transaction }) {
439
+ if (request.cost === void 0) return request.memoryPerWorker;
440
+ const samples = transaction.costSamples(costKey(session.repository, request.cost));
441
+ return learnedCost(samples) ?? request.memoryPerWorker;
442
+ }
443
+ function recordWaiter({ session, transaction, waiterId }, { now, request }) {
444
+ transaction.upsertWaiter({
445
+ id: waiterId,
446
+ isBig: !isSmallRequest(request),
447
+ memory: request.minWorkers * request.memoryPerWorker,
448
+ session: session.id,
449
+ since: now,
450
+ threads: request.minWorkers
451
+ });
452
+ }
453
+ function grant({ session, transaction, waiterId }, { decision, request }) {
454
+ const { lane, workers } = decision;
455
+ const memory = workers * request.memoryPerWorker;
456
+ const lease = {
457
+ id: randomUUID(),
458
+ lane,
459
+ memory,
460
+ session: session.id,
461
+ threads: workers
462
+ };
463
+ transaction.addLease(lease);
464
+ transaction.removeWaiter(waiterId);
465
+ return {
466
+ kind: "grant",
467
+ lease,
468
+ memoryPerWorker: request.memoryPerWorker
469
+ };
470
+ }
471
+ function decide(context) {
472
+ const { isWaiting, reading, session, survey, transaction, waiterId } = context;
473
+ const { platform } = session.options;
474
+ const now = restore(transaction, {
475
+ session,
476
+ survey
477
+ });
478
+ const request = {
479
+ ...context.request,
480
+ memoryPerWorker: workerMemory(context)
481
+ };
482
+ const input = {
483
+ leases: transaction.leases(),
484
+ machine: {
485
+ ...reading,
486
+ threads: platform.threads,
487
+ totalMemory: platform.totalMemory
488
+ },
489
+ now,
490
+ request,
491
+ session: session.id,
492
+ waiterId,
493
+ waiters: transaction.waiters()
494
+ };
495
+ const decision = admit(input);
496
+ if (decision.kind === "grant") return grant(context, {
497
+ decision,
498
+ request
499
+ });
500
+ if (isWaiting) recordWaiter(context, {
501
+ now,
502
+ request
503
+ });
504
+ return {
505
+ kind: "wait",
506
+ ...waitLine({
507
+ ...input,
508
+ ...decision,
509
+ sessions: transaction.sessions()
510
+ })
511
+ };
512
+ }
513
+ function attempt(pending) {
514
+ const survey = surveySessions(pending.session);
515
+ const reading = pending.session.options.platform.readMemory();
516
+ return pending.session.ledger.transact((transaction) => {
517
+ return decide({
518
+ ...pending,
519
+ reading,
520
+ survey,
521
+ transaction
522
+ });
523
+ });
524
+ }
525
+ function readRunCap(session, request) {
526
+ const { platform } = session.options;
527
+ return session.ledger.transact((transaction) => {
528
+ return runCapWorkers({
529
+ leases: transaction.leases(),
530
+ machine: {
531
+ threads: platform.threads,
532
+ totalMemory: platform.totalMemory
533
+ },
534
+ request: {
535
+ ...request,
536
+ memoryPerWorker: workerMemory({
537
+ request,
538
+ session,
539
+ transaction
540
+ })
541
+ },
542
+ session: session.id,
543
+ waiters: transaction.waiters()
544
+ });
545
+ });
546
+ }
547
+ function releaseLease({ lease, report, request, session }) {
548
+ if (!session.held.delete(lease.id)) return;
549
+ const survey = surveySessions(session);
550
+ session.ledger.transact((transaction) => {
551
+ const now = session.options.platform.now();
552
+ prune(transaction, {
553
+ now,
554
+ survey
555
+ });
556
+ transaction.removeLease(lease.id);
557
+ if (report !== void 0 && request.cost !== void 0) {
558
+ const bytes = report.peakPerWorker ?? Math.round(report.peakMemory / lease.threads);
559
+ transaction.addSample({
560
+ key: costKey(session.repository, request.cost),
561
+ at: now,
562
+ bytes
563
+ });
564
+ }
565
+ });
566
+ }
567
+ function toLease({ outcome, request, session }) {
568
+ const { lease } = outcome;
569
+ session.held.set(lease.id, lease);
570
+ return {
571
+ memoryPerWorker: outcome.memoryPerWorker,
572
+ release: (report) => {
573
+ releaseLease({
574
+ lease,
575
+ report,
576
+ request,
577
+ session
578
+ });
579
+ },
580
+ workers: lease.threads
581
+ };
582
+ }
583
+ function attemptUnlessLocked(pending) {
584
+ try {
585
+ return attempt(pending);
586
+ } catch (err) {
587
+ if (isLedgerLocked(err)) return { kind: "locked" };
588
+ throw err;
589
+ }
590
+ }
591
+ async function leaseAsync(session, request) {
592
+ const pending = {
593
+ isWaiting: true,
594
+ request,
595
+ session,
596
+ waiterId: randomUUID()
597
+ };
598
+ let reprintKey;
599
+ for (let delay = FIRST_RETRY_MS;; delay = Math.min(delay * 2, LAST_RETRY_MS)) {
600
+ const outcome = attemptUnlessLocked(pending);
601
+ if (outcome.kind === "grant") return toLease({
602
+ outcome,
603
+ request,
604
+ session
605
+ });
606
+ if (outcome.kind === "wait" && outcome.reprintKey !== reprintKey) {
607
+ ({reprintKey} = outcome);
608
+ session.options.log(outcome.line);
609
+ }
610
+ await session.options.platform.sleepAsync(delay);
611
+ }
612
+ }
613
+ // src/tree-watch.ts
614
+ const TREE_SAMPLE_MS = 100;
615
+ const BLIND_WATCH = { stop: () => ({
616
+ peakMemory: void 0,
617
+ peakPerWorker: void 0
618
+ }) };
619
+ /**
620
+ * Samples a process tree until the watch stops.
621
+ *
622
+ * @param options - The timer and the probe of the tree.
623
+ * @returns The watch, which samples until its stop reads the peaks.
624
+ */
625
+ function watchWith({ every, probe }) {
626
+ if (probe === void 0) return BLIND_WATCH;
627
+ probe.sample();
628
+ const stopSampling = every(TREE_SAMPLE_MS, probe.sample);
629
+ return { stop: () => {
630
+ stopSampling();
631
+ probe.sample();
632
+ const peaks = [...probe.descendants().values()];
633
+ const result = {
634
+ peakMemory: probe.tree(),
635
+ peakPerWorker: peaks.length === 0 ? void 0 : Math.max(...peaks)
636
+ };
637
+ probe.close?.();
638
+ return result;
639
+ } };
640
+ }
641
+ // src/index.ts
642
+ /**
643
+ * Joins the budget that every dev tool on this machine shares. Close it when
644
+ * the run ends; a run that dies is taken back by the next run that leases.
645
+ * `MACHINE_BUDGET=off` or CI turns it off, and `MACHINE_BUDGET_DIR` moves the
646
+ * ledger.
647
+ *
648
+ * @param options - The logger and the workspace root.
649
+ * @returns The budget of this run.
650
+ */
651
+ function openMachineBudget(options) {
652
+ return openBudget({
653
+ ...options,
654
+ environment: process.env,
655
+ openLedger: openSharedLedger,
656
+ platform: nodePlatform
657
+ });
658
+ }
659
+ /**
660
+ * Watches a running process and every process it starts from now on, to
661
+ * report the peaks that a lease release takes. Call it right after the spawn;
662
+ * a descendant that starts and ends between two samples is missed. On Windows
663
+ * the root joins a Job Object; on Linux the peaks are resident sets read from
664
+ * `/proc`; elsewhere both peaks are undefined. It never throws.
665
+ *
666
+ * @param pid - The pid of the process at the top of the tree.
667
+ * @returns The watch; stop it once the process exits.
668
+ */
669
+ function watchTree(pid) {
670
+ return watchWith({
671
+ every: nodePlatform.every,
672
+ probe: treeProbe(pid)
673
+ });
674
+ }
675
+ export { openMachineBudget, watchTree };