sakura-infinity 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT-GUIDE.md +104 -0
- package/LICENSE +21 -0
- package/README.md +275 -2
- package/dist/bin/flags.js +110 -0
- package/dist/bin/infinity.js +98 -0
- package/dist/bin/load-task.js +39 -0
- package/dist/bin/model.js +37 -0
- package/dist/bin/scaffold.js +121 -0
- package/dist/src/agent-worker.js +156 -0
- package/dist/src/backoff.js +12 -0
- package/dist/src/budget.js +49 -0
- package/dist/src/capacity.js +103 -0
- package/dist/src/clock.js +16 -0
- package/dist/src/code-leaderboard.js +48 -0
- package/dist/src/code-report.js +157 -0
- package/dist/src/command-class.js +59 -0
- package/dist/src/command-limits.js +46 -0
- package/dist/src/commit-plugin.js +36 -0
- package/dist/src/component.js +1 -0
- package/dist/src/csv.js +8 -0
- package/dist/src/defaults.js +35 -0
- package/dist/src/error-cluster.js +20 -0
- package/dist/src/evaluation.js +84 -0
- package/dist/src/form.js +191 -0
- package/dist/src/gate.js +111 -0
- package/dist/src/gpu-shim.js +165 -0
- package/dist/src/hidden-keeper.js +183 -0
- package/dist/src/host.js +180 -0
- package/dist/src/jsonl.js +30 -0
- package/dist/src/ladder.js +118 -0
- package/dist/src/launch.js +123 -0
- package/dist/src/lean-kit.js +42 -0
- package/dist/src/lean-runner.js +84 -0
- package/dist/src/lean-setup.js +23 -0
- package/dist/src/lean-tool.js +57 -0
- package/dist/src/leftover.js +59 -0
- package/dist/src/machine-config.js +43 -0
- package/dist/src/machine-sampler.js +103 -0
- package/dist/src/machine-summary.js +64 -0
- package/dist/src/mode-factory.js +25 -0
- package/dist/src/mode.js +1 -0
- package/dist/src/network.js +12 -0
- package/dist/src/orchestrator.js +375 -0
- package/dist/src/planner.js +98 -0
- package/dist/src/platform.js +21 -0
- package/dist/src/pool.js +73 -0
- package/dist/src/pressure-brake.js +26 -0
- package/dist/src/proc-readings.js +207 -0
- package/dist/src/prompts.js +46 -0
- package/dist/src/records.js +2 -0
- package/dist/src/report.js +81 -0
- package/dist/src/review-loop.js +141 -0
- package/dist/src/review-rules.js +104 -0
- package/dist/src/review-run.js +110 -0
- package/dist/src/review-schedule.js +53 -0
- package/dist/src/review-snapshot.js +150 -0
- package/dist/src/run-layout.js +29 -0
- package/dist/src/run-notes.js +61 -0
- package/dist/src/run-recorder.js +51 -0
- package/dist/src/run-state.js +17 -0
- package/dist/src/run-status.js +37 -0
- package/dist/src/rung-meter.js +39 -0
- package/dist/src/safety-review.js +43 -0
- package/dist/src/sakura-tools.js +130 -0
- package/dist/src/shell-kit.js +113 -0
- package/dist/src/slot-gate.js +136 -0
- package/dist/src/slot-leases.js +64 -0
- package/dist/src/stuck.js +47 -0
- package/dist/src/submit-tool.js +99 -0
- package/dist/src/task-mode.js +170 -0
- package/dist/src/task.js +85 -0
- package/dist/src/verifier.js +115 -0
- package/dist/src/work-repo.js +50 -0
- package/dist/src/worker-policy.js +16 -0
- package/dist/tasks/math-odd-sum/task.js +6 -0
- package/dist/tasks/math-parity/task.js +6 -0
- package/dist/viewer/index.html +397 -0
- package/dist/viewer/run-reader.js +600 -0
- package/dist/viewer/server.js +160 -0
- package/dist/viewer/view.js +50 -0
- package/package.json +52 -4
package/dist/src/gate.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { ClusterDetector } from "./error-cluster.js";
|
|
2
|
+
import { ProviderError } from "sakura-agent";
|
|
3
|
+
const THROTTLE_KINDS = new Set(["rate_limit", "overloaded"]);
|
|
4
|
+
/**
|
|
5
|
+
* One shared brake in front of every model request.
|
|
6
|
+
* - Waits while a pause is active; a throttling answer pauses everybody.
|
|
7
|
+
* - A quota error stops everything for good: later requests fail at once with the same error kind.
|
|
8
|
+
* - Reports the usage of every request that passes (also compaction and goal checks).
|
|
9
|
+
* It throws ProviderError("quota") to refuse; the framework turns that into a paused run, and the session stays resumable.
|
|
10
|
+
*/
|
|
11
|
+
export class Gate {
|
|
12
|
+
pausedUntil = 0;
|
|
13
|
+
stopMessage;
|
|
14
|
+
inflightCount = 0;
|
|
15
|
+
connectionCluster;
|
|
16
|
+
options;
|
|
17
|
+
constructor(options) {
|
|
18
|
+
this.options = options;
|
|
19
|
+
this.connectionCluster = new ClusterDetector(options.connectionErrors ?? 5, options.connectionWindowMs ?? 10_000);
|
|
20
|
+
}
|
|
21
|
+
get inflight() {
|
|
22
|
+
return this.inflightCount;
|
|
23
|
+
}
|
|
24
|
+
/** True while a throttling answer has everybody waiting. */
|
|
25
|
+
get paused() {
|
|
26
|
+
return this.pausedUntil > this.options.now();
|
|
27
|
+
}
|
|
28
|
+
get stopped() {
|
|
29
|
+
return this.stopMessage;
|
|
30
|
+
}
|
|
31
|
+
/** Pass this to the chat client's `retry` option so the Gate hears about every throttling answer. */
|
|
32
|
+
retry = {
|
|
33
|
+
onRetry: (info) => {
|
|
34
|
+
if (THROTTLE_KINDS.has(info.error.kind))
|
|
35
|
+
this.pause(info.delayMs);
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Stops everything for good: requests in flight finish, every later request fails at once. Announces it as a "quota" event
|
|
40
|
+
* unless `silent` (the orchestrator, which already knows why, stops the gate that way).
|
|
41
|
+
*/
|
|
42
|
+
stop(message, options = {}) {
|
|
43
|
+
if (this.stopMessage !== undefined)
|
|
44
|
+
return;
|
|
45
|
+
this.stopMessage = message;
|
|
46
|
+
if (!options.silent)
|
|
47
|
+
this.options.onEvent?.({ type: "quota", message });
|
|
48
|
+
}
|
|
49
|
+
wrap(client) {
|
|
50
|
+
return { model: client.model, stream: (request, signal) => this.stream(client, request, signal) };
|
|
51
|
+
}
|
|
52
|
+
pause(delayMs, cause = "provider") {
|
|
53
|
+
const until = this.options.now() + delayMs;
|
|
54
|
+
if (until <= this.pausedUntil)
|
|
55
|
+
return;
|
|
56
|
+
this.pausedUntil = until;
|
|
57
|
+
this.options.onEvent?.({ type: "throttle", delayMs, pausedUntil: until, cause });
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Connection errors in a cluster mean that the machine or the provider cannot take this many connections at once (or something is wrong with the network);
|
|
61
|
+
* replacing the failed agents at once only adds more connections. So a cluster is treated like a throttle. One error alone is not: the framework retries it.
|
|
62
|
+
*/
|
|
63
|
+
noteConnectionError() {
|
|
64
|
+
if (this.connectionCluster.note(this.options.now()))
|
|
65
|
+
this.pause(this.options.defaultPauseMs, "connection");
|
|
66
|
+
}
|
|
67
|
+
async admit(signal) {
|
|
68
|
+
for (;;) {
|
|
69
|
+
if (this.stopMessage !== undefined)
|
|
70
|
+
throw new ProviderError("quota", this.stopMessage);
|
|
71
|
+
const waitMs = this.pausedUntil - this.options.now();
|
|
72
|
+
if (waitMs <= 0)
|
|
73
|
+
break;
|
|
74
|
+
await this.options.sleep(waitMs, signal);
|
|
75
|
+
}
|
|
76
|
+
const reason = this.options.refusal?.();
|
|
77
|
+
if (reason === undefined)
|
|
78
|
+
return;
|
|
79
|
+
this.options.onEvent?.({ type: "refused", reason });
|
|
80
|
+
throw new ProviderError("quota", reason);
|
|
81
|
+
}
|
|
82
|
+
async *stream(client, request, signal) {
|
|
83
|
+
await this.admit(signal);
|
|
84
|
+
this.inflightCount += 1;
|
|
85
|
+
const startedAt = this.options.now();
|
|
86
|
+
try {
|
|
87
|
+
for await (const event of client.stream(request, signal)) {
|
|
88
|
+
if (event.type === "usage")
|
|
89
|
+
this.options.onEvent?.({ type: "usage", usage: event.usage, latencyMs: this.options.now() - startedAt });
|
|
90
|
+
yield event;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
this.learnFrom(error);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
this.inflightCount -= 1;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
learnFrom(error) {
|
|
102
|
+
if (!(error instanceof ProviderError))
|
|
103
|
+
return;
|
|
104
|
+
if (error.kind === "quota")
|
|
105
|
+
this.stop(error.message);
|
|
106
|
+
else if (THROTTLE_KINDS.has(error.kind))
|
|
107
|
+
this.pause(error.retryAfterMs ?? this.options.defaultPauseMs);
|
|
108
|
+
else if (error.kind === "network")
|
|
109
|
+
this.noteConnectionError();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { binDirOf, gpuLocksDirOf } from "./run-layout.js";
|
|
4
|
+
import { JsonlFile } from "./jsonl.js";
|
|
5
|
+
/**
|
|
6
|
+
* GPU slots (docs/16 section C): a GPU job is started as `gpu <command>`. The shim takes one of N lock files with flock (N = the GPU slots, files under the run
|
|
7
|
+
* directory), sets CUDA_VISIBLE_DEVICES to the GPU of that slot (file descriptor 9 holds the lock; the command inherits it, so the slot lasts as long as anything started by the command), runs the command and gives the slot back when it ends. The agents' commands start with no GPU
|
|
8
|
+
* visible, so a command without the shim sees none. The CPU slot of the surrounding bash command is held as usual; the order is always the GPU lock inside the
|
|
9
|
+
* command, never the reverse. Linux only (flock).
|
|
10
|
+
*/
|
|
11
|
+
export { binDirOf as gpuBinDirOf, gpuLocksDirOf as gpuDirOf } from "./run-layout.js";
|
|
12
|
+
const quote = (text) => `'${text.replaceAll("'", `'\\''`)}'`;
|
|
13
|
+
/** The text of the shim. `slotMap` has one GPU index per slot. */
|
|
14
|
+
export function gpuShimText(options) {
|
|
15
|
+
return `#!/bin/bash
|
|
16
|
+
# gpu <command> [args...]: wait for a GPU slot, run the command with that GPU visible, give the slot back when it ends.
|
|
17
|
+
if [ $# -eq 0 ]; then echo "usage: gpu <command> [args...]" >&2; exit 2; fi
|
|
18
|
+
dir=${quote(options.dir)}
|
|
19
|
+
gpus=(${options.slotMap.join(" ")})
|
|
20
|
+
n=\${#gpus[@]}
|
|
21
|
+
agent=\${INFINITY_AGENT:-0}
|
|
22
|
+
now() { date +%s%3N; }
|
|
23
|
+
note() { printf '%s\\n' "$1" >> "$dir/events.jsonl"; }
|
|
24
|
+
note "{\\"e\\":\\"request\\",\\"t\\":$(now),\\"p\\":$$,\\"a\\":$agent}"
|
|
25
|
+
while :; do
|
|
26
|
+
for ((i = 0; i < n; i++)); do
|
|
27
|
+
exec 9>>"$dir/slot$i"
|
|
28
|
+
if flock -n 9; then
|
|
29
|
+
note "{\\"e\\":\\"grant\\",\\"t\\":$(now),\\"p\\":$$,\\"a\\":$agent,\\"gpu\\":\${gpus[$i]}}"
|
|
30
|
+
CUDA_VISIBLE_DEVICES=\${gpus[$i]} "$@"
|
|
31
|
+
code=$?
|
|
32
|
+
note "{\\"e\\":\\"end\\",\\"t\\":$(now),\\"p\\":$$}"
|
|
33
|
+
exit $code
|
|
34
|
+
fi
|
|
35
|
+
exec 9>&-
|
|
36
|
+
done
|
|
37
|
+
sleep 0.2
|
|
38
|
+
done
|
|
39
|
+
`;
|
|
40
|
+
}
|
|
41
|
+
/** What the shim's log says now: jobs holding a slot, jobs waiting, and the totals for the summary. */
|
|
42
|
+
export class GpuLedger {
|
|
43
|
+
capacity;
|
|
44
|
+
stats = { commands: 0, waited: 0, totalWaitMs: 0, maxWaitMs: 0 };
|
|
45
|
+
asked = new Map();
|
|
46
|
+
granted = new Map();
|
|
47
|
+
busyMs = 0;
|
|
48
|
+
first;
|
|
49
|
+
last = 0;
|
|
50
|
+
constructor(capacity) {
|
|
51
|
+
this.capacity = capacity;
|
|
52
|
+
}
|
|
53
|
+
get inUse() {
|
|
54
|
+
return this.granted.size;
|
|
55
|
+
}
|
|
56
|
+
get waiting() {
|
|
57
|
+
return this.asked.size;
|
|
58
|
+
}
|
|
59
|
+
/** Feeds one line; returns the wait in ms when the line was a grant. */
|
|
60
|
+
feed(line) {
|
|
61
|
+
this.first ??= line.t;
|
|
62
|
+
this.last = Math.max(this.last, line.t);
|
|
63
|
+
if (line.e === "request") {
|
|
64
|
+
this.asked.set(line.p, line.t);
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
if (line.e === "grant") {
|
|
68
|
+
const waitMs = Math.max(0, line.t - (this.asked.get(line.p) ?? line.t));
|
|
69
|
+
this.asked.delete(line.p);
|
|
70
|
+
this.granted.set(line.p, line.t);
|
|
71
|
+
this.stats.commands += 1;
|
|
72
|
+
this.stats.totalWaitMs += waitMs;
|
|
73
|
+
this.stats.maxWaitMs = Math.max(this.stats.maxWaitMs, waitMs);
|
|
74
|
+
if (waitMs >= 1000)
|
|
75
|
+
this.stats.waited += 1;
|
|
76
|
+
return waitMs;
|
|
77
|
+
}
|
|
78
|
+
const start = this.granted.get(line.p);
|
|
79
|
+
if (start !== undefined)
|
|
80
|
+
this.busyMs += line.t - start;
|
|
81
|
+
this.granted.delete(line.p);
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
/** Busy slot time over all slot time between the first and the last line (0 to 1); jobs still running count up to the last line. */
|
|
85
|
+
utilisation() {
|
|
86
|
+
const span = this.last - (this.first ?? this.last);
|
|
87
|
+
if (span <= 0)
|
|
88
|
+
return 0;
|
|
89
|
+
const open = [...this.granted.values()].reduce((sum, start) => sum + (this.last - start), 0);
|
|
90
|
+
return (this.busyMs + open) / (this.capacity * span);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** Complete lines of a file after `offset` bytes, and the new offset. */
|
|
94
|
+
export function readNewLines(path, offset) {
|
|
95
|
+
if (!existsSync(path))
|
|
96
|
+
return { lines: [], offset };
|
|
97
|
+
const text = readFileSync(path, "utf8");
|
|
98
|
+
const end = text.lastIndexOf("\n") + 1;
|
|
99
|
+
const lines = [];
|
|
100
|
+
for (const raw of text.slice(offset, end).split("\n")) {
|
|
101
|
+
try {
|
|
102
|
+
if (raw.trim() !== "")
|
|
103
|
+
lines.push(JSON.parse(raw));
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
// a damaged line
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { lines, offset: Math.max(offset, end) };
|
|
110
|
+
}
|
|
111
|
+
/** Writes `bin/gpu` into the run directory, follows the shim's log, writes `slot_wait` (kind gpu) events and a summary at the end. */
|
|
112
|
+
export function gpuShim(options) {
|
|
113
|
+
const ledger = options.ledger ?? new GpuLedger(options.slotMap.length);
|
|
114
|
+
const stopping = new AbortController();
|
|
115
|
+
let loop;
|
|
116
|
+
let finish;
|
|
117
|
+
return {
|
|
118
|
+
name: "gpu-shim",
|
|
119
|
+
start(context) {
|
|
120
|
+
const root = context.layout.root;
|
|
121
|
+
const dir = gpuLocksDirOf(root);
|
|
122
|
+
mkdirSync(dir, { recursive: true });
|
|
123
|
+
mkdirSync(binDirOf(root), { recursive: true });
|
|
124
|
+
const shim = join(binDirOf(root), "gpu");
|
|
125
|
+
writeFileSync(shim, gpuShimText({ dir, slotMap: options.slotMap }));
|
|
126
|
+
chmodSync(shim, 0o755);
|
|
127
|
+
const events = new JsonlFile(context.layout.events);
|
|
128
|
+
const log = join(dir, "events.jsonl");
|
|
129
|
+
let offset = 0;
|
|
130
|
+
const drain = () => {
|
|
131
|
+
const next = readNewLines(log, offset);
|
|
132
|
+
offset = next.offset;
|
|
133
|
+
for (const line of next.lines) {
|
|
134
|
+
const waitMs = ledger.feed(line);
|
|
135
|
+
if (waitMs !== undefined && waitMs >= 1000)
|
|
136
|
+
events.append({ type: "slot_wait", ts: context.clock.now(), kind: "gpu", agent: line.a ?? 0, waitMs });
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
finish = () => {
|
|
140
|
+
drain();
|
|
141
|
+
events.append({
|
|
142
|
+
type: "slot_summary",
|
|
143
|
+
ts: context.clock.now(),
|
|
144
|
+
kind: "gpu",
|
|
145
|
+
slots: ledger.capacity,
|
|
146
|
+
...ledger.stats,
|
|
147
|
+
utilisation: ledger.utilisation(),
|
|
148
|
+
});
|
|
149
|
+
};
|
|
150
|
+
loop = (async () => {
|
|
151
|
+
while (!stopping.signal.aborted) {
|
|
152
|
+
await context.clock.sleep(options.everyMs ?? 2000, stopping.signal).catch(() => undefined);
|
|
153
|
+
if (!stopping.signal.aborted)
|
|
154
|
+
drain();
|
|
155
|
+
}
|
|
156
|
+
})();
|
|
157
|
+
},
|
|
158
|
+
async stop() {
|
|
159
|
+
stopping.abort();
|
|
160
|
+
await loop;
|
|
161
|
+
finish?.();
|
|
162
|
+
finish = undefined;
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, renameSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
import { JsonlFile } from "./jsonl.js";
|
|
5
|
+
export class DifferentFilesystemError extends Error {
|
|
6
|
+
constructor(from, keeperDir) {
|
|
7
|
+
super(`${from} is not on the same filesystem as ${keeperDir}; hidden data is moved by renaming, which needs one filesystem`);
|
|
8
|
+
this.name = "DifferentFilesystemError";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
const JOURNAL = "journal.jsonl";
|
|
12
|
+
/**
|
|
13
|
+
* Takes the evaluator and the hidden data away from the places the agents can see while they work, and puts them back afterwards.
|
|
14
|
+
* Moves, never deletes: a rename to `<dir>/<random>`, journalled first. The data stays on disk under a name that cannot be guessed;
|
|
15
|
+
* the evaluator is given that private path. This is not a lock: see docs/06-hiding-data-from-agents.md for what it does not stop.
|
|
16
|
+
*/
|
|
17
|
+
export class HiddenKeeper {
|
|
18
|
+
dir;
|
|
19
|
+
journal;
|
|
20
|
+
deviceOf;
|
|
21
|
+
now;
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.dir = resolve(options.dir);
|
|
24
|
+
this.deviceOf = options.deviceOf;
|
|
25
|
+
this.now = options.now ?? Date.now;
|
|
26
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
27
|
+
this.journal = new JsonlFile(join(this.dir, JOURNAL));
|
|
28
|
+
}
|
|
29
|
+
/** Hides each path (a file or a directory). All paths are checked first, so a bad one hides nothing. */
|
|
30
|
+
hide(paths) {
|
|
31
|
+
const absolute = paths.map((path) => resolve(path));
|
|
32
|
+
for (const path of absolute)
|
|
33
|
+
this.check(path);
|
|
34
|
+
for (const from of absolute) {
|
|
35
|
+
const id = randomBytes(16).toString("hex");
|
|
36
|
+
const to = join(this.dir, id);
|
|
37
|
+
this.journal.append({ type: "plan", id, from, to, ts: this.now() });
|
|
38
|
+
try {
|
|
39
|
+
renameSync(from, to);
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
// The real test of "one filesystem" is the rename itself: comparing device numbers is wrong on overlay file systems (Docker), where a file and
|
|
43
|
+
// a directory of one layer report different ones. Whatever was moved before is put back, so that a bad path hides nothing.
|
|
44
|
+
this.restore();
|
|
45
|
+
if (error.code === "EXDEV")
|
|
46
|
+
throw new DifferentFilesystemError(from, this.dir);
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
this.journal.append({ type: "moved", id, ts: this.now() });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Where a hidden thing is now. */
|
|
53
|
+
privatePath(original) {
|
|
54
|
+
const from = resolve(original);
|
|
55
|
+
const open = this.openPlans().find((plan) => plan.from === from);
|
|
56
|
+
if (!open)
|
|
57
|
+
throw new Error(`${from} is not hidden`);
|
|
58
|
+
return open.to;
|
|
59
|
+
}
|
|
60
|
+
/** Runs `fn` with the private paths of everything hidden: the only moment the data is used. Nothing is moved back and forth. */
|
|
61
|
+
async withHidden(fn) {
|
|
62
|
+
const map = Object.fromEntries(this.openPlans().map((plan) => [plan.from, plan.to]));
|
|
63
|
+
return fn(map);
|
|
64
|
+
}
|
|
65
|
+
/** Puts everything back. Safe to call again and again; synchronous so that it can run in an exit handler. */
|
|
66
|
+
restore() {
|
|
67
|
+
return restoreFrom(this.journal, this.now);
|
|
68
|
+
}
|
|
69
|
+
/** The journal-based restore for a run that was killed: `new HiddenKeeper({ dir }).restore()` does the same; this needs no instance. */
|
|
70
|
+
static recover(dir) {
|
|
71
|
+
const journal = new JsonlFile(join(resolve(dir), JOURNAL));
|
|
72
|
+
return restoreFrom(journal, Date.now);
|
|
73
|
+
}
|
|
74
|
+
check(path) {
|
|
75
|
+
if (!existsSync(path)) {
|
|
76
|
+
const holder = this.holderOf(path);
|
|
77
|
+
throw new Error(holder
|
|
78
|
+
? `Cannot hide ${path}: it does not exist. The run ${holder.run} holds ${holder.from} (hidden data is moved away while a run's agents work and comes back when that run ends), so a task copied during that run has no hidden data. Stop that run first, or copy the task when no run is using it.`
|
|
79
|
+
: `Cannot hide ${path}: it does not exist`);
|
|
80
|
+
}
|
|
81
|
+
if (this.openPlans().some((plan) => plan.from === path))
|
|
82
|
+
throw new Error(`Cannot hide ${path}: it is already hidden`);
|
|
83
|
+
if (isInside(path, this.dir) || isInside(this.dir, path))
|
|
84
|
+
throw new Error(`Cannot hide ${path}: it overlaps the keeper directory ${this.dir}`);
|
|
85
|
+
if (this.deviceOf && this.deviceOf(path) !== this.deviceOf(this.dir))
|
|
86
|
+
throw new DifferentFilesystemError(path, this.dir);
|
|
87
|
+
}
|
|
88
|
+
/** The other run (beside this one in the runs directory) whose keeper has taken this path, or a file of the same name (a copy of the task), away. */
|
|
89
|
+
holderOf(path) {
|
|
90
|
+
const runsDir = dirname(dirname(this.dir));
|
|
91
|
+
let names;
|
|
92
|
+
try {
|
|
93
|
+
names = readdirSync(runsDir);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
for (const name of names) {
|
|
99
|
+
const journal = join(runsDir, name, basename(this.dir), JOURNAL);
|
|
100
|
+
if (journal === join(this.dir, JOURNAL) || !existsSync(journal))
|
|
101
|
+
continue;
|
|
102
|
+
const plans = openPlans(new JsonlFile(journal));
|
|
103
|
+
const plan = plans.find((candidate) => candidate.from === path) ?? plans.find((candidate) => basename(candidate.from) === basename(path));
|
|
104
|
+
if (plan)
|
|
105
|
+
return { run: join(runsDir, name), from: plan.from };
|
|
106
|
+
}
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
openPlans() {
|
|
110
|
+
return openPlans(this.journal);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function isInside(path, parent) {
|
|
114
|
+
return path === parent || path.startsWith(`${parent}/`);
|
|
115
|
+
}
|
|
116
|
+
function openPlans(journal) {
|
|
117
|
+
const entries = journal.readAll();
|
|
118
|
+
const restored = new Set(entries.filter((entry) => entry.type === "restored").map((entry) => entry.id));
|
|
119
|
+
return entries.filter((entry) => entry.type === "plan" && !restored.has(entry.id));
|
|
120
|
+
}
|
|
121
|
+
/** Decides from the files themselves, not from what the journal hopes: a crash can happen between the journal line and the rename. */
|
|
122
|
+
function restoreFrom(journal, now) {
|
|
123
|
+
const report = { restored: [], conflicts: [], missing: [] };
|
|
124
|
+
for (const plan of openPlans(journal).reverse()) {
|
|
125
|
+
const hidden = existsSync(plan.to);
|
|
126
|
+
const original = existsSync(plan.from);
|
|
127
|
+
if (hidden && !original) {
|
|
128
|
+
renameSync(plan.to, plan.from);
|
|
129
|
+
journal.append({ type: "restored", id: plan.id, ts: now() });
|
|
130
|
+
report.restored.push(plan.from);
|
|
131
|
+
}
|
|
132
|
+
else if (hidden && original) {
|
|
133
|
+
report.conflicts.push({ from: plan.from, to: plan.to });
|
|
134
|
+
}
|
|
135
|
+
else if (original) {
|
|
136
|
+
journal.append({ type: "restored", id: plan.id, ts: now() }); // the crash came before the move: nothing was ever hidden
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
report.missing.push(plan.from);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return report;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Restores on a normal exit, on SIGINT and SIGTERM, and on an uncaught exception. After a signal it removes its own handler and sends the same
|
|
146
|
+
* signal again, so the process ends the way it would have. SIGKILL and a power loss cannot be caught: `HiddenKeeper.recover(dir)` handles those.
|
|
147
|
+
*/
|
|
148
|
+
export function restoreOnExit(keeper, target = process, stopping) {
|
|
149
|
+
const restore = () => {
|
|
150
|
+
try {
|
|
151
|
+
keeper.restore();
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
target.stderr.write(`hidden-keeper: restore failed: ${String(error)}\n`);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
const onSignal = (signal) => {
|
|
158
|
+
// A graceful stop is already draining the workers. The run restores the data after they exit.
|
|
159
|
+
if (stopping?.aborted)
|
|
160
|
+
return;
|
|
161
|
+
restore();
|
|
162
|
+
target.off("SIGINT", onSignal);
|
|
163
|
+
target.off("SIGTERM", onSignal);
|
|
164
|
+
target.kill(target.pid, signal);
|
|
165
|
+
};
|
|
166
|
+
const onUncaught = (error) => {
|
|
167
|
+
restore();
|
|
168
|
+
target.stderr.write(`${error.stack ?? String(error)}\n`);
|
|
169
|
+
target.exit(1);
|
|
170
|
+
};
|
|
171
|
+
target.on("exit", restore);
|
|
172
|
+
target.on("SIGINT", onSignal);
|
|
173
|
+
target.on("SIGTERM", onSignal);
|
|
174
|
+
target.on("uncaughtException", onUncaught);
|
|
175
|
+
return {
|
|
176
|
+
dispose() {
|
|
177
|
+
target.off("exit", restore);
|
|
178
|
+
target.off("SIGINT", onSignal);
|
|
179
|
+
target.off("SIGTERM", onSignal);
|
|
180
|
+
target.off("uncaughtException", onUncaught);
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
package/dist/src/host.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, readlinkSync, realpathSync } from "node:fs";
|
|
3
|
+
import { cpus, freemem, loadavg, release, totalmem } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
const PROCESS_CAP = 20_000;
|
|
6
|
+
const run = (command, args) => new Promise((resolve) => execFile(command, args, { timeout: 4000 }, (error, stdout) => resolve(error ? undefined : stdout)));
|
|
7
|
+
/** The host of a Linux machine. `procDir` is for tests that point it at a fake /proc tree. */
|
|
8
|
+
export class LinuxHost {
|
|
9
|
+
platform = process.platform;
|
|
10
|
+
procDir;
|
|
11
|
+
constructor(options = {}) {
|
|
12
|
+
this.procDir = options.procDir ?? "/proc";
|
|
13
|
+
}
|
|
14
|
+
hasProc() {
|
|
15
|
+
return existsSync(join(this.procDir, "self"));
|
|
16
|
+
}
|
|
17
|
+
readProc(relative) {
|
|
18
|
+
const path = join(this.procDir, relative);
|
|
19
|
+
return existsSync(path) ? readFileSync(path, "utf8") : undefined;
|
|
20
|
+
}
|
|
21
|
+
processes(options = {}) {
|
|
22
|
+
const found = [];
|
|
23
|
+
let seen = 0;
|
|
24
|
+
for (const entry of readdirSync(this.procDir)) {
|
|
25
|
+
if (!/^\d+$/.test(entry))
|
|
26
|
+
continue;
|
|
27
|
+
if (++seen > (options.cap ?? PROCESS_CAP))
|
|
28
|
+
break;
|
|
29
|
+
try {
|
|
30
|
+
const stat = readFileSync(join(this.procDir, entry, "stat"), "utf8");
|
|
31
|
+
let cwd;
|
|
32
|
+
if (options.cwd) {
|
|
33
|
+
try {
|
|
34
|
+
cwd = readlinkSync(join(this.procDir, entry, "cwd"));
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// ended meanwhile, or belongs to somebody whose directory cannot be read
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
found.push({ pid: Number(entry), stat, ...(cwd === undefined ? {} : { cwd }) });
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// the process ended meanwhile
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return found;
|
|
47
|
+
}
|
|
48
|
+
isAlive(pid) {
|
|
49
|
+
try {
|
|
50
|
+
return !readFileSync(join(this.procDir, String(pid), "stat"), "utf8").includes(") Z "); // a zombie has ended
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
signal(pid, signal) {
|
|
57
|
+
process.kill(pid, signal);
|
|
58
|
+
}
|
|
59
|
+
setPriority(pid, nice) {
|
|
60
|
+
return new Promise((resolve) => execFile("renice", ["-n", String(Math.floor(nice)), "-p", String(pid)], { timeout: 4000 }, (error) => resolve(!error)));
|
|
61
|
+
}
|
|
62
|
+
cpuCount() {
|
|
63
|
+
return cpus().length;
|
|
64
|
+
}
|
|
65
|
+
loadAverage() {
|
|
66
|
+
const [one, five, fifteen] = loadavg();
|
|
67
|
+
return [one ?? 0, five ?? 0, fifteen ?? 0];
|
|
68
|
+
}
|
|
69
|
+
totalMemoryBytes() {
|
|
70
|
+
return totalmem();
|
|
71
|
+
}
|
|
72
|
+
freeMemoryBytes() {
|
|
73
|
+
return freemem();
|
|
74
|
+
}
|
|
75
|
+
release() {
|
|
76
|
+
return release();
|
|
77
|
+
}
|
|
78
|
+
realPath(path) {
|
|
79
|
+
try {
|
|
80
|
+
return realpathSync(path);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return path;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
gpuQuery(query) {
|
|
87
|
+
return run("nvidia-smi", [query, "--format=csv,noheader,nounits"]);
|
|
88
|
+
}
|
|
89
|
+
hasProgram(program) {
|
|
90
|
+
return new Promise((resolve) => execFile("sh", ["-c", `command -v ${program}`], (error) => resolve(!error)));
|
|
91
|
+
}
|
|
92
|
+
gitCommit() {
|
|
93
|
+
return run("git", ["rev-parse", "HEAD"]);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** A host that lives in memory: the same operations, answered from a table, with a record of the signals and priorities it was given. */
|
|
97
|
+
export class FakeHost {
|
|
98
|
+
platform;
|
|
99
|
+
signals = [];
|
|
100
|
+
priorities = [];
|
|
101
|
+
state;
|
|
102
|
+
constructor(state = {}) {
|
|
103
|
+
this.platform = state.platform ?? "linux";
|
|
104
|
+
this.state = {
|
|
105
|
+
platform: this.platform,
|
|
106
|
+
files: state.files ?? {},
|
|
107
|
+
proc: state.proc ?? true,
|
|
108
|
+
processes: state.processes ?? [],
|
|
109
|
+
cores: state.cores ?? 4,
|
|
110
|
+
load: state.load ?? [0, 0, 0],
|
|
111
|
+
totalMemoryBytes: state.totalMemoryBytes ?? 8 * 1024 ** 3,
|
|
112
|
+
freeMemoryBytes: state.freeMemoryBytes ?? 4 * 1024 ** 3,
|
|
113
|
+
release: state.release ?? "fake-release",
|
|
114
|
+
gpu: state.gpu ?? {},
|
|
115
|
+
programs: state.programs ?? [],
|
|
116
|
+
commit: state.commit ?? "",
|
|
117
|
+
onSignal: state.onSignal,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** The process ended (or was never there). */
|
|
121
|
+
end(pid) {
|
|
122
|
+
this.state.processes = this.state.processes.filter((process) => process.pid !== pid);
|
|
123
|
+
}
|
|
124
|
+
hasProc() {
|
|
125
|
+
return this.state.proc;
|
|
126
|
+
}
|
|
127
|
+
readProc(relative) {
|
|
128
|
+
return this.state.proc ? this.state.files[relative] : undefined;
|
|
129
|
+
}
|
|
130
|
+
processes(options = {}) {
|
|
131
|
+
if (!this.state.proc)
|
|
132
|
+
return [];
|
|
133
|
+
return this.state.processes
|
|
134
|
+
.slice(0, options.cap ?? PROCESS_CAP)
|
|
135
|
+
.map(({ pid, stat, cwd }) => ({ pid, stat, ...(options.cwd && cwd !== undefined ? { cwd } : {}) }));
|
|
136
|
+
}
|
|
137
|
+
isAlive(pid) {
|
|
138
|
+
const found = this.state.processes.find((process) => process.pid === pid);
|
|
139
|
+
return found !== undefined && !found.stat.includes(") Z ");
|
|
140
|
+
}
|
|
141
|
+
signal(pid, signal) {
|
|
142
|
+
if (!this.state.processes.some((process) => process.pid === pid))
|
|
143
|
+
throw Object.assign(new Error("no such process"), { code: "ESRCH" });
|
|
144
|
+
this.signals.push([pid, signal]);
|
|
145
|
+
this.state.onSignal?.(pid, signal, this);
|
|
146
|
+
}
|
|
147
|
+
async setPriority(pid, nice) {
|
|
148
|
+
if (!this.state.processes.some((process) => process.pid === pid))
|
|
149
|
+
return false;
|
|
150
|
+
this.priorities.push([pid, nice]);
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
cpuCount() {
|
|
154
|
+
return this.state.cores;
|
|
155
|
+
}
|
|
156
|
+
loadAverage() {
|
|
157
|
+
return [...this.state.load];
|
|
158
|
+
}
|
|
159
|
+
totalMemoryBytes() {
|
|
160
|
+
return this.state.totalMemoryBytes;
|
|
161
|
+
}
|
|
162
|
+
freeMemoryBytes() {
|
|
163
|
+
return this.state.freeMemoryBytes;
|
|
164
|
+
}
|
|
165
|
+
release() {
|
|
166
|
+
return this.state.release;
|
|
167
|
+
}
|
|
168
|
+
realPath(path) {
|
|
169
|
+
return path;
|
|
170
|
+
}
|
|
171
|
+
async gpuQuery(query) {
|
|
172
|
+
return this.state.gpu[query];
|
|
173
|
+
}
|
|
174
|
+
async hasProgram(program) {
|
|
175
|
+
return this.state.programs.includes(program);
|
|
176
|
+
}
|
|
177
|
+
async gitCommit() {
|
|
178
|
+
return this.state.commit === "" ? undefined : this.state.commit;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* An append-only file with one JSON value per line. Lines are written synchronously, so two writers in one process never interleave
|
|
4
|
+
* and a crash leaves at most a torn last line, which reading skips.
|
|
5
|
+
*/
|
|
6
|
+
export class JsonlFile {
|
|
7
|
+
path;
|
|
8
|
+
constructor(path) {
|
|
9
|
+
this.path = path;
|
|
10
|
+
}
|
|
11
|
+
append(entry) {
|
|
12
|
+
appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
|
|
13
|
+
}
|
|
14
|
+
readAll() {
|
|
15
|
+
if (!existsSync(this.path))
|
|
16
|
+
return [];
|
|
17
|
+
const entries = [];
|
|
18
|
+
for (const line of readFileSync(this.path, "utf8").split("\n")) {
|
|
19
|
+
if (line.trim() === "")
|
|
20
|
+
continue;
|
|
21
|
+
try {
|
|
22
|
+
entries.push(JSON.parse(line));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// a torn last line after a crash; nothing after it can be trusted to be whole
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return entries;
|
|
29
|
+
}
|
|
30
|
+
}
|