@dibssoftware/dibs 0.0.0-stage → 0.0.178
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/CHANGELOG.md +577 -0
- package/LICENSE +670 -0
- package/README.md +234 -2
- package/bin/dibs-guard.mjs +7 -0
- package/bin/dibs.mjs +526 -0
- package/docs/benchmarks.md +193 -0
- package/docs/files.md +30 -0
- package/docs/guard.md +91 -0
- package/docs/later.md +43 -0
- package/docs/machines.md +147 -0
- package/docs/questions.md +78 -0
- package/docs/relay.md +196 -0
- package/docs/releasing.md +25 -0
- package/docs/scheduling.md +163 -0
- package/docs/simulators.md +17 -0
- package/package.json +44 -4
- package/skills/dibs/SKILL.md +162 -0
- package/src/acquire.mjs +697 -0
- package/src/admin.mjs +145 -0
- package/src/agents.mjs +145 -0
- package/src/alerts.mjs +437 -0
- package/src/answers.mjs +65 -0
- package/src/board.mjs +202 -0
- package/src/broker.mjs +369 -0
- package/src/commands.mjs +801 -0
- package/src/config.mjs +320 -0
- package/src/connect.mjs +106 -0
- package/src/cool.mjs +160 -0
- package/src/diskwarn.mjs +161 -0
- package/src/events.mjs +94 -0
- package/src/files.mjs +1100 -0
- package/src/guard.mjs +583 -0
- package/src/history.mjs +247 -0
- package/src/hogs.mjs +214 -0
- package/src/later.mjs +487 -0
- package/src/measure.mjs +262 -0
- package/src/nodecheck.mjs +17 -0
- package/src/notices.mjs +121 -0
- package/src/ondemand.mjs +572 -0
- package/src/overlap.mjs +151 -0
- package/src/override.mjs +351 -0
- package/src/owner.mjs +30 -0
- package/src/plain.mjs +467 -0
- package/src/platform.mjs +357 -0
- package/src/preempt.mjs +438 -0
- package/src/primer.mjs +61 -0
- package/src/proc.mjs +98 -0
- package/src/progress.mjs +158 -0
- package/src/qr.mjs +204 -0
- package/src/questions.mjs +389 -0
- package/src/quota.mjs +81 -0
- package/src/reads.mjs +54 -0
- package/src/relay.mjs +779 -0
- package/src/remote.mjs +584 -0
- package/src/reset.mjs +127 -0
- package/src/schedule.mjs +995 -0
- package/src/scratch.mjs +61 -0
- package/src/serve.mjs +736 -0
- package/src/service.mjs +221 -0
- package/src/shard.mjs +59 -0
- package/src/simctl.mjs +42 -0
- package/src/simpool.mjs +258 -0
- package/src/state.mjs +201 -0
- package/src/stats.mjs +328 -0
- package/src/style.mjs +44 -0
- package/src/talk.mjs +523 -0
- package/src/thin.sh +130 -0
- package/src/trust.mjs +152 -0
- package/src/util.mjs +184 -0
- package/src/version.mjs +2 -0
- package/src/web.mjs +1117 -0
- package/src/worker.mjs +318 -0
package/src/schedule.mjs
ADDED
|
@@ -0,0 +1,995 @@
|
|
|
1
|
+
// Who goes next. Pure functions of the state, config, history and clock, so
|
|
2
|
+
// they can be tested without processes.
|
|
3
|
+
import { resCfg, machine, hardware, RECENT, SWAP_WINDOW } from './config.mjs';
|
|
4
|
+
import { bytes, ms, dur, gb, now, runsOf, indexed } from './util.mjs';
|
|
5
|
+
import { tag, isMine } from './proc.mjs';
|
|
6
|
+
import { isFiles, overlap, short, clash, coversAgent, elsewhere } from './files.mjs';
|
|
7
|
+
import { poolBlock } from './simpool.mjs';
|
|
8
|
+
import { dibsMem } from './platform.mjs';
|
|
9
|
+
import { alongside, merge, onTop } from './overlap.mjs';
|
|
10
|
+
|
|
11
|
+
const MIN = 6e4;
|
|
12
|
+
|
|
13
|
+
// How far each priority moves a request in line. A high job goes ahead of
|
|
14
|
+
// normal ones unless they have waited an hour longer, and urgent ahead of high
|
|
15
|
+
// the same way: on 2026-10-19 two high jobs ("owner waiting on build 125") sat
|
|
16
|
+
// sixth and ninth behind normal jobs that had waited 15 minutes longer, under
|
|
17
|
+
// the old 10-minute shift, until someone boosted them to urgent by hand.
|
|
18
|
+
export const PRIORITY_SHIFT = {
|
|
19
|
+
urgent: 120 * MIN, // something is broken or a person is waiting right now
|
|
20
|
+
high: 60 * MIN, // on the critical path
|
|
21
|
+
normal: 0,
|
|
22
|
+
low: -10 * MIN, // nobody is waiting on it
|
|
23
|
+
idle: -60 * MIN, // only when the machine is otherwise quiet
|
|
24
|
+
};
|
|
25
|
+
export const PRIORITIES = Object.keys(PRIORITY_SHIFT);
|
|
26
|
+
// Also accept 1 (urgent) to 5 (idle).
|
|
27
|
+
export const priority = p => (/^[1-5]$/.test(String(p)) ? PRIORITIES[Number(p) - 1] : String(p).toLowerCase());
|
|
28
|
+
// These need a reason everyone can see, and the background ones run at low OS priority.
|
|
29
|
+
export const NEEDS_REASON = new Set(['urgent', 'high']);
|
|
30
|
+
export const BACKGROUND = new Set(['low', 'idle']);
|
|
31
|
+
|
|
32
|
+
const DEADLINE_WINDOW = 20 * MIN; // a deadline starts to count when slack drops under this
|
|
33
|
+
export const DEADLINE_MAX = 60 * MIN; // and moves a request up by at most this
|
|
34
|
+
// Shortest first, with aging: a waiter moves back by its expected run time,
|
|
35
|
+
// counted from PROBE, so a job shorter than that moves up and a longer one
|
|
36
|
+
// back. A 30-second check that arrives within 19 minutes of a 20-minute suite
|
|
37
|
+
// goes first; one that arrives later doesn't. So a job waits behind shorter work
|
|
38
|
+
// at most about its own run time, never more than LENGTH_MAX. On 2026-10-20 46%
|
|
39
|
+
// of jobs waited longer than they ran (57% over the week before).
|
|
40
|
+
// A command dibs has never seen counts as PROBE long, not the worst case: its
|
|
41
|
+
// first run teaches its length.
|
|
42
|
+
const PROBE = 2 * MIN;
|
|
43
|
+
const LENGTH_MAX = 60 * MIN;
|
|
44
|
+
const SHARE_WINDOW = 60 * MIN; // recent use counted for fair share
|
|
45
|
+
const SHARE_MAX = 10 * MIN; // heavy recent users move back by up to this
|
|
46
|
+
const SHARE_RATE = 0.2; // 5 minutes of use costs a minute back, so SHARE_MAX takes 50 minutes of use
|
|
47
|
+
export const UNKNOWN_RUN = 5 * MIN; // run-time guess for a job with no history
|
|
48
|
+
// A running job always has at least this long left, so one that has overrun
|
|
49
|
+
// its typical time doesn't forecast its slot as free right now.
|
|
50
|
+
const MIN_LEFT = 30e3;
|
|
51
|
+
const BIG_JOB = 2 * 1024 ** 3; // jobs this size and up wait for minFreeMem (the ram rule)
|
|
52
|
+
export const IDLE_MEM_FREE = 30; // idle work also waits for this % of memory free
|
|
53
|
+
// A session's hold moves its other waits up only this long after it was taken.
|
|
54
|
+
// Past that it's sitting on the resource, and dibs says to release it instead.
|
|
55
|
+
const HOLD_FRESH = 10 * MIN;
|
|
56
|
+
|
|
57
|
+
export function typical(hist, key) {
|
|
58
|
+
const d = runsOf(hist, key).filter(h => !h.failed).slice(-10).map(h => h.dur).sort((a, b) => a - b);
|
|
59
|
+
return d.length ? d[Math.floor(d.length / 2)] : null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// How much free disk a command eats while it runs: the middle of its last ten
|
|
63
|
+
// runs' shares of the disk's fall (src/measure.mjs shareDisk), or, until it has
|
|
64
|
+
// DISK_RUNS, its resources' last twenty.
|
|
65
|
+
// On 2026-10-22 a private simulator declared 6 GB, started with 6.0 GB free,
|
|
66
|
+
// and took the disk to 0.7 GB: the floor holds only with its real need on top.
|
|
67
|
+
const DISK_RUNS = 3;
|
|
68
|
+
const DISK_BY_RES = new WeakMap();
|
|
69
|
+
const mid = xs => (xs.sort((a, b) => a - b), xs[Math.floor(xs.length / 2)]);
|
|
70
|
+
export function typicalDisk(hist, key) {
|
|
71
|
+
if (!hist) return null;
|
|
72
|
+
const d = runsOf(hist, key).filter(h => h.ate != null).slice(-10).map(h => h.ate);
|
|
73
|
+
if (d.length >= DISK_RUNS) return mid(d);
|
|
74
|
+
const res = key?.split('|')[0];
|
|
75
|
+
if (!res) return null;
|
|
76
|
+
let by = DISK_BY_RES.get(hist);
|
|
77
|
+
if (!by) {
|
|
78
|
+
by = new Map();
|
|
79
|
+
for (const h of hist) if (h.ate != null && h.key) { const r = h.key.split('|')[0]; (by.get(r) || by.set(r, []).get(r)).push(h.ate); }
|
|
80
|
+
DISK_BY_RES.set(hist, by);
|
|
81
|
+
}
|
|
82
|
+
const r = (by.get(res) || []).slice(-20);
|
|
83
|
+
return r.length >= DISK_RUNS ? mid([...r]) : null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// What a command has really taken comes first; --est only stands in until dibs has seen it run.
|
|
87
|
+
export const expected = (x, hist) => typical(hist, x.key) || x.est || UNKNOWN_RUN;
|
|
88
|
+
export const known = (x, hist) => !!(x.est || typical(hist, x.key));
|
|
89
|
+
// Its slow runs: the 90th percentile of the last ten, for promises that mustn't
|
|
90
|
+
// be broken (a job let past a waiter has to be done before that one could start).
|
|
91
|
+
export function slow(hist, key) {
|
|
92
|
+
const d = runsOf(hist, key).filter(h => !h.failed).slice(-10).map(h => h.dur).sort((a, b) => a - b);
|
|
93
|
+
return d.length ? d[Math.min(d.length - 1, Math.floor(d.length * 0.9))] : null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Which jobs slow each other down, from the history alone: each run is an
|
|
97
|
+
// interval [at - dur, at] under its key, whose first part is its resources. A
|
|
98
|
+
// command's runs that spent most of their time beside a run on resource r,
|
|
99
|
+
// against its runs that didn't: the ratio of their middle durations. Null until
|
|
100
|
+
// there are PAIR_RUNS of each. Two browser suites on one Mac can take twice as
|
|
101
|
+
// long side by side, or barely longer; this tells which.
|
|
102
|
+
const PAIR_RUNS = 3;
|
|
103
|
+
const PAIR_RECENT = 20; // the last runs of a command that count: machines and suites change
|
|
104
|
+
const PAIRS = new WeakMap();
|
|
105
|
+
function byRes(hist) {
|
|
106
|
+
let x = PAIRS.get(hist);
|
|
107
|
+
if (x?.n === hist.length) return x;
|
|
108
|
+
x = { n: hist.length, res: new Map(), memo: new Map() };
|
|
109
|
+
for (const h of hist) {
|
|
110
|
+
if (!h.at || !h.dur) continue;
|
|
111
|
+
for (const r of String(h.key).split('|')[0].split(',')) (x.res.get(r) || x.res.set(r, []).get(r)).push(h);
|
|
112
|
+
}
|
|
113
|
+
PAIRS.set(hist, x);
|
|
114
|
+
return x;
|
|
115
|
+
}
|
|
116
|
+
const middle = xs => { const v = [...xs].sort((a, b) => a - b); return v[Math.floor(v.length / 2)]; };
|
|
117
|
+
export function slowdown(hist, key, r) {
|
|
118
|
+
const x = byRes(hist), k = `${key}\n${r}`;
|
|
119
|
+
if (x.memo.has(k)) return x.memo.get(k);
|
|
120
|
+
const others = x.res.get(r) || [];
|
|
121
|
+
const beside = h => others.some(o => o !== h && Math.min(o.at, h.at) - Math.max(o.at - o.dur, h.at - h.dur) >= h.dur / 2);
|
|
122
|
+
const runs = runsOf(hist, key).filter(h => !h.failed && h.at && h.dur).slice(-PAIR_RECENT);
|
|
123
|
+
const yes = [], no = [];
|
|
124
|
+
for (const h of runs) (beside(h) ? yes : no).push(h.dur);
|
|
125
|
+
const f = yes.length >= PAIR_RUNS && no.length >= PAIR_RUNS ? middle(yes) / middle(no) : null;
|
|
126
|
+
x.memo.set(k, f);
|
|
127
|
+
return f;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Time a lease has spent paused (src/preempt.mjs), which its run clock skips.
|
|
131
|
+
export const pausedFor = (l, t = now()) => (l.pausedMs || 0) + (l.pausedAt ? t - l.pausedAt : 0);
|
|
132
|
+
// A lease paused for an urgent or high job has lent it its cores, and its
|
|
133
|
+
// slots of the resources that job needs. Its other slots stay its own: they're
|
|
134
|
+
// still taken when it resumes. With r, lent on that resource.
|
|
135
|
+
export const lent = (l, r) => !!l.pauses?.some(p => p.lease != null && (!r || !p.res || p.res.includes(r)));
|
|
136
|
+
// How far a running lease is over the memory dibs handed it, by its last
|
|
137
|
+
// measurement (src/measure.mjs), or 0. Footprints wobble by a few percent, so
|
|
138
|
+
// under OVER_SLACK past its number a job counts as on budget.
|
|
139
|
+
// A job planned at the budget (measure.mjs sized) is measured against what it usually uses.
|
|
140
|
+
const OVER_SLACK = 0.1;
|
|
141
|
+
export const overBy = l => { const m = Math.max(l.mem, l.usual || 0); return l.use && l.use.mem > m * (1 + OVER_SLACK) ? l.use.mem - m : 0; };
|
|
142
|
+
|
|
143
|
+
// Time left on a lease, or null when there's nothing to go on.
|
|
144
|
+
export function remaining(l, hist, t = now()) {
|
|
145
|
+
if (l.kind === 'hold') return Math.max(l.expires - t, 0);
|
|
146
|
+
const e = typical(hist, l.key) || l.est;
|
|
147
|
+
return e == null ? null : Math.max(e - (t - l.start - pausedFor(l, t)), MIN_LEFT);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Time an agent spent on these resources in the last hour, and which of them
|
|
151
|
+
// it used. Only the resources it's waiting for count: an hour of tests says
|
|
152
|
+
// nothing about whose turn the simulator is.
|
|
153
|
+
export function recentUse(hist, who, res, t = now()) {
|
|
154
|
+
const want = new Set(res);
|
|
155
|
+
let total = 0;
|
|
156
|
+
const on = new Set();
|
|
157
|
+
for (const h of indexed(hist).byWho.get(who) || []) {
|
|
158
|
+
if (t - h.at >= SHARE_WINDOW) continue;
|
|
159
|
+
const hit = h.res.filter(r => want.has(r));
|
|
160
|
+
if (!hit.length) continue;
|
|
161
|
+
total += Math.min(h.dur, SHARE_WINDOW);
|
|
162
|
+
for (const r of hit) on.add(r);
|
|
163
|
+
}
|
|
164
|
+
return { total, res: [...on] };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// A waiter's place in line: arrival time, moved by each rule. Every rule is
|
|
168
|
+
// bounded, so a job is never passed forever. Lower goes sooner.
|
|
169
|
+
// priority urgent +2h, high +1h ... idle -60m
|
|
170
|
+
// deadline as slack drops under 20m, up to +60m
|
|
171
|
+
// length shorter than 2m moves up, longer moves back, by its expected run time (at most 60m)
|
|
172
|
+
// recent use agents who used the same resources a lot in the last hour, up to -10m (fair share)
|
|
173
|
+
// holds already holds a lease (holdingOf), moves like high
|
|
174
|
+
// let ahead someone yielded their place to you
|
|
175
|
+
// A waiter that already holds part of what it needs (holdingOf) moves up this
|
|
176
|
+
// far: enough to pass waiters that hold nothing, not past a high job.
|
|
177
|
+
const HOLDING_SHIFT = 10 * MIN;
|
|
178
|
+
export function rankParts(q, hist, t = now()) {
|
|
179
|
+
const parts = [];
|
|
180
|
+
const add = (label, shift) => { if (Math.abs(shift) >= 1000) parts.push({ label, shift: Math.round(shift) }); };
|
|
181
|
+
add(q.prio, PRIORITY_SHIFT[q.prio] || 0);
|
|
182
|
+
if (q.holding && (!q.prio || q.prio === 'normal')) add(`holds ${q.holding.res.join(',')}`, HOLDING_SHIFT);
|
|
183
|
+
if (q.by) {
|
|
184
|
+
const slack = q.by - t - expected(q, hist);
|
|
185
|
+
if (slack < DEADLINE_WINDOW) add('deadline', Math.min(DEADLINE_MAX, DEADLINE_WINDOW - slack));
|
|
186
|
+
}
|
|
187
|
+
const e = known(q, hist) ? expected(q, hist) : PROBE;
|
|
188
|
+
add(e < PROBE ? 'short job' : 'long job', PROBE - Math.min(e, LENGTH_MAX));
|
|
189
|
+
const usedRecently = recentUse(hist, q.who, q.res, t).total;
|
|
190
|
+
if (usedRecently > 0) add('recent use', -Math.min(SHARE_MAX, usedRecently * SHARE_RATE));
|
|
191
|
+
let value = q.enq - parts.reduce((a, p) => a + p.shift, 0);
|
|
192
|
+
if (q.yieldRank != null && q.yieldRank < value) { add('let ahead', value - q.yieldRank); value = q.yieldRank; }
|
|
193
|
+
return { value, parts };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export const rank = (q, hist, t = now()) => rankParts(q, hist, t).value;
|
|
197
|
+
// Each waiter's rank is worked out once per sort, not once per comparison.
|
|
198
|
+
export const byRank = (hist, t = now()) => {
|
|
199
|
+
const memo = new Map();
|
|
200
|
+
const r = q => { if (!memo.has(q)) memo.set(q, rank(q, hist, t)); return memo.get(q); };
|
|
201
|
+
return (a, b) => r(a) - r(b) || a.id - b.id;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
export const sum = (xs, f) => xs.reduce((a, x) => a + f(x), 0);
|
|
205
|
+
|
|
206
|
+
// Resources the waiter already has: its agent's holds, and the dibs run it's
|
|
207
|
+
// nested in (me.outer). They cover its own runs on the same resource, so you
|
|
208
|
+
// never queue behind yourself. Two subagents of one session are different
|
|
209
|
+
// agents when the guard told dibs which is which (src/files.mjs).
|
|
210
|
+
const covers = (h, x) => (h.kind === 'hold' && !!x.spid && h.pid === x.spid && coversAgent(h, x)) || (!!x.outer && h.id === x.outer);
|
|
211
|
+
export const holdsOf = (s, me) => new Set(s.leases.filter(l => covers(l, me)).flatMap(l => l.res));
|
|
212
|
+
// Slots of r in use. A run covered by its own hold or outer run doesn't count
|
|
213
|
+
// twice, but only while that lasts: once it ends, the run is a user again.
|
|
214
|
+
export const coveredNow = (s, l, r) => l.covered?.includes(r) && s.leases.some(h => h.res.includes(r) && covers(h, l));
|
|
215
|
+
|
|
216
|
+
// What a waiter already holds while it waits, or null: the dibs run it's
|
|
217
|
+
// nested in, unless that runs at low or idle priority, and its session's holds
|
|
218
|
+
// taken in the last HOLD_FRESH. Leaving those idle while it waits stalls work
|
|
219
|
+
// that matters (a ship holding deploy waiting for a build), so it goes ahead
|
|
220
|
+
// of waiters that hold nothing, like high priority, and passes the load
|
|
221
|
+
// ceiling. It never pauses anyone's job (preempt.mjs goes by -p only). Only
|
|
222
|
+
// configured resources count: a lease on a made-up name costs nobody anything,
|
|
223
|
+
// so wrapping work in one mustn't buy a place in line.
|
|
224
|
+
export function holdingOf(s, q, cfg, t = now()) {
|
|
225
|
+
const ls = s.leases.filter(l => l.res.some(r => cfg.resources[r]) && ((q.outer && l.id === q.outer && !BACKGROUND.has(l.prio))
|
|
226
|
+
|| (l.kind === 'hold' && q.spid && l.pid === q.spid && t - l.start < HOLD_FRESH)));
|
|
227
|
+
if (!ls.length) return null;
|
|
228
|
+
return { res: [...new Set(ls.flatMap(l => l.res))], purpose: ls.find(l => l.purpose)?.purpose || '' };
|
|
229
|
+
}
|
|
230
|
+
// A job running on top of a full resource (src/overlap.mjs) doesn't take a slot.
|
|
231
|
+
export const used = (s, r) => s.leases.filter(l => l.res.includes(r) && !coveredNow(s, l, r) && !lent(l, r) && !onTop(l, r)).length;
|
|
232
|
+
|
|
233
|
+
// A resource that's one at a time per project (exclusiveBy: "repo", deploys by default):
|
|
234
|
+
// slots is per project, and across caps every project's together. A 6-second web deploy
|
|
235
|
+
// waited behind another project's TestFlight upload in the one deploy slot, and the person
|
|
236
|
+
// had to tell its agent to go around dibs (2026-11-03). A config that says only slots: 1
|
|
237
|
+
// keeps the default's exclusiveBy and across, so it reads per project too.
|
|
238
|
+
const byRepo = (cfg, r) => resCfg(cfg, r).exclusiveBy === 'repo';
|
|
239
|
+
// A lease's or waiter's project (src/files.mjs projectKey), or its folder before dibs recorded one.
|
|
240
|
+
export const laneOf = x => x.repo || x.cwd || null;
|
|
241
|
+
// The leases holding r's slots that q waits on: on a per-project resource, only its own project's.
|
|
242
|
+
const holdersFor = (s, q, r, cfg) => s.leases.filter(l => l.res.includes(r) && !coveredNow(s, l, r) && !lent(l, r) && !onTop(l, r)
|
|
243
|
+
&& (!byRepo(cfg, r) || laneOf(l) === laneOf(q)));
|
|
244
|
+
// Free slots of r for q, and whether the cap across projects is what's full.
|
|
245
|
+
export function roomFor(s, q, r, cfg) {
|
|
246
|
+
const c = resCfg(cfg, r);
|
|
247
|
+
if (!byRepo(cfg, r)) return { open: c.slots - used(s, r), across: false };
|
|
248
|
+
const mine = c.slots - holdersFor(s, q, r, cfg).length, all = (c.across ?? c.slots) - used(s, r);
|
|
249
|
+
return { open: Math.min(mine, all), across: all < mine };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Time a lease should end. Without history, assume it runs at least UNKNOWN_RUN.
|
|
253
|
+
const endOf = (l, hist, t) => t + (remaining(l, hist, t) ?? Math.max(UNKNOWN_RUN - (t - l.start - pausedFor(l, t)), MIN_LEFT));
|
|
254
|
+
// When a lease's slot of r frees. A slot lent to an urgent job goes back to the
|
|
255
|
+
// paused job when that one ends, so it frees only after both.
|
|
256
|
+
const slotEnd = (s, l, hist, t, r) => endOf(l, hist, t)
|
|
257
|
+
+ sum(s.leases.filter(p => p.res.includes(r) && p.pauses?.some(x => x.lease === l.id)), p => endOf(p, hist, t) - t);
|
|
258
|
+
|
|
259
|
+
// Whether the machine is short on memory right now, or null. On macOS the
|
|
260
|
+
// OS's free-memory figure counts compressed and cached pages as free, so it
|
|
261
|
+
// can read 60% free while the Mac pages gigabytes to disk. Two signals don't
|
|
262
|
+
// lie: the OS's own memory pressure (warning or critical), and swap past
|
|
263
|
+
// cfg.maxSwap that grew by SWAP_GROWTH in the last 5 minutes. Swap alone
|
|
264
|
+
// doesn't count: macOS keeps it allocated for hours after the crunch ends.
|
|
265
|
+
// And swap lives on the startup disk, so it eats the free disk every job needs.
|
|
266
|
+
export const SWAP_GROWTH = 512 * 1024 ** 2;
|
|
267
|
+
// Jobs at or under this size start through swap and warning-level pressure (not critical).
|
|
268
|
+
export const LIGHT_MEM = 512 * 1024 ** 2; // a few hundred MB of churn is normal; half a gigabyte in 5 minutes is paging for real
|
|
269
|
+
// Growing over 5 minutes and still growing now (config.mjs RECENT), at the
|
|
270
|
+
// same rate. The 5-minute total alone stays high for 5 minutes after swap
|
|
271
|
+
// stops, which held work back and paused jobs long after the crunch.
|
|
272
|
+
const RECENT_SHARE = RECENT / SWAP_WINDOW;
|
|
273
|
+
export const swapGrowing = m => (m.swapGrowth || 0) > SWAP_GROWTH && (m.swapRecent ?? m.swapGrowth ?? 0) > SWAP_GROWTH * RECENT_SHARE;
|
|
274
|
+
export function swapping(cfg, m = machine()) {
|
|
275
|
+
if (m.vmPressure >= 1) return { rule: 'pressure', level: m.vmPressure === 1 ? 'warning' : 'critical' };
|
|
276
|
+
if (cfg.maxSwap == null || m.swapUsed == null) return null;
|
|
277
|
+
const limit = bytes(cfg.maxSwap);
|
|
278
|
+
return m.swapUsed > limit && swapGrowing(m) && swapNotOurs(m) > limit ? { rule: 'swap', used: m.swapUsed, grew: m.swapGrowth, limit } : null;
|
|
279
|
+
}
|
|
280
|
+
// Swap less what dibs's own processes could account for. A line of idle
|
|
281
|
+
// waiters is the first thing macOS pages out, and starting nothing never
|
|
282
|
+
// shrinks it: on 2026-10-15, 45 of them held 2.4 GB while the gate waited on swap.
|
|
283
|
+
const swapNotOurs = m => m.swapUsed - (m.dibsMem ?? (m.dibsMem = dibsMem()));
|
|
284
|
+
|
|
285
|
+
// Free disk falling this fast is swap (or a job) filling it. An incremental
|
|
286
|
+
// Xcode build writes 1-2.5 GB over several minutes; 3 GB in 5 minutes is more
|
|
287
|
+
// than any one job here writes, and swap on 2026-10-15 drank 2 GB a minute.
|
|
288
|
+
export const DISK_DRAIN = 3 * 1024 ** 3;
|
|
289
|
+
export const diskDraining = m => (m.diskDrain || 0) > DISK_DRAIN && (m.drainRecent ?? m.diskDrain ?? 0) > DISK_DRAIN * RECENT_SHARE;
|
|
290
|
+
// How far ahead a falling disk is projected. Ten minutes covers a build or an
|
|
291
|
+
// archive finishing its writes, and is longer than the watcher needs to act.
|
|
292
|
+
const DRAIN_AHEAD = 10 * MIN;
|
|
293
|
+
// Bytes per ms free disk is falling at, over the 5-minute window.
|
|
294
|
+
const drainRate = m => (m.diskDrain || 0) / Math.max(m.drainMs || 0, 30e3);
|
|
295
|
+
// Swap needs free disk to grow into. While the machine swaps (past maxSwap or
|
|
296
|
+
// growing), work below urgent keeps cfg.swapRoom free on top of what it would
|
|
297
|
+
// need anyway; and while free disk falls fast enough to be under that within
|
|
298
|
+
// DRAIN_AHEAD, it waits for it to hold steady. Two builds writing 4 GB on a
|
|
299
|
+
// disk with 200 GB free hold nobody up. Null when neither applies.
|
|
300
|
+
export function diskSqueeze(cfg, need, m = machine()) {
|
|
301
|
+
if (m.diskFree == null) return null;
|
|
302
|
+
// Swap over maxSwap that holds still with pressure normal is left over from
|
|
303
|
+
// an earlier crunch: macOS keeps it allocated for hours. On 2026-10-15 a flat
|
|
304
|
+
// 4.6 GB held every start for 30 minutes with 77% of memory free.
|
|
305
|
+
const paging = m.swapUsed != null && (swapGrowing(m) || m.vmPressure >= 1);
|
|
306
|
+
const room = cfg.swapRoom != null ? bytes(cfg.swapRoom) : 0;
|
|
307
|
+
if (cfg.swapRoom != null && paging && m.diskFree < need + room)
|
|
308
|
+
return { rule: 'swaproom', free: m.diskFree, need: need + room, room, used: m.swapUsed,
|
|
309
|
+
why: `disk: ${gb(m.diskFree)} free, and while the machine swaps (${gb(m.swapUsed)} of swap) dibs keeps ${gb(need + room)} free before starting anything new, so swap has room to grow (swapRoom ${gb(room)})` };
|
|
310
|
+
const ahead = m.diskFree - drainRate(m) * DRAIN_AHEAD;
|
|
311
|
+
if (diskDraining(m) && ahead < need + room)
|
|
312
|
+
return { rule: 'drain', free: m.diskFree, fell: m.diskDrain, projected: Math.max(0, ahead),
|
|
313
|
+
why: `free disk fell ${gb(m.diskDrain)} in 5 min to ${gb(m.diskFree)}, and at that rate it's under ${gb(need + room)} within ${DRAIN_AHEAD / MIN} min, so dibs starts nothing new until it holds steady` };
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Said wherever the machine holds new work back, so nobody reads it as a hint to raise priority.
|
|
318
|
+
export const NOT_PRIORITY = 'Keep waiting: raising the priority is not the fix';
|
|
319
|
+
export const swapWhy = sw => (sw.rule === 'pressure'
|
|
320
|
+
? `memory pressure is high (the OS says ${sw.level}), so dibs starts nothing new while other jobs run`
|
|
321
|
+
: `swap grew ${gb(sw.grew)} in 5 min, ${gb(sw.used)} in use (over maxSwap ${gb(sw.limit)}), so dibs starts nothing new while other jobs run`);
|
|
322
|
+
|
|
323
|
+
// The budgets exist to stop pile-ups, not to leave a quiet machine idle. While
|
|
324
|
+
// the OS reports plenty of free memory and spare cores, they don't apply. Never
|
|
325
|
+
// while the machine swaps (its free-memory reading is wrong then), and never
|
|
326
|
+
// once the budget is already used up: then the room was an illusion.
|
|
327
|
+
function roomy(cfg, full, m = machine()) {
|
|
328
|
+
if (full || swapping(cfg, m) || swapGrowing(m)) return false;
|
|
329
|
+
// Cores in use, like the load ceiling: a load average swollen by disk waits isn't work.
|
|
330
|
+
const load = cpuLoad(m);
|
|
331
|
+
return m.memFree >= cfg.roomyMemFree && load < (m.cores || 8) * cfg.roomyLoad;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Cores a lease takes from the CPU budget: what it was last measured using
|
|
335
|
+
// (src/measure.mjs) once it has been, else what it asked for. Test suites and
|
|
336
|
+
// builds ask for their peak and spend most of a run well under it, and too
|
|
337
|
+
// many busy cores only slows everyone a little, where too little memory kills
|
|
338
|
+
// jobs. So cores go by what's in use, and memory (memOf) by the larger of the
|
|
339
|
+
// planned number and what's in use.
|
|
340
|
+
export const coresOf = l => (l.kind === 'run' && l.use?.cpu != null ? l.use.cpu : l.cpu ?? 1);
|
|
341
|
+
// Memory a lease takes from the budget: what it was planned at, or what its
|
|
342
|
+
// whole process tree was last measured using when that's more. A job that
|
|
343
|
+
// outgrows its number still fills the machine.
|
|
344
|
+
//
|
|
345
|
+
// Once a run is measured and its memory has stopped climbing (settled), the
|
|
346
|
+
// plan gives way to what it uses now. A run idle IDLE_BOOK books only that:
|
|
347
|
+
// it isn't climbing anywhere. A busy one books it plus BUSY_MARGIN: footprints
|
|
348
|
+
// move by hundreds of MB between 10-second samples, and a test worker starting
|
|
349
|
+
// a browser adds most of a gigabyte. On 2026-10-15 two Playwright runs booked
|
|
350
|
+
// 12 of 11 GB on the strength of past peaks while using 3 GB between them, one
|
|
351
|
+
// idle for 7 minutes, and a high deploy waited 11 minutes with 12 GB free.
|
|
352
|
+
//
|
|
353
|
+
// A run measured for BOOK_AFTER books its peak plus BUSY_MARGIN even while it
|
|
354
|
+
// still climbs, never more than its plan: on 2026-10-19 a test suite that asked
|
|
355
|
+
// 8 GB used 0.8, and three like it held 16 GB of an 11 GB budget while 18 jobs
|
|
356
|
+
// waited with 12 GB free. A waiter let into that gap still needs the memory to
|
|
357
|
+
// be really free (overBudget): the OS's pressure is the guard, not the asks.
|
|
358
|
+
const IDLE_BOOK = 5 * MIN; // the same 5 minutes acquire.mjs marks a run idle at (IDLE_AFTER)
|
|
359
|
+
const BUSY_MARGIN = 1024 ** 3;
|
|
360
|
+
// Long enough for a test suite to start its workers and a build its compiler:
|
|
361
|
+
// eighteen 10-second samples.
|
|
362
|
+
const BOOK_AFTER = 3 * MIN;
|
|
363
|
+
export const plannedOf = l => Math.max(l.mem || 0, l.use?.mem || 0);
|
|
364
|
+
// What a lease uses this moment: its last measurement, or its plan until it has one.
|
|
365
|
+
const usedNow = l => (l.kind === 'run' && l.use?.mem != null ? l.use.mem : plannedOf(l));
|
|
366
|
+
export const memOf = (l, t = now()) => {
|
|
367
|
+
const planned = plannedOf(l);
|
|
368
|
+
if (l.kind !== 'run' || l.use?.mem == null) return planned;
|
|
369
|
+
if (steady(l, t)) return l.idleSince && t - l.idleSince >= IDLE_BOOK ? l.use.mem : l.use.mem + BUSY_MARGIN;
|
|
370
|
+
if (t - l.start - pausedFor(l, t) < BOOK_AFTER) return planned;
|
|
371
|
+
const peak = Math.max(l.peak?.mem || 0, l.use.mem);
|
|
372
|
+
return Math.min(peak + BUSY_MARGIN, Math.max(planned, peak));
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
// The lease a run sits inside, when its own hold or outer dibs run covers all
|
|
376
|
+
// it asked for, or null.
|
|
377
|
+
const coverOf = (s, l) => (l.covered && l.res.every(r => coveredNow(s, l, r)) ? s.leases.find(h => h !== l && covers(h, l)) || null : null);
|
|
378
|
+
// Memory every lease takes from the budget, each byte counted once. A run
|
|
379
|
+
// inside its own hold or dibs run uses memory that cover already reserved:
|
|
380
|
+
// adding both counted a simulator hold and the tests run in it twice. The
|
|
381
|
+
// cover counts at the larger of what it reserved and what it and the runs
|
|
382
|
+
// inside it use.
|
|
383
|
+
export function memUsed(s, of = memOf) {
|
|
384
|
+
const inside = new Map();
|
|
385
|
+
for (const l of s.leases) { const c = coverOf(s, l); if (c) inside.set(c.id, [...(inside.get(c.id) || []), l]); }
|
|
386
|
+
const charge = (l, depth = 0) => {
|
|
387
|
+
const kids = inside.get(l.id);
|
|
388
|
+
if (!kids || depth > 4) return of(l);
|
|
389
|
+
return Math.max(l.mem || 0, (l.use?.mem || 0) + sum(kids, k => charge(k, depth + 1)));
|
|
390
|
+
};
|
|
391
|
+
const top = new Set([...inside.values()].flat());
|
|
392
|
+
return sum(s.leases.filter(l => !top.has(l)), l => charge(l));
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// The leases taking the most memory, biggest first, for a memory wait to name.
|
|
396
|
+
// asked: what it asked for (--mem or its resource's default); use: what its
|
|
397
|
+
// last measurement found, or null before the first.
|
|
398
|
+
export const memHolders = (s, n = 3) => s.leases.filter(l => memOf(l) > 0 && !coverOf(s, l)).sort((a, b) => memOf(b) - memOf(a)).slice(0, n)
|
|
399
|
+
.map(l => ({ id: l.id, who: l.agent || l.who, label: l.label, purpose: l.purpose || '', mem: memOf(l), asked: l.asked ?? l.mem ?? 0, use: l.use?.mem ?? null, idleSince: l.idleSince || null }));
|
|
400
|
+
|
|
401
|
+
// Memory the OS says is free right now, in bytes, or null.
|
|
402
|
+
export const realFree = m => (m.memFree == null ? null : m.memFree / 100 * (m.memTotal || hardware().mem));
|
|
403
|
+
// The free memory people are shown: free plus what the OS reclaims on demand (vm_stat, MemAvailable),
|
|
404
|
+
// the figure the real-memory wait uses, so the Limits line and that wait never show two numbers.
|
|
405
|
+
export const shownFree = m => m.memAvail ?? realFree(m);
|
|
406
|
+
|
|
407
|
+
// The room a job let into the gap between what running jobs ask for and what
|
|
408
|
+
// they use must really be there (overBudget): memory pressure normal, swap not
|
|
409
|
+
// growing, and the job plus ROOM_RESERVE free by the OS's reading (macOS's
|
|
410
|
+
// kern.memorystatus_level, MemAvailable on Linux). That reading counts cached
|
|
411
|
+
// and compressed pages as free, which is why pressure and swap must both be
|
|
412
|
+
// quiet too: 0.0.81 saw it say 60% free while the Mac paged gigabytes to disk.
|
|
413
|
+
const ROOM_RESERVE = Math.max(3 * 1024 ** 3, 0.2 * hardware().mem); // 3 GB, or a fifth of the machine on a big one
|
|
414
|
+
function realRoom(q, cfg, m = machine()) {
|
|
415
|
+
if (m.vmPressure >= 1 || swapGrowing(m) || swapping(cfg, m)) return false;
|
|
416
|
+
const free = realFree(m);
|
|
417
|
+
return free != null && free >= q.mem + ROOM_RESERVE;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// Leases that stand between a waiter and a machine of its own. Its own holds
|
|
421
|
+
// and leases that cost nothing (file leases) don't count: waiting on them
|
|
422
|
+
// would mean waiting on itself, or on an hour-long file hold.
|
|
423
|
+
const othersOf = (s, q) => s.leases.filter(l => !covers(l, q) && ((l.mem || 0) > 0 || (l.cpu ?? 1) > 0));
|
|
424
|
+
// A lease doing work right now. A hold with nothing running under it, a file
|
|
425
|
+
// lease and a paused job grow neither swap nor the disk, so they aren't
|
|
426
|
+
// "anything else running" for the machine's gates: on 2026-10-15 forty-odd
|
|
427
|
+
// idle holds and paused jobs kept every new start out while swap ate the disk,
|
|
428
|
+
// and nothing ever ran to end the wait. A run under a hold is its own lease.
|
|
429
|
+
export const working = l => l.kind === 'run' && !l.pausedAt && !l.res.every(isFiles);
|
|
430
|
+
|
|
431
|
+
// When swap, the disk swap grows on, or memory pressure has kept every start
|
|
432
|
+
// out for STALL while waiters wait, the smallest and shortest of them starts
|
|
433
|
+
// anyway, one at a time. Ten minutes is two of the 5-minute windows swap and
|
|
434
|
+
// disk are judged over: a real crunch has had time to pass by then, and
|
|
435
|
+
// waiting longer only piles more waiters up, each one more process in memory.
|
|
436
|
+
export const STALL = 10 * MIN;
|
|
437
|
+
// A job let in that way counts as settled once its measured memory hasn't
|
|
438
|
+
// risen more than 5% (measure.mjs peakAt) for this long: twelve samples.
|
|
439
|
+
const SETTLED = 2 * MIN;
|
|
440
|
+
// A lease dibs never measures (a hold, a run with no process group of its
|
|
441
|
+
// own) can't settle, and held the real-room path shut for good on 2026-10-15
|
|
442
|
+
// (a file hold let in past the budget). It counts as settled, and so does a
|
|
443
|
+
// run still unmeasured UNMEASURED after it started.
|
|
444
|
+
const UNMEASURED = 2 * MIN;
|
|
445
|
+
const steady = (l, t) => l.peakAt != null && t - l.peakAt >= SETTLED;
|
|
446
|
+
const settled = (l, t) => (l.peakAt != null ? steady(l, t) : l.kind !== 'run' || !l.pgid || t - l.start >= UNMEASURED);
|
|
447
|
+
// The last start the gates allowed: one still running, or one noted in
|
|
448
|
+
// s.lastStart when it started (it may have ended since).
|
|
449
|
+
// Only starts that passed the machine's gates (gated): a run inside its own
|
|
450
|
+
// hold, or urgent work, starts past them and says nothing about the stall.
|
|
451
|
+
const lastStart = s => Math.max(s.lastStart || 0, ...s.leases.filter(l => l.gated).map(l => l.start));
|
|
452
|
+
function breaksStall(s, me, cfg, hist, t, m) {
|
|
453
|
+
if (m.vmPressure >= 2 || s.leases.some(l => l.breaker && !settled(l, t))) return false;
|
|
454
|
+
// Waiters the machine holds back, as their last poll found (machineHeld,
|
|
455
|
+
// acquire.mjs decide). An open slot isn't enough: on 2026-10-15 the breaker
|
|
456
|
+
// picked a heavy job waiting its turn behind another, which never reached
|
|
457
|
+
// the breaker, so nobody went.
|
|
458
|
+
const held = [me, ...s.queue.filter(q => q.pid && q.id !== me.id && q.machineHeld && (q.prio || 'normal') !== 'urgent')];
|
|
459
|
+
if (t - Math.max(lastStart(s), Math.min(...held.map(q => q.enq))) < STALL) return false;
|
|
460
|
+
const pick = held.sort((a, b) => (a.mem || 0) - (b.mem || 0) || expected(a, hist) - expected(b, hist) || a.enq - b.enq || a.id - b.id)[0];
|
|
461
|
+
return pick.id === me.id;
|
|
462
|
+
}
|
|
463
|
+
export const BREAKER_LINE = `let in: nothing had started for ${STALL / MIN} min, so dibs starts the smallest waiter, one at a time`;
|
|
464
|
+
|
|
465
|
+
// strict: the roomy rule doesn't apply (a job on top of a full resource has
|
|
466
|
+
// already been let past its slots once).
|
|
467
|
+
// Cores in use: a paused job burns none, whatever paused it.
|
|
468
|
+
export const cpuUsed = s => Math.round(sum(s.leases.filter(l => !lent(l) && !l.pausedAt), coresOf) * 10) / 10;
|
|
469
|
+
// Swap that grew in the last 5 minutes is memory jobs took that the budget
|
|
470
|
+
// never handed out: macOS pages it to disk instead of saying no. Counting it
|
|
471
|
+
// stops new work while swap climbs, not after it has eaten the disk.
|
|
472
|
+
// REAL_WAIT was 10 minutes (0.0.159). On 2026-10-25 twenty Xcode builds and simulator
|
|
473
|
+
// jobs that book 7 to 9 GB waited out nearly all of it on a Mac whose free-or-reclaimable
|
|
474
|
+
// memory sits near 5 GB, then ran with free memory never under 31% and nothing paused for
|
|
475
|
+
// them. Two minutes is enough for the readings to show anything that started before.
|
|
476
|
+
const YOUNG = 3 * MIN, REAL_WAIT = 2 * MIN;
|
|
477
|
+
export const swapTaken = m => (swapGrowing(m) ? m.swapGrowth : 0);
|
|
478
|
+
// noSwap: swap growth doesn't count (the stall breaker let it by).
|
|
479
|
+
function overBudget(s, q, cfg, strict = false, noSwap = false, t = now()) {
|
|
480
|
+
// A job as big as the whole budget runs when nothing else is.
|
|
481
|
+
if (!othersOf(s, q).length) return null;
|
|
482
|
+
const m = machine();
|
|
483
|
+
const swap = noSwap ? 0 : swapTaken(m);
|
|
484
|
+
const mem = memUsed(s) + swap;
|
|
485
|
+
const cpu = cpuUsed(s);
|
|
486
|
+
// Memory booked never goes past the budget, however roomy the machine looks:
|
|
487
|
+
// only cores, which cost a little speed when overcommitted, get the roomy rule.
|
|
488
|
+
const budget = bytes(cfg.budget);
|
|
489
|
+
// Booked past the budget, but what running jobs measure using right now, plus
|
|
490
|
+
// this job, fits it, and the machine shows the room (pressure normal, swap not
|
|
491
|
+
// growing, the job plus a reserve free): it starts. Booking keeps a job's peak
|
|
492
|
+
// for minutes after it falls; on 2026-10-20 twenty jobs waited "blocked by
|
|
493
|
+
// memory" with 8.6 GB free and 1 of 10 cores busy.
|
|
494
|
+
const fitsUse = () => memUsed(s, usedNow) + swap + q.mem <= budget && realRoom(q, cfg, m);
|
|
495
|
+
if (mem + q.mem > budget && !fitsUse())
|
|
496
|
+
return { rule: 'memory', used: mem, of: budget, need: q.mem, ...(swap && { swap }),
|
|
497
|
+
why: `memory budget: ${gb(mem)} of ${gb(budget)} handed out or in use${swap ? ` (${gb(swap)} of it swap that grew in the last 5 min)` : ''}, you need ${gb(q.mem)}` };
|
|
498
|
+
// It fits only because running jobs book what they were measured using, not
|
|
499
|
+
// what they asked for. One of them may still grow into its ask, so the room
|
|
500
|
+
// must be real: memory pressure normal, swap still, and the job plus a
|
|
501
|
+
// reserve free on the machine.
|
|
502
|
+
if (memUsed(s, plannedOf) + swap + q.mem > budget && !realRoom(q, cfg, m))
|
|
503
|
+
return { rule: 'memory', used: mem, of: budget, need: q.mem, pressure: true, free: realFree(m), reserve: ROOM_RESERVE, high: m.vmPressure >= 1, growing: swapGrowing(m),
|
|
504
|
+
why: `memory: running jobs ask for more than they use, but the machine doesn't have the room to show for it (${realFree(m) == null ? 'free memory unknown' : `${gb(realFree(m))} free`}${m.vmPressure >= 1 ? ', memory pressure high' : ''}${swapGrowing(m) ? ', swap growing' : ''}), you need ${gb(q.mem)} plus ${gb(ROOM_RESERVE)} to spare` };
|
|
505
|
+
// Within the budget, the machine must still have it: what's really available
|
|
506
|
+
// (src/platform.mjs vmAvail), less what running jobs booked and haven't
|
|
507
|
+
// touched yet, must hold the job (macOS still compresses idle apps' pages to
|
|
508
|
+
// make a little more, so no spare on top). The budget alone counts only
|
|
509
|
+
// dibs's jobs: on 2026-10-22 Claude sessions, apps and simulators held 8 GB
|
|
510
|
+
// of the 16, dibs booked two 6 GB browser runs into the rest, and swap took
|
|
511
|
+
// the disk to 0.7 GB. Small jobs, and the stall breaker, are let by.
|
|
512
|
+
// A job that has waited REAL_WAIT on it goes once swap holds still, pressure is normal and no big job just started: the
|
|
513
|
+
// watcher's swap and disk guards still stand, and on a busy Mac the room may never come.
|
|
514
|
+
// A big job that started under YOUNG ago isn't in those readings yet, so the next one waits for it.
|
|
515
|
+
const bigYoung = s.leases.some(l => !covers(l, q) && l.kind === 'run' && (l.mem || 0) > LIGHT_MEM && t - (l.start || 0) < YOUNG);
|
|
516
|
+
const waitedOut = q.enq != null && t - q.enq >= REAL_WAIT && !bigYoung && !swapGrowing(m) && !(m.vmPressure >= 1);
|
|
517
|
+
if (!noSwap && !waitedOut && m.memAvail != null && (q.mem || 0) > LIGHT_MEM) {
|
|
518
|
+
// Its own hold or the dibs run it's nested in booked memory for it: that's no one else's.
|
|
519
|
+
// Only a job that just started may still grow into its booking: one that has run
|
|
520
|
+
// a while at less is done growing. On 2026-10-22 a ship's deploy and simulator,
|
|
521
|
+
// 20 minutes in at 0 GB measured, kept 5 GB of 4.3 spoken for and held four jobs.
|
|
522
|
+
// Its age by its last measurement: not measured yet is young.
|
|
523
|
+
const young = l => l.use?.at == null || l.use.at - (l.start || 0) < YOUNG;
|
|
524
|
+
const others = { ...s, leases: s.leases.filter(l => !covers(l, q) && young(l)) };
|
|
525
|
+
const untouched = Math.max(0, memUsed(others, plannedOf) - memUsed(others, usedNow));
|
|
526
|
+
if (m.memAvail - untouched < q.mem)
|
|
527
|
+
return { rule: 'memory', real: true, used: mem, of: budget, need: q.mem, free: m.memAvail, untouched,
|
|
528
|
+
why: `memory: ${gb(m.memAvail)} free or reclaimable on the machine${untouched ? ` (${gb(untouched)} of it booked by running jobs)` : ''}, you need ${gb(q.mem)}` };
|
|
529
|
+
}
|
|
530
|
+
if (!strict && roomy(cfg, mem > budget || cpu > cfg.cores, m)) return null;
|
|
531
|
+
if (cpu + q.cpu > cfg.cores)
|
|
532
|
+
return { rule: 'cpu', used: cpu, of: cfg.cores, need: q.cpu, why: `CPU budget: ${cpu} of ${cfg.cores} cores in use, you need ${q.cpu}` };
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// The 1-minute load average moves toward the real load with a 60s time
|
|
537
|
+
// constant, so a job started t ago shows in it as only 1 - e^(-t/60s) of its
|
|
538
|
+
// cores. The rest is added back here. Without it, a burst of waiters would all
|
|
539
|
+
// start under one reading taken before any of them. Each counts at what it
|
|
540
|
+
// asked for, not coresOf: a job seconds in is measured before it ramps up.
|
|
541
|
+
const LOAD_LAG = 60e3;
|
|
542
|
+
export const loadAhead = (s, m = machine()) => sum(s.leases.filter(l => l.kind === 'run' && !l.pausedAt),
|
|
543
|
+
l => (l.cpu ?? 1) * Math.exp(-Math.max(0, m.at - l.start) / LOAD_LAG));
|
|
544
|
+
|
|
545
|
+
// Urgent and high work isn't held back by the load ceiling: it's rare, and says
|
|
546
|
+
// why. Nor is work that holds a lease while it waits.
|
|
547
|
+
const PAST_CEILING = new Set(['urgent', 'high']);
|
|
548
|
+
const pastsCeiling = q => PAST_CEILING.has((q.prio || 'normal')) || !!q.holding;
|
|
549
|
+
// The load as it will read once recent starts show up, when it's over maxLoad.
|
|
550
|
+
// What the CPU is really doing: the load average, unless it's inflated by
|
|
551
|
+
// processes waiting on swap or disk (memory pressure has its own guard): then
|
|
552
|
+
// the cores in use. Cores in use can't pass the core count, so with every core
|
|
553
|
+
// busy the load average is the only measure of how much more wants to run. Taking
|
|
554
|
+
// the smaller of the two always, as before 2026-11-02, capped the reading at the
|
|
555
|
+
// cores: on max pace (a ceiling of 1.5 per core) the ceiling could never hold, and
|
|
556
|
+
// the load ran to 12 times the cores.
|
|
557
|
+
const SATURATED = 0.9;
|
|
558
|
+
export function cpuLoad(m) {
|
|
559
|
+
if (m.busy == null) return m.load;
|
|
560
|
+
const cores = m.cores || hardware().cores;
|
|
561
|
+
return m.busy >= cores * SATURATED ? m.load : Math.min(m.load, m.busy);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
export function overLoad(s, cfg, m = machine()) {
|
|
565
|
+
if (cfg.maxLoad == null) return null;
|
|
566
|
+
const ahead = loadAhead(s, m);
|
|
567
|
+
const load = cpuLoad(m);
|
|
568
|
+
return load + ahead > cfg.maxLoad ? { load, ahead } : null;
|
|
569
|
+
}
|
|
570
|
+
// A job the load ceiling alone has held LOAD_STARVE starts anyway, at
|
|
571
|
+
// background priority (taskpolicy -b: the efficiency cores on Apple silicon),
|
|
572
|
+
// which barely warms the fan the ceiling is there for. On 2026-10-18 an idle
|
|
573
|
+
// OCR job waited 2h52m: maxLoad 5 on 10 cores, with 7.5 to 11 of load from
|
|
574
|
+
// work dibs doesn't run. Jobs let in that way share LOAD_SHARE of the cores,
|
|
575
|
+
// a little under the efficiency cores' part of these Macs; more than that only
|
|
576
|
+
// queues them behind each other. One that asks for more still goes alone.
|
|
577
|
+
export const LOAD_STARVE = 20 * MIN;
|
|
578
|
+
const LOAD_SHARE = 0.4;
|
|
579
|
+
function loadShare(s, me) {
|
|
580
|
+
const share = Math.max(1, Math.floor(hardware().cores * LOAD_SHARE));
|
|
581
|
+
const taken = sum(s.leases.filter(l => l.loadPast && !l.pausedAt), coresOf);
|
|
582
|
+
return !taken || taken + (me.cpu ?? 1) <= share;
|
|
583
|
+
}
|
|
584
|
+
export const loadWhy = (hot, cfg) => `load ${(hot.load + hot.ahead).toFixed(1)} is over maxLoad ${cfg.maxLoad}`
|
|
585
|
+
+ `${hot.ahead >= 0.1 ? ` (${hot.load.toFixed(1)} now, plus ${hot.ahead.toFixed(1)} for jobs too new to show in it)` : ''}`
|
|
586
|
+
+ `. New work waits for it to cool down, except work finishing what it already holds; one held ${LOAD_STARVE / MIN} min starts anyway at background priority`;
|
|
587
|
+
|
|
588
|
+
// The soonest a waiter could start, judging only by what's running now.
|
|
589
|
+
function soonestStart(s, q, cfg, hist, t = now()) {
|
|
590
|
+
const mine = holdsOf(s, q);
|
|
591
|
+
let at = t;
|
|
592
|
+
for (const r of q.res) {
|
|
593
|
+
if (!mine.has(r) && roomFor(s, q, r, cfg).open <= 0) {
|
|
594
|
+
const across = roomFor(s, q, r, cfg).across;
|
|
595
|
+
at = Math.max(at, Math.min(...s.leases.filter(l => l.res.includes(r) && !lent(l, r) && !onTop(l, r) && (across || !byRepo(cfg, r) || laneOf(l) === laneOf(q))).map(l => slotEnd(s, l, hist, t, r))));
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
if (overBudget(s, q, cfg)) at = Math.max(at, budgetFrees(s, q, cfg, hist, t));
|
|
599
|
+
return at;
|
|
600
|
+
}
|
|
601
|
+
// Whether q's turn at the budget rests only on jobs whose run time dibs knows
|
|
602
|
+
// (--est or history) and that haven't overrun it: then its start is a real time.
|
|
603
|
+
// Otherwise it's a guess, and a short job of known length doesn't wait on it.
|
|
604
|
+
// On 2026-10-20 three 2-minute browser runs and a test run sat behind an Xcode
|
|
605
|
+
// build waiting for 6.4 GB, which waited on a build said to take 3 minutes
|
|
606
|
+
// that had run 74, while the memory they needed was free.
|
|
607
|
+
function budgetSure(s, q, cfg, hist, t) {
|
|
608
|
+
let mem = memUsed(s), cpu = cpuUsed(s);
|
|
609
|
+
const fits = () => mem + q.mem <= bytes(cfg.budget) && cpu + q.cpu <= cfg.cores;
|
|
610
|
+
const ends = s.leases.filter(l => !covers(l, q) && !coverOf(s, l)).map(l => [l, likelyEnd(l, hist, t)]).sort((a, b) => a[1] - b[1]);
|
|
611
|
+
for (const [l] of ends) {
|
|
612
|
+
// A hold ends when it expires (dibs hold --for); a run, at its --est or usual time.
|
|
613
|
+
if (l.kind === 'hold' ? !l.expires : !known(l, hist) || overran(l, hist, t)) return false;
|
|
614
|
+
mem -= memOf(l);
|
|
615
|
+
if (!lent(l) && !l.pausedAt) cpu -= coresOf(l);
|
|
616
|
+
if (fits()) return true;
|
|
617
|
+
}
|
|
618
|
+
return false;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// When enough of what's booked ends for q to fit the memory and CPU budgets,
|
|
622
|
+
// leases ending in order. Not the first lease to end: on 2026-10-18 a job
|
|
623
|
+
// waiting on the budget behind a long hold counted as starting "soon" for
|
|
624
|
+
// 4.5 hours, and as the oldest waiter it held 26 jobs back, every one of
|
|
625
|
+
// which would have been done long before it could start.
|
|
626
|
+
function budgetFrees(s, q, cfg, hist, t) {
|
|
627
|
+
let mem = memUsed(s), cpu = cpuUsed(s);
|
|
628
|
+
const fits = () => mem + q.mem <= bytes(cfg.budget) && cpu + q.cpu <= cfg.cores;
|
|
629
|
+
const ends = s.leases.filter(l => !covers(l, q) && !coverOf(s, l)).map(l => [l, likelyEnd(l, hist, t)]).sort((a, b) => a[1] - b[1]);
|
|
630
|
+
for (const [l, end] of ends) {
|
|
631
|
+
mem -= memOf(l);
|
|
632
|
+
if (!lent(l) && !l.pausedAt) cpu -= coresOf(l);
|
|
633
|
+
if (fits()) return end;
|
|
634
|
+
}
|
|
635
|
+
// A job as big as the whole budget runs when nothing else is.
|
|
636
|
+
return ends.length ? ends.at(-1)[1] : t;
|
|
637
|
+
}
|
|
638
|
+
// When a lease will really end, for reserving memory. One already past its
|
|
639
|
+
// usual time isn't ending in 30 seconds (endOf's floor), over and over: count
|
|
640
|
+
// it as running as long again as it has so far. On 2026-10-19 a waiter for 11 GB read as starting
|
|
641
|
+
// "in a minute" for half an hour while the jobs it waited on overran, and as
|
|
642
|
+
// the head of the line it held 22 jobs, two of them high, on a quiet Mac.
|
|
643
|
+
const ranFor = (l, t) => t - l.start - pausedFor(l, t);
|
|
644
|
+
const overran = (l, hist, t) => l.kind === 'run' && ranFor(l, t) >= expected(l, hist);
|
|
645
|
+
const likelyEnd = (l, hist, t) => (overran(l, hist, t) ? t + ranFor(l, t) : endOf(l, hist, t));
|
|
646
|
+
// A waiter that needs most of the budget reserves it (holds back jobs that
|
|
647
|
+
// would still be running when it could start) only once it could start
|
|
648
|
+
// within RESERVE_SOON. Further off, it waits for a quiet moment and lets jobs
|
|
649
|
+
// that fit start meanwhile: reserving a whole machine on a forecast an hour
|
|
650
|
+
// out froze every other queue for it.
|
|
651
|
+
const BIG_SHARE = 0.75;
|
|
652
|
+
const RESERVE_SOON = 5 * MIN;
|
|
653
|
+
// A waiter of lower priority than me, held by the budgets: it doesn't hold me
|
|
654
|
+
// back by being ahead in line. High and urgent work never waits behind a
|
|
655
|
+
// normal job's memory reservation.
|
|
656
|
+
const reservesFor = (s, q, me, cfg) => !(PRIORITIES.indexOf(q.prio || 'normal') > PRIORITIES.indexOf(me.prio || 'normal') && overBudget(s, q, cfg));
|
|
657
|
+
|
|
658
|
+
// Why q could never start on this machine, whatever ends: it asks for more
|
|
659
|
+
// memory or cores than dibs hands out at once. Null when it could. A job
|
|
660
|
+
// another machine sent here (q.sent) was placed for this machine's size, as a
|
|
661
|
+
// VM made big enough for it is, and runs alone past the budget: only more than
|
|
662
|
+
// the machine itself has counts then.
|
|
663
|
+
export function neverFits(cfg, q) {
|
|
664
|
+
const { mem, cpu: cores, whole } = mostHere(cfg, q.sent);
|
|
665
|
+
if (q.mem > mem) return { what: 'memory', need: q.mem, most: mem, flag: '--mem', unit: gb, whole };
|
|
666
|
+
if (q.cpu > cores) return { what: 'cores', need: q.cpu, most: cores, flag: '--cpu', unit: n => String(n), whole };
|
|
667
|
+
return null;
|
|
668
|
+
}
|
|
669
|
+
// The most one job may book on this machine: the budgets, or for a job sent
|
|
670
|
+
// here (neverFits) the machine itself.
|
|
671
|
+
export function mostHere(cfg, sent) {
|
|
672
|
+
const hw = sent && hardware();
|
|
673
|
+
return { mem: hw ? hw.mem : bytes(cfg.budget), cpu: hw ? hw.cores : cfg.cores, whole: !!hw };
|
|
674
|
+
}
|
|
675
|
+
// What a job asked for in so many words (--mem, --cpu), which alone can make
|
|
676
|
+
// it never fit. A size dibs chose (the resource's default, or one learned on
|
|
677
|
+
// a bigger machine) is booked at most at mostHere instead: a lone job past the
|
|
678
|
+
// budget still runs. On 2026-10-18 a test run that had used 5 cores on the
|
|
679
|
+
// 10-core Mac was refused on a 4-core VM, though it asked for 3.
|
|
680
|
+
export const explicitAsk = q => ({ mem: q.declared ? q.asked ?? q.mem : 0, cpu: q.cpuDeclared ? q.askedCpu ?? q.cpu : 0, sent: q.sent });
|
|
681
|
+
export function capToMachine(cfg, q) {
|
|
682
|
+
const most = mostHere(cfg, q.sent);
|
|
683
|
+
let changed = false;
|
|
684
|
+
if (q.mem > most.mem) { q.mem = most.mem; changed = true; }
|
|
685
|
+
if (q.cpu > most.cpu) { q.cpu = most.cpu; changed = true; }
|
|
686
|
+
return changed;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// A file lease waits for every other agent's lease on an overlapping path, and
|
|
690
|
+
// for other agents ahead in line for one. An agent never waits on its own. Two
|
|
691
|
+
// subagents of one session are different agents when the guard told dibs which
|
|
692
|
+
// is which (src/files.mjs); otherwise a session is one agent.
|
|
693
|
+
const own = (x, me) => isMine(x, me) && coversAgent(x, me);
|
|
694
|
+
function filesBlock(s, me, r, ahead) {
|
|
695
|
+
for (const l of s.leases) {
|
|
696
|
+
const x = !own(l, me) && l.res.find(y => isFiles(y) && overlap(y, r));
|
|
697
|
+
if (x) return { ok: false, rule: 'files', why: `${short(x)} is leased to ${tag(l)}${elsewhere(l)}${x === r ? '' : `, which overlaps ${short(r)}`}`, on: x };
|
|
698
|
+
}
|
|
699
|
+
const q = ahead.find(q => !own(q, me) && q.res.some(y => isFiles(y) && overlap(y, r)));
|
|
700
|
+
return q ? { ok: false, rule: 'ahead', why: `${tag(q)} is ahead of you for files overlapping ${short(r)}`, on: r, ahead: q } : null;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
// Nearly twice as long side by side is a fight for the same thing (cores, the
|
|
704
|
+
// GPU, one port); sharing a machine always costs something, so less isn't held back.
|
|
705
|
+
const SLOW_PAIR = 1.8;
|
|
706
|
+
function clashOf(s, me, hist) {
|
|
707
|
+
for (const l of s.leases) {
|
|
708
|
+
if (l.kind !== 'run' || l.pausedAt || isMine(l, me)) continue;
|
|
709
|
+
for (const r of l.res) {
|
|
710
|
+
const f = slowdown(hist, me.key, r);
|
|
711
|
+
if (f >= SLOW_PAIR) return { lease: l, res: r, why: `it usually runs ${f.toFixed(1)}x as long beside ${r} work, and ${tag(l)}'s is running` };
|
|
712
|
+
}
|
|
713
|
+
for (const r of me.res) {
|
|
714
|
+
const f = slowdown(hist, l.key, r);
|
|
715
|
+
if (f >= SLOW_PAIR) return { lease: l, res: r, why: `${tag(l)}'s job usually runs ${f.toFixed(1)}x as long beside ${r} work like this` };
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return null;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// The instant lane: a job whose command has taken under INSTANT (the middle of
|
|
722
|
+
// its runs) starts beside anything, past full slots and the line, while the
|
|
723
|
+
// machine's memory, disk, load and swap gates still hold. On 2026-10-21 most of
|
|
724
|
+
// the jobs that waited longer than they ran were checks of under a minute that
|
|
725
|
+
// waited tens of seconds for a browser slot. Only on resources whose slots are
|
|
726
|
+
// capacity: never an exclusive one (the shared simulator, deploys, a lock) or a
|
|
727
|
+
// pool that hands each job its own simulator.
|
|
728
|
+
const INSTANT = 15e3;
|
|
729
|
+
// A job over in seconds that has never been seen using much memory: its middle
|
|
730
|
+
// run under INSTANT (or, before dibs has seen it, an --est that short with no --mem
|
|
731
|
+
// asked), and no run measured over LIGHT_MEM. It can't tip the machine into swap,
|
|
732
|
+
// so swap and warning pressure don't hold it, and its resource's default size
|
|
733
|
+
// (2 GB for a test run) doesn't book it past the budget. Critical pressure and
|
|
734
|
+
// the disk floor still do. On 2026-10-23 a 70 ms node --test of one file waited
|
|
735
|
+
// minutes on "memory pressure high" behind a 4 GB Docker build.
|
|
736
|
+
export function featherweight(me, hist) {
|
|
737
|
+
const d = typical(hist, me.key) ?? (me.declared ? null : me.est);
|
|
738
|
+
if (d == null || d >= INSTANT) return false;
|
|
739
|
+
return runsOf(hist, me.key).slice(-10).every(h => h.mem == null || h.mem <= LIGHT_MEM);
|
|
740
|
+
}
|
|
741
|
+
// Probation: a command dibs has never seen, with no --mem and no --est, has
|
|
742
|
+
// nothing to vouch for it, so featherweight can't pass it. On 2026-10-24, 13 of
|
|
743
|
+
// the 17 short jobs held on memory pressure were first runs (one-file tests,
|
|
744
|
+
// a tsc, a swift build), and they waited up to 7 minutes to run for seconds.
|
|
745
|
+
// Once it has waited PROBATION_AFTER, one such job at a time starts through
|
|
746
|
+
// warning pressure, on resources that can pause. Growing swap and the memory
|
|
747
|
+
// budget still hold it, since nothing pauses a job for those. The watcher pauses it before anyone else if the pressure turns critical
|
|
748
|
+
// (src/overlap.mjs pressureVictim), and once it has run, its measured size decides.
|
|
749
|
+
const PROBATION_AFTER = 30e3;
|
|
750
|
+
export function probation(s, me, cfg, hist, t) {
|
|
751
|
+
if (t - me.enq < PROBATION_AFTER) return false;
|
|
752
|
+
if (me.kind === 'hold' || me.declared || me.est != null || !me.key || runsOf(hist, me.key).length) return false;
|
|
753
|
+
if (!me.res.every(r => !isFiles(r) && resCfg(cfg, r).pausable === true)) return false;
|
|
754
|
+
return !s.leases.some(l => l.trial);
|
|
755
|
+
}
|
|
756
|
+
function instant(me, cfg, hist) {
|
|
757
|
+
const d = typical(hist, me.key);
|
|
758
|
+
// A resource's own config: a name dibs doesn't know takes cfg.unknown's exclusive.
|
|
759
|
+
return d != null && d < INSTANT && me.res.every(r => isFiles(r) || (cfg.resources[r] && !cfg.resources[r].exclusive && !cfg.resources[r].pool));
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// Can this waiter start now? If not: the rule that stops it (slot, ahead,
|
|
763
|
+
// reset, disk, pressure, swap, swaproom, drain, memory, cpu, ram, load, idle), a sentence, and what it's stuck on.
|
|
764
|
+
//
|
|
765
|
+
// Earlier waiters go first, with one exception (backfill): you may take a free
|
|
766
|
+
// slot ahead of someone who can't start yet anyway, if you'll be done before
|
|
767
|
+
// they could have started.
|
|
768
|
+
// What a job's own runs show it eats of the free disk: the middle of its last
|
|
769
|
+
// successful runs of the same command, or null until there are DISK_RUNS. Unlike
|
|
770
|
+
// typicalDisk, never borrowed from other commands on the resource: this one holds
|
|
771
|
+
// back even a job alone, or on a resource that declares no disk.
|
|
772
|
+
function ownDisk(hist, key) {
|
|
773
|
+
const d = runsOf(hist || [], key).filter(h => h.ate != null && !h.failed).slice(-10).map(h => h.ate);
|
|
774
|
+
return d.length >= DISK_RUNS ? mid(d) : null;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// The free disk a job needs to start, as the verdict will want it at its turn:
|
|
778
|
+
// { need, ate }, ate being what it usually eats (null when unknown or --disk says).
|
|
779
|
+
// A --disk given in so many words is the job's own: on 2026-10-26 a streaming loader that writes one
|
|
780
|
+
// 12 MB chunk was held for 23 GB it had "eaten" on a run whose swap grew while it sat paused.
|
|
781
|
+
export function diskNeed(s, me, cfg, hist) {
|
|
782
|
+
const floor = bytes(cfg.minDisk);
|
|
783
|
+
// With others running, a resource that declares disk (simulators, builds, browsers, heavy) also
|
|
784
|
+
// counts what its kind of job usually eats. Alone, or on a resource that declares none, the
|
|
785
|
+
// job's own runs still count: starting a job that always eats more than there is only fails it.
|
|
786
|
+
// Alone, nothing else needs the floor while it runs, so it needs what it eats and ALONE_ROOM on top.
|
|
787
|
+
const others = othersOf(s, me).length > 0;
|
|
788
|
+
if (me.diskDeclared) return { need: Math.max(me.disk || 0, floor), ate: null, others };
|
|
789
|
+
// What a resource declares is a guess made before any run. Once runs of this command, or of
|
|
790
|
+
// its resource, show what they really eat, that wins: the simulator declares 8 GB, its 58 runs
|
|
791
|
+
// here ate 0.17 GB at the middle and 1.6 GB at most, and on 2026-11-03 a hold on it was
|
|
792
|
+
// refused with 7 GB free.
|
|
793
|
+
const learned = (me.disk || 0) > 0 ? typicalDisk(hist, me.key) : null;
|
|
794
|
+
const ate = (others ? learned : null) ?? ownDisk(hist, me.key);
|
|
795
|
+
return { need: Math.max(learned ?? me.disk ?? 0, floor, ate != null ? ate + (others ? floor : ALONE_ROOM) : 0), ate, others };
|
|
796
|
+
}
|
|
797
|
+
// A job alone still leaves this much free past what it eats: the system writes while it runs too.
|
|
798
|
+
const ALONE_ROOM = 1024 ** 3;
|
|
799
|
+
|
|
800
|
+
// The verdict, and for a job held by something else (its turn, memory, cores) a
|
|
801
|
+
// word that free disk will hold it next, while there's still time to free some.
|
|
802
|
+
// On 2026-11-02 a job waited over 10 hours on memory, then failed for disk the
|
|
803
|
+
// moment it started.
|
|
804
|
+
export function verdict(s, me, cfg, hist, t = now()) {
|
|
805
|
+
const v = decide(s, me, cfg, hist, t);
|
|
806
|
+
if (v.ok || v.disk || v.machine) return v;
|
|
807
|
+
const m = machine();
|
|
808
|
+
const { need } = diskNeed(s, me, cfg, hist);
|
|
809
|
+
if (m.diskFree != null && m.diskFree < need) v.diskNext = { free: m.diskFree, need };
|
|
810
|
+
return v;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
function decide(s, me, cfg, hist, t) {
|
|
814
|
+
if ((me.mem || 0) > LIGHT_MEM && featherweight(me, hist)) me = { ...me, mem: LIGHT_MEM, feather: true };
|
|
815
|
+
const myRank = rank(me, hist, t);
|
|
816
|
+
// When it would be done, at its slow runs: passing a waiter is a promise not to delay it.
|
|
817
|
+
const myEnd = t + Math.max(expected(me, hist), slow(hist, me.key) || 0);
|
|
818
|
+
const mine = holdsOf(s, me);
|
|
819
|
+
const m = machine();
|
|
820
|
+
const hot = overLoad(s, cfg, m);
|
|
821
|
+
// The instant lane passes the load ceiling too: a job of a few seconds barely shows in a
|
|
822
|
+
// 1-minute load average. On 2026-10-21 a 1-second vitest run waited 99 s at load 42.
|
|
823
|
+
// A small job on an exclusive resource (a deploy, someone's lock) uses little CPU and
|
|
824
|
+
// writes next to nothing: the load ceiling, the room kept for swap and a falling disk
|
|
825
|
+
// don't hold it (over minDisk, it goes). On 2026-10-21 0.5 GB deploys waited 79 and 92 s
|
|
826
|
+
// on the room kept for swap, and one waited 9 minutes on load.
|
|
827
|
+
const lightTurn = (me.mem || 0) <= LIGHT_MEM && me.res.every(r => cfg.resources[r]?.exclusive);
|
|
828
|
+
const pastCeiling = pastsCeiling(me) || instant(me, cfg, hist) || lightTurn;
|
|
829
|
+
// Over the ceiling, a waiter that passes it doesn't wait behind ones the ceiling holds back.
|
|
830
|
+
const ahead = s.queue
|
|
831
|
+
.filter(q => q.pid && q.id !== me.id && !(hot && pastCeiling && !pastsCeiling(q)))
|
|
832
|
+
.filter(q => { const r = rank(q, hist, t); return r < myRank || (r === myRank && q.id < me.id); })
|
|
833
|
+
.filter(q => reservesFor(s, q, me, cfg))
|
|
834
|
+
.sort(byRank(hist, t));
|
|
835
|
+
// A waiter ahead that needs more free disk than there is can't start, so it
|
|
836
|
+
// doesn't hold back one that leaves minDisk free after its own declared disk:
|
|
837
|
+
// on 2026-10-15 a heavy job needing 10 GB, with 4 to 6 GB free, held the
|
|
838
|
+
// whole heavy line. It keeps its place, and once the disk has room for it,
|
|
839
|
+
// it's ahead of everyone again. A job that would eat into that room waits.
|
|
840
|
+
const floor = bytes(cfg.minDisk);
|
|
841
|
+
const diskStuck = q => m.diskFree != null && m.diskFree < Math.max(q.disk || 0, floor);
|
|
842
|
+
const leavesRoom = m.diskFree != null && m.diskFree - floor >= (me.disk || 0);
|
|
843
|
+
const blocks = q => {
|
|
844
|
+
if (leavesRoom && diskStuck(q)) return false;
|
|
845
|
+
// A waiter held for memory blocks a job of known length only when its own start is known, and comes first.
|
|
846
|
+
if (known(me, hist) && overBudget(s, q, cfg) && !budgetSure(s, q, cfg, hist, t)) return false;
|
|
847
|
+
const at = soonestStart(s, q, cfg, hist, t);
|
|
848
|
+
if (q.mem >= BIG_SHARE * bytes(cfg.budget) && at - t > RESERVE_SOON) return false;
|
|
849
|
+
return at < myEnd;
|
|
850
|
+
};
|
|
851
|
+
const side = [];
|
|
852
|
+
const quick = instant(me, cfg, hist);
|
|
853
|
+
for (const r of me.res) {
|
|
854
|
+
if (mine.has(r)) continue;
|
|
855
|
+
if (isFiles(r)) {
|
|
856
|
+
const f = filesBlock(s, me, r, ahead.filter(blocks));
|
|
857
|
+
if (f) return f;
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
if (quick) continue;
|
|
861
|
+
const { open, across } = roomFor(s, me, r, cfg);
|
|
862
|
+
if (open <= 0) {
|
|
863
|
+
// Full, but the machine may have room for one more on top (src/overlap.mjs).
|
|
864
|
+
const a = alongside(s, me, r, cfg, hist, t, ahead);
|
|
865
|
+
if (a?.ok) { side.push(a); continue; }
|
|
866
|
+
const why = !byRepo(cfg, r) ? `${r} is in use` : across ? `${r} is in use by ${resCfg(cfg, r).across} projects at once, the most at a time` : `${r} is in use for this project`;
|
|
867
|
+
return { ok: false, rule: 'slot', why, on: r, ...(a && { alongside: a.why }) };
|
|
868
|
+
}
|
|
869
|
+
// Waiters ahead that will start before you'd finish take the open slots first; on a
|
|
870
|
+
// per-project resource, only this project's (the cap across projects is room enough for the rest).
|
|
871
|
+
const before = ahead.filter(q => q.res.includes(r) && blocks(q) && (!byRepo(cfg, r) || laneOf(q) === laneOf(me)));
|
|
872
|
+
if (before.length >= open) return { ok: false, rule: 'ahead', why: `${tag(before[0])} is ahead of you for ${r}`, on: r, ahead: before[0] };
|
|
873
|
+
}
|
|
874
|
+
// Learned clashes: a job that runs SLOW_PAIR times as slow beside one running now, or
|
|
875
|
+
// makes it that slow, waits for it, but no longer than its own run time since it
|
|
876
|
+
// joined, so it can't starve. Both finish sooner one after the other.
|
|
877
|
+
const pair = t - me.enq < expected(me, hist) && clashOf(s, me, hist);
|
|
878
|
+
if (pair) return { ok: false, rule: 'together', why: pair.why, on: pair.res, ahead: pair.lease };
|
|
879
|
+
// The last user's onRelease is still putting it back (src/reset.mjs).
|
|
880
|
+
const reset = (s.resets || []).find(x => me.res.includes(x.res) && !mine.has(x.res));
|
|
881
|
+
if (reset) return { ok: false, rule: 'reset', why: `${reset.res} is being reset after ${reset.agent || reset.who}'s turn (onRelease, at most ${dur(reset.timeout)})`, on: reset.res };
|
|
882
|
+
// Holding paths runs nothing, so the machine's budgets and load don't apply.
|
|
883
|
+
if (me.res.every(isFiles)) return { ok: true, covered: me.res.filter(r => mine.has(r)) };
|
|
884
|
+
// A run inside your own hold already has the memory, cores and disk the hold got at its
|
|
885
|
+
// grant: charging them again would queue it behind jobs that need what it already has, and
|
|
886
|
+
// checking the disk again refused (exit 74) a run right after "you already have the
|
|
887
|
+
// simulator, so you go ahead" (2026-11-03). The watcher's low-disk pauses still hold it.
|
|
888
|
+
if (me.res.every(r => mine.has(r))) return { ok: true, covered: [...me.res] };
|
|
889
|
+
// Below minDisk nothing else starts, urgent work included:
|
|
890
|
+
// a full disk breaks every job on the machine, and on macOS swap needs it too.
|
|
891
|
+
const others = othersOf(s, me);
|
|
892
|
+
// The floor plus what it usually eats (diskNeed).
|
|
893
|
+
const { need: needDisk, ate, others: crowded } = diskNeed(s, me, cfg, hist);
|
|
894
|
+
// An unreadable disk (null) doesn't stop work; the board and dibs run say it's unknown.
|
|
895
|
+
if (m.diskFree != null && m.diskFree < needDisk)
|
|
896
|
+
return { ok: false, rule: 'disk', why: `disk: ${gb(m.diskFree)} free, you need ${gb(needDisk)}${ate != null && ate + (crowded ? bytes(cfg.minDisk) : ALONE_ROOM) >= needDisk ? ` (${crowded ? `the ${gb(bytes(cfg.minDisk))} dibs keeps free` : `${gb(ALONE_ROOM)} to spare`}, plus the ${gb(ate)} this usually takes; --disk <size> says this run needs less)` : ''}`, disk: true, free: m.diskFree, need: needDisk, alone: !others.length, ...(ate != null && { usual: ate }) };
|
|
897
|
+
// While the machine swaps, only urgent work starts on top of what's running.
|
|
898
|
+
// With nothing else working, one job may start: waiting can't make the swap
|
|
899
|
+
// go down then, and swap the OS hasn't reclaimed yet mustn't stop dibs for good.
|
|
900
|
+
const busy = others.some(working);
|
|
901
|
+
// A job this small (a deploy, a lint, a quick script) can't make the paging
|
|
902
|
+
// worse, so only critical pressure holds it. On 2026-10-19 a 0.5 GB deploy
|
|
903
|
+
// waited on swap while the person waited on it, and its agent went around dibs.
|
|
904
|
+
const light = (me.mem || 0) <= LIGHT_MEM;
|
|
905
|
+
let sw = (me.prio || 'normal') !== 'urgent' && busy && swapping(cfg, m);
|
|
906
|
+
let trial = false;
|
|
907
|
+
if (sw && sw.level !== 'critical' && !light && sw.rule === 'pressure' && probation(s, me, cfg, hist, t)) trial = true;
|
|
908
|
+
if (sw && (light || trial) && sw.level !== 'critical') sw = null;
|
|
909
|
+
// The same for the disk swap grows on: one job may still start alone, since waiting frees nothing then.
|
|
910
|
+
// A light job can't grow the swap, so on a resource that writes little (exclusive, or declaring
|
|
911
|
+
// no disk: tests, deploys) only the floor holds it. On 2026-10-26 every start waited on the room
|
|
912
|
+
// kept for swap with 6.8 GB free, one-second test runs included.
|
|
913
|
+
const writesLittle = me.res.every(r => cfg.resources[r]?.exclusive || !resCfg(cfg, r).disk);
|
|
914
|
+
const squeeze = (me.prio || 'normal') !== 'urgent' && busy && !sw && !(light && writesLittle) && diskSqueeze(cfg, needDisk, m);
|
|
915
|
+
let breaker = (sw || squeeze) && breaksStall(s, me, cfg, hist, t, m);
|
|
916
|
+
if (sw && !breaker) return { ok: false, why: swapWhy(sw), ...sw, machine: true };
|
|
917
|
+
if (squeeze && !breaker) return { ok: false, ...squeeze, machine: true };
|
|
918
|
+
// A light job may pass one stuck on the budget, but not once that one has
|
|
919
|
+
// waited long, unless it'll be done before that one could start. Waiters
|
|
920
|
+
// stuck on something else (machine memory, disk) don't hold anyone up.
|
|
921
|
+
const head = ahead.find(q => q.res.every(r => roomFor(s, q, r, cfg).open > 0) && !neverFits(cfg, q) && overBudget(s, q, cfg));
|
|
922
|
+
if (head && t - head.enq > ms(cfg.starveAfter) && blocks(head))
|
|
923
|
+
return { ok: false, rule: 'ahead', why: `${tag(head)} has waited ${dur(t - head.enq)}, so it goes first`, ahead: head, starved: true };
|
|
924
|
+
let budget = overBudget(s, me, cfg, side.length > 0, breaker, t);
|
|
925
|
+
// Nothing starts past the memory budget (0.0.125). Jobs book what they're
|
|
926
|
+
// measured using once they've run a few minutes (memOf), so the gap between
|
|
927
|
+
// asks and use goes to waiters that way, with the machine's pressure as the guard.
|
|
928
|
+
// Held only by swap growth, the budget is a machine gate like swap itself: the stall breaker may pass it.
|
|
929
|
+
const swapOnly = budget?.swap && !overBudget(s, me, cfg, side.length > 0, true);
|
|
930
|
+
if (swapOnly && breaksStall(s, me, cfg, hist, t, m)) { budget = null; breaker = true; }
|
|
931
|
+
if (budget) return { ok: false, ...budget, ...(swapOnly && { machine: true }) };
|
|
932
|
+
if (me.mem >= BIG_JOB && m.memFree < cfg.minFreeMem && s.leases.some(working) && !breaker)
|
|
933
|
+
return { ok: false, rule: 'ram', why: `machine memory: ${m.memFree}% free, big jobs need ${cfg.minFreeMem}%` };
|
|
934
|
+
// Stopped last time for using far more than it booked (src/preempt.mjs diskRequeue):
|
|
935
|
+
// it starts again only once what it's now booked at is really free and swap
|
|
936
|
+
// has stopped growing, or it would land in the same crunch.
|
|
937
|
+
if (me.requeued === 'over' && ((realFree(m) ?? 0) < me.mem || swapGrowing(m)))
|
|
938
|
+
return { ok: false, rule: 'oversize', machine: true, why: `${gb(me.mem)} of memory to be really free and swap to hold still, since it used far more than it booked last time`
|
|
939
|
+
+ ` (now ${gb(realFree(m) ?? 0)} free${swapGrowing(m) ? ', swap growing' : ''})` };
|
|
940
|
+
const pool = poolBlock(s, me, cfg, mine, m);
|
|
941
|
+
if (pool) return { ok: false, ...pool };
|
|
942
|
+
// Squeezing in (src/overlap.mjs) may take the load past the ceiling, but never starts once it's already there.
|
|
943
|
+
// since: when the ceiling started holding it (acquire.mjs decide), or now on its first poll.
|
|
944
|
+
const since = me.loadSince ?? t;
|
|
945
|
+
const loadPast = hot && !pastCeiling && t - since >= LOAD_STARVE && loadShare(s, me);
|
|
946
|
+
if (hot && !pastCeiling && !loadPast) return { ok: false, rule: 'load', why: loadWhy(hot, cfg), load: hot.load + hot.ahead, since, by: since + LOAD_STARVE };
|
|
947
|
+
if (me.prio === 'idle') {
|
|
948
|
+
const busy = s.queue.find(q => q.pid && q.id !== me.id && q.prio !== 'idle');
|
|
949
|
+
if (busy) return { ok: false, rule: 'idle', why: `idle work waits while anyone else is waiting (${tag(busy)})`, ahead: busy };
|
|
950
|
+
}
|
|
951
|
+
if ((me.prio || 'normal') === 'idle') {
|
|
952
|
+
if (m.memFree < IDLE_MEM_FREE) return { ok: false, rule: 'idle', why: `idle work waits for ${IDLE_MEM_FREE}% memory free (now ${m.memFree}%)` };
|
|
953
|
+
}
|
|
954
|
+
return { ok: true, covered: me.res.filter(r => mine.has(r)), ...(quick && { instant: true }), ...(trial && { trial: true }), ...(side.length && { alongside: merge(side) }), ...(breaker && { breaker: true }), ...(loadPast && { loadPast: true, loadWaited: t - since }),
|
|
955
|
+
...(!breaker && (me.prio || 'normal') !== 'urgent' && { gated: true }) };
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
// When each waiter should start: hand every slot of its resources to the
|
|
959
|
+
// requests ahead of it in rank order, using their typical run times. Pass
|
|
960
|
+
// `extra` to ask where a request would land without adding it.
|
|
961
|
+
//
|
|
962
|
+
// Each start also says whether it's sure: every job it waits on has a run time
|
|
963
|
+
// from history or --est (a hold's end is only its longest). When it isn't,
|
|
964
|
+
// `after` is the lease or waiter whose unknown end it waits on.
|
|
965
|
+
export function forecastDetail(s, cfg, hist, t = now(), extra = null) {
|
|
966
|
+
const free = {};
|
|
967
|
+
const open = () => ({ at: t, sure: true, after: null });
|
|
968
|
+
// A per-project resource's slots are kept per project (byRepo): the cap across projects isn't forecast.
|
|
969
|
+
const slotsFor = (r, q) => {
|
|
970
|
+
const lane = byRepo(cfg, r) ? laneOf(q) : null;
|
|
971
|
+
const k = lane == null ? r : `${r}\0${lane}`;
|
|
972
|
+
if (!free[k]) {
|
|
973
|
+
// A file lease waits on any lease of an overlapping path, not just the same name.
|
|
974
|
+
const busy = s.leases.filter(l => l.res.some(x => clash(x, r)) && !coveredNow(s, l, r) && !lent(l, r) && !onTop(l, r) && (lane == null || laneOf(l) === lane))
|
|
975
|
+
.map(l => ({ at: slotEnd(s, l, hist, t, r), sure: l.kind !== 'hold' && remaining(l, hist, t) != null, after: l }));
|
|
976
|
+
const n = Math.max(resCfg(cfg, r).slots - busy.length, 0);
|
|
977
|
+
free[k] = [...busy, ...Array.from({ length: n }, open)].sort((a, b) => a.at - b.at);
|
|
978
|
+
}
|
|
979
|
+
return free[k];
|
|
980
|
+
};
|
|
981
|
+
const out = new Map();
|
|
982
|
+
const line = (extra ? [...s.queue, extra] : [...s.queue]).filter(q => q.pid || q === extra);
|
|
983
|
+
for (const q of line.sort(byRank(hist, t))) {
|
|
984
|
+
const firsts = q.res.map(r => slotsFor(r, q)[0] ?? open());
|
|
985
|
+
const startAt = Math.max(t, ...firsts.map(f => f.at));
|
|
986
|
+
const unsure = firsts.find(f => f.at > t && !f.sure);
|
|
987
|
+
const end = { at: startAt + expected(q, hist), sure: !unsure && known(q, hist), after: q };
|
|
988
|
+
for (const r of q.res) { const sl = slotsFor(r, q); sl.shift(); sl.push({ ...end }); sl.sort((a, b) => a.at - b.at); }
|
|
989
|
+
out.set(q.id, { at: startAt, sure: !unsure, after: unsure?.after || null });
|
|
990
|
+
}
|
|
991
|
+
return out;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
export const forecast = (s, cfg, hist, t = now(), extra = null) =>
|
|
995
|
+
new Map([...forecastDetail(s, cfg, hist, t, extra)].map(([id, f]) => [id, f.at]));
|