@dibssoftware/dibs 0.0.179 → 0.0.180
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 +23 -2
- package/README.md +4 -2
- package/bin/dibs-guard.mjs +10 -1
- package/bin/dibs.mjs +28 -9
- package/docs/benchmarks.md +1 -1
- package/docs/files.md +1 -1
- package/docs/guard.md +6 -0
- package/docs/questions.md +6 -2
- package/docs/reference.md +4 -4
- package/docs/relay.md +9 -7
- package/docs/releasing.md +4 -3
- package/docs/scheduling.md +4 -4
- package/docs/windows.md +14 -0
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +5 -5
- package/src/acquire.mjs +91 -26
- package/src/agents.mjs +7 -22
- package/src/alerts.mjs +59 -21
- package/src/board.mjs +1 -2
- package/src/broker.mjs +26 -11
- package/src/commands.mjs +25 -9
- package/src/config.mjs +21 -4
- package/src/cool.mjs +104 -9
- package/src/diskwarn.mjs +4 -0
- package/src/events.mjs +10 -1
- package/src/files.mjs +49 -87
- package/src/guard.mjs +24 -8
- package/src/guardd.mjs +97 -0
- package/src/guardw.mjs +19 -0
- package/src/later.mjs +20 -25
- package/src/lock.mjs +292 -0
- package/src/measure.mjs +9 -4
- package/src/ondemand.mjs +5 -2
- package/src/override.mjs +39 -2
- package/src/plain.mjs +2 -2
- package/src/platform.mjs +165 -35
- package/src/preempt.mjs +51 -3
- package/src/primer.mjs +1 -1
- package/src/proc.mjs +35 -5
- package/src/questions.mjs +8 -22
- package/src/relay.mjs +10 -22
- package/src/remote.mjs +12 -8
- package/src/schedule.mjs +139 -26
- package/src/serve.mjs +16 -3
- package/src/service.mjs +4 -3
- package/src/state.mjs +139 -47
- package/src/stats.mjs +3 -2
- package/src/talk.mjs +160 -77
- package/src/trust.mjs +7 -1
- package/src/util.mjs +28 -2
- package/src/version.mjs +1 -1
- package/src/web.mjs +15 -25
- package/src/worker.mjs +2 -1
package/src/lock.mjs
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
// The lock every shared file in ~/.dibs changes under: state.json (src/state.mjs), and
|
|
2
|
+
// messages, questions, later jobs, the subagent ledger, alerts and the web's pairing file.
|
|
3
|
+
//
|
|
4
|
+
// A lock is a directory, <name>, as every dibs before it made, so an older dibs still running
|
|
5
|
+
// during a rollout and this one keep out of each other's way. What holds:
|
|
6
|
+
//
|
|
7
|
+
// 1. One holder. A process holds the lock while <name>/owner.<pid>.<start>.<nonce> is its own
|
|
8
|
+
// file. The directory is made whole beside it (<name>.new.*, with that file and a pid file
|
|
9
|
+
// for older dibs to read) and renamed into place. A rename onto a directory that has
|
|
10
|
+
// anything in it fails (ENOTEMPTY on APFS, ENOTEMPTY or EEXIST on Linux), so of two makers
|
|
11
|
+
// one wins, and no lock is ever seen without its owner.
|
|
12
|
+
// 2. Staleness is the owner's death, never the lock's age. A lock is stale when its owner is
|
|
13
|
+
// gone (kill 0 says so, or ps shows that pid started at another time: a reused pid), a
|
|
14
|
+
// zombie, or stopped (a paused job's own dibs, which nobody can resume while it holds the
|
|
15
|
+
// lock everyone needs). A live owner, however slow, is waited for; one holding past
|
|
16
|
+
// STUCK_AFTER is reported (onStuck), since a hung one stops every dibs command. A lock held 30 s used to be
|
|
17
|
+
// taken from its live owner: at load 238 (2026-11-08) a starved holder lost it
|
|
18
|
+
// mid-change, two writers ran at once, and each crashed on the other's files (exit 70).
|
|
19
|
+
// 3. Takeover is atomic and never moves the lock. The taker renames the stale owner's file to
|
|
20
|
+
// its own owner name, inside <name>: of two takers one wins, and a fresh lock that replaced
|
|
21
|
+
// the stale one has no file of that name, so it can't be taken by mistake. (Moving the whole
|
|
22
|
+
// lock aside to look at it, then back, could hide a live owner's lock from it for a moment:
|
|
23
|
+
// its release then left the lock in place and everyone waited on it for good.)
|
|
24
|
+
// 4. A holder checks its owner file is still there just before it commits (commit() below), so
|
|
25
|
+
// a holder taken over while stopped never writes over its taker's change. Each writer's
|
|
26
|
+
// temporary file has its pid in the name: two writers never share one.
|
|
27
|
+
// 5. Release removes only the holder's own lock, checked by its owner file, and never throws.
|
|
28
|
+
// A lock with this process's pid and another nonce is one it no longer holds: stale.
|
|
29
|
+
//
|
|
30
|
+
// A lock made by an older dibs (a directory with only a pid file in it) is judged by that pid,
|
|
31
|
+
// the same way; with no pid in it after PIDLESS_STALE, its writer died before writing one.
|
|
32
|
+
// That older dibs can still take a lock from a live owner after 30 s (and a new lock renamed
|
|
33
|
+
// in the moment between its mkdir and its pid write replaces it): both end once every running
|
|
34
|
+
// dibs process is this version.
|
|
35
|
+
import fs from 'node:fs';
|
|
36
|
+
import path from 'node:path';
|
|
37
|
+
import { spawnSync } from 'node:child_process';
|
|
38
|
+
import { sleepSync } from './util.mjs';
|
|
39
|
+
|
|
40
|
+
const WIN = process.platform === 'win32';
|
|
41
|
+
// This process's start, to tell it from a later process given the same pid.
|
|
42
|
+
const START = Math.round(Date.now() - process.uptime() * 1000);
|
|
43
|
+
// An older dibs makes its lock empty and writes its pid just after.
|
|
44
|
+
const PIDLESS_STALE = 3000;
|
|
45
|
+
// A live owner holds for milliseconds. Held past this, ps is asked whether it's stopped, a zombie
|
|
46
|
+
// or a newer process under a reused pid: one ps call, then again after twice as long each time, up
|
|
47
|
+
// to ASK_MOST apart, so forty waiters on one slow owner don't each run ps every 2 s.
|
|
48
|
+
const ASK_AFTER = 2000, ASK_MOST = 30e3;
|
|
49
|
+
// START is Node's own start, which comes after the exec ps reports (seconds after, under memory
|
|
50
|
+
// pressure), so the owner's real start is never after it. A pid reused by a later process started
|
|
51
|
+
// after it: only a ps start this much later than START is another process (ps counts whole seconds).
|
|
52
|
+
const SAME_START = 5000;
|
|
53
|
+
// A stale lock that can't be taken (a plain file where the lock goes, a folder of another user's):
|
|
54
|
+
// after this many tries in a row, the waiter gives up (LockBroken), naming the path to remove.
|
|
55
|
+
const CLAIM_TRIES = 200;
|
|
56
|
+
// A live owner holding this long is hung, not slow (a ps that never returns, a frozen disk, a
|
|
57
|
+
// debugger): waiters keep waiting, but say so once each (onStuck), so the person hears of it.
|
|
58
|
+
export const STUCK_AFTER = 60e3;
|
|
59
|
+
|
|
60
|
+
let made = 0;
|
|
61
|
+
const nonce = () => `${process.pid}.${START}.${(++made).toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
62
|
+
|
|
63
|
+
export class LostLock extends Error {
|
|
64
|
+
constructor(lock) { super(`${lock} was taken over while this process held it`); this.code = 'ELOSTLOCK'; }
|
|
65
|
+
}
|
|
66
|
+
export class LockBroken extends Error {
|
|
67
|
+
constructor(lock) {
|
|
68
|
+
super(`${lock} is in the way and dibs can't take it over (a file, or a folder it may not change). Nothing ran. If no dibs is running, remove it: rm -rf ${lock}`);
|
|
69
|
+
this.code = 'ELOCKBROKEN';
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Waits for the lock and returns its handle ({ owns, release }), or null once `wait` ms pass.
|
|
74
|
+
// fake: called while the lock is made, so a test can make that step fail as a full disk would.
|
|
75
|
+
// files: data files whose per-process temporary copies (commit) a dead writer may have left.
|
|
76
|
+
export function acquire(lock, { wait = Infinity, fake, files = [], onStuck } = {}) {
|
|
77
|
+
fs.mkdirSync(path.dirname(lock), { recursive: true });
|
|
78
|
+
const owner = `owner.${nonce()}`;
|
|
79
|
+
const t0 = Date.now();
|
|
80
|
+
let seen = null, told = false, failed = 0;
|
|
81
|
+
for (;;) {
|
|
82
|
+
// Made only where there's no lock: a rename onto an older dibs's lock in the moment it's still
|
|
83
|
+
// an empty folder (made, its pid not written yet) would replace it under its writer.
|
|
84
|
+
const o = holder(lock);
|
|
85
|
+
if (!o) {
|
|
86
|
+
if (make(lock, owner, fake)) return handle(lock, owner);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (seen?.key !== o.key) seen = { key: o.key, since: Date.now(), asked: 0, gap: ASK_AFTER };
|
|
90
|
+
if (stale(o, seen)) {
|
|
91
|
+
if (claim(lock, o, owner)) { sweep(lock, files); return handle(lock, owner); }
|
|
92
|
+
if (++failed >= CLAIM_TRIES) throw new LockBroken(lock);
|
|
93
|
+
} else failed = 0;
|
|
94
|
+
if (Date.now() - t0 >= wait) return null;
|
|
95
|
+
if (told !== o.key && onStuck) {
|
|
96
|
+
const held = heldFor(lock, o);
|
|
97
|
+
if (held > STUCK_AFTER) { told = o.key; try { onStuck(o, held); } catch {} }
|
|
98
|
+
}
|
|
99
|
+
sleepSync(10 + Math.random() * 20);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// How long the owner has held it: its owner file dates from when it took the lock (a claim
|
|
104
|
+
// touches the file it renamed in); an older dibs's lock dates from its directory.
|
|
105
|
+
function heldFor(lock, o) {
|
|
106
|
+
try { return Date.now() - (o.old ? fs.statSync(lock) : fs.statSync(path.join(lock, o.name))).mtimeMs; } catch { return 0; }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Who holds the lock and for how long, for a board that mustn't wait for it: { key, pid, held }, or null.
|
|
110
|
+
export function heldBy(lock) {
|
|
111
|
+
const o = holder(lock);
|
|
112
|
+
return o ? { key: o.key, pid: o.pid, held: heldFor(lock, o) } : null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Made whole, then renamed into place: false if someone else's lock is there.
|
|
116
|
+
function make(lock, owner, fake) {
|
|
117
|
+
const tmp = `${lock}.new.${owner.slice(6)}`;
|
|
118
|
+
try {
|
|
119
|
+
fs.mkdirSync(tmp);
|
|
120
|
+
fake?.();
|
|
121
|
+
fs.writeFileSync(path.join(tmp, 'pid'), String(process.pid));
|
|
122
|
+
fs.writeFileSync(path.join(tmp, owner), '');
|
|
123
|
+
if (exists(lock)) throw Object.assign(new Error('taken'), { code: 'EEXIST' });
|
|
124
|
+
fs.renameSync(tmp, lock);
|
|
125
|
+
return true;
|
|
126
|
+
} catch (e) {
|
|
127
|
+
try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {}
|
|
128
|
+
// Windows refuses a rename onto any directory with EPERM.
|
|
129
|
+
if (e.code === 'ENOTEMPTY' || e.code === 'EEXIST' || e.code === 'ENOTDIR' || (WIN && e.code === 'EPERM')) return false;
|
|
130
|
+
throw e;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const exists = p => { try { fs.lstatSync(p); return true; } catch { return false; } };
|
|
135
|
+
|
|
136
|
+
// Who holds it: { key, pid, start, name } for a lock of this version, { key, pid, ino, age, old } for an
|
|
137
|
+
// older dibs's, or null when it's gone or changed while being read (look again).
|
|
138
|
+
function holder(lock) {
|
|
139
|
+
let a, names, b;
|
|
140
|
+
try { a = fs.statSync(lock); names = a.isDirectory() ? fs.readdirSync(lock) : []; b = fs.statSync(lock); }
|
|
141
|
+
catch (e) { if (e.code === 'ENOENT') return null; throw e; }
|
|
142
|
+
if (a.ino !== b.ino) return null;
|
|
143
|
+
if (!a.isDirectory()) return { key: `file.${b.ino}`, pid: 0, ino: b.ino, age: Date.now() - b.mtimeMs, old: true, file: true };
|
|
144
|
+
const name = names.find(n => n.startsWith('owner.'));
|
|
145
|
+
if (name) {
|
|
146
|
+
const [, pid, start] = name.split('.');
|
|
147
|
+
return { key: name, name, pid: Number(pid) || 0, start: Number(start) || 0 };
|
|
148
|
+
}
|
|
149
|
+
let pid = 0;
|
|
150
|
+
try { pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8')) || 0; } catch {}
|
|
151
|
+
return { key: `old.${b.ino}.${pid}`, pid, ino: b.ino, age: Date.now() - b.mtimeMs, old: true };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const answers = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
155
|
+
|
|
156
|
+
function stale(o, seen) {
|
|
157
|
+
if (!o.pid) return o.age > PIDLESS_STALE;
|
|
158
|
+
if (o.pid === process.pid) return true; // single-threaded: not a lock this process is in
|
|
159
|
+
if (!answers(o.pid)) return true;
|
|
160
|
+
const t = Date.now();
|
|
161
|
+
if (WIN || t - seen.since < ASK_AFTER || t - seen.asked < seen.gap) return false;
|
|
162
|
+
if (seen.asked) seen.gap = Math.min(seen.gap * 2, ASK_MOST);
|
|
163
|
+
seen.asked = t;
|
|
164
|
+
const p = psOf(o.pid);
|
|
165
|
+
if (p === undefined) return false; // can't tell: wait, rather than take a live owner's lock
|
|
166
|
+
if (p === null || /^[TZ]/.test(p.stat)) return true;
|
|
167
|
+
return !!o.start && t - p.elapsed - o.start > SAME_START;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// The command line a pid runs, for saying who dibs is stuck behind, or '' when ps can't say.
|
|
171
|
+
export function commandOf(pid) {
|
|
172
|
+
if (WIN) return '';
|
|
173
|
+
const r = spawnSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
|
|
174
|
+
return (r.stdout || '').trim().slice(0, 200);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// { stat, elapsed ms } from ps, null when the process is gone, undefined when ps can't say.
|
|
178
|
+
function psOf(pid) {
|
|
179
|
+
const r = spawnSync('ps', ['-o', 'stat=,etime=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
|
|
180
|
+
if (r.status == null) return undefined;
|
|
181
|
+
const m = r.stdout.trim().match(/^(\S+)\s+(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);
|
|
182
|
+
if (!m) return r.status === 0 ? undefined : null;
|
|
183
|
+
const [, stat, d = 0, h = 0, mi, s] = m;
|
|
184
|
+
return { stat, elapsed: (((Number(d) * 24 + Number(h)) * 60 + Number(mi)) * 60 + Number(s)) * 1000 };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Takes the stale lock where it stands. An older dibs's lock is claimed through its pid file the
|
|
188
|
+
// same way; with nothing in it to claim (it died before writing its pid), it's emptied, and the
|
|
189
|
+
// next make() renames a whole lock over the empty directory.
|
|
190
|
+
function claim(lock, o, owner) {
|
|
191
|
+
if (o.file) return false; // a plain file where the lock goes: not dibs's to take (LockBroken)
|
|
192
|
+
const mine = path.join(lock, owner), from = path.join(lock, o.old ? 'pid' : o.name);
|
|
193
|
+
try {
|
|
194
|
+
if (o.old && !o.pid) {
|
|
195
|
+
for (const n of fs.readdirSync(lock)) if (!n.startsWith('owner.')) fs.rmSync(path.join(lock, n), { recursive: true, force: true });
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
fs.renameSync(from, mine);
|
|
199
|
+
} catch { return false; }
|
|
200
|
+
try {
|
|
201
|
+
// An older dibs's pid file: the one judged only if it still names the dead pid in the same folder.
|
|
202
|
+
// An older waiter may have taken the lock over meanwhile and written its own live pid, or a lock
|
|
203
|
+
// of this version may have replaced the folder (another owner file): either way, not ours.
|
|
204
|
+
const theirs = o.old
|
|
205
|
+
&& (Number(fs.readFileSync(mine, 'utf8')) !== o.pid || fs.statSync(lock).ino !== o.ino || fs.readdirSync(lock).some(n => n.startsWith('owner.') && n !== owner));
|
|
206
|
+
if (theirs) { fs.renameSync(mine, from); return false; }
|
|
207
|
+
const at = new Date();
|
|
208
|
+
fs.utimesSync(mine, at, at);
|
|
209
|
+
fs.writeFileSync(path.join(lock, 'pid'), String(process.pid));
|
|
210
|
+
return true;
|
|
211
|
+
} catch (e) {
|
|
212
|
+
// Half claimed: put back what was there, so the next waiter judges the lock as it was.
|
|
213
|
+
try { fs.renameSync(mine, from); } catch {}
|
|
214
|
+
if (e.code === 'ENOSPC' || e.code === 'EDQUOT') throw e;
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// What a writer killed mid-change leaves beside the lock: a lock it was making, one it moved
|
|
220
|
+
// aside, its temporary data file. Only names with a pid in them, and only a dead pid's. Run when a
|
|
221
|
+
// dead owner's lock is claimed, and now and then by the broker (sweepLock).
|
|
222
|
+
export const sweepLock = (lock, files = []) => sweep(lock, files);
|
|
223
|
+
function sweep(lock, files) {
|
|
224
|
+
const dir = path.dirname(lock), base = path.basename(lock);
|
|
225
|
+
const dibsMade = [new RegExp(`^${re(base)}\\.(?:new|gone)\\.(\\d+)\\.`), new RegExp(`^${re(base)}\\.stale-(\\d+)-`),
|
|
226
|
+
...files.filter(f => path.dirname(f) === dir).map(f => new RegExp(`^${re(path.basename(f))}\\.(\\d+)\\.tmp$`))];
|
|
227
|
+
let names = [];
|
|
228
|
+
try { names = fs.readdirSync(dir); } catch { return; }
|
|
229
|
+
for (const n of names) {
|
|
230
|
+
const pid = dibsMade.map(r => n.match(r)?.[1]).find(Boolean);
|
|
231
|
+
if (pid && !answers(Number(pid))) try { fs.rmSync(path.join(dir, n), { recursive: true, force: true }); } catch {}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const re = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
235
|
+
|
|
236
|
+
function handle(lock, owner) {
|
|
237
|
+
const mine = path.join(lock, owner);
|
|
238
|
+
return {
|
|
239
|
+
owns: () => fs.existsSync(mine),
|
|
240
|
+
release() {
|
|
241
|
+
// Nobody moves a live owner's lock (3), so the one found here is still this one when it's
|
|
242
|
+
// renamed aside: whole, in one step, so nobody sees it half removed.
|
|
243
|
+
try {
|
|
244
|
+
if (!fs.existsSync(mine)) return false;
|
|
245
|
+
const aside = `${lock}.gone.${nonce()}`;
|
|
246
|
+
fs.renameSync(lock, aside);
|
|
247
|
+
fs.rmSync(aside, { recursive: true, force: true });
|
|
248
|
+
return true;
|
|
249
|
+
} catch { return false; }
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// The holder's write of a whole file: a temporary copy named for this process (no two writers share
|
|
255
|
+
// one, and a write cut short by a full disk leaves the old file whole), then a rename, only while it
|
|
256
|
+
// still holds the lock (LostLock if not, with nothing written). fake as in acquire.
|
|
257
|
+
// Returns whether it still held the lock just after the rename: false means another writer took it in
|
|
258
|
+
// the moment between the check and the rename (only possible from a holder stopped right there), and
|
|
259
|
+
// one of the two changes may be lost; the caller puts that on record.
|
|
260
|
+
export function commit(h, file, text, opts = {}) {
|
|
261
|
+
return commitAll(h, [[file, text, opts]]);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Several files as one change: every copy written, one check that the lock is still held, then the
|
|
265
|
+
// renames. Checking before each instead could lose the lock after the first file landed, and the
|
|
266
|
+
// change made again would land twice in that file (a message sent twice).
|
|
267
|
+
export function commitAll(h, files) {
|
|
268
|
+
const tmps = [];
|
|
269
|
+
try {
|
|
270
|
+
for (const [file, text, { mode, fake } = {}] of files) {
|
|
271
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
272
|
+
tmps.push(tmp);
|
|
273
|
+
fake?.();
|
|
274
|
+
fs.writeFileSync(tmp, text, mode ? { mode } : undefined);
|
|
275
|
+
}
|
|
276
|
+
if (!h.owns()) throw new LostLock(path.dirname(files[0][0]));
|
|
277
|
+
} catch (e) { for (const tmp of tmps) try { fs.rmSync(tmp, { force: true }); } catch {} throw e; }
|
|
278
|
+
files.forEach(([file], i) => fs.renameSync(tmps[i], file));
|
|
279
|
+
return h.owns();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// fn under the lock, done again from the start if the lock was lost before it wrote.
|
|
283
|
+
// null when wait passes first.
|
|
284
|
+
export function underLock(lock, fn, opts = {}) {
|
|
285
|
+
for (;;) {
|
|
286
|
+
const h = acquire(lock, opts);
|
|
287
|
+
if (!h) return null;
|
|
288
|
+
try { return { out: fn(h) }; }
|
|
289
|
+
catch (e) { if (!(e instanceof LostLock)) throw e; }
|
|
290
|
+
finally { h.release(); }
|
|
291
|
+
}
|
|
292
|
+
}
|
package/src/measure.mjs
CHANGED
|
@@ -111,7 +111,7 @@ function shareDisk(s, got, m, t) {
|
|
|
111
111
|
const last = s.diskSample;
|
|
112
112
|
s.diskSample = { free: m.diskFree ?? null, swap: m.swapUsed ?? null, ...(m.swapFiles != null && { files: m.swapFiles }), at: t };
|
|
113
113
|
const runs = s.leases.filter(l => got.has(l.id) && !l.pausedAt);
|
|
114
|
-
for (const l of runs) l.ate ??= 0;
|
|
114
|
+
for (const l of runs) { l.ate ??= 0; l.ateLast = 0; }
|
|
115
115
|
if (!last || last.free == null || m.diskFree == null || t - last.at > 3 * SAMPLE_EVERY) return;
|
|
116
116
|
const swapGrew = Math.max(0, last.swap != null && m.swapUsed != null ? m.swapUsed - last.swap : 0,
|
|
117
117
|
last.files != null && m.swapFiles != null ? m.swapFiles - last.files : 0);
|
|
@@ -119,7 +119,8 @@ function shareDisk(s, got, m, t) {
|
|
|
119
119
|
if (!fell || !runs.length) return;
|
|
120
120
|
const w = l => Math.max(l.disk || 0, DISK_WEIGHT);
|
|
121
121
|
const all = runs.reduce((a, l) => a + w(l), 0);
|
|
122
|
-
|
|
122
|
+
// ateLast, this reading's share alone: which run is writing now, for the hard stop (src/preempt.mjs).
|
|
123
|
+
for (const l of runs) { l.ateLast = fell * w(l) / all; l.ate += l.ateLast; }
|
|
123
124
|
}
|
|
124
125
|
|
|
125
126
|
// Measure every run lease on the machine, if this process won the slot.
|
|
@@ -148,9 +149,13 @@ export function sample(t = now()) {
|
|
|
148
149
|
l.use = { ...u, at: t };
|
|
149
150
|
// When its memory last rose past what it had reached: a job let in by the
|
|
150
151
|
// stall breaker counts as settled once this is a while ago (schedule.mjs).
|
|
151
|
-
|
|
152
|
+
// How far into the run that was goes into history, so a later run of the same
|
|
153
|
+
// command that has run past it is known to be done growing (schedule.mjs pastPeak).
|
|
154
|
+
const rose = !(u.mem <= (l.peak?.mem ?? -1) * 1.05);
|
|
155
|
+
if (rose) l.peakAt = t;
|
|
156
|
+
const at = rose ? t - l.start : l.peak?.in;
|
|
152
157
|
l.peak = { mem: Math.max(l.peak?.mem || 0, u.mem), cpu: Math.max(l.peak?.cpu || 0, u.cpu), fit: true,
|
|
153
|
-
...(l.ate != null && { ate: l.ate }) };
|
|
158
|
+
...(at != null && { in: at }), ...(l.ate != null && { ate: l.ate }) };
|
|
154
159
|
const x = overAsk(l);
|
|
155
160
|
if (!x) continue;
|
|
156
161
|
if (!l.overAsk) {
|
package/src/ondemand.mjs
CHANGED
|
@@ -26,6 +26,7 @@ import fs from 'node:fs';
|
|
|
26
26
|
import os from 'node:os';
|
|
27
27
|
import path from 'node:path';
|
|
28
28
|
import { spawn, execFile } from 'node:child_process';
|
|
29
|
+
import { runnable } from './platform.mjs';
|
|
29
30
|
import { fileURLToPath } from 'node:url';
|
|
30
31
|
import { HOME } from './config.mjs';
|
|
31
32
|
import { event } from './events.mjs';
|
|
@@ -186,7 +187,8 @@ const hhmm = (t = now()) => new Date(t).toTimeString().slice(0, 5);
|
|
|
186
187
|
export function boat(args, { timeout = 60e3 } = {}) {
|
|
187
188
|
return new Promise(resolve => {
|
|
188
189
|
// --no-update first: after `--` it would go to the command run on the VM.
|
|
189
|
-
|
|
190
|
+
const [cmd, ...argv] = runnable([process.env.DIBS_BOAT || 'boat', '--no-update', ...args]);
|
|
191
|
+
execFile(cmd, argv, { timeout, maxBuffer: 16 * 1024 ** 2, encoding: 'utf8', windowsVerbatimArguments: cmd === 'cmd.exe', windowsHide: true }, (e, out, err) => {
|
|
190
192
|
const r = { code: e ? (typeof e.code === 'number' ? e.code : 1) : 0, out: out || '', err: (err || e?.message || '').trim() };
|
|
191
193
|
const j = args[0] === 'exec' && !args.includes('--detach') ? json(r.out) : null;
|
|
192
194
|
if (j && typeof j.stdout === 'string') Object.assign(r, { out: j.stdout, err: (j.stderr || r.err).trim(), code: j.exitCode ?? r.code });
|
|
@@ -288,7 +290,8 @@ export function ondemand(list, srv, { port, tick = TICK, log: say = log, clock =
|
|
|
288
290
|
// The reverse forward lives as long as the VM is up, started again if it drops.
|
|
289
291
|
const forward = vm => {
|
|
290
292
|
if (vm.forward || !['waking', 'running'].includes(vm.state)) return;
|
|
291
|
-
const
|
|
293
|
+
const [cmd, ...argv] = runnable([process.env.DIBS_BOAT || 'boat', '--no-update', 'forward', vm.id, '--reverse', '--local', String(port)]);
|
|
294
|
+
const p = spawn(cmd, argv, { stdio: 'ignore', windowsVerbatimArguments: cmd === 'cmd.exe', windowsHide: true });
|
|
292
295
|
vm.forward = p;
|
|
293
296
|
p.on('exit', () => { vm.forward = null; if (['waking', 'running'].includes(vm.state)) setTimeout(() => forward(vm), 2000).unref(); });
|
|
294
297
|
p.on('error', () => {});
|
package/src/override.mjs
CHANGED
|
@@ -20,10 +20,10 @@ import { tag, makeAlive, identity, isMine } from './proc.mjs';
|
|
|
20
20
|
import { descendants, processes, pidsIn, stopTree, lower, raise, OS } from './platform.mjs';
|
|
21
21
|
import { withState, history } from './state.mjs';
|
|
22
22
|
import { ownerPause, pauseLabel } from './preempt.mjs';
|
|
23
|
-
import { PRIORITIES, BACKGROUND, NEEDS_REASON, priority, byRank } from './schedule.mjs';
|
|
23
|
+
import { PRIORITIES, BACKGROUND, NEEDS_REASON, priority, byRank, roomFor } from './schedule.mjs';
|
|
24
24
|
import { actor } from './owner.mjs';
|
|
25
25
|
import { event } from './events.mjs';
|
|
26
|
-
import { die, now, say, sleepSync } from './util.mjs';
|
|
26
|
+
import { die, now, say, sleepSync, unpolled } from './util.mjs';
|
|
27
27
|
import { takeAgent, callKey } from './files.mjs';
|
|
28
28
|
import { quoted } from './style.mjs';
|
|
29
29
|
|
|
@@ -203,6 +203,35 @@ export function boost(args) {
|
|
|
203
203
|
recordAll('boost', r.filter(c => !c.same).map(({ id, res, who, prio, from }) => ({ id, res, who, prio, from })), who, reason);
|
|
204
204
|
}
|
|
205
205
|
|
|
206
|
+
// Priority inversion: a low or idle run is at background QoS, which macOS starves while
|
|
207
|
+
// normal work fills every core (a 0.08 s loop took 13.6 s at load 35, 2026-11-03). One
|
|
208
|
+
// holding a full slot that a normal-or-higher waiter wants makes that waiter wait on the
|
|
209
|
+
// starving, so it's lifted to normal QoS while such a waiter is in line, and dropped back
|
|
210
|
+
// once none is. Under the state lock: marks the leases and returns the moves, made after it.
|
|
211
|
+
export function inversions(s, cfg) {
|
|
212
|
+
const moves = [];
|
|
213
|
+
for (const l of s.leases) {
|
|
214
|
+
if (l.kind !== 'run' || !l.pgid || !(l.background ?? BACKGROUND.has(l.prio))) continue;
|
|
215
|
+
const stuck = s.queue.find(q => q.pid && !BACKGROUND.has(q.prio || 'normal') && q.res.some(r => l.res.includes(r) && roomFor(s, q, r, cfg).open <= 0));
|
|
216
|
+
if (stuck && !l.lifted) { l.lifted = stuck.id; moves.push({ id: l.id, res: l.res, who: l.who, pgid: l.pgid, pgstart: l.pgstart, groups: l.groups, bg: false, for: stuck.id }); }
|
|
217
|
+
else if (!stuck && l.lifted) { moves.push({ id: l.id, res: l.res, who: l.who, pgid: l.pgid, pgstart: l.pgstart, groups: l.groups, bg: true, for: l.lifted }); delete l.lifted; }
|
|
218
|
+
}
|
|
219
|
+
return moves;
|
|
220
|
+
}
|
|
221
|
+
// Make the moves inversions() decided, after the lock, with boost's catch-up rounds.
|
|
222
|
+
export function lift(moves) {
|
|
223
|
+
for (const m of moves) {
|
|
224
|
+
const groups = [...groupsOf(m)];
|
|
225
|
+
const move = pid => (m.bg ? lower(pid) : raise(pid));
|
|
226
|
+
for (let i = 0; i <= CATCH_UP; i++) {
|
|
227
|
+
if (i) sleepSync(CATCH_GAP);
|
|
228
|
+
for (const pid of pidsIn(groups)) move(pid);
|
|
229
|
+
}
|
|
230
|
+
event({ kind: 'override', act: m.bg ? 'unlift' : 'lift', id: m.id, res: m.res, who: m.who, for: m.for,
|
|
231
|
+
why: m.bg ? `dropped #${m.id} back to background priority: nobody is stuck behind it now` : `lifted #${m.id} so #${m.for} isn't stuck behind it` });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
206
235
|
// Why the owner can't pause this lease, or null. Resources marked pausable:
|
|
207
236
|
// false (sim, xcode-build and deploy by default) stay unpaused unless --force:
|
|
208
237
|
// a frozen deploy, simulator or build can time out against the services it
|
|
@@ -296,6 +325,14 @@ export function stop(args) {
|
|
|
296
325
|
x.ownerStop = now();
|
|
297
326
|
if (who.agent || who.via) x.stopBy = who.name;
|
|
298
327
|
if (reason) x.stopReason = reason;
|
|
328
|
+
if (c.kind === 'wait') {
|
|
329
|
+
// Recorded apart from the place, so its waiter can say why once the place is gone. A place
|
|
330
|
+
// its dibs is still deciding for stays until that dibs sees the stop (its waiter says so and
|
|
331
|
+
// leaves; src/state.mjs reap takes it after STOP_GRACE); one nothing decides for goes now.
|
|
332
|
+
// On 2026-11-04 "took #19783 out of line" left #19783 at the head of heavy, twice.
|
|
333
|
+
(s.stopped ||= {})[x.id] = { at: x.ownerStop, by: x.stopBy, reason: x.stopReason };
|
|
334
|
+
if (unpolled(x, now())) s.queue = s.queue.filter(q => q !== x);
|
|
335
|
+
}
|
|
299
336
|
// SIGKILL ends stopped processes too, so a paused run needs no SIGCONT first.
|
|
300
337
|
// The lock is still held, so the run's own dibs can't remove the lease
|
|
301
338
|
// (and its group number can't be handed out again) in between.
|
package/src/plain.mjs
CHANGED
|
@@ -219,7 +219,7 @@ function waitingFor(s, q, v, cfg, hist, t, m, f) {
|
|
|
219
219
|
+ `${v.high ? ' with memory pressure high' : ''}${v.growing ? ' and swap growing' : ''}, and it needs ${GB(v.need)} plus ${GB(v.reserve)} to spare`;
|
|
220
220
|
return `room in memory: ${memoryPicture(s, cfg, m, v.need, t)}`;
|
|
221
221
|
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)})${hogHint()}`;
|
|
222
|
+
case 'disk': return `more free disk (${GB(v.free)} free, it needs ${GB(v.need)}${v.floorWhy ? `: ${v.floorWhy}` : ''})${hogHint()}`;
|
|
223
223
|
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
224
|
case 'swaproom': return `more free disk for swap to grow into (${GB(v.free)} free; while this machine swaps, dibs starts nothing new until ${GB(v.need)} is free or nothing else is running)${hogHint()}`;
|
|
225
225
|
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()}`;
|
|
@@ -417,7 +417,7 @@ export function lineParts(p) {
|
|
|
417
417
|
let now = rows.length ? usingText(rows, named(p.cfg, l.res)) : 'free';
|
|
418
418
|
if (notes.length) now += ` (${rows.length > 1 ? notes.map(([w, x]) => `${w} is ${lower(x)}`).join('; ') : lower(notes[0][1])})`;
|
|
419
419
|
let next = '';
|
|
420
|
-
const names = l.waiting.map(id => p.names.get(id));
|
|
420
|
+
const names = l.waiting.map(id => `${p.names.get(id)} (#${id})`); // the id, for dibs why, boost or stop
|
|
421
421
|
if (names.length) {
|
|
422
422
|
// Say why the next one waits only when it isn't simply its turn here:
|
|
423
423
|
// stuck on the machine, or on another resource it needs too.
|