pi-durable-subagents 1.0.41 → 1.0.43
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 +43 -0
- package/README.md +29 -1
- package/dist/agent/main/snapshots.js +24 -1
- package/dist/agent/main/tool.js +3 -2
- package/dist/agent/main.js +5 -11
- package/dist/cli/control.js +20 -10
- package/dist/cli/main.js +13 -3
- package/dist/cli/requests.js +51 -32
- package/dist/events/fence.js +2 -0
- package/dist/events/pump.js +6 -2
- package/dist/events/waiting.js +12 -2
- package/dist/kernel/journal.js +294 -52
- package/dist/kernel/lifecycle.js +66 -23
- package/dist/kernel/mailbox.js +51 -32
- package/dist/kernel/overlay.js +47 -0
- package/dist/orchestrator/engine.js +228 -35
- package/dist/orchestrator/executor/effects/gate.js +10 -3
- package/dist/orchestrator/executor/effects/index.js +2 -1
- package/dist/orchestrator/executor/index.js +114 -40
- package/dist/orchestrator/executor/indexes.js +34 -0
- package/dist/orchestrator/executor/recovered.js +85 -0
- package/dist/orchestrator/executor/session.js +4 -0
- package/dist/orchestrator/executor/sweep.js +41 -9
- package/dist/orchestrator/ledger.js +12 -4
- package/dist/orchestrator/main.js +5 -2
- package/dist/orchestrator/providers.js +2 -0
- package/dist/orchestrator/reader-ledger.js +13 -3
- package/dist/orchestrator/settled.js +142 -0
- package/dist/orchestrator/snapshot.js +91 -11
- package/dist/orchestrator/store.js +248 -39
- package/dist/requests.js +41 -5
- package/dist/ui/tool.js +5 -3
- package/dist/ui/view.js +20 -8
- package/package.json +1 -1
|
@@ -6,6 +6,7 @@ import { publishFile } from "../../../kernel/mailbox.js";
|
|
|
6
6
|
import { callDir } from "../../../paths.js";
|
|
7
7
|
import { validate } from "../../../agent/child/schema.js";
|
|
8
8
|
import { fenceAttentionResolved, recordFenceFailure, recordOnce } from "../sweep.js";
|
|
9
|
+
import { entriesOf } from "../indexes.js";
|
|
9
10
|
const tracked = (journal, id) => journal.entries().filter(e => e.type === "gate-tracked" && e.id === id).map(e => e.process);
|
|
10
11
|
// Calls parked on an unfenced gate, woken when the sweep records the gate's outcome.
|
|
11
12
|
const parked = new Map();
|
|
@@ -63,12 +64,18 @@ async function fenceGate(journal, intent, containment) {
|
|
|
63
64
|
/** P30, A5, F1: Fence unresolved gate identities before recording their outcome as unknown; a gate whose fence fails
|
|
64
65
|
* never fails recovery: it stays without an outcome and the executor sweep retries it every K1. */
|
|
65
66
|
export async function recoverGates(journal, containment) {
|
|
66
|
-
|
|
67
|
+
const intents = entriesOf(journal, "gate-intent");
|
|
68
|
+
if (!intents.length)
|
|
69
|
+
return;
|
|
70
|
+
const outcomes = new Set(entriesOf(journal, "gate").map(e => String(e.id)));
|
|
71
|
+
for (const intent of intents) {
|
|
67
72
|
const id = String(intent.id);
|
|
68
|
-
if (
|
|
73
|
+
if (outcomes.has(id))
|
|
69
74
|
continue;
|
|
70
|
-
if (await fenceGate(journal, intent, containment))
|
|
75
|
+
if (await fenceGate(journal, intent, containment)) {
|
|
71
76
|
await gateRetired(journal, id);
|
|
77
|
+
outcomes.add(id);
|
|
78
|
+
}
|
|
72
79
|
}
|
|
73
80
|
}
|
|
74
81
|
function apply(result, record) {
|
|
@@ -20,7 +20,8 @@ export default function createEffects(ledgers, containment = serialContainment()
|
|
|
20
20
|
return { cwd };
|
|
21
21
|
}),
|
|
22
22
|
beforeSeal: (t, exec, result, ctl) => serial(t.callId, async () => {
|
|
23
|
-
|
|
23
|
+
// A refused call did no work: no gate, no output (the executor does not call this for one either).
|
|
24
|
+
if (t.refusal !== undefined || ctl.signal.aborted || ["stopped", "timeout", "budget"].includes(result.status))
|
|
24
25
|
return result;
|
|
25
26
|
const intent = t.journal.entries().find(e => e.type === "wt-intent" && e.call === t.callId);
|
|
26
27
|
const gated = await runGate(t, ledgers.home, intent ? String(intent.path) : t.cwd, exec, result, ctl.signal, containment);
|
|
@@ -16,7 +16,7 @@ import { delimiter, dirname, join } from "node:path";
|
|
|
16
16
|
import { fileURLToPath } from "node:url";
|
|
17
17
|
import { CT, JT, attentionEntries, isEntry } from "../../types.js";
|
|
18
18
|
import { binDir, callDir, callInbox, callSession, journalPath, outboxRoot } from "../../paths.js";
|
|
19
|
-
import { readJournalSnapshot } from "../../kernel/journal.js";
|
|
19
|
+
import { readJournalSnapshot, syncDirectory } from "../../kernel/journal.js";
|
|
20
20
|
import { Outbox } from "../../kernel/mailbox.js";
|
|
21
21
|
import { contentHash, forwardRid } from "../../kernel/ids.js";
|
|
22
22
|
import { capacity, seal } from "../../kernel/guards.js";
|
|
@@ -30,11 +30,12 @@ import { SessionFold, answerKey, digestOpenQuestion, supersededBy } from "./dige
|
|
|
30
30
|
import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
|
|
31
31
|
import { evidence, fatalProviderError, quotaExhausted, refusedByProvider, forgetSession, readSessionState, receiptId, sessionModel } from "./session.js";
|
|
32
32
|
import { activeTotal } from "./time.js";
|
|
33
|
-
import { entriesOf, trackedState, usageIds } from "./indexes.js";
|
|
33
|
+
import { callEntries, entriesOf, forwardsTo, trackedState, usageIds } from "./indexes.js";
|
|
34
|
+
import { RECOVERED, RECOVERY_VERSION, completeCalls } from "./recovered.js";
|
|
34
35
|
import { observeExecution } from "./observe.js";
|
|
35
36
|
import { availableMemory } from "./memory.js";
|
|
36
37
|
import { reached, sessionUsage, totalUsage } from "./usage.js";
|
|
37
|
-
import { indexSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
|
|
38
|
+
import { indexSweep, seededSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
|
|
38
39
|
import { gateRetired } from "./effects/gate.js";
|
|
39
40
|
import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
|
|
40
41
|
import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidates } from "./pool.js";
|
|
@@ -49,9 +50,10 @@ const ignoreMissing = (error) => { if (error.code !== "ENOENT")
|
|
|
49
50
|
const callOf = (exec) => exec.slice(0, exec.lastIndexOf("#"));
|
|
50
51
|
const shutdownError = () => Object.assign(new Error("executor shutdown; call resumes on recovery"), { name: "ExecutorShutdown" });
|
|
51
52
|
const extension = fileURLToPath(new URL(`../../agent/extension.${import.meta.url.endsWith(".ts") ? "ts" : "js"}`, import.meta.url));
|
|
52
|
-
const entriesFor =
|
|
53
|
+
const entriesFor = callEntries;
|
|
53
54
|
const current = (journal, call) => entriesFor(journal, call).findLast(e => e.type === JT.exec)?.exec;
|
|
54
55
|
const sealed = (journal, call) => entriesFor(journal, call).find(e => e.type === JT.sealed)?.result;
|
|
56
|
+
const retiredCall = (journal, call) => entriesFor(journal, call).some(e => e.type === "retired");
|
|
55
57
|
const has = (journal, type, exec) => entriesOf(journal, type, exec).length > 0;
|
|
56
58
|
/** The run of executions of `call` whose launches failed for a reason of the environment, ending at `exec`: its first
|
|
57
59
|
* execution and the one before it (absent for the call's first). Undefined when `exec` did not fail so. */
|
|
@@ -100,6 +102,7 @@ export function requestedModel(journal, call, followUp) {
|
|
|
100
102
|
}
|
|
101
103
|
return wanted;
|
|
102
104
|
}
|
|
105
|
+
const callWid = (call) => /^(.*)@\d+\/.*@\d+$/.exec(call)?.[1];
|
|
103
106
|
function address(call) {
|
|
104
107
|
const match = /^(.*)@(\d+)\/(.*)@(\d+)$/.exec(call);
|
|
105
108
|
if (!match)
|
|
@@ -152,9 +155,11 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
152
155
|
// F1: execs whose fence failed in this process; they are retried only by the sweep.
|
|
153
156
|
const failing = new Set();
|
|
154
157
|
// F2: a sweep error is transient: report it and retry at the next K1; it never blocks dispatch.
|
|
158
|
+
/** The sweep state of settled journals not decoded (recover with `settled`). */
|
|
159
|
+
const seeds = new WeakMap();
|
|
155
160
|
const sweepTimer = setInterval(() => {
|
|
156
161
|
if (!sweeping)
|
|
157
|
-
sweeping = sweepExecutions([...journals.values()].filter(j => !j.closed), containment, { failing: exec => failing.has(exec), fenced: swept, failed: fenceFailed })
|
|
162
|
+
sweeping = sweepExecutions([...journals.values()].filter(j => !j.closed), containment, { failing: exec => failing.has(exec), fenced: swept, failed: fenceFailed, seeded: journal => seeds.get(journal) })
|
|
158
163
|
.catch(error => console.error(`durable-subagents: sweep failed, retrying in K1: ${String(error)}`)).finally(() => { sweeping = undefined; });
|
|
159
164
|
}, options.sweepMs ?? 30000);
|
|
160
165
|
sweepTimer.unref();
|
|
@@ -346,13 +351,37 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
346
351
|
done.add(rid);
|
|
347
352
|
}
|
|
348
353
|
}
|
|
354
|
+
/** Remove a sealed call's inbox files, then sync the directory: the removals are durable before anything recorded
|
|
355
|
+
* after them (a `recovered` receipt). The directory is synced whenever it exists, also when it is already empty (an
|
|
356
|
+
* earlier attempt may have removed the files and failed to sync); a failure rejects (the caller records no receipt). */
|
|
349
357
|
async function collectSealed(call) {
|
|
350
358
|
const sender = await outbox, dir = inbox(call);
|
|
351
|
-
|
|
359
|
+
let exists = true;
|
|
360
|
+
for (const name of await readdir(dir).catch(error => { ignoreMissing(error); exists = false; return []; })) {
|
|
352
361
|
if (name.endsWith(".json") && !name.startsWith("."))
|
|
353
362
|
await sender.markResolved(name.slice(0, -5));
|
|
354
363
|
await rm(join(dir, name), { force: true });
|
|
355
364
|
}
|
|
365
|
+
if (exists)
|
|
366
|
+
await (options.syncDirectory ?? syncDirectory)(dir);
|
|
367
|
+
}
|
|
368
|
+
/** Sealed or retired calls a batched recovery read, finished by finishRecovery. */
|
|
369
|
+
const unfinished = [];
|
|
370
|
+
/** The end of the recovery of sealed or retired calls, after republication: the inbox cleanup of the sealed ones (E2),
|
|
371
|
+
* then each call's `recovered` receipt (recovered.ts), once. A failed cleanup records none: the next start recovers
|
|
372
|
+
* the call again. */
|
|
373
|
+
async function finishCalls(journal, calls) {
|
|
374
|
+
for (const call of calls) {
|
|
375
|
+
// F1: an execution whose fence failed is fenced again by every start (and the sweep) until it is: no receipt yet.
|
|
376
|
+
let clean = entriesFor(journal, call).every(e => e.type !== JT.exec || has(journal, JT.fenced, String(e.exec)));
|
|
377
|
+
if (clean && sealed(journal, call))
|
|
378
|
+
await collectSealed(call).catch(error => { clean = false; console.error(`durable-subagents: inbox cleanup of ${call} failed: ${String(error)}`); });
|
|
379
|
+
if (clean)
|
|
380
|
+
await serial(async () => {
|
|
381
|
+
if (!journal.closed && !completeCalls(journal, address(call).wid).has(call))
|
|
382
|
+
await journal.append(RECOVERED, { call, v: RECOVERY_VERSION });
|
|
383
|
+
});
|
|
384
|
+
}
|
|
356
385
|
}
|
|
357
386
|
/** P7, P27: Record forward-delivered once when a forward's child receipt is first observed; serial sections only. */
|
|
358
387
|
/** The reply to a model send says which model and when it applies (orchestrator ledger `send-note`, once per rid). */
|
|
@@ -379,13 +408,13 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
379
408
|
const entries = await readCall(journal, call);
|
|
380
409
|
await forwardsDelivered(journal, call, entries);
|
|
381
410
|
const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
|
|
382
|
-
for (const e of journal
|
|
383
|
-
if (!receipts.has(String(e.rid2)) && !journal
|
|
411
|
+
for (const e of [...forwardsTo(journal, call)]) {
|
|
412
|
+
if (!receipts.has(String(e.rid2)) && !entriesOf(journal, "forward-retired").some(r => r.rid2 === e.rid2)) {
|
|
384
413
|
// A notify the call never received is not lost: it becomes a pending note (before its forward is retired, so a
|
|
385
414
|
// crash in between finds the forward open again and the note is written once). A withdrawn one is not.
|
|
386
|
-
const envelope = e.envelope
|
|
387
|
-
const withdrawn =
|
|
388
|
-
if (envelope.kind === "notify" && !withdrawn && !
|
|
415
|
+
const envelope = e.envelope;
|
|
416
|
+
const withdrawn = forwardsTo(journal, call).some(r => r.envelope.kind === "withdraw" && r.envelope.body.rids?.includes(String(e.rid2)));
|
|
417
|
+
if (envelope.kind === "notify" && !withdrawn && !entriesOf(journal, PENDING_NOTE).some(r => r.rid === e.rid))
|
|
389
418
|
await journal.append(PENDING_NOTE, { rid: e.rid, call, key: address(call).key, message: String(envelope.body?.message ?? "") });
|
|
390
419
|
// A follow-up the call never took is not lost either: the orchestrator opens the next generation with it (or a
|
|
391
420
|
// later follow-up takes it along). A stop is final and drops it; a withdrawn one is gone.
|
|
@@ -410,7 +439,9 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
410
439
|
return hit;
|
|
411
440
|
}
|
|
412
441
|
const roots = worktreeRoots(), writes = new WorktreeIndex();
|
|
413
|
-
|
|
442
|
+
// A journal not decoded (a settled workflow) has no open reminder and only ended calls: nothing of it is indexed.
|
|
443
|
+
const indexed = () => writes.scan([...journals.values()].filter(j => j.loaded !== false));
|
|
444
|
+
const endedCall = (call) => writes.ended(call) || journals.get(callWid(call) ?? "")?.loaded === false;
|
|
414
445
|
const origin = (w) => writes.origin(w.journal) ?? orch.entries().find(e => e.type === JT.created && e.wid === address(w.call).wid)?.origin;
|
|
415
446
|
// Serial sections only: wrote and attention are durable before another writer or seal can interleave.
|
|
416
447
|
/** Remind of every pair of calls that wrote in `root` and have not ended, once per pair and journal. The index must be
|
|
@@ -451,7 +482,7 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
451
482
|
async function resolveWorktrees(call) {
|
|
452
483
|
for (const { id, journal, item } of indexed().open()) {
|
|
453
484
|
const pair = worktreeCalls(id);
|
|
454
|
-
if (call ? pair.includes(call) : pair.some(
|
|
485
|
+
if (call ? pair.includes(call) : pair.some(endedCall))
|
|
455
486
|
await journal.append(JT.attentionResolved, { id, rev: item.rev, resolution: "ended" });
|
|
456
487
|
}
|
|
457
488
|
}
|
|
@@ -474,7 +505,8 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
474
505
|
}
|
|
475
506
|
async function finish(journal, call, exec, result) {
|
|
476
507
|
const a = active.get(call);
|
|
477
|
-
|
|
508
|
+
// A refused call (CallTicket.refusal) runs none of the pre-seal effects (gate, output publication): it did no work.
|
|
509
|
+
if (a && a.ticket.refusal === undefined && !sealed(journal, call) && !["stopped", "timeout", "budget"].includes(result.status)) {
|
|
478
510
|
const started = Date.now(), prior = activeTotal(journal.entries(), call);
|
|
479
511
|
const check = async () => {
|
|
480
512
|
if (stopped(a))
|
|
@@ -1136,16 +1168,22 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1136
1168
|
await effects.afterSeal(t, result);
|
|
1137
1169
|
return result;
|
|
1138
1170
|
}
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1171
|
+
// A call that cannot run (CallTicket.refusal) or whose preparation failed is sealed failed without a child.
|
|
1172
|
+
let unprepared = t.refusal;
|
|
1173
|
+
if (unprepared === undefined)
|
|
1174
|
+
try {
|
|
1175
|
+
await continueSession(home, t, session);
|
|
1176
|
+
cwd = (await effects.prepare(t, { sessionPath: session })).cwd;
|
|
1177
|
+
}
|
|
1178
|
+
catch (error) {
|
|
1179
|
+
unprepared = String(error);
|
|
1180
|
+
}
|
|
1181
|
+
if (unprepared !== undefined) {
|
|
1144
1182
|
const exec = current(journal, t.callId) ?? `${t.callId}#1.1`;
|
|
1145
1183
|
if (!current(journal, t.callId))
|
|
1146
1184
|
await serial(() => journal.append(JT.exec, { call: t.callId, exec }));
|
|
1147
1185
|
await fence(journal, exec, { park: a });
|
|
1148
|
-
return finish(journal, t.callId, exec, makeResult("failed", "",
|
|
1186
|
+
return finish(journal, t.callId, exec, makeResult("failed", "", unprepared));
|
|
1149
1187
|
}
|
|
1150
1188
|
for (;;) {
|
|
1151
1189
|
const old = sealed(journal, t.callId);
|
|
@@ -1792,39 +1830,52 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1792
1830
|
}
|
|
1793
1831
|
}
|
|
1794
1832
|
},
|
|
1795
|
-
async recover(wid, journal) {
|
|
1833
|
+
async recover(wid, journal, options = {}) {
|
|
1796
1834
|
journals.set(wid, journal);
|
|
1835
|
+
// A settled workflow (orchestrator/settled.ts) not decoded: every call recovered; only the sweep needs its executions.
|
|
1836
|
+
if (journal.loaded === false && options.settled) {
|
|
1837
|
+
seeds.set(journal, seededSweep(options.settled.sweep));
|
|
1838
|
+
return { calls: 0, skipped: options.settled.calls };
|
|
1839
|
+
}
|
|
1797
1840
|
indexSweep(journal);
|
|
1798
|
-
|
|
1841
|
+
// Batched (the engine recovers every workflow, then calls finishRecovery): the steps that do not depend on the
|
|
1842
|
+
// workflow run once, in finishRecovery.
|
|
1843
|
+
if (!options.batch)
|
|
1844
|
+
await serial(() => resolveWorktrees());
|
|
1799
1845
|
await effects.recover(journal);
|
|
1800
|
-
|
|
1846
|
+
// A call whose recovery ran to its end before (and that nothing concerned since) is not read again: all its
|
|
1847
|
+
// executions were fenced and released, its session read, its forwards, attention and inbox settled.
|
|
1848
|
+
const complete = completeCalls(journal, wid), execs = entriesOf(journal, JT.exec).filter(e => !complete.has(String(e.call)));
|
|
1849
|
+
for (const e of execs) {
|
|
1801
1850
|
// F1: an exec whose fence fails stays unfenced and holding; its call parks until a sweep retires it.
|
|
1802
1851
|
const exec = String(e.exec);
|
|
1803
1852
|
if (await fence(journal, exec))
|
|
1804
1853
|
await release(exec);
|
|
1805
1854
|
}
|
|
1806
1855
|
// Writers that waited before the restart keep their order while their calls come back.
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
if (
|
|
1814
|
-
writerWaits.
|
|
1856
|
+
const waits = entriesOf(journal, "writer-wait");
|
|
1857
|
+
if (waits.length)
|
|
1858
|
+
for (const e of [...waits, ...entriesOf(journal, "writer-acquired"), ...entriesOf(journal, JT.sealed), ...entriesOf(journal, "retired")].sort((x, y) => x.seq - y.seq)) {
|
|
1859
|
+
const call = String(e.call);
|
|
1860
|
+
if (e.type === "writer-wait" && !writerWaits.has(call))
|
|
1861
|
+
writerWaits.set(call, { root: String(e.root), since: e.ts, recovered: Date.now() });
|
|
1862
|
+
else if (e.type === "writer-acquired" || e.type === JT.sealed || e.type === "retired") {
|
|
1863
|
+
const w = writerWaits.get(call);
|
|
1864
|
+
if (w?.recovered !== undefined)
|
|
1865
|
+
writerWaits.delete(call);
|
|
1866
|
+
}
|
|
1815
1867
|
}
|
|
1816
|
-
|
|
1817
|
-
const calls = new Set(journal.entries().filter(e => e.type === JT.exec).map(e => String(e.call)));
|
|
1868
|
+
const calls = new Set(execs.map(e => String(e.call)));
|
|
1818
1869
|
for (const call of calls) {
|
|
1819
1870
|
const session = await readCall(journal, call), values = sessionUsage(session, call);
|
|
1820
1871
|
await serial(async () => {
|
|
1821
1872
|
await repairConsumedAnswers(journal, call, session);
|
|
1822
1873
|
await forwardsDelivered(journal, call, session);
|
|
1823
|
-
const recorded = new Set(journal
|
|
1874
|
+
const recorded = new Set(entriesFor(journal, call).filter(e => e.type === "usage").map(e => e.id));
|
|
1824
1875
|
for (const u of values)
|
|
1825
1876
|
if (!recorded.has(u.id))
|
|
1826
1877
|
await journal.append("usage", { call, ...u });
|
|
1827
|
-
if (sealed(journal, call) || journal
|
|
1878
|
+
if (sealed(journal, call) || retiredCall(journal, call)) {
|
|
1828
1879
|
await retireForwards(journal, call);
|
|
1829
1880
|
await retireAttention(journal, call);
|
|
1830
1881
|
await unknownAttention(journal, call);
|
|
@@ -1838,13 +1889,36 @@ export default function createExecutor(ledgers, options = {}) {
|
|
|
1838
1889
|
if (!active.has(call))
|
|
1839
1890
|
forgetCall(call);
|
|
1840
1891
|
}
|
|
1841
|
-
|
|
1892
|
+
const retiredForwards = new Set(entriesOf(journal, "forward-retired").map(r => r.rid2));
|
|
1893
|
+
for (const e of entriesOf(journal, "forward").filter(e => !retiredForwards.has(e.rid2)))
|
|
1842
1894
|
await replayForward(e);
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1895
|
+
const ended = [...calls].filter(call => sealed(journal, call) || retiredCall(journal, call));
|
|
1896
|
+
if (options.batch)
|
|
1897
|
+
unfinished.push({ journal, calls: ended });
|
|
1898
|
+
else {
|
|
1899
|
+
await (await outbox).republishPending();
|
|
1900
|
+
await finishCalls(journal, ended);
|
|
1901
|
+
}
|
|
1902
|
+
return { calls: calls.size, skipped: new Set(entriesOf(journal, JT.exec).map(e => String(e.call))).size - calls.size };
|
|
1903
|
+
},
|
|
1904
|
+
async finishRecovery() {
|
|
1905
|
+
const batch = unfinished.splice(0);
|
|
1906
|
+
await serial(() => resolveWorktrees());
|
|
1907
|
+
const sender = await outbox;
|
|
1908
|
+
await sender.republishPending();
|
|
1909
|
+
// E2: republication may restore envelopes of sealed calls, also of calls skipped as complete; the seal resolves them.
|
|
1910
|
+
const destinations = sender.pendingDestinations();
|
|
1911
|
+
for (const call of destinations) {
|
|
1912
|
+
const wid = callWid(call), journal = wid === undefined ? undefined : journals.get(wid);
|
|
1913
|
+
if (wid !== undefined && journal && completeCalls(journal, wid).has(call) && sealed(journal, call))
|
|
1847
1914
|
await collectSealed(call).catch(error => console.error(`durable-subagents: inbox cleanup of ${call} failed: ${String(error)}`));
|
|
1915
|
+
}
|
|
1916
|
+
for (const { journal, calls } of batch)
|
|
1917
|
+
await finishCalls(journal, calls);
|
|
1918
|
+
},
|
|
1919
|
+
recovered(journal, call) {
|
|
1920
|
+
const wid = address(call).wid;
|
|
1921
|
+
return completeCalls(journal, wid).has(call) && ![...folded().writers.values()].some(w => w.call === call);
|
|
1848
1922
|
},
|
|
1849
1923
|
async retire(widRev) {
|
|
1850
1924
|
const journal = journals.get(widRev.slice(0, widRev.lastIndexOf("@")));
|
|
@@ -23,6 +23,40 @@ export function entriesOf(journal, type, exec) {
|
|
|
23
23
|
}
|
|
24
24
|
return (exec === undefined ? index.types.get(type) : index.execs.get(type)?.get(exec)) ?? [];
|
|
25
25
|
}
|
|
26
|
+
const keyedIndexes = new Map();
|
|
27
|
+
function keyed(journal, keyOf, key) {
|
|
28
|
+
let byJournal = keyedIndexes.get(keyOf);
|
|
29
|
+
if (!byJournal) {
|
|
30
|
+
byJournal = new WeakMap();
|
|
31
|
+
keyedIndexes.set(keyOf, byJournal);
|
|
32
|
+
}
|
|
33
|
+
let index = byJournal.get(journal);
|
|
34
|
+
if (!index) {
|
|
35
|
+
index = { count: 0, keys: new Map() };
|
|
36
|
+
byJournal.set(journal, index);
|
|
37
|
+
}
|
|
38
|
+
const entries = journal.committed?.() ?? journal.entries();
|
|
39
|
+
while (index.count < entries.length) {
|
|
40
|
+
const e = entries[index.count++], k = keyOf(e);
|
|
41
|
+
if (k === undefined)
|
|
42
|
+
continue;
|
|
43
|
+
const bucket = index.keys.get(k);
|
|
44
|
+
if (bucket)
|
|
45
|
+
bucket.push(e);
|
|
46
|
+
else
|
|
47
|
+
index.keys.set(k, [e]);
|
|
48
|
+
}
|
|
49
|
+
return index.keys.get(key) ?? [];
|
|
50
|
+
}
|
|
51
|
+
const byCall = (e) => typeof e.call === "string" ? e.call : undefined;
|
|
52
|
+
const byDest = (e) => e.type === "forward" && typeof e.dest === "string" ? e.dest : undefined;
|
|
53
|
+
const byRid2 = (e) => e.type === "forward" && typeof e.rid2 === "string" ? e.rid2 : undefined;
|
|
54
|
+
/** The entries whose `call` field names `call`, in journal order. */
|
|
55
|
+
export function callEntries(journal, call) { return keyed(journal, byCall, call); }
|
|
56
|
+
/** The `forward` entries whose destination is `call`, in journal order. */
|
|
57
|
+
export function forwardsTo(journal, call) { return keyed(journal, byDest, call); }
|
|
58
|
+
/** The `forward` entry with this forwarded identity (the first, should a replay have recorded it twice). */
|
|
59
|
+
export function forwardOf(journal, rid2) { return keyed(journal, byRid2, rid2)[0]; }
|
|
26
60
|
const identities = new WeakMap();
|
|
27
61
|
export function trackedState(journal, exec) {
|
|
28
62
|
let byExec = identities.get(journal);
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { entriesOf, forwardOf } from "./indexes.js";
|
|
2
|
+
/** Bump whenever the recovery of a sealed or retired call gains a step: every call is then recovered once more. */
|
|
3
|
+
export const RECOVERY_VERSION = 1;
|
|
4
|
+
export const RECOVERED = "recovered";
|
|
5
|
+
const CALL = /^(.*)@(\d+)\/(.*)@(\d+)$/;
|
|
6
|
+
const digit = (code) => code >= 48 && code <= 57;
|
|
7
|
+
/** The calls among `among` (call ids of workflow `wid`) that entry `e` concerns: one whose id appears in any string of
|
|
8
|
+
* the entry (fields such as call, exec, dest, target, from, an attention item or its id; an id followed by a digit is a
|
|
9
|
+
* longer generation, not this one), a `call`/`generation` of the same key, and the destination of the forward a
|
|
10
|
+
* `rid2` names. Receipts themselves concern nothing. Conservative: a false match only costs one more read. */
|
|
11
|
+
export function concernedCalls(e, wid, among, forwardDest, lengths = [...new Set([...among].map(c => c.length))]) {
|
|
12
|
+
const found = new Set();
|
|
13
|
+
if (e.type === RECOVERED || !among.size)
|
|
14
|
+
return found;
|
|
15
|
+
const marker = `${wid}@`;
|
|
16
|
+
const visit = (value) => {
|
|
17
|
+
if (typeof value === "string") {
|
|
18
|
+
for (let p = value.indexOf(marker); p >= 0; p = value.indexOf(marker, p + 1))
|
|
19
|
+
for (const length of lengths) {
|
|
20
|
+
if (p + length > value.length)
|
|
21
|
+
continue;
|
|
22
|
+
const id = value.substr(p, length);
|
|
23
|
+
if (among.has(id) && !digit(value.charCodeAt(p + length)))
|
|
24
|
+
found.add(id);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
else if (Array.isArray(value))
|
|
28
|
+
for (const v of value)
|
|
29
|
+
visit(v);
|
|
30
|
+
else if (value && typeof value === "object")
|
|
31
|
+
for (const v of Object.values(value))
|
|
32
|
+
visit(v);
|
|
33
|
+
};
|
|
34
|
+
visit(e);
|
|
35
|
+
if ((e.type === "generation" || e.type === "call") && e.key !== undefined)
|
|
36
|
+
for (const call of among)
|
|
37
|
+
if (CALL.exec(call)?.[3] === String(e.key))
|
|
38
|
+
found.add(call);
|
|
39
|
+
if (typeof e.rid2 === "string" && forwardDest) {
|
|
40
|
+
const dest = forwardDest(e.rid2);
|
|
41
|
+
if (dest !== undefined && among.has(dest))
|
|
42
|
+
found.add(dest);
|
|
43
|
+
}
|
|
44
|
+
return found;
|
|
45
|
+
}
|
|
46
|
+
/** Whether entry `e` of workflow `wid`'s journal concerns `call` (concernedCalls for one call). */
|
|
47
|
+
export function concerns(e, call, forwardDest) {
|
|
48
|
+
const wid = CALL.exec(call)?.[1] ?? call;
|
|
49
|
+
return concernedCalls(e, wid, new Set([call]), forwardDest).size > 0;
|
|
50
|
+
}
|
|
51
|
+
const complete = new WeakMap();
|
|
52
|
+
/** The calls of workflow `wid` whose recovery is complete: their latest `recovered` entry has the current version and
|
|
53
|
+
* no later entry concerns them. One pass over the entries after the earliest such receipt; cached per journal length. */
|
|
54
|
+
export function completeCalls(journal, wid) {
|
|
55
|
+
const entries = journal.committed?.() ?? journal.entries(), cached = complete.get(journal);
|
|
56
|
+
if (cached && cached.length === entries.length)
|
|
57
|
+
return cached.calls;
|
|
58
|
+
const receipts = new Map();
|
|
59
|
+
for (const r of entriesOf(journal, RECOVERED)) {
|
|
60
|
+
const call = String(r.call);
|
|
61
|
+
if (r.v === RECOVERY_VERSION)
|
|
62
|
+
receipts.set(call, r.seq);
|
|
63
|
+
else
|
|
64
|
+
receipts.delete(call);
|
|
65
|
+
}
|
|
66
|
+
const calls = new Set(receipts.keys());
|
|
67
|
+
if (calls.size) {
|
|
68
|
+
const lengths = [...new Set([...calls].map(c => c.length))], dest = (rid2) => {
|
|
69
|
+
const d = forwardOf(journal, rid2)?.dest;
|
|
70
|
+
return typeof d === "string" ? d : undefined;
|
|
71
|
+
};
|
|
72
|
+
const from = Math.min(...receipts.values());
|
|
73
|
+
// seq is dense from 1: the entries after the earliest receipt start at index `from`.
|
|
74
|
+
for (let i = entries[from - 1]?.seq === from ? from : 0; i < entries.length && calls.size; i++) {
|
|
75
|
+
const e = entries[i];
|
|
76
|
+
if (e.seq <= from)
|
|
77
|
+
continue;
|
|
78
|
+
for (const call of concernedCalls(e, wid, calls, dest, lengths))
|
|
79
|
+
if (receipts.get(call) < e.seq)
|
|
80
|
+
calls.delete(call);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
complete.set(journal, { length: entries.length, calls });
|
|
84
|
+
return calls;
|
|
85
|
+
}
|
|
@@ -11,6 +11,7 @@ const EMPTY = { entries: [], corrupt: [] };
|
|
|
11
11
|
/** C5, E4, F3: Read complete native entries incrementally; an unfinished trailing line is ignored and a malformed
|
|
12
12
|
* complete line is skipped (pi's own loader does the same), reported by its 1-based line number in `corrupt`. */
|
|
13
13
|
export async function readSessionState(path) {
|
|
14
|
+
reads++;
|
|
14
15
|
const file = await open(path, "r").catch(error => { if (error.code === "ENOENT")
|
|
15
16
|
return undefined; throw error; });
|
|
16
17
|
if (!file) {
|
|
@@ -63,6 +64,9 @@ export async function readSessionState(path) {
|
|
|
63
64
|
await file.close();
|
|
64
65
|
}
|
|
65
66
|
}
|
|
67
|
+
let reads = 0;
|
|
68
|
+
/** How many session reads (readSessionState calls) this process made: a diagnostic, e.g. of what a recovery read. */
|
|
69
|
+
export function sessionReads() { return reads; }
|
|
66
70
|
/** C5: Complete native session entries (see readSessionState). The result is shared: never mutate it. */
|
|
67
71
|
export async function readSession(path) {
|
|
68
72
|
return (await readSessionState(path)).entries;
|
|
@@ -61,11 +61,17 @@ export async function fenceAttentionResolved(journal, id) {
|
|
|
61
61
|
await journal.append(JT.attentionResolved, { id: `fence:${id}`, rev: item.rev, resolution: "fenced" });
|
|
62
62
|
}
|
|
63
63
|
const sweeps = new WeakMap();
|
|
64
|
+
export function sweepSeed(journal) {
|
|
65
|
+
return [...indexSweep(journal).fenced].sort((a, b) => a[1] - b[1]).map(([exec]) => String(exec));
|
|
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; }
|
|
64
70
|
/** A1: Fold old history during recovery, so the first sweep does not allocate it on the timer path. */
|
|
65
71
|
export function indexSweep(journal) {
|
|
66
72
|
let state = sweeps.get(journal);
|
|
67
73
|
if (!state) {
|
|
68
|
-
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: [] };
|
|
69
75
|
sweeps.set(journal, state);
|
|
70
76
|
}
|
|
71
77
|
const { fenced, retired, failed, gated, tracked, execs, gates } = state, entries = journal.entries();
|
|
@@ -75,21 +81,37 @@ export function indexSweep(journal) {
|
|
|
75
81
|
execs.push(e);
|
|
76
82
|
else if (e.type === "gate-intent")
|
|
77
83
|
gates.push(e);
|
|
78
|
-
else if (e.type === JT.fenced)
|
|
79
|
-
|
|
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));
|
|
80
92
|
else if (e.type === "retired")
|
|
81
93
|
retired.add(e.call);
|
|
82
94
|
else if (e.type === "fence-failed")
|
|
83
95
|
failed.add(e.exec);
|
|
84
|
-
else if (e.type === "gate")
|
|
96
|
+
else if (e.type === "gate") {
|
|
85
97
|
gated.add(e.id);
|
|
98
|
+
tracked.delete(String(e.id));
|
|
99
|
+
failed.delete(e.id);
|
|
100
|
+
}
|
|
86
101
|
else if (e.type === "tracked" || e.type === "gate-tracked") {
|
|
87
|
-
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) ?? [];
|
|
88
106
|
if (!tracked.has(id))
|
|
89
107
|
tracked.set(id, list);
|
|
90
108
|
list.push(e.type === "tracked" ? { pid: Number(e.pid), ppid: 0, start: String(e.start) } : e.process);
|
|
91
109
|
}
|
|
92
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();
|
|
93
115
|
return state;
|
|
94
116
|
}
|
|
95
117
|
/** P23, F1, F2: Every K1 re-fence retired identities and retry failed fences (executions and gates without an outcome)
|
|
@@ -97,6 +119,12 @@ export function indexSweep(journal) {
|
|
|
97
119
|
export async function sweepExecutions(journals, containment, hooks = {}) {
|
|
98
120
|
const targets = [];
|
|
99
121
|
for (const journal of journals) {
|
|
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
|
+
}
|
|
100
128
|
const { fenced, retired, failed, gated, tracked, execs, gates } = indexSweep(journal);
|
|
101
129
|
// A gate whose recovery fence failed has no outcome yet; it is retried here until its processes are gone.
|
|
102
130
|
for (const e of gates) {
|
|
@@ -104,10 +132,14 @@ export async function sweepExecutions(journals, containment, hooks = {}) {
|
|
|
104
132
|
if (e.type === "gate-intent" && !gated.has(id) && (failed.has(id) || hooks.failing?.(id)))
|
|
105
133
|
targets.push({ journal, exec: id, call: String(e.call), fenced: false, failed: true, tracked: tracked.get(id) ?? [] });
|
|
106
134
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
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) ?? [] });
|
|
111
143
|
}
|
|
112
144
|
}
|
|
113
145
|
if (!targets.length)
|
|
@@ -5,13 +5,17 @@
|
|
|
5
5
|
// provider-*: used-up usage windows (providers.ts).
|
|
6
6
|
// config{hash,config}: the orchestrator settings in effect from here; config-rejected{error,hash?}: a change of
|
|
7
7
|
// config.json refused, while the earlier settings stay (cleared by the next config record).
|
|
8
|
-
// orchestrator{version,pid,pi?} / orchestrator-exit{pid,reason?,signal?,error?}: the orchestrator running (its
|
|
9
|
-
// version, the pi it launches) and its exit (why: idle, restart, signal, error).
|
|
8
|
+
// orchestrator{version,pid,pi?,recovery?} / orchestrator-exit{pid,reason?,signal?,error?}: the orchestrator running (its
|
|
9
|
+
// package version, the pi it launches) and its exit (why: idle, restart, signal, error). `recovery`: it recovers the
|
|
10
|
+
// home's workflows before it dispatches anything, until its recovered{pid,ms,workflows,calls,skipped}.
|
|
10
11
|
// restart{rid,force,reason?,initiator?,from?,live}: accepted restart; the next start consumes its status provenance.
|
|
11
12
|
// Old records lack reason/initiator/from and remain readable (A1).
|
|
12
13
|
// writer-hold/writer-release{root,call}: the writer lock of a worktree root, held by one call until it ends.
|
|
13
|
-
import { foldExhaustion } from "./providers.js";
|
|
14
|
+
import { EXHAUSTION_ENTRY_TYPES, foldExhaustion } from "./providers.js";
|
|
14
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];
|
|
15
19
|
export function emptyLedger() {
|
|
16
20
|
return { seen: 0, held: new Map(), writers: new Map(), observed: new Set(), skips: new Map(), exhausted: new Map() };
|
|
17
21
|
}
|
|
@@ -37,9 +41,13 @@ export function applyLedger(state, e) {
|
|
|
37
41
|
else if (e.type === "restart")
|
|
38
42
|
state.pendingRestart = e.force === true ? { ts: e.ts, reason: e.reason, initiator: e.initiator, from: e.from } : undefined;
|
|
39
43
|
else if (isEntry(e, "orchestrator")) {
|
|
40
|
-
state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.pi !== undefined ? { pi: e.pi } : {}), ...(e.restart === true ? { restart: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
|
|
44
|
+
state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.pi !== undefined ? { pi: e.pi } : {}), ...(e.restart === true ? { restart: true } : {}), ...(e.recovery === true ? { recovery: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
|
|
41
45
|
delete state.pendingRestart;
|
|
42
46
|
}
|
|
47
|
+
else if (isEntry(e, "recovered")) {
|
|
48
|
+
if (state.orchestrator && state.orchestrator.pid === Number(e.pid))
|
|
49
|
+
state.orchestrator.recovered = { ts: e.ts, ms: Number(e.ms) };
|
|
50
|
+
}
|
|
43
51
|
else if (e.type === "writer-hold") {
|
|
44
52
|
if (!state.writers.has(String(e.root)))
|
|
45
53
|
state.writers.set(String(e.root), { call: String(e.call), ts: e.ts });
|
|
@@ -61,7 +61,9 @@ export async function main(options = {}) {
|
|
|
61
61
|
const pi = resolvePi(process.env).path ?? resolvePi({ PATH: process.env.PATH }).path;
|
|
62
62
|
if (!pi)
|
|
63
63
|
console.error('durable-subagents: pi not found (DSA_PI_BIN unset or not executable, not on PATH); subagents launch `pi` from PATH');
|
|
64
|
-
|
|
64
|
+
// `recovery: true` announces the `recovered` entry this pid appends once its recovery ends (none if it fails first).
|
|
65
|
+
await ledgers.orch.append('orchestrator', { version: packageVersion(), pid: process.pid, ...(start ? { start } : {}), restart: true, pi: pi ?? null, recovery: true });
|
|
66
|
+
const recoveryStarted = performance.now();
|
|
65
67
|
const factory = options.executor ?? (await import(__rewriteRelativeImportExtension(new URL(import.meta.url.endsWith('.ts') ? './executor/index.ts' : './executor/index.js', import.meta.url).href))).default;
|
|
66
68
|
const executor = factory(ledgers, pi ? { pi } : {});
|
|
67
69
|
engine = new Engine(ledgers, executor, options);
|
|
@@ -72,7 +74,8 @@ export async function main(options = {}) {
|
|
|
72
74
|
watcher = watchConfig({ path: configPath(home), stamp, config, orch: ledgers.orch, intervalMs: Math.min(1000, config.k?.trackerMs ?? 1000),
|
|
73
75
|
apply: change => executor.reconfigure ? executor.reconfigure(change) : change() });
|
|
74
76
|
}
|
|
75
|
-
await engine.recover();
|
|
77
|
+
const recovered = await engine.recover();
|
|
78
|
+
await ledgers.orch.append('recovered', { pid: process.pid, ms: Math.round(performance.now() - recoveryStarted), ...recovered });
|
|
76
79
|
await engine.loop(options.signal);
|
|
77
80
|
const reason = options.signal?.reason;
|
|
78
81
|
exit = engine.restartRequested ? { reason: 'restart' }
|
|
@@ -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 ?? "");
|