pi-durable-subagents 1.0.42 → 1.0.45
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 +61 -0
- package/README.md +90 -8
- package/dist/agent/main/schema.js +6 -2
- package/dist/agent/main/snapshots.js +74 -5
- package/dist/agent/main/tool.js +21 -8
- package/dist/agent/main.js +10 -12
- package/dist/cli/control.js +20 -10
- package/dist/cli/main.js +5 -3
- package/dist/cli/requests.js +70 -34
- package/dist/compat/fanout.js +13 -5
- package/dist/compat/spec.js +46 -1
- package/dist/events/fence.js +2 -0
- package/dist/events/waiting.js +25 -3
- package/dist/kernel/journal.js +114 -25
- package/dist/kernel/lifecycle.js +66 -23
- package/dist/kernel/mailbox.js +49 -32
- package/dist/kernel/overlay.js +47 -0
- package/dist/orchestrator/engine.js +175 -41
- package/dist/orchestrator/executor/command.js +54 -0
- package/dist/orchestrator/executor/index.js +360 -8
- package/dist/orchestrator/executor/sweep.js +40 -24
- package/dist/orchestrator/ledger.js +4 -1
- package/dist/orchestrator/main.js +4 -2
- package/dist/orchestrator/providers.js +2 -0
- package/dist/orchestrator/reader-ledger.js +13 -3
- package/dist/orchestrator/restart.js +4 -1
- package/dist/orchestrator/settled.js +14 -2
- package/dist/orchestrator/snapshot.js +88 -9
- package/dist/orchestrator/store.js +133 -33
- package/dist/platform/command.js +98 -0
- package/dist/platform/launch.js +13 -3
- package/dist/requests.js +41 -5
- package/dist/types.js +2 -0
- package/dist/ui/screen.js +62 -13
- package/dist/ui/tool.js +8 -4
- package/dist/ui/view.js +18 -7
- package/package.json +1 -1
|
@@ -8,13 +8,23 @@
|
|
|
8
8
|
// session-corrupt{call,line}: a malformed native session line was skipped (once per line, E4).
|
|
9
9
|
// spawn-env-failed{exec,call,command,error}: launching the child failed for a reason of the environment (ENOENT, EACCES:
|
|
10
10
|
// pi or its interpreter missing or not executable); the call stays queued and launches again after a backoff.
|
|
11
|
+
// Command calls (CallSpec.command) record no exec/tracked/fenced entries (nothing that handles agent executions picks them
|
|
12
|
+
// up): command-intent{call,id,n} before the spawn (id = command:<call>#<n> is the attempt and its process tag DSA_EXEC;
|
|
13
|
+
// n is 1, or 2 for the single rerun); command-started{call,id,pid,start,dir} after it (the wrapper's identity, the
|
|
14
|
+
// attempt directory; its ts starts the wall-clock timeout); command-spawn-failed{call,id,error}: the command could not
|
|
15
|
+
// start (it seals failed, never reruns); command-timeout{call,id}: the deadline passed, recorded before the process tree
|
|
16
|
+
// is ended (as stop-intent is for a stop), so a crash during that fence still seals timeout; command-withdrawn{call,id}:
|
|
17
|
+
// the intent was recorded but no process started (a retirement or the orchestrator's exit came first): a later start
|
|
18
|
+
// decides again, as if there were no intent.
|
|
11
19
|
// fence-failed{exec,error} is documented in sweep.ts. The orchestrator ledger owns hold/release{pool,slot,exec}
|
|
12
20
|
// and mem{available,admitted,exec} (every admission; a repeated refusal at most every 30 s per call). All transitions are serialized before publication.
|
|
13
|
-
import { mkdir, open, readdir, readFile, realpath, rm, unlink, writeFile } from "node:fs/promises";
|
|
21
|
+
import { mkdir, open, readdir, readFile, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
22
|
+
import { watch } from "node:fs";
|
|
23
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
14
24
|
import { homedir } from "node:os";
|
|
15
25
|
import { delimiter, dirname, join } from "node:path";
|
|
16
26
|
import { fileURLToPath } from "node:url";
|
|
17
|
-
import { CT, JT, attentionEntries, isEntry } from "../../types.js";
|
|
27
|
+
import { CT, JT, attentionEntries, isCommandCall, isEntry } from "../../types.js";
|
|
18
28
|
import { binDir, callDir, callInbox, callSession, journalPath, outboxRoot } from "../../paths.js";
|
|
19
29
|
import { readJournalSnapshot, syncDirectory } from "../../kernel/journal.js";
|
|
20
30
|
import { Outbox } from "../../kernel/mailbox.js";
|
|
@@ -40,7 +50,18 @@ import { gateRetired } from "./effects/gate.js";
|
|
|
40
50
|
import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
|
|
41
51
|
import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidates } from "./pool.js";
|
|
42
52
|
import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
|
|
53
|
+
import { COMMAND_LOG, exitMeaning, readExitRecord, readTail, spawnCommand } from "../../platform/command.js";
|
|
54
|
+
import { captureStart } from "../../platform/proctable.js";
|
|
55
|
+
import { heldIn } from "../snapshot.js";
|
|
56
|
+
import { COMMAND_INTENT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandId, retiredCommandAttempts } from "./command.js";
|
|
43
57
|
const MEM_RECORD_MS = 30000;
|
|
58
|
+
/** How long the processes of a stopped or timed-out command get between SIGTERM and SIGKILL. */
|
|
59
|
+
const COMMAND_GRACE_MS = 2000;
|
|
60
|
+
/** A command's exit status as a result: 0 is ok; otherwise the error names the status, or the signal (exitMeaning). */
|
|
61
|
+
function exitResult(status) {
|
|
62
|
+
const meaning = exitMeaning(status);
|
|
63
|
+
return status === 0 ? meaning : { ...meaning, error: meaning.signal ? `Command killed by ${meaning.signal}` : `Command exited ${status}` };
|
|
64
|
+
}
|
|
44
65
|
/** A4, P29: A child admitted within this window may not show in MemAvailable yet; its share is reserved explicitly. */
|
|
45
66
|
const MEM_WARMUP_MS = 30000;
|
|
46
67
|
/** Quota refusals in a row that find a provider's usage window used up while pi is still retrying. */
|
|
@@ -1158,7 +1179,306 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1158
1179
|
while (!interrupted(a) && Date.now() < until)
|
|
1159
1180
|
await new Promise(resolve => { const timer = setTimeout(resolve, Math.min(until - Date.now(), config.k?.trackerMs ?? 1000)); a.wake = () => { clearTimeout(timer); resolve(); }; });
|
|
1160
1181
|
}
|
|
1182
|
+
// ---- Command calls: no model, slot, usage, hibernation or budget; the process outlives the orchestrator. ----
|
|
1183
|
+
const commandTick = () => Math.min(config.k?.trackerMs ?? 1000, 1000);
|
|
1184
|
+
const hasStopIntent = (journal, call) => entriesFor(journal, call).some(e => e.type === "stop-intent");
|
|
1185
|
+
/** The wrapper's identity of an attempt (from its latest command-started), for scans and fences. */
|
|
1186
|
+
const commandKnown = (started) => started && started.start ? [{ pid: Number(started.pid), ppid: 0, start: String(started.start) }] : [];
|
|
1187
|
+
/** The processes of an attempt: tagged with its id, the wrapper while it lives, and their live descendants. */
|
|
1188
|
+
async function commandProcesses(id, known) {
|
|
1189
|
+
return (await containment.scan(new Map([[id, known]]), { fresh: true })).get(id) ?? [];
|
|
1190
|
+
}
|
|
1191
|
+
/** End an attempt's whole process tree: SIGTERM, a grace period, then the fence (SIGKILL until a rescan finds none).
|
|
1192
|
+
* A failing fence is retried until it works; the orchestrator's exit interrupts it (the next start fences again). */
|
|
1193
|
+
async function endCommand(id, known) {
|
|
1194
|
+
let live = await commandProcesses(id, known);
|
|
1195
|
+
if (!live.length)
|
|
1196
|
+
return;
|
|
1197
|
+
for (const p of live) {
|
|
1198
|
+
if (p.start !== "" && await captureStart(p.pid).catch(() => "") !== p.start)
|
|
1199
|
+
continue;
|
|
1200
|
+
try {
|
|
1201
|
+
process.kill(p.pid, "SIGTERM");
|
|
1202
|
+
}
|
|
1203
|
+
catch (error) {
|
|
1204
|
+
if (error.code !== "ESRCH")
|
|
1205
|
+
throw error;
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
const graceUntil = Date.now() + COMMAND_GRACE_MS;
|
|
1209
|
+
while (Date.now() < graceUntil) {
|
|
1210
|
+
await delay(100);
|
|
1211
|
+
live = await commandProcesses(id, known);
|
|
1212
|
+
if (!live.length)
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
1215
|
+
for (;;) {
|
|
1216
|
+
try {
|
|
1217
|
+
await containment.fence(id, [...known, ...live]);
|
|
1218
|
+
return;
|
|
1219
|
+
}
|
|
1220
|
+
catch (error) {
|
|
1221
|
+
console.error(`durable-subagents: fence of ${id} failed: ${String(error)}; retrying`);
|
|
1222
|
+
if (closed)
|
|
1223
|
+
throw shutdownError();
|
|
1224
|
+
await delay(commandTick());
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
/** Seal a command call through the normal seal path (forwards, attention, inbox) with the pinned result: a stop or a
|
|
1229
|
+
* recorded timeout of the attempt wins, as they do for agent calls. */
|
|
1230
|
+
async function sealCommand(journal, t, id, outcome, dir) {
|
|
1231
|
+
const call = t.callId, output = dir ? await readTail(join(dir, COMMAND_LOG)) : "";
|
|
1232
|
+
const value = await serial(async () => {
|
|
1233
|
+
const old = sealed(journal, call);
|
|
1234
|
+
if (old)
|
|
1235
|
+
return old;
|
|
1236
|
+
if (closed || retiredCall(journal, call))
|
|
1237
|
+
throw shutdownError();
|
|
1238
|
+
const started = entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id);
|
|
1239
|
+
let { status, error } = outcome;
|
|
1240
|
+
if (hasStopIntent(journal, call)) {
|
|
1241
|
+
status = "stopped";
|
|
1242
|
+
error = undefined;
|
|
1243
|
+
}
|
|
1244
|
+
else if (entriesFor(journal, call).some(e => e.type === COMMAND_TIMEOUT && e.id === id)) {
|
|
1245
|
+
status = "timeout";
|
|
1246
|
+
error = `Command timed out after ${t.spec.timeoutMs} ms`;
|
|
1247
|
+
}
|
|
1248
|
+
const durationMs = started ? Math.max(0, Math.round((outcome.at ?? Date.now()) - started.ts)) : 0;
|
|
1249
|
+
const result = { ...buildCallResult({ key: t.key, gen: t.gen, status, output, ...(error ? { error } : {}) }),
|
|
1250
|
+
data: { exitCode: outcome.exitCode ?? null, signal: outcome.signal ?? null, durationMs }, usage: { input: 0, output: 0, costUsd: 0 } };
|
|
1251
|
+
await journal.append(JT.sealed, { call, exec: id, result });
|
|
1252
|
+
await retireForwards(journal, call);
|
|
1253
|
+
await retireAttention(journal, call);
|
|
1254
|
+
await unknownAttention(journal, call);
|
|
1255
|
+
return result;
|
|
1256
|
+
});
|
|
1257
|
+
await collectSealed(call).catch(error => console.error(`durable-subagents: inbox cleanup of ${call} failed: ${String(error)}`));
|
|
1258
|
+
wake();
|
|
1259
|
+
return value;
|
|
1260
|
+
}
|
|
1261
|
+
/** Whether a drain holds workflow `wid` now (the engine's hold rule): a held command call does not start. */
|
|
1262
|
+
const held = (wid) => heldIn(orch.entries())(wid);
|
|
1263
|
+
/** Why a command call cannot start attempt `n` now: retired or closed (the run ends), stopped (it seals), held (the
|
|
1264
|
+
* run ends; the engine runs the call again after resume), or undefined. */
|
|
1265
|
+
const commandBlocked = (a) => {
|
|
1266
|
+
const t = a.ticket;
|
|
1267
|
+
if (closed || a.suspended || a.retired || retiredCall(t.journal, t.callId))
|
|
1268
|
+
return "shutdown";
|
|
1269
|
+
if (stopped(a))
|
|
1270
|
+
return "stopped";
|
|
1271
|
+
if (held(t.wid))
|
|
1272
|
+
return "held";
|
|
1273
|
+
return undefined;
|
|
1274
|
+
};
|
|
1275
|
+
/** The writer lock of a command call with `writer: true`, before its first attempt; the reason it stopped waiting. */
|
|
1276
|
+
async function commandWriter(a) {
|
|
1277
|
+
const t = a.ticket, root = await roots(t.cwd, "x") ?? await realpath(t.cwd).catch(() => t.cwd);
|
|
1278
|
+
for (;;) {
|
|
1279
|
+
const blocked = commandBlocked(a);
|
|
1280
|
+
if (blocked)
|
|
1281
|
+
return blocked;
|
|
1282
|
+
let signal;
|
|
1283
|
+
const changed = new Promise(resolve => { signal = resolve; waiters.add(resolve); });
|
|
1284
|
+
if (await serial(async () => !commandBlocked(a) && await writerAdmit(a, root))) {
|
|
1285
|
+
waiters.delete(signal);
|
|
1286
|
+
return undefined;
|
|
1287
|
+
}
|
|
1288
|
+
a.wake = signal;
|
|
1289
|
+
const timer = setTimeout(signal, commandTick());
|
|
1290
|
+
try {
|
|
1291
|
+
await changed;
|
|
1292
|
+
}
|
|
1293
|
+
finally {
|
|
1294
|
+
clearTimeout(timer);
|
|
1295
|
+
waiters.delete(signal);
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
/** Record the intent of attempt `n` (the start decision): in one serial step with the checks of commandBlocked, so no
|
|
1300
|
+
* stop, retirement, close or hold slips in between. `a.commandStarting` marks the decision for suspend(). */
|
|
1301
|
+
function commandIntent(a, n) {
|
|
1302
|
+
const t = a.ticket, journal = t.journal, call = t.callId;
|
|
1303
|
+
return serial(async () => {
|
|
1304
|
+
const blocked = commandBlocked(a);
|
|
1305
|
+
if (blocked)
|
|
1306
|
+
return blocked;
|
|
1307
|
+
const existing = entriesFor(journal, call).findLast(e => e.type === COMMAND_INTENT && e.n === n && !intentWithdrawn(journal, call, String(e.id), e.seq));
|
|
1308
|
+
if (existing)
|
|
1309
|
+
return existing;
|
|
1310
|
+
a.commandStarting = true;
|
|
1311
|
+
return journal.append(COMMAND_INTENT, { call, id: commandId(call, n), n });
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
/** Whether a later command-withdrawn voids the intent at `seq` (no process was started for it). */
|
|
1315
|
+
const intentWithdrawn = (journal, call, id, seq) => entriesFor(journal, call).some(e => e.type === COMMAND_WITHDRAWN && e.id === id && e.seq > seq);
|
|
1316
|
+
/** Start the attempt whose intent is recorded; records command-started, or command-spawn-failed when it cannot start.
|
|
1317
|
+
* Rechecked synchronously right before the spawn: a stop means no process (the watch seals it stopped), a retirement or the orchestrator's exit
|
|
1318
|
+
* withdraws the intent (nothing started; the next start decides again). */
|
|
1319
|
+
async function launchCommand(a, id, dir) {
|
|
1320
|
+
const t = a.ticket;
|
|
1321
|
+
let spawned;
|
|
1322
|
+
try {
|
|
1323
|
+
if (!(await stat(t.cwd).catch(() => undefined))?.isDirectory())
|
|
1324
|
+
throw new Error(`cwd ${t.cwd} is not a directory`);
|
|
1325
|
+
await rm(join(dir, "exit"), { force: true });
|
|
1326
|
+
await rm(join(dir, "exit.tmp"), { force: true });
|
|
1327
|
+
// The last check is synchronous, right before the spawn (spawnCommand calls it after its own preparation).
|
|
1328
|
+
let refused;
|
|
1329
|
+
const proceed = () => {
|
|
1330
|
+
if (stopped(a))
|
|
1331
|
+
refused = "stopped";
|
|
1332
|
+
else if (closed || a.retired || retiredCall(t.journal, t.callId))
|
|
1333
|
+
refused = "withdrawn";
|
|
1334
|
+
return refused === undefined;
|
|
1335
|
+
};
|
|
1336
|
+
const result = await spawnCommand({ command: t.spec.command, cwd: t.cwd, dir, proceed,
|
|
1337
|
+
env: { ...process.env, ...t.spec.env, DSA_EXEC: id, DSA_CALL: t.callId, DSA_HOME: home } });
|
|
1338
|
+
if (!result) {
|
|
1339
|
+
if (refused === "withdrawn")
|
|
1340
|
+
await serial(() => t.journal.append(COMMAND_WITHDRAWN, { call: t.callId, id }));
|
|
1341
|
+
return undefined;
|
|
1342
|
+
}
|
|
1343
|
+
spawned = result;
|
|
1344
|
+
}
|
|
1345
|
+
catch (error) {
|
|
1346
|
+
await serial(() => t.journal.append(COMMAND_SPAWN_FAILED, { call: t.callId, id, error: String(error instanceof Error ? error.message : error).slice(0, 300) }));
|
|
1347
|
+
return undefined;
|
|
1348
|
+
}
|
|
1349
|
+
await serial(() => t.journal.append(COMMAND_STARTED, { call: t.callId, id, pid: spawned.pid, start: spawned.start, dir }));
|
|
1350
|
+
return spawned;
|
|
1351
|
+
}
|
|
1352
|
+
/** Run, adopt or settle a command call (see the journal records at the top). One attempt runs at a time; a lost first
|
|
1353
|
+
* attempt of a `rerun: true` call starts once more, only after a scan found none of its processes. A start (the
|
|
1354
|
+
* first attempt or the rerun) waits while the workflow is held: the run ends and the engine runs it after resume. */
|
|
1355
|
+
async function executeCommand(a) {
|
|
1356
|
+
const t = a.ticket, journal = t.journal, call = t.callId;
|
|
1357
|
+
const own = () => entriesFor(journal, call);
|
|
1358
|
+
const dirOf = (n) => join(callDir(home, t.wid, t.key, t.gen), commandDirName(n));
|
|
1359
|
+
const fail = (error) => sealCommand(journal, t, commandId(call, 1), { status: "failed", error });
|
|
1360
|
+
const latest = () => { const e = own().findLast(e => e.type === COMMAND_INTENT); return e && !intentWithdrawn(journal, call, String(e.id), e.seq) ? e : undefined; };
|
|
1361
|
+
/** Start attempt `n`: the intent, then the process; undefined when it did not start (and the run goes on). */
|
|
1362
|
+
const begin = async (n) => {
|
|
1363
|
+
const intent = await commandIntent(a, n);
|
|
1364
|
+
if (intent === "stopped")
|
|
1365
|
+
return undefined;
|
|
1366
|
+
if (intent === "shutdown" || intent === "held")
|
|
1367
|
+
throw shutdownError();
|
|
1368
|
+
return { spawned: await launchCommand(a, String(intent.id), dirOf(n)) };
|
|
1369
|
+
};
|
|
1370
|
+
let spawned;
|
|
1371
|
+
for (;;) {
|
|
1372
|
+
const old = sealed(journal, call);
|
|
1373
|
+
if (old)
|
|
1374
|
+
return old;
|
|
1375
|
+
if (closed || a.retired || retiredCall(journal, call)) {
|
|
1376
|
+
if (!closed) {
|
|
1377
|
+
const intent = latest();
|
|
1378
|
+
if (intent)
|
|
1379
|
+
await endCommand(String(intent.id), commandKnown(own().findLast(e => e.type === COMMAND_STARTED && e.id === intent.id)));
|
|
1380
|
+
}
|
|
1381
|
+
throw shutdownError();
|
|
1382
|
+
}
|
|
1383
|
+
let intent = latest();
|
|
1384
|
+
if (!intent) {
|
|
1385
|
+
if (t.refusal !== undefined)
|
|
1386
|
+
return fail(t.refusal);
|
|
1387
|
+
const n = Math.max(1, ...own().filter(e => e.type === COMMAND_INTENT).map(e => Number(e.n)));
|
|
1388
|
+
if (stopped(a))
|
|
1389
|
+
return sealCommand(journal, t, commandId(call, n), { status: "stopped" });
|
|
1390
|
+
if (t.spec.writer === true) {
|
|
1391
|
+
const blocked = await commandWriter(a);
|
|
1392
|
+
if (blocked === "stopped")
|
|
1393
|
+
continue;
|
|
1394
|
+
if (blocked)
|
|
1395
|
+
throw shutdownError();
|
|
1396
|
+
}
|
|
1397
|
+
spawned = (await begin(n))?.spawned;
|
|
1398
|
+
continue;
|
|
1399
|
+
}
|
|
1400
|
+
const id = String(intent.id), n = Number(intent.n), dir = dirOf(n);
|
|
1401
|
+
const failed = own().find(e => e.type === COMMAND_SPAWN_FAILED && e.id === id);
|
|
1402
|
+
if (failed)
|
|
1403
|
+
return sealCommand(journal, t, id, { status: "failed", error: `Command could not start: ${String(failed.error)}` });
|
|
1404
|
+
const outcome = await watchCommand(a, id, dir, intent, spawned);
|
|
1405
|
+
spawned = undefined;
|
|
1406
|
+
if (outcome !== "lost")
|
|
1407
|
+
return outcome;
|
|
1408
|
+
if (n === 1 && t.spec.rerun === true) {
|
|
1409
|
+
// The scan found no process of the first attempt: start it once more (attempt 2 never reruns), a new start.
|
|
1410
|
+
if (!own().some(e => e.type === COMMAND_INTENT && e.n === 2)) {
|
|
1411
|
+
spawned = (await begin(2))?.spawned;
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
return sealCommand(journal, t, id, { status: "unknown", error: "Command ended without an exit record" }, dir);
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
/** Watch one attempt until it has an outcome: its exit record, a stop, its deadline, or its loss (no exit record and
|
|
1419
|
+
* no process left). The orchestrator's exit ends the watch without touching the process (ExecutorShutdown). */
|
|
1420
|
+
async function watchCommand(a, id, dir, intent, spawned) {
|
|
1421
|
+
const t = a.ticket, journal = t.journal, call = t.callId;
|
|
1422
|
+
let watcher;
|
|
1423
|
+
try {
|
|
1424
|
+
watcher = watch(dir, () => a.wake());
|
|
1425
|
+
watcher.on("error", () => watcher?.close());
|
|
1426
|
+
}
|
|
1427
|
+
catch {
|
|
1428
|
+
watcher = undefined;
|
|
1429
|
+
}
|
|
1430
|
+
void spawned?.exited.then(() => a.wake());
|
|
1431
|
+
try {
|
|
1432
|
+
for (;;) {
|
|
1433
|
+
const started = entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id), known = commandKnown(started);
|
|
1434
|
+
// The timeout is wall clock from the start (command-started, else the intent: a crash before the started record),
|
|
1435
|
+
// downtime included.
|
|
1436
|
+
const deadline = t.spec.timeoutMs !== undefined ? (started ?? intent).ts + t.spec.timeoutMs : undefined;
|
|
1437
|
+
const exit = await readExitRecord(dir);
|
|
1438
|
+
if (exit) {
|
|
1439
|
+
// Processes the command left behind (background ones included) end with it, as a call's processes always do.
|
|
1440
|
+
if (!closed)
|
|
1441
|
+
await endCommand(id, known);
|
|
1442
|
+
// An exit after the deadline (seen late: the orchestrator was down) is a timeout, with the record's data.
|
|
1443
|
+
const late = deadline !== undefined && exit.at > deadline;
|
|
1444
|
+
return await sealCommand(journal, t, id, { status: late ? "timeout" : exit.status === 0 ? "ok" : "failed", ...exitResult(exit.status),
|
|
1445
|
+
...(late ? { error: `Command timed out after ${t.spec.timeoutMs} ms` } : {}), at: exit.at }, dir);
|
|
1446
|
+
}
|
|
1447
|
+
if (closed)
|
|
1448
|
+
throw shutdownError();
|
|
1449
|
+
if (a.retired || retiredCall(journal, call)) {
|
|
1450
|
+
await endCommand(id, known);
|
|
1451
|
+
throw shutdownError();
|
|
1452
|
+
}
|
|
1453
|
+
if (hasStopIntent(journal, call)) {
|
|
1454
|
+
await endCommand(id, known);
|
|
1455
|
+
return await sealCommand(journal, t, id, { status: "stopped" }, dir);
|
|
1456
|
+
}
|
|
1457
|
+
if (deadline !== undefined && Date.now() >= deadline || entriesFor(journal, call).some(e => e.type === COMMAND_TIMEOUT && e.id === id)) {
|
|
1458
|
+
await serial(async () => { if (!entriesFor(journal, call).some(e => e.type === COMMAND_TIMEOUT && e.id === id))
|
|
1459
|
+
await journal.append(COMMAND_TIMEOUT, { call, id }); });
|
|
1460
|
+
await endCommand(id, known);
|
|
1461
|
+
return await sealCommand(journal, t, id, { status: "timeout" }, dir);
|
|
1462
|
+
}
|
|
1463
|
+
const wrapper = !!started?.start && await captureStart(Number(started.pid)).catch(() => "") === started.start;
|
|
1464
|
+
if (!wrapper && !(await commandProcesses(id, known)).length) {
|
|
1465
|
+
// The wrapper may have written its record just before it ended.
|
|
1466
|
+
const late = await readExitRecord(dir);
|
|
1467
|
+
if (!late)
|
|
1468
|
+
return "lost";
|
|
1469
|
+
continue;
|
|
1470
|
+
}
|
|
1471
|
+
const wait = Math.max(1, Math.min(commandTick(), deadline !== undefined ? deadline - Date.now() : Infinity));
|
|
1472
|
+
await new Promise(resolve => { const timer = setTimeout(resolve, wait); a.wake = () => { clearTimeout(timer); resolve(); }; });
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
finally {
|
|
1476
|
+
watcher?.close();
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1161
1479
|
async function execute(a) {
|
|
1480
|
+
if (isCommandCall(a.ticket.spec))
|
|
1481
|
+
return executeCommand(a);
|
|
1162
1482
|
const t = a.ticket, journal = t.journal;
|
|
1163
1483
|
const session = callSession(home, t.wid, t.key, t.gen), dir = callDir(home, t.wid, t.key, t.gen);
|
|
1164
1484
|
const makeResult = (status, output = "", error) => buildCallResult({ key: t.key, gen: t.gen, status, output, ...(error ? { error } : {}) });
|
|
@@ -1795,7 +2115,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1795
2115
|
const journal = journals.get(target.wid);
|
|
1796
2116
|
if (!journal)
|
|
1797
2117
|
return;
|
|
1798
|
-
const calls = new Set(journal.entries().filter(e => e.type === JT.exec && (!target.callId || e.call === target.callId)).map(e => String(e.call)));
|
|
2118
|
+
const calls = new Set(journal.entries().filter(e => (e.type === JT.exec || e.type === COMMAND_INTENT) && (!target.callId || e.call === target.callId)).map(e => String(e.call)));
|
|
1799
2119
|
for (const a of active.values())
|
|
1800
2120
|
if (a.ticket.wid === target.wid && (!target.callId || a.ticket.callId === target.callId))
|
|
1801
2121
|
calls.add(a.ticket.callId);
|
|
@@ -1818,6 +2138,16 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1818
2138
|
const a = active.get(call);
|
|
1819
2139
|
if (a)
|
|
1820
2140
|
await settledOrParked(a);
|
|
2141
|
+
else if (entriesFor(journal, call).some(e => e.type === COMMAND_INTENT)) {
|
|
2142
|
+
// A command call nobody watches here (not adopted yet): end its tree, then seal it stopped.
|
|
2143
|
+
if (sealed(journal, call) || retiredCall(journal, call))
|
|
2144
|
+
continue;
|
|
2145
|
+
const intent = entriesFor(journal, call).findLast(e => e.type === COMMAND_INTENT), id = String(intent.id);
|
|
2146
|
+
await endCommand(id, commandKnown(entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id)));
|
|
2147
|
+
const { wid, key, gen } = address(call);
|
|
2148
|
+
await sealCommand(journal, { wid, key, gen, callId: call, spec: {} }, id, { status: "stopped" }, join(callDir(home, wid, key, gen), commandDirName(Number(intent.n)))).catch(error => { if (error?.name !== "ExecutorShutdown")
|
|
2149
|
+
throw error; });
|
|
2150
|
+
}
|
|
1821
2151
|
else {
|
|
1822
2152
|
const exec = current(journal, call);
|
|
1823
2153
|
if (!exec || sealed(journal, call))
|
|
@@ -1845,6 +2175,10 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1845
2175
|
await effects.recover(journal);
|
|
1846
2176
|
// A call whose recovery ran to its end before (and that nothing concerned since) is not read again: all its
|
|
1847
2177
|
// executions were fenced and released, its session read, its forwards, attention and inbox settled.
|
|
2178
|
+
// A retired command call's processes, if any still run (an orchestrator ended during its retirement), end now.
|
|
2179
|
+
if (entriesOf(journal, COMMAND_INTENT).length)
|
|
2180
|
+
for (const r of retiredCommandAttempts(journal.entries()))
|
|
2181
|
+
await endCommand(r.id, r.start ? [{ pid: r.pid, ppid: 0, start: r.start }] : []);
|
|
1848
2182
|
const complete = completeCalls(journal, wid), execs = entriesOf(journal, JT.exec).filter(e => !complete.has(String(e.call)));
|
|
1849
2183
|
for (const e of execs) {
|
|
1850
2184
|
// F1: an exec whose fence fails stays unfenced and holding; its call parks until a sweep retires it.
|
|
@@ -1924,7 +2258,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1924
2258
|
const journal = journals.get(widRev.slice(0, widRev.lastIndexOf("@")));
|
|
1925
2259
|
if (!journal)
|
|
1926
2260
|
return;
|
|
1927
|
-
const calls = new Set(journal.entries().filter(e => e.type === JT.exec && String(e.call).startsWith(`${widRev}/`)).map(e => String(e.call)));
|
|
2261
|
+
const calls = new Set(journal.entries().filter(e => (e.type === JT.exec || e.type === COMMAND_INTENT) && String(e.call).startsWith(`${widRev}/`)).map(e => String(e.call)));
|
|
1928
2262
|
for (const a of active.values())
|
|
1929
2263
|
if (a.ticket.widRev === widRev) {
|
|
1930
2264
|
a.retired = true;
|
|
@@ -1944,19 +2278,30 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1944
2278
|
for (const e of journal.entries().filter(e => e.type === JT.exec && e.call === call))
|
|
1945
2279
|
if (await fence(journal, String(e.exec)))
|
|
1946
2280
|
await release(String(e.exec));
|
|
2281
|
+
// A command call's processes end with its retirement (one nobody watched here included).
|
|
2282
|
+
const intent = sealed(journal, call) ? undefined : entriesFor(journal, call).findLast(e => e.type === COMMAND_INTENT);
|
|
2283
|
+
if (intent)
|
|
2284
|
+
await endCommand(String(intent.id), commandKnown(entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === intent.id)));
|
|
1947
2285
|
await serial(async () => { await retireForwards(journal, call); await retireAttention(journal, call); });
|
|
1948
2286
|
}
|
|
1949
2287
|
},
|
|
1950
2288
|
busy: () => active.size > 0,
|
|
2289
|
+
exclusive: fn => serial(fn),
|
|
1951
2290
|
quiesce() {
|
|
1952
2291
|
paused = true;
|
|
1953
2292
|
const live = [...active.values()].filter(a => a.live).map(a => ({ wid: a.ticket.wid, key: a.ticket.key, gen: a.ticket.gen, callId: a.ticket.callId, ...a.live }));
|
|
1954
|
-
|
|
2293
|
+
// Command calls never count as live: they keep running across a restart and the successor adopts them.
|
|
2294
|
+
const commands = [...active.values()].filter(a => isCommandCall(a.ticket.spec)).length;
|
|
2295
|
+
return { live, commands, resume: () => { paused = false; for (const fn of [...unpaused])
|
|
1955
2296
|
fn(); } };
|
|
1956
2297
|
},
|
|
1957
2298
|
suspend(only) {
|
|
2299
|
+
// A drain with fence does not fence command calls: they keep running and seal (the held workflow starts nothing
|
|
2300
|
+
// after them). Only the orchestrator's exit (shutdown) ends their watchers, leaving the processes running.
|
|
2301
|
+
// One that has not started (no intent: waiting for the writer lock, say) is suspended like a call not launched.
|
|
2302
|
+
const suspendable = (a) => closed || !isCommandCall(a.ticket.spec) || (!a.commandStarting && !entriesFor(a.ticket.journal, a.ticket.callId).some(e => e.type === COMMAND_INTENT));
|
|
1958
2303
|
if (only) { // scoped (one session's quit, one workflow): other workflows keep running and dispatching
|
|
1959
|
-
const targets = [...active.values()].filter(a => only(a.ticket.wid));
|
|
2304
|
+
const targets = [...active.values()].filter(a => only(a.ticket.wid) && suspendable(a));
|
|
1960
2305
|
for (const a of targets) {
|
|
1961
2306
|
a.suspended = true;
|
|
1962
2307
|
a.controller.abort();
|
|
@@ -1973,14 +2318,15 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1973
2318
|
}
|
|
1974
2319
|
if (suspending)
|
|
1975
2320
|
return suspending;
|
|
1976
|
-
|
|
2321
|
+
const targets = [...active.values()].filter(suspendable);
|
|
2322
|
+
for (const a of targets) {
|
|
1977
2323
|
a.suspended = true;
|
|
1978
2324
|
a.controller.abort();
|
|
1979
2325
|
a.wake();
|
|
1980
2326
|
}
|
|
1981
2327
|
wake();
|
|
1982
2328
|
suspending = (async () => {
|
|
1983
|
-
const results = await Promise.allSettled(
|
|
2329
|
+
const results = await Promise.allSettled(targets.map(a => a.promise));
|
|
1984
2330
|
await queue;
|
|
1985
2331
|
const failed = results.find(r => r.status === "rejected" && r.reason?.name !== "ExecutorShutdown");
|
|
1986
2332
|
if (failed?.status === "rejected")
|
|
@@ -1995,6 +2341,12 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1995
2341
|
clearInterval(sweepTimer);
|
|
1996
2342
|
try {
|
|
1997
2343
|
await this.suspend();
|
|
2344
|
+
// Command watchers end at once (their processes keep running; the next start adopts them), also when an
|
|
2345
|
+
// earlier drain's suspension was still settling and did not include them.
|
|
2346
|
+
const commands = [...active.values()].filter(a => isCommandCall(a.ticket.spec));
|
|
2347
|
+
for (const a of commands)
|
|
2348
|
+
a.wake();
|
|
2349
|
+
await Promise.allSettled(commands.map(a => a.promise));
|
|
1998
2350
|
await sweeping;
|
|
1999
2351
|
}
|
|
2000
2352
|
finally {
|
|
@@ -62,26 +62,16 @@ export async function fenceAttentionResolved(journal, id) {
|
|
|
62
62
|
}
|
|
63
63
|
const sweeps = new WeakMap();
|
|
64
64
|
export function sweepSeed(journal) {
|
|
65
|
-
|
|
66
|
-
return execs.map(e => {
|
|
67
|
-
const exec = String(e.exec);
|
|
68
|
-
const ids = [...new Set((tracked.get(exec) ?? []).map(p => `${p.pid} ${p.start}`))];
|
|
69
|
-
// Only a failure not fenced since is still a failure: a fenced one would make the sweep record (and decode) again.
|
|
70
|
-
return { exec, call: String(e.call), ...(failed.has(exec) && !fenced.has(exec) ? { failed: true } : {}), tracked: ids };
|
|
71
|
-
});
|
|
72
|
-
}
|
|
73
|
-
const procOf = (id) => { const space = id.indexOf(" "); return { pid: Number(id.slice(0, space)), ppid: 0, start: id.slice(space + 1) }; };
|
|
74
|
-
/** The sweep state of a journal that is not decoded, from its seed (every execution fenced, no open gate): no failed
|
|
75
|
-
* fence is open (settledFacts requires it), so none is seeded, also from an older record. */
|
|
76
|
-
export function seededSweep(seed) {
|
|
77
|
-
return { count: 0, fenced: new Set(seed.map(s => s.exec)), retired: new Set(), failed: new Set(), gated: new Set(),
|
|
78
|
-
tracked: new Map(seed.map(s => [s.exec, s.tracked.map(procOf)])), execs: seed.map(s => ({ seq: 0, ts: 0, type: JT.exec, exec: s.exec, call: s.call })), gates: [] };
|
|
65
|
+
return [...indexSweep(journal).fenced].sort((a, b) => a[1] - b[1]).map(([exec]) => String(exec));
|
|
79
66
|
}
|
|
67
|
+
/** Settled executions need only tags, in exec-entry order. Share the store's list; older test seeds keep their stored
|
|
68
|
+
* order until the journal is naturally decoded. Released object seeds already have exec-entry order. */
|
|
69
|
+
export function seededSweep(seed) { return seed; }
|
|
80
70
|
/** A1: Fold old history during recovery, so the first sweep does not allocate it on the timer path. */
|
|
81
71
|
export function indexSweep(journal) {
|
|
82
72
|
let state = sweeps.get(journal);
|
|
83
73
|
if (!state) {
|
|
84
|
-
state = { count: 0, fenced: new
|
|
74
|
+
state = { count: 0, fenced: new Map(), retired: new Set(), failed: new Set(), gated: new Set(), tracked: new Map(), execs: [], gates: [] };
|
|
85
75
|
sweeps.set(journal, state);
|
|
86
76
|
}
|
|
87
77
|
const { fenced, retired, failed, gated, tracked, execs, gates } = state, entries = journal.entries();
|
|
@@ -91,21 +81,37 @@ export function indexSweep(journal) {
|
|
|
91
81
|
execs.push(e);
|
|
92
82
|
else if (e.type === "gate-intent")
|
|
93
83
|
gates.push(e);
|
|
94
|
-
else if (e.type === JT.fenced)
|
|
95
|
-
|
|
84
|
+
else if (e.type === JT.fenced) {
|
|
85
|
+
// One sequence number per retained tag preserves exec order without retaining the exec or its processes.
|
|
86
|
+
if (!fenced.has(e.exec))
|
|
87
|
+
fenced.set(e.exec, execs.find(exec => exec.exec === e.exec)?.seq ?? e.seq);
|
|
88
|
+
tracked.delete(String(e.exec));
|
|
89
|
+
}
|
|
90
|
+
else if (e.type === JT.attentionResolved && typeof e.id === "string" && e.id.startsWith("fence:"))
|
|
91
|
+
failed.delete(e.id.slice(6));
|
|
96
92
|
else if (e.type === "retired")
|
|
97
93
|
retired.add(e.call);
|
|
98
94
|
else if (e.type === "fence-failed")
|
|
99
95
|
failed.add(e.exec);
|
|
100
|
-
else if (e.type === "gate")
|
|
96
|
+
else if (e.type === "gate") {
|
|
101
97
|
gated.add(e.id);
|
|
98
|
+
tracked.delete(String(e.id));
|
|
99
|
+
failed.delete(e.id);
|
|
100
|
+
}
|
|
102
101
|
else if (e.type === "tracked" || e.type === "gate-tracked") {
|
|
103
|
-
const id = String(e.type === "tracked" ? e.exec : e.id)
|
|
102
|
+
const id = String(e.type === "tracked" ? e.exec : e.id);
|
|
103
|
+
if (fenced.has(id) || gated.has(id))
|
|
104
|
+
continue;
|
|
105
|
+
const list = tracked.get(id) ?? [];
|
|
104
106
|
if (!tracked.has(id))
|
|
105
107
|
tracked.set(id, list);
|
|
106
108
|
list.push(e.type === "tracked" ? { pid: Number(e.pid), ppid: 0, start: String(e.start) } : e.process);
|
|
107
109
|
}
|
|
108
110
|
}
|
|
111
|
+
state.execs = execs.filter(e => !fenced.has(e.exec));
|
|
112
|
+
state.gates = gates.filter(e => !gated.has(e.id));
|
|
113
|
+
if (!state.execs.length)
|
|
114
|
+
retired.clear();
|
|
109
115
|
return state;
|
|
110
116
|
}
|
|
111
117
|
/** P23, F1, F2: Every K1 re-fence retired identities and retry failed fences (executions and gates without an outcome)
|
|
@@ -113,17 +119,27 @@ export function indexSweep(journal) {
|
|
|
113
119
|
export async function sweepExecutions(journals, containment, hooks = {}) {
|
|
114
120
|
const targets = [];
|
|
115
121
|
for (const journal of journals) {
|
|
116
|
-
const
|
|
122
|
+
const seed = journal.loaded === false ? hooks.seeded?.(journal) : undefined;
|
|
123
|
+
if (seed) {
|
|
124
|
+
for (const exec of seed)
|
|
125
|
+
targets.push({ journal, exec, call: exec.slice(0, exec.lastIndexOf("#")), fenced: true, failed: !!hooks.failing?.(exec), tracked: [] });
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const { fenced, retired, failed, gated, tracked, execs, gates } = indexSweep(journal);
|
|
117
129
|
// A gate whose recovery fence failed has no outcome yet; it is retried here until its processes are gone.
|
|
118
130
|
for (const e of gates) {
|
|
119
131
|
const id = String(e.id);
|
|
120
132
|
if (e.type === "gate-intent" && !gated.has(id) && (failed.has(id) || hooks.failing?.(id)))
|
|
121
133
|
targets.push({ journal, exec: id, call: String(e.call), fenced: false, failed: true, tracked: tracked.get(id) ?? [] });
|
|
122
134
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
135
|
+
const ordered = [
|
|
136
|
+
...execs.map(e => ({ exec: String(e.exec), call: String(e.call), order: e.seq, fenced: false })),
|
|
137
|
+
...[...fenced].map(([id, order]) => { const exec = String(id); return { exec, call: exec.slice(0, exec.lastIndexOf("#")), order, fenced: true }; }),
|
|
138
|
+
].sort((a, b) => a.order - b.order);
|
|
139
|
+
for (const e of ordered) {
|
|
140
|
+
const isFailed = failed.has(e.exec) || !!hooks.failing?.(e.exec);
|
|
141
|
+
if (e.fenced || retired.has(e.call) || isFailed)
|
|
142
|
+
targets.push({ journal, exec: e.exec, call: e.call, fenced: e.fenced, failed: isFailed, tracked: e.fenced ? [] : tracked.get(e.exec) ?? [] });
|
|
127
143
|
}
|
|
128
144
|
}
|
|
129
145
|
if (!targets.length)
|
|
@@ -11,8 +11,11 @@
|
|
|
11
11
|
// restart{rid,force,reason?,initiator?,from?,live}: accepted restart; the next start consumes its status provenance.
|
|
12
12
|
// Old records lack reason/initiator/from and remain readable (A1).
|
|
13
13
|
// writer-hold/writer-release{root,call}: the writer lock of a worktree root, held by one call until it ends.
|
|
14
|
-
import { foldExhaustion } from "./providers.js";
|
|
14
|
+
import { EXHAUSTION_ENTRY_TYPES, foldExhaustion } from "./providers.js";
|
|
15
15
|
import { isEntry } from "../types.js";
|
|
16
|
+
/** Entry types consumed by applyLedger (excluding fold bookkeeping), shared with filtered readers. */
|
|
17
|
+
export const LEDGER_ENTRY_TYPES = ['hold', 'release', 'switch-observed', 'skip', 'config', 'config-rejected',
|
|
18
|
+
'restart', 'orchestrator', 'recovered', 'writer-hold', 'writer-release', 'orchestrator-exit', ...EXHAUSTION_ENTRY_TYPES];
|
|
16
19
|
export function emptyLedger() {
|
|
17
20
|
return { seen: 0, held: new Map(), writers: new Map(), observed: new Set(), skips: new Map(), exhausted: new Map() };
|
|
18
21
|
}
|
|
@@ -12,7 +12,7 @@ import { realpathSync } from 'node:fs';
|
|
|
12
12
|
import { join, resolve } from 'node:path';
|
|
13
13
|
import { binDir, dsaHome, orchLedger, orchLock } from "../paths.js";
|
|
14
14
|
import { removeStaleTemps, writeShim } from "../platform/lease.js";
|
|
15
|
-
import { launchOrchestrator, resolvePi } from "../platform/launch.js";
|
|
15
|
+
import { launchOrchestrator, PER_CALL_ENV, resolvePi } from "../platform/launch.js";
|
|
16
16
|
import { openJournal } from "../kernel/journal.js";
|
|
17
17
|
import { OsLock } from "../platform/lock.js";
|
|
18
18
|
import { captureStart } from "../platform/proctable.js";
|
|
@@ -23,7 +23,9 @@ import { packageVersion } from "../version.js";
|
|
|
23
23
|
* applied restart request ended it (the caller starts the successor once the lock is released). */
|
|
24
24
|
export async function main(options = {}) {
|
|
25
25
|
// Serves every session: whichever pi session started it, its children and their CLI runs must not name that session.
|
|
26
|
-
|
|
26
|
+
// Nor any call's identity, should it have been started from inside one (its processes inherit this environment).
|
|
27
|
+
for (const name of PER_CALL_ENV)
|
|
28
|
+
delete process.env[name];
|
|
27
29
|
const home = options.home ?? dsaHome();
|
|
28
30
|
await mkdir(home, { recursive: true });
|
|
29
31
|
const lock = await new OsLock().tryAcquire(orchLock(home));
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** Entry types consumed by foldExhaustion, shared with filtered ledger readers. */
|
|
2
|
+
export const EXHAUSTION_ENTRY_TYPES = ['provider-exhausted', 'provider-available', 'provider-probe', 'release'];
|
|
1
3
|
/** Apply one orchestrator ledger entry to the map of used-up providers. */
|
|
2
4
|
export function foldExhaustion(exhausted, e) {
|
|
3
5
|
const provider = String(e.provider ?? e.pool ?? "");
|