@dibssoftware/dibs 0.0.180 → 0.0.195
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 +111 -1
- package/README.md +10 -8
- package/bin/dibs.mjs +379 -74
- package/docs/agents.md +303 -0
- package/docs/council.md +88 -0
- package/docs/files.md +3 -3
- package/docs/guard.md +86 -11
- package/docs/json.md +211 -0
- package/docs/later.md +5 -5
- package/docs/machines.md +6 -6
- package/docs/questions.md +104 -3
- package/docs/reference.md +124 -30
- package/docs/relay.md +135 -11
- package/docs/releasing.md +7 -1
- package/docs/scheduling.md +28 -6
- package/docs/secrets.md +53 -0
- package/docs/simulators.md +3 -3
- package/docs/windows.md +3 -3
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +79 -149
- package/src/about.mjs +341 -0
- package/src/acquire.mjs +113 -28
- package/src/after.mjs +127 -0
- package/src/agents.mjs +2 -1
- package/src/alerts.mjs +109 -48
- package/src/answers.mjs +2 -2
- package/src/board.mjs +21 -16
- package/src/broker.mjs +23 -7
- package/src/carry.mjs +287 -0
- package/src/codex.mjs +132 -0
- package/src/commands.mjs +254 -86
- package/src/config.mjs +85 -14
- package/src/connect.mjs +4 -2
- package/src/cool.mjs +28 -12
- package/src/council.mjs +482 -0
- package/src/cwd.mjs +9 -0
- package/src/decisions.mjs +250 -0
- package/src/declare.mjs +96 -0
- package/src/diskreport.mjs +306 -0
- package/src/diskuse.mjs +420 -0
- package/src/diskwarn.mjs +68 -13
- package/src/doctor.mjs +149 -0
- package/src/doors.mjs +547 -0
- package/src/durable.mjs +143 -0
- package/src/envs.mjs +372 -0
- package/src/events.mjs +7 -2
- package/src/files.mjs +121 -7
- package/src/guard.mjs +288 -105
- package/src/guardd.mjs +8 -1
- package/src/halt.mjs +63 -0
- package/src/handoffs.mjs +362 -0
- package/src/history.mjs +34 -4
- package/src/hogs.mjs +36 -8
- package/src/jobprogress.mjs +283 -0
- package/src/later.mjs +21 -10
- package/src/lock.mjs +51 -11
- package/src/measure.mjs +60 -14
- package/src/media.mjs +240 -0
- package/src/news.mjs +31 -0
- package/src/notes.mjs +49 -8
- package/src/notices.mjs +126 -43
- package/src/ondemand.mjs +25 -2
- package/src/outcome.mjs +163 -0
- package/src/overlap.mjs +2 -2
- package/src/override.mjs +149 -79
- package/src/owner.mjs +15 -2
- package/src/people.mjs +236 -0
- package/src/pickup.mjs +72 -0
- package/src/picture.mjs +321 -0
- package/src/plain.mjs +84 -18
- package/src/platform.mjs +29 -7
- package/src/preempt.mjs +123 -15
- package/src/primer.mjs +91 -20
- package/src/prints.mjs +99 -0
- package/src/proc.mjs +11 -1
- package/src/progress.mjs +49 -3
- package/src/proof.mjs +102 -0
- package/src/push.mjs +271 -0
- package/src/questions.mjs +328 -57
- package/src/quota.mjs +1 -1
- package/src/recap.mjs +205 -0
- package/src/relay.mjs +262 -26
- package/src/remote.mjs +23 -10
- package/src/reviewgate.mjs +268 -0
- package/src/reviews.mjs +377 -0
- package/src/route.mjs +263 -0
- package/src/rules.mjs +216 -0
- package/src/schedule.mjs +238 -44
- package/src/schema.mjs +62 -0
- package/src/scratch.mjs +2 -2
- package/src/serve.mjs +3 -2
- package/src/service.mjs +5 -1
- package/src/signed.mjs +97 -0
- package/src/simpool.mjs +46 -1
- package/src/spend.mjs +375 -0
- package/src/state.mjs +43 -17
- package/src/talk.mjs +1082 -134
- package/src/thin.sh +2 -0
- package/src/trail.mjs +290 -0
- package/src/trailnote.mjs +209 -0
- package/src/util.mjs +7 -0
- package/src/vault.mjs +435 -0
- package/src/vendors.mjs +327 -0
- package/src/version.mjs +1 -1
- package/src/web.mjs +354 -60
- package/src/work.mjs +487 -0
- package/src/worker.mjs +7 -1
package/src/plain.mjs
CHANGED
|
@@ -7,11 +7,13 @@
|
|
|
7
7
|
// job in the way has a run time from history or --est, "as soon as X finishes"
|
|
8
8
|
// when X has none, and "unknown" when the wait is on the machine (disk, memory,
|
|
9
9
|
// load), which no clock predicts.
|
|
10
|
-
import { IDLE_MEM_FREE, verdict, forecastDetail, expected, known, remaining, rankParts, byRank, recentUse, coveredNow, memUsed, memHolders, shownFree, NOT_PRIORITY, swapping, diskSqueeze, overLoad, STALL, QUICK_LINE } from './schedule.mjs';
|
|
10
|
+
import { IDLE_MEM_FREE, verdict, forecastDetail, expected, known, remaining, rankParts, byRank, recentUse, coveredNow, memUsed, memHolders, shownFree, NOT_PRIORITY, swapping, diskSqueeze, overLoad, STALL, QUICK_LINE, EASED_LINE, keptFree, halted, haltUntil, haltBy, fairShare, shareText, sessionOf, OVER_SHARE } from './schedule.mjs';
|
|
11
11
|
import { quotaBlock, isQuota, QUOTA } from './quota.mjs';
|
|
12
12
|
import { isFiles, short, elsewhere } from './files.mjs';
|
|
13
13
|
import { machine, resCfg } from './config.mjs';
|
|
14
14
|
import { hogHint } from './hogs.mjs';
|
|
15
|
+
import { useHint } from './diskuse.mjs';
|
|
16
|
+
import { progressOf, slowness, cpuLeft } from './jobprogress.mjs';
|
|
15
17
|
import { gb, clock, now, bytes, inClaudeCode, agentLabel } from './util.mjs';
|
|
16
18
|
|
|
17
19
|
const MIN = 6e4;
|
|
@@ -60,8 +62,8 @@ export const ordinal = n => {
|
|
|
60
62
|
export const andList = xs => (xs.length < 2 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);
|
|
61
63
|
// A job held by the load ceiling starts on its own by v.by at the latest (schedule.mjs LOAD_STARVE).
|
|
62
64
|
export const heldByLoad = v => `held by load since ${clock(v.since)}, starts by ${clock(v.by)} at the latest`;
|
|
63
|
-
//
|
|
64
|
-
const LOAD_ADVICE = '
|
|
65
|
+
// What passes the load ceiling, said as facts: whether a job needs it is its agent's call.
|
|
66
|
+
const LOAD_ADVICE = 'A run with -p high -m "why" starts past the load limit, and so does a job sent to another machine (--on <machine>; dibs machines lists them)';
|
|
65
67
|
export const minutes = t => {
|
|
66
68
|
const m = Math.max(1, Math.round(t / MIN));
|
|
67
69
|
return m < 60 ? `${m} min` : `${Math.floor(m / 60)} hr${m % 60 ? ` ${m % 60} min` : ''}`;
|
|
@@ -91,23 +93,57 @@ const who = x => {
|
|
|
91
93
|
const MOVE_SHOWN = MIN;
|
|
92
94
|
|
|
93
95
|
// When a running job ends. A hold's end is only its longest: it may be given back sooner.
|
|
96
|
+
// A job that says how far it is (src/jobprogress.mjs) leads with that: "40% done, about 2 hr left".
|
|
97
|
+
// One far off its own pace says how, so a job hogging a line reads as one.
|
|
94
98
|
export function ends(l, hist, t) {
|
|
95
99
|
if (l.kind === 'hold') { const left = Math.max(l.expires - t, 0); return { endsIn: left, endsText: `up to ${minutes(left)} left` }; }
|
|
96
100
|
const left = remaining(l, hist, t);
|
|
97
|
-
|
|
101
|
+
const pr = progressOf(l, t), sl = slowness(l, hist, t);
|
|
102
|
+
const pace = sl?.stalled ? `no progress for ${minutes(sl.quiet)}` : sl?.share ? `going at ${fractionText(sl.share)} of its earlier speed` : '';
|
|
103
|
+
// Past several times its usual run, with nothing but the clock to go on, "under a minute left" is no estimate.
|
|
104
|
+
const own = pr?.left != null || cpuLeft(l, hist, t) != null;
|
|
105
|
+
const time = !own && sl?.times ? `running ${Math.round(sl.times)} times as long as usual (${minutes(sl.usual)})` : left == null ? (pr ? '' : 'time left unknown') : `${about(left)} left`;
|
|
106
|
+
return { endsIn: left, endsText: [pr ? doneText(pr) : '', time, pace, sl?.cpu != null ? cpuText(sl) : ''].filter(Boolean).join(', ') };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// The CPU a job gets against what its own runs usually get, with the numbers:
|
|
110
|
+
// "getting about a sixth of its usual processing (0.3 of the 1.8 cores its runs usually get)".
|
|
111
|
+
const cpuText = sl => `getting ${sl.starved ? `about ${fractionText(sl.cpu / sl.usualCpu)} of its usual` : 'almost no'} processing`
|
|
112
|
+
+ ` (${sl.cpu.toFixed(1)} of the ${sl.usualCpu.toFixed(1)} cores its runs usually get)`;
|
|
113
|
+
|
|
114
|
+
// A job's own count in words: "13% done, 1200/9000 flops solved". Never 100% before it is.
|
|
115
|
+
// No parentheses: it goes inside them in a wait line.
|
|
116
|
+
export function doneText(pr) {
|
|
117
|
+
const pct = pr.pct >= 100 ? '100%' : pr.pct < 1 ? 'under 1%' : `${Math.floor(pr.pct)}%`;
|
|
118
|
+
return `${pct} done${pr.total != null ? `, ${pr.done}/${pr.total}${pr.unit ? ` ${pr.unit}` : ''}` : ''}`;
|
|
119
|
+
}
|
|
120
|
+
// A rate as a share of an earlier one: "a sixth". slowness only reports under a quarter.
|
|
121
|
+
const SHARES = { 2: 'half', 3: 'a third', 4: 'a quarter', 5: 'a fifth', 6: 'a sixth', 7: 'a seventh', 8: 'an eighth', 9: 'a ninth', 10: 'a tenth' };
|
|
122
|
+
const fractionText = share => { const n = Math.round(1 / share); return n > 10 ? 'under a tenth' : SHARES[n] || 'a quarter'; };
|
|
123
|
+
// How a job is off its pace (src/jobprogress.mjs slowness), to follow its name:
|
|
124
|
+
// "is going at a sixth of its earlier speed (40% done after 7 hr)".
|
|
125
|
+
export function slowText(sl) {
|
|
126
|
+
const parts = [];
|
|
127
|
+
if (sl.stalled) parts.push(`has made no progress for ${minutes(sl.quiet)} (${Math.floor(sl.pct)}% done)`);
|
|
128
|
+
else if (sl.share) parts.push(`is going at ${fractionText(sl.share)} of its earlier speed (${Math.floor(sl.pct)}% done after ${minutes(sl.ran)})`);
|
|
129
|
+
if (sl.times) parts.push(`has run ${minutes(sl.ran)}, ${Math.round(sl.times)} times as long as it usually takes (${minutes(sl.usual)})`);
|
|
130
|
+
if (sl.cpu != null) parts.push(`${sl.starved ? 'is starved' : 'looks stuck'}, ${cpuText(sl)}`);
|
|
131
|
+
return andList(parts);
|
|
98
132
|
}
|
|
99
133
|
|
|
100
134
|
// Who has a line now. rows: { who, endsIn, endsText, hold }.
|
|
101
135
|
// "onboarding is using it, about 4 min left"; "web-app and ios-checkout are using it, time left unknown for both"
|
|
136
|
+
// Each with its job number, the one dibs stop, boost and why take, unless its name already has it.
|
|
137
|
+
const numbered = (name, x) => (x.id == null || /#\d/.test(name) ? name : `${name} (#${x.id})`);
|
|
102
138
|
export function usingText(rows, n) {
|
|
103
139
|
if (rows.length === 1) {
|
|
104
140
|
const x = rows[0];
|
|
105
|
-
return `${x.who} ${x.hold && n.one !== 'has reserved them' ? 'has reserved it' : n.one}, ${x.endsText}`;
|
|
141
|
+
return `${numbered(x.who, x)} ${x.hold && n.one !== 'has reserved them' ? 'has reserved it' : n.one}, ${x.endsText}`;
|
|
106
142
|
}
|
|
107
143
|
const soon = rows.filter(x => x.endsIn != null).sort((a, b) => a.endsIn - b.endsIn)[0];
|
|
108
144
|
const tail = !soon ? `time left unknown for ${rows.length === 2 ? 'both' : `all ${rows.length}`}`
|
|
109
145
|
: soon.hold ? `one is free within ${minutes(soon.endsIn)}` : `the first should be done in ${about(soon.endsIn)}`;
|
|
110
|
-
return `${andList(rows.map(who))} ${n.many}, ${tail}`;
|
|
146
|
+
return `${andList(rows.map(x => numbered(who(x), x)))} ${n.many}, ${tail}`;
|
|
111
147
|
}
|
|
112
148
|
|
|
113
149
|
// "Next: api-refactor, then onboarding and 2 others"
|
|
@@ -118,6 +154,7 @@ export function nextText(names) {
|
|
|
118
154
|
|
|
119
155
|
// Why a job was paused, as a sentence, or null.
|
|
120
156
|
function pausedText(l, cfg) {
|
|
157
|
+
if (l.requeue?.why === 'yield') return `Stepping aside for ${l.requeue.toWho}'s job (#${l.requeue.to}): asked to save its progress, then it goes back in line`;
|
|
121
158
|
if (!l.pausedAt) return null;
|
|
122
159
|
const hand = l.pauses?.find(p => p.owner);
|
|
123
160
|
if (hand) return `Paused by ${hand.by || 'the person at this machine'}`;
|
|
@@ -149,10 +186,13 @@ export const stuckText = (l, t = now()) => { const d = stuckFor(l, t); return d
|
|
|
149
186
|
// The memory picture a memory wait needs: what it needs, what's left of the
|
|
150
187
|
// budget and of the machine's real free memory, and who holds the most, so
|
|
151
188
|
// an agent can tell which of its own jobs to end.
|
|
189
|
+
const SAME = 0.05 * 1024 ** 3; // two sizes this close read the same at one decimal
|
|
152
190
|
export function memoryPicture(s, cfg, m, need, t = now()) {
|
|
153
191
|
const budget = bytes(cfg.budget), out = memUsed(s), free = shownFree(m);
|
|
154
192
|
const left = Math.max(0, budget - out);
|
|
155
|
-
|
|
193
|
+
// What each one counts at, when that's neither its use nor its ask: a run measured a few minutes books its use plus a margin.
|
|
194
|
+
const counted = h => (Math.abs(h.mem - h.asked) > SAME && (h.use == null || Math.abs(h.mem - h.use) > SAME) ? `, counted at ${GB(h.mem)}` : '');
|
|
195
|
+
const holders = memHolders(s).map(h => `${h.who} #${h.id}${h.purpose ? ` ("${h.purpose}")` : ''}: ${h.use != null ? `using ${GB(h.use)}` : 'not measured yet'}, asked ${GB(h.asked)}${counted(h)}`
|
|
156
196
|
+ `${h.idleSince && t - h.idleSince >= STUCK_AFTER ? `, idle for ${minutes(t - h.idleSince)}` : ''}`);
|
|
157
197
|
return `it needs ${GB(need)}; ${GB(out)} of the ${GB(budget)} dibs shares out is taken, ${left ? `${GB(left)} left` : 'none left'}`
|
|
158
198
|
+ `${free != null ? `, and the machine has ${GB(free)} free or reclaimable` : ''}${m.vmPressure >= 1 ? ' with memory pressure high' : ''}`
|
|
@@ -163,13 +203,15 @@ export function memoryPicture(s, cfg, m, need, t = now()) {
|
|
|
163
203
|
// until ...", or ''. A line with free slots isn't free to use while this
|
|
164
204
|
// holds, so the board, who and the wait lines say it next to "free".
|
|
165
205
|
export function machineHold(s, cfg, m = machine()) {
|
|
206
|
+
const h = halted(s);
|
|
207
|
+
if (h) return `the hold on new jobs lifts (${haltUntil(h)}, set by ${haltBy(h)})`;
|
|
166
208
|
const othersRun = s.leases.some(l => (l.mem || 0) > 0 || (l.cpu ?? 1) > 0);
|
|
167
|
-
if (m.diskFree != null && m.diskFree < bytes(cfg.minDisk)) return `more disk is free (${GB(m.diskFree)} free
|
|
209
|
+
if (m.diskFree != null && m.diskFree < bytes(cfg.minDisk)) return `more disk is free (${GB(m.diskFree)} free; dibs keeps ${keptFree(cfg)})`;
|
|
168
210
|
const hot = overLoad(s, cfg, m);
|
|
169
211
|
if (hot) return `the machine cools down (load ${(hot.load + hot.ahead).toFixed(1)}, over maxLoad ${cfg.maxLoad})`;
|
|
170
212
|
if (!othersRun) return '';
|
|
171
213
|
const sq = diskSqueeze(cfg, bytes(cfg.minDisk), m);
|
|
172
|
-
if (sq) return sq.rule === 'drain' ? `free disk stops falling (it fell ${GB(sq.fell)} in 5 min)` : `${GB(sq.need)} of disk is free
|
|
214
|
+
if (sq) return sq.rule === 'drain' ? `free disk stops falling (it fell ${GB(sq.fell)} in 5 min)` : `${GB(sq.need)} of disk is free (${GB(sq.free)} now; dibs keeps ${keptFree(cfg)}, and it's swapping now)`;
|
|
173
215
|
const sw = swapping(cfg, m);
|
|
174
216
|
if (sw) return sw.rule === 'pressure' ? 'memory pressure eases' : `swap stops growing (it grew ${GB(sw.grew)} in 5 min)`;
|
|
175
217
|
const out = memUsed(s), budget = bytes(cfg.budget);
|
|
@@ -200,6 +242,7 @@ function waitingFor(s, q, v, cfg, hist, t, m, f) {
|
|
|
200
242
|
}
|
|
201
243
|
case 'ahead':
|
|
202
244
|
if (v.starved) return `${who(v.ahead)} to go first (it's waited ${minutes(t - v.ahead.enq)} for room on the machine)`;
|
|
245
|
+
if (v.fair) return `${who(v.ahead)} to go first (another session's job, while this one's holds more than its share)`;
|
|
203
246
|
return `${who(v.ahead)} to go first (it's ahead in the queue)`;
|
|
204
247
|
case 'files': {
|
|
205
248
|
const l = s.leases.find(l => l.res.includes(v.on));
|
|
@@ -219,9 +262,9 @@ function waitingFor(s, q, v, cfg, hist, t, m, f) {
|
|
|
219
262
|
+ `${v.high ? ' with memory pressure high' : ''}${v.growing ? ' and swap growing' : ''}, and it needs ${GB(v.need)} plus ${GB(v.reserve)} to spare`;
|
|
220
263
|
return `room in memory: ${memoryPicture(s, cfg, m, v.need, t)}`;
|
|
221
264
|
case 'cpu': return `free processor cores (jobs running now are using ${v.used} of the ${v.of} cores dibs shares out, and it needs ${v.need})`;
|
|
222
|
-
case 'disk': return `more free disk (${GB(v.free)} free, it needs ${GB(v.need)}${v.floorWhy ? `: ${v.floorWhy}` : ''})${hogHint()}`;
|
|
265
|
+
case 'disk': return `more free disk (${GB(v.free)} free, it needs ${GB(v.need)}${v.floorWhy ? `: ${v.floorWhy}` : ''})${hogHint() || useHint()}`;
|
|
223
266
|
case 'pressure': return `memory pressure to ease (the OS says it's high, so dibs starts nothing new until it eases): ${memoryPicture(s, cfg, m, q.mem, t)}`;
|
|
224
|
-
case 'swaproom': return `more free disk
|
|
267
|
+
case 'swaproom': return `more free disk (${GB(v.free)} free; dibs keeps ${keptFree(cfg)}, and it's swapping now, so nothing new starts until ${GB(v.need)} is free or nothing else is running)${hogHint()}`;
|
|
225
268
|
case 'drain': return `free disk to stop falling (it fell ${GB(v.fell)} in 5 min to ${GB(v.free)}; dibs starts nothing new while it falls this fast and anything else is running)${hogHint()}`;
|
|
226
269
|
case 'swap': return `this machine to stop swapping (swap grew ${GB(v.grew)} in 5 min, ${GB(v.used)} in use, so dibs starts nothing new until it stops growing): ${memoryPicture(s, cfg, m, q.mem, t)}`;
|
|
227
270
|
case 'ram':
|
|
@@ -237,6 +280,9 @@ function waitingFor(s, q, v, cfg, hist, t, m, f) {
|
|
|
237
280
|
}
|
|
238
281
|
}
|
|
239
282
|
|
|
283
|
+
// What a waiter is waiting for, as the person reads it (src/alerts.mjs).
|
|
284
|
+
export const waitingText = (s, q, v, cfg, hist, t = now(), m = machine()) => waitingFor(s, q, v, cfg, hist, t, m, null);
|
|
285
|
+
|
|
240
286
|
// Behind others in its line, a waiter waits for them too, not only for the job running now.
|
|
241
287
|
const NAMED_AHEAD = 2;
|
|
242
288
|
function inTurn(ahead, v, why) {
|
|
@@ -246,9 +292,9 @@ function inTurn(ahead, v, why) {
|
|
|
246
292
|
}
|
|
247
293
|
|
|
248
294
|
// Why a waiter moved from its arrival time, one plain sentence per rule.
|
|
249
|
-
export function moves(q, hist, t, cfg) {
|
|
295
|
+
export function moves(q, hist, t, cfg, fair = null) {
|
|
250
296
|
const out = [];
|
|
251
|
-
for (const p of rankParts(q, hist, t).parts) {
|
|
297
|
+
for (const p of rankParts(q, hist, t, fair).parts) {
|
|
252
298
|
if (Math.abs(p.shift) < MOVE_SHOWN) continue;
|
|
253
299
|
let reason, label;
|
|
254
300
|
if (p.label === q.prio) {
|
|
@@ -272,6 +318,9 @@ export function moves(q, hist, t, cfg) {
|
|
|
272
318
|
} else if (p.label === 'recent use') {
|
|
273
319
|
label = 'taking turns';
|
|
274
320
|
reason = `this agent used ${andList(recentUse(hist, q.who, q.res, t).res.map(r => named(cfg, r).the))} a lot in the last hour`;
|
|
321
|
+
} else if (p.label === OVER_SHARE) {
|
|
322
|
+
label = 'fair share';
|
|
323
|
+
reason = `${shareText(fair(q), "this agent's session")}, more than its share while other sessions wait, so their jobs go first. It goes once one of the session's jobs ends, or nobody else is waiting`;
|
|
275
324
|
} else if (p.label === 'quick') {
|
|
276
325
|
label = 'quick';
|
|
277
326
|
reason = "it runs in seconds (the quick lane), so it goes before anyone who'd hold the slot for longer";
|
|
@@ -284,6 +333,20 @@ export function moves(q, hist, t, cfg) {
|
|
|
284
333
|
return out;
|
|
285
334
|
}
|
|
286
335
|
|
|
336
|
+
// A waiter held back by another session over its fair share (src/schedule.mjs fairShare): who,
|
|
337
|
+
// what it holds, and that this one goes before that session's next jobs. On 2026-11-29 the person
|
|
338
|
+
// asked for "waiting: session X holds 3 of 3 heavy slots and 7.1 GB; you're next when one ends" (said with turns, not slots).
|
|
339
|
+
function shareLine(s, q, v, fair, place) {
|
|
340
|
+
if (v.ok || fair(q)) return {};
|
|
341
|
+
const r = q.res.includes(v.on) ? v.on : null;
|
|
342
|
+
const mine = sessionOf(q);
|
|
343
|
+
const over = [...(r ? fair.over(r) : []), ...(family(v.rule) === 'memory' || v.rule === 'ahead' ? fair.over(null) : [])]
|
|
344
|
+
.filter((x, i, all) => x.session !== mine && all.findIndex(y => y.session === x.session) === i);
|
|
345
|
+
if (!over.length) return {};
|
|
346
|
+
const next = place === 1 ? "you're next when one ends" : `you're ${ordinal(place)} in line when one ends, ahead of its next jobs`;
|
|
347
|
+
return { share: `${upper(andList(over.map(x => shareText(x))))}; ${next}` };
|
|
348
|
+
}
|
|
349
|
+
|
|
287
350
|
// When a waiter's start hangs on a job using another of the resources it
|
|
288
351
|
// needs, say which: "as soon as api finishes with Xcode builds".
|
|
289
352
|
function elsewhereOn(after, q, focus, s, cfg) {
|
|
@@ -305,8 +368,8 @@ export function askFirst(s, p, q) {
|
|
|
305
368
|
const them = x?.agent;
|
|
306
369
|
if (!them || them === q.agent) return '';
|
|
307
370
|
// SendMessage is Claude Code's, and reaches only another Claude Code session.
|
|
308
|
-
|
|
309
|
-
return
|
|
371
|
+
const yieldTo = `dibs yield ${q.agent || q.who}, run by ${them}, puts you ahead of ${them}.`;
|
|
372
|
+
return inClaudeCode() && x.sessionId ? `${yieldTo} SendMessage reaches ${them}.` : yieldTo;
|
|
310
373
|
}
|
|
311
374
|
|
|
312
375
|
// Waits whose start dibs can forecast from the jobs in the way. The others
|
|
@@ -317,7 +380,8 @@ const QUEUED = new Set(['slot', 'ahead', 'files', 'reset']);
|
|
|
317
380
|
export function plainBoard(s, cfg, hist, t = now(), m = machine(), me = null) {
|
|
318
381
|
viewer = me;
|
|
319
382
|
const fc = forecastDetail(s, cfg, hist, t);
|
|
320
|
-
const
|
|
383
|
+
const fair = fairShare(s, cfg, t);
|
|
384
|
+
const order = s.queue.filter(q => q.pid).sort(byRank(hist, t, fair));
|
|
321
385
|
const verdicts = new Map(order.map(q => {
|
|
322
386
|
const v = verdict(s, q, cfg, hist, t);
|
|
323
387
|
return [q.id, v.ok ? quotaBlock(s, q, cfg, hist, t) || v : v];
|
|
@@ -365,7 +429,8 @@ export function plainBoard(s, cfg, hist, t = now(), m = machine(), me = null) {
|
|
|
365
429
|
headline: `${place === 1 ? 'Next' : ordinal(place)} in ${named(cfg, focus).queue}`,
|
|
366
430
|
...start, waitingFor: why + diskNext, ...(v.diskNext && { diskNext: v.diskNext }),
|
|
367
431
|
...(kind === 'load' ? { advice: LOAD_ADVICE } : MACHINE.has(kind) && kind !== 'idle' ? { advice: NOT_PRIORITY } : {}),
|
|
368
|
-
moves: moves(q, hist, t, cfg),
|
|
432
|
+
moves: moves(q, hist, t, cfg, fair),
|
|
433
|
+
...shareLine(s, q, v, fair, place),
|
|
369
434
|
});
|
|
370
435
|
if (!v.ok) rules.set(q.id, { rule: v.rule, on: v.on, alongside: v.alongside });
|
|
371
436
|
}
|
|
@@ -393,7 +458,7 @@ export function plainBoard(s, cfg, hist, t = now(), m = machine(), me = null) {
|
|
|
393
458
|
const someoneWaits = order.length > 0;
|
|
394
459
|
const held = new Map(s.leases.map(l => [l.id, {
|
|
395
460
|
headline: l.res.map((r, i) => (i ? lower(named(cfg, r).doing) : named(cfg, r).doing)).join(' and '),
|
|
396
|
-
endsText: ends(l, hist, t).endsText, paused: pausedText(l, cfg), ...(l.alongside ? { alongside: alongsideText(l.alongside) } : l.breaker ? { alongside: `Let in although the machine is short of disk or memory, since nothing had started for ${STALL / 6e4} min` } : l.quick ? { alongside: upper(QUICK_LINE) } : {}),
|
|
461
|
+
endsText: ends(l, hist, t).endsText, paused: pausedText(l, cfg), ...(l.alongside ? { alongside: alongsideText(l.alongside) } : l.eased ? { alongside: upper(EASED_LINE) } : l.breaker ? { alongside: `Let in although the machine is short of disk or memory, since nothing had started for ${STALL / 6e4} min` } : l.quick ? { alongside: upper(QUICK_LINE) } : {}),
|
|
397
462
|
...(someoneWaits && stuckFor(l, t) ? { stuck: `${stuckText(l, t)} (#${l.id}${l.purpose ? `, "${l.purpose}"` : ''})` } : {}) }]));
|
|
398
463
|
return { lines, held, waiting, rules, names: new Map(s.queue.map(q => [q.id, holderName(q)])), holds: new Set(s.leases.filter(l => l.kind === 'hold').map(l => l.id)), cfg,
|
|
399
464
|
hold: machineHold(s, cfg, m) };
|
|
@@ -465,6 +530,7 @@ export function whyLines(p, q, cfg) {
|
|
|
465
530
|
` ${w.startsText === 'now' ? "It's about to start" : `Waiting for ${w.waitingFor}`}.${w.advice ? ` ${w.advice}.` : ''}`,
|
|
466
531
|
// Why it can't start next to the jobs filling its queue (src/overlap.mjs), when that was tried.
|
|
467
532
|
...(p.rules.get(q.id)?.alongside ? [` ${p.rules.get(q.id).alongside}`] : []),
|
|
533
|
+
...(w.share ? [` Waiting: ${lower(w.share)}.`] : []),
|
|
468
534
|
// How far it moved is in --detail and moves[].amount; the cause is what a person needs.
|
|
469
535
|
...w.moves.map(m => ` Moved ${m.dir === 'up' ? 'ahead' : 'back'} because ${m.reason}.`)];
|
|
470
536
|
}
|
package/src/platform.mjs
CHANGED
|
@@ -119,8 +119,8 @@ export function parent(pid) {
|
|
|
119
119
|
}
|
|
120
120
|
|
|
121
121
|
// Every process: pid, parent, process group, % of one core, resident bytes
|
|
122
|
-
// (
|
|
123
|
-
// no process groups.
|
|
122
|
+
// (the working set on Windows), command line. The group is the pid on Windows,
|
|
123
|
+
// which has no process groups.
|
|
124
124
|
let procCache = null;
|
|
125
125
|
export function processes() {
|
|
126
126
|
if (procCache && Date.now() - procCache.at < 5000) return procCache.list;
|
|
@@ -129,12 +129,15 @@ export function processes() {
|
|
|
129
129
|
|
|
130
130
|
function readProcesses() {
|
|
131
131
|
if (WIN) {
|
|
132
|
-
// Two samples of total processor time, a second apart, give a CPU
|
|
132
|
+
// Two samples of total processor time, a second apart, give a CPU %; one WMI query gives
|
|
133
|
+
// parents, working sets and command lines. One PowerShell for all of it, never one per pid.
|
|
134
|
+
// WMI's ProcessId is a UInt32 and Get-Process's Id an Int32: as hashtable keys they never match uncast.
|
|
133
135
|
const txt = ps(`$a = @{}; Get-Process | ForEach-Object { $a[$_.Id] = $_.TotalProcessorTime.TotalMilliseconds }; Start-Sleep -Milliseconds 1000;`
|
|
134
|
-
+ ` Get-
|
|
135
|
-
+ `
|
|
136
|
-
|
|
137
|
-
|
|
136
|
+
+ ` $b = @{}; Get-Process | ForEach-Object { $b[$_.Id] = $_.TotalProcessorTime.TotalMilliseconds };`
|
|
137
|
+
+ ` Get-CimInstance Win32_Process | ForEach-Object { $i = [int]$_.ProcessId;`
|
|
138
|
+
+ ` if ($a[$i] -ne $null -and $b[$i] -ne $null) { "$i\`t$($_.ParentProcessId)\`t$([math]::Round(($b[$i] - $a[$i]) / 10, 1))\`t$($_.WorkingSetSize)\`t$($_.CommandLine)" } }`);
|
|
139
|
+
return (txt ?? '').split(/\r?\n/).map(l => l.split('\t')).filter(f => f.length === 5 && f[4])
|
|
140
|
+
.map(([pid, ppid, cpu, rss, args]) => ({ pid: Number(pid), ppid: Number(ppid), pgid: Number(pid), cpu: Number(cpu), rss: Number(rss) || 0, args }));
|
|
138
141
|
}
|
|
139
142
|
return run('ps', ['-Ao', 'pid=,ppid=,pgid=,pcpu=,rss=,args=']).split('\n')
|
|
140
143
|
.map(l => l.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/)).filter(Boolean)
|
|
@@ -331,6 +334,20 @@ export function stopTree(id, signal = 'SIGTERM') {
|
|
|
331
334
|
// never landing (2026-11-03). One ps call for all of them. Windows can't stop a
|
|
332
335
|
// tree, so there's nothing to check.
|
|
333
336
|
export const inKernelOrStopped = stat => /[TZDU]/.test(stat || '');
|
|
337
|
+
// Every process in the groups that a stop hasn't reached yet: not stopped or a zombie. A stop
|
|
338
|
+
// reaches a thread when it next runs, so this is what's still starved of a core (R) or
|
|
339
|
+
// waiting in the kernel (D, or U: macOS's throttled writes) as well as what really runs.
|
|
340
|
+
// DIBS_FAKE_UNSTOPPED: this process's first call reports every process in the groups as not
|
|
341
|
+
// stopped yet, as on a loaded Mac, so a test can see what dibs does about it.
|
|
342
|
+
let fakedUnstopped = false;
|
|
343
|
+
export function unstoppedIn(groups) {
|
|
344
|
+
if (WIN || !groups.length) return [];
|
|
345
|
+
const want = new Set(groups.map(Number));
|
|
346
|
+
const fake = process.env.DIBS_FAKE_UNSTOPPED && !fakedUnstopped;
|
|
347
|
+
if (fake) fakedUnstopped = true;
|
|
348
|
+
return run('ps', ['-A', '-o', 'pid=,pgid=,stat=']).split('\n').map(l => l.trim().split(/\s+/))
|
|
349
|
+
.filter(([pid, pgid, stat]) => pid && want.has(Number(pgid)) && (fake || !/[TZ]/.test(stat || ''))).map(([pid]) => Number(pid));
|
|
350
|
+
}
|
|
334
351
|
export function runningIn(groups) {
|
|
335
352
|
if (WIN || !groups.length) return [];
|
|
336
353
|
const want = new Set(groups.map(Number));
|
|
@@ -340,6 +357,11 @@ export function runningIn(groups) {
|
|
|
340
357
|
|
|
341
358
|
// Lower a running process's priority: background QoS on macOS (efficiency
|
|
342
359
|
// cores on Apple silicon), nice 10 on Linux, below normal on Windows.
|
|
360
|
+
// macOS's background state (PRIO_DARWIN_BG, setpriority(2)) also throttles disk
|
|
361
|
+
// I/O and every socket opened after it, so a low job's uploads crawl. macOS has
|
|
362
|
+
// nothing that lowers CPU and disk but not network on a running process
|
|
363
|
+
// (taskpolicy -c and -d work only at launch, and couldn't be undone by dibs
|
|
364
|
+
// boost), so dibs help run says to upload at -p normal instead.
|
|
343
365
|
export function lower(pid) {
|
|
344
366
|
try {
|
|
345
367
|
if (OS === 'macos') execFileSync('taskpolicy', ['-b', '-p', String(pid)], { stdio: 'ignore' });
|
package/src/preempt.mjs
CHANGED
|
@@ -35,11 +35,12 @@ import fs from 'node:fs';
|
|
|
35
35
|
import path from 'node:path';
|
|
36
36
|
import { resCfg, HOME } from './config.mjs';
|
|
37
37
|
import { makeAlive, pstart, tag, isMine } from './proc.mjs';
|
|
38
|
-
import { descendants, stopTree, runningIn, OS } from './platform.mjs';
|
|
38
|
+
import { descendants, stopTree, runningIn, unstoppedIn, pidsIn, raise, lower, OS } from './platform.mjs';
|
|
39
39
|
import { verdict, used, holdsOf, lent, coveredNow, overBy, BACKGROUND, swapGrowing, diskDraining, working, remaining, typical, pausedFor } from './schedule.mjs';
|
|
40
40
|
import { pressureVictim, pausedLine } from './overlap.mjs';
|
|
41
41
|
import { tellOverAsk } from './measure.mjs';
|
|
42
42
|
import { bytes, dur, say, now, sleepSync } from './util.mjs';
|
|
43
|
+
import { event } from './events.mjs';
|
|
43
44
|
|
|
44
45
|
// Stop rounds for a pause, and the wait before each check: 25 ms lets a stop
|
|
45
46
|
// land on a busy machine, and 5 rounds catch a child that forks once more.
|
|
@@ -48,16 +49,49 @@ const STOP_ROUNDS = 5, STOP_GAP = 25;
|
|
|
48
49
|
// Waiters that may pause someone else's work.
|
|
49
50
|
const PREEMPTS = new Set(['urgent', 'high']);
|
|
50
51
|
|
|
52
|
+
// The yield protocol. A run started with --pausable says it's safe to pause, or to stop at its
|
|
53
|
+
// next checkpoint: on SIGUSR1 (DIBS_CHECKPOINT_SIGNAL in its environment) it saves its progress
|
|
54
|
+
// and exits 0, and its dibs run puts it back in line and runs it again. An urgent or high waiter
|
|
55
|
+
// may make one of lower priority yield; any waiter that has waited YIELD_AFTER may make one of its
|
|
56
|
+
// own priority or lower yield. For a slot, the job is paused (SIGSTOP) and resumes when the waiter's
|
|
57
|
+
// job ends, as low work always was for urgent work. For memory, pausing frees nothing (a stopped
|
|
58
|
+
// job keeps every byte), so it's asked to checkpoint and step aside. dibs never stops a job that
|
|
59
|
+
// didn't say --pausable on its own. Every yield is an event naming who yielded to whom and why
|
|
60
|
+
// (dibs history, dibs why), so "who made the solver lose 3 hours" has an answer.
|
|
61
|
+
export const YIELD_AFTER = Number(process.env.DIBS_YIELD_AFTER) || 20 * 60e3; // the load ceiling's LOAD_STARVE: long enough that a yield is rare
|
|
62
|
+
// A job asked to checkpoint that hasn't exited after this is ended (SIGKILL) and put back in line
|
|
63
|
+
// anyway: it said it was safe to stop, and the waiter needs the memory now. Two minutes is enough
|
|
64
|
+
// to write out a solver's tables or finish a test file.
|
|
65
|
+
export const YIELD_GRACE = Number(process.env.DIBS_YIELD_GRACE) || 2 * 60e3;
|
|
66
|
+
export const CHECKPOINT_SIGNAL = 'SIGUSR1';
|
|
67
|
+
const PRIO_ORDER = ['urgent', 'high', 'normal', 'low', 'idle'];
|
|
68
|
+
const prioIdx = x => PRIO_ORDER.indexOf(x.prio || 'normal');
|
|
69
|
+
export const waitedLong = (me, t = now()) => me.enq != null && t - me.enq >= YIELD_AFTER;
|
|
70
|
+
// Whether l may yield to waiter me: a --pausable job below me, or at my level once I've waited long.
|
|
71
|
+
// Without --pausable, only what dibs always paused: low and idle work on pausable resources, for urgent or high.
|
|
72
|
+
function mayYield(l, me, cfg, t) {
|
|
73
|
+
if (!pausable(l, cfg)) return false;
|
|
74
|
+
if (l.pausable) return prioIdx(l) > prioIdx(me) || (waitedLong(me, t) && prioIdx(l) >= prioIdx(me));
|
|
75
|
+
return PREEMPTS.has(me.prio);
|
|
76
|
+
}
|
|
77
|
+
const entitled = (me, t) => PREEMPTS.has(me.prio) || waitedLong(me, t);
|
|
78
|
+
// One line in the event log per yield: who yielded, to whom, why and how.
|
|
79
|
+
function logYield(l, me, why, how, t) {
|
|
80
|
+
event({ kind: 'yield', id: l.id, res: l.res, who: l.who, ...(l.agent && { agent: l.agent }), prio: l.prio || 'normal', ...(l.purpose && { purpose: String(l.purpose).slice(0, 120) }),
|
|
81
|
+
to: me.id, toWho: tag(me), toName: me.who, toPrio: me.prio || 'normal', ...(me.purpose && { toPurpose: String(me.purpose).slice(0, 120) }),
|
|
82
|
+
why, how, ran: Math.round(t - l.start - pausedFor(l, t)), waited: Math.round(t - (me.enq ?? t)), pausable: !!l.pausable });
|
|
83
|
+
}
|
|
84
|
+
|
|
51
85
|
// Memory pressure readings in a row before acting: two critical ones (20s at
|
|
52
86
|
// the watcher's 10s pace) to pause, six normal ones (a minute) to resume. A
|
|
53
87
|
// warning reading resets both, so nothing flaps while the machine hovers.
|
|
54
88
|
export const PRESSURE = { pauseAfter: 2, resumeAfter: 6 };
|
|
55
89
|
|
|
56
|
-
// A run
|
|
90
|
+
// A run whose process tree dibs knows that said --pausable, or low or idle work on resources that
|
|
57
91
|
// all allow pausing. Holds are never paused: their pid is the agent itself.
|
|
58
92
|
export function pausable(l, cfg) {
|
|
59
|
-
return OS !== 'windows' && l.kind === 'run' && !!l.pgid
|
|
60
|
-
&& l.res.every(r => resCfg(cfg, r).pausable === true);
|
|
93
|
+
return OS !== 'windows' && l.kind === 'run' && !!l.pgid
|
|
94
|
+
&& (!!l.pausable || (BACKGROUND.has((l.prio || 'normal')) && l.res.every(r => resCfg(cfg, r).pausable === true)));
|
|
61
95
|
}
|
|
62
96
|
|
|
63
97
|
const pressured = l => !!l.pauses?.some(p => p.watcher);
|
|
@@ -143,6 +177,13 @@ function sync(l) {
|
|
|
143
177
|
}
|
|
144
178
|
l.stopped = [...groups];
|
|
145
179
|
l.pausedAt = now();
|
|
180
|
+
// A stop lands when the process next runs, and a low job at background priority on a loaded
|
|
181
|
+
// Mac can go 45 s without a core, or with its writes throttled behind others' (U): the urgent
|
|
182
|
+
// job got the slot, but the low one read as running all that time (preempt.test, full suite,
|
|
183
|
+
// 2026-11-13). So what the first stop didn't reach is raised out of background, which lets it
|
|
184
|
+
// take the stop at once, and lowered again when it resumes.
|
|
185
|
+
const bg = OS === 'macos' && (l.background ?? BACKGROUND.has(l.prio)) && !l.lifted;
|
|
186
|
+
if (bg) l.raisedToStop = true;
|
|
146
187
|
const { stopped } = l;
|
|
147
188
|
// A child forked while the stop goes out isn't in the group yet and runs on
|
|
148
189
|
// while the job reads as paused: 1 pause in 30 left one running on
|
|
@@ -151,6 +192,12 @@ function sync(l) {
|
|
|
151
192
|
// STOP_ROUNDS, rather than call it paused. The usual cost is one ps call.
|
|
152
193
|
queued.push(() => {
|
|
153
194
|
for (const g of stopped) stopTree(g, 'SIGSTOP');
|
|
195
|
+
if (bg) {
|
|
196
|
+
sleepSync(STOP_GAP);
|
|
197
|
+
const slow = unstoppedIn(stopped);
|
|
198
|
+
for (const pid of slow) raise(pid);
|
|
199
|
+
if (slow.length) for (const g of stopped) stopTree(g, 'SIGSTOP');
|
|
200
|
+
}
|
|
154
201
|
let left = [];
|
|
155
202
|
for (let i = 0; i < STOP_ROUNDS; i++) {
|
|
156
203
|
sleepSync(STOP_GAP);
|
|
@@ -166,7 +213,13 @@ function sync(l) {
|
|
|
166
213
|
tell(l);
|
|
167
214
|
} else if (!l.pauses?.length && l.pausedAt) {
|
|
168
215
|
const groups = new Set([l.pgid, ...(l.stopped || []), ...(l.groups || [])]);
|
|
169
|
-
|
|
216
|
+
// Back to background first, while still stopped, if the stop raised any of it and it's still low work.
|
|
217
|
+
const lowerAgain = l.raisedToStop && (l.background ?? BACKGROUND.has(l.prio)) && !l.lifted;
|
|
218
|
+
queued.push(() => {
|
|
219
|
+
if (lowerAgain) for (const pid of pidsIn([...groups].filter(Boolean))) lower(pid);
|
|
220
|
+
for (const g of groups) if (g) stopTree(g, 'SIGCONT');
|
|
221
|
+
});
|
|
222
|
+
delete l.raisedToStop;
|
|
170
223
|
l.pausedMs = (l.pausedMs || 0) + now() - l.pausedAt;
|
|
171
224
|
delete l.pausedAt; delete l.stopped; delete l.pauses;
|
|
172
225
|
tell(l);
|
|
@@ -182,15 +235,16 @@ function tell(l) {
|
|
|
182
235
|
}
|
|
183
236
|
|
|
184
237
|
// Fewest new stops first: a lease already paused for memory costs nothing to
|
|
185
|
-
// lend. Then
|
|
186
|
-
const victimOrder = (a, b) => pressured(b) - pressured(a) || (b
|
|
238
|
+
// lend. Then the lowest priority, then the most recently started.
|
|
239
|
+
const victimOrder = (a, b) => pressured(b) - pressured(a) || prioIdx(b) - prioIdx(a) || b.start - a.start;
|
|
187
240
|
|
|
188
|
-
// Called when
|
|
189
|
-
//
|
|
241
|
+
// Called when a waiter can't start because a slot is full: an urgent or high one, or one that has
|
|
242
|
+
// waited YIELD_AFTER (mayYield says whose jobs each may pause).
|
|
243
|
+
// Pauses the fewest leases that would let it start now, or none:
|
|
190
244
|
// if pausing wouldn't get it going (budget, disk, someone ahead), nothing is
|
|
191
245
|
// touched. Returns the verdict with the paused leases, or null.
|
|
192
246
|
export function preempt(s, me, cfg, hist, t = now()) {
|
|
193
|
-
if (!
|
|
247
|
+
if (!entitled(me, t) || OS === 'windows') return null;
|
|
194
248
|
// Raised by its own agent: it may pause that session's runs, nobody else's.
|
|
195
249
|
const mine = holdsOf(s, me);
|
|
196
250
|
const victims = [];
|
|
@@ -199,7 +253,7 @@ export function preempt(s, me, cfg, hist, t = now()) {
|
|
|
199
253
|
const need = used(s, r) - resCfg(cfg, r).slots + 1 - victims.filter(l => l.res.includes(r)).length;
|
|
200
254
|
if (need <= 0) continue;
|
|
201
255
|
// A run its own session's hold covers takes no slot, so pausing it frees none.
|
|
202
|
-
const pick = s.leases.filter(l => l.res.includes(r) && !victims.includes(l) && !lent(l) && !coveredNow(s, l, r) &&
|
|
256
|
+
const pick = s.leases.filter(l => l.res.includes(r) && !victims.includes(l) && !lent(l) && !coveredNow(s, l, r) && mayYield(l, me, cfg, t)
|
|
203
257
|
&& mayPause(s, l, hist, t, true)).sort(victimOrder);
|
|
204
258
|
if (pick.length < need) return null;
|
|
205
259
|
victims.push(...pick.slice(0, need));
|
|
@@ -212,10 +266,49 @@ export function preempt(s, me, cfg, hist, t = now()) {
|
|
|
212
266
|
for (const l of victims) { l.pauses.pop(); if (!l.pauses.length) delete l.pauses; }
|
|
213
267
|
return null;
|
|
214
268
|
}
|
|
215
|
-
for (const l of victims) sync(l);
|
|
269
|
+
for (const l of victims) { sync(l); logYield(l, me, 'slot', 'pause', t); }
|
|
216
270
|
return { ...v, paused: victims.map(l => ({ id: l.id, who: tag(l), res: l.res, prio: l.prio })) };
|
|
217
271
|
}
|
|
218
272
|
|
|
273
|
+
// Called when a waiter entitled to it (an urgent or high one, or one that has waited YIELD_AFTER)
|
|
274
|
+
// can't start for memory, or for a slot pausing alone won't free. Asks the fewest --pausable jobs
|
|
275
|
+
// that would make the room to checkpoint and step aside: the lowest priority first, then the most
|
|
276
|
+
// memory. For the budget or a slot, only when the waiter could start with them gone; for the
|
|
277
|
+
// machine's own memory (pressure, swap, really free memory), when they measure at least what it
|
|
278
|
+
// needs. One yield at a time per waiter: until the job asked has left, nobody else is asked.
|
|
279
|
+
// Returns { asked: [...] } for the waiter to say, { pending } while one is under way, or null.
|
|
280
|
+
const MACHINE_MEM = new Set(['pressure', 'swap', 'ram', 'oversize']);
|
|
281
|
+
const MAX_YIELDS = 2; // at most this many jobs step aside for one waiter: past that, the waiter is the problem
|
|
282
|
+
export function yieldFor(s, me, cfg, hist, v, t = now()) {
|
|
283
|
+
if (!entitled(me, t) || OS === 'windows' || me.kind === 'hold') return null;
|
|
284
|
+
const pending = s.leases.find(l => l.requeue?.why === 'yield' && l.requeue.to === me.id);
|
|
285
|
+
if (pending) return { pending: { id: pending.id, who: tag(pending) } };
|
|
286
|
+
const machineMem = MACHINE_MEM.has(v.rule) || (v.rule === 'memory' && (v.real || v.pressure));
|
|
287
|
+
if (!machineMem && v.rule !== 'memory' && v.rule !== 'slot') return null;
|
|
288
|
+
const order = l => [prioIdx(l), measured(l) || l.mem || 0];
|
|
289
|
+
const pool = s.leases.filter(l => l.pausable && !l.requeue && l.requeuable && !l.pauses?.some(p => p.owner) && mayYield(l, me, cfg, t) && !nearlyDone(l, hist, t))
|
|
290
|
+
.sort((a, b) => { const [x, y] = [order(a), order(b)]; return y[0] - x[0] || y[1] - x[1]; });
|
|
291
|
+
const picked = [];
|
|
292
|
+
for (const l of pool) {
|
|
293
|
+
if (picked.length >= MAX_YIELDS) break;
|
|
294
|
+
if (v.rule === 'slot' && !v.on) break;
|
|
295
|
+
if (v.rule === 'slot' && !l.res.includes(v.on)) continue;
|
|
296
|
+
picked.push(l);
|
|
297
|
+
const freed = picked.reduce((a, x) => a + (measured(x) || x.mem || 0), 0);
|
|
298
|
+
const ok = machineMem ? freed >= (me.mem || 0) : verdict({ ...s, leases: s.leases.filter(x => !picked.includes(x)) }, me, cfg, hist, t).ok;
|
|
299
|
+
if (ok) {
|
|
300
|
+
for (const x of picked) {
|
|
301
|
+
// Paused for someone or for memory, it runs again to take the signal; it's leaving anyway.
|
|
302
|
+
if (x.pausedAt) { x.pauses = []; sync(x); }
|
|
303
|
+
stopToRequeue(x, 'yield', t, { to: me.id, toWho: tag(me), toPrio: me.prio || 'normal', toEnq: me.enq, checkpoint: true });
|
|
304
|
+
logYield(x, me, v.rule, 'checkpoint', t);
|
|
305
|
+
}
|
|
306
|
+
return { asked: picked.map(x => ({ id: x.id, who: tag(x), res: x.res, prio: x.prio || 'normal' })) };
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
|
|
219
312
|
// Drop pauses whose waker is gone and resume what that frees: the lease it
|
|
220
313
|
// was lent to has ended (or its process died and was reaped), or the pressure
|
|
221
314
|
// watcher died. Runs at the end of every state change.
|
|
@@ -226,6 +319,7 @@ export function preempt(s, me, cfg, hist, t = now()) {
|
|
|
226
319
|
// crunch would undo the pauses it took minutes to make.
|
|
227
320
|
export const WATCHER_GRACE = 60e3;
|
|
228
321
|
export function settle(s, t = now(), hist = () => []) {
|
|
322
|
+
overdueYields(s, t);
|
|
229
323
|
const paused = s.leases.filter(l => l.pauses || l.pausedAt);
|
|
230
324
|
if (!paused.length) return;
|
|
231
325
|
const ids = new Set(s.leases.map(l => l.id));
|
|
@@ -381,14 +475,27 @@ export function diskRequeue(s, cfg, t = now(), hist = []) {
|
|
|
381
475
|
|
|
382
476
|
// Killed where it stands: SIGKILL ends a stopped process too. Its dibs run sees it end and
|
|
383
477
|
// puts it back in line (src/commands.mjs requeue).
|
|
384
|
-
|
|
385
|
-
|
|
478
|
+
// A yield (extra.checkpoint) asks first: CHECKPOINT_SIGNAL to every group, continued if paused so it
|
|
479
|
+
// can act on it, and SIGKILL only once YIELD_GRACE has passed (overdueYields).
|
|
480
|
+
function stopToRequeue(l, why, t, extra = {}) {
|
|
481
|
+
l.requeue = { at: t, why, ...extra };
|
|
386
482
|
if (ours(l)) {
|
|
387
483
|
const groups = [...new Set([l.pgid, ...(l.stopped || []), ...(l.groups || [])].filter(Boolean))];
|
|
388
|
-
|
|
484
|
+
const sig = extra.checkpoint ? CHECKPOINT_SIGNAL : 'SIGKILL';
|
|
485
|
+
queued.push(() => { for (const g of groups) { stopTree(g, sig); if (extra.checkpoint) stopTree(g, 'SIGCONT'); } });
|
|
389
486
|
}
|
|
390
487
|
return { ...l };
|
|
391
488
|
}
|
|
489
|
+
// A job asked to checkpoint that is still there YIELD_GRACE later is ended. Called from settle.
|
|
490
|
+
function overdueYields(s, t) {
|
|
491
|
+
for (const l of s.leases) {
|
|
492
|
+
if (l.requeue?.why !== 'yield' || l.requeue.killed || t - l.requeue.at < YIELD_GRACE) continue;
|
|
493
|
+
l.requeue.killed = t;
|
|
494
|
+
if (!ours(l)) continue;
|
|
495
|
+
const groups = [...new Set([l.pgid, ...(l.stopped || []), ...(l.groups || [])].filter(Boolean))];
|
|
496
|
+
queued.push(() => { for (const g of groups) stopTree(g, 'SIGKILL'); });
|
|
497
|
+
}
|
|
498
|
+
}
|
|
392
499
|
|
|
393
500
|
// Memory pressure still critical with a job already paused for it: a stopped job keeps every
|
|
394
501
|
// byte it had, and under pressure those go to swap, so pausing more only moves memory to the
|
|
@@ -448,6 +555,7 @@ const pausedBy = l => { const p = l.pauses?.find(x => x.owner); return p ? p.by
|
|
|
448
555
|
|
|
449
556
|
// What the board shows next to a paused lease.
|
|
450
557
|
export function pauseLabel(l) {
|
|
558
|
+
if (l.requeue?.why === 'yield') return `stepping aside for ${l.requeue.toWho}`;
|
|
451
559
|
if (!l.pausedAt) return '';
|
|
452
560
|
if (pausedBy(l)) return `paused by ${pausedBy(l)}`;
|
|
453
561
|
const by = (l.pauses || []).filter(p => p.lease != null).map(p => p.who);
|