pi-durable-subagents 1.0.42 → 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 +21 -0
- package/dist/agent/main/snapshots.js +24 -1
- package/dist/agent/main/tool.js +3 -2
- package/dist/agent/main.js +4 -10
- package/dist/cli/control.js +20 -10
- package/dist/cli/requests.js +51 -32
- package/dist/events/fence.js +2 -0
- package/dist/events/waiting.js +9 -2
- 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 +88 -31
- package/dist/orchestrator/executor/sweep.js +40 -24
- package/dist/orchestrator/ledger.js +4 -1
- package/dist/orchestrator/providers.js +2 -0
- package/dist/orchestrator/reader-ledger.js +13 -3
- package/dist/orchestrator/settled.js +10 -2
- package/dist/orchestrator/snapshot.js +2 -0
- package/dist/orchestrator/store.js +133 -33
- package/dist/requests.js +41 -5
- package/package.json +1 -1
|
@@ -17,7 +17,7 @@ import { mkdir, readdir, unlink } from 'node:fs/promises';
|
|
|
17
17
|
import { resolve, join } from 'node:path';
|
|
18
18
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
19
19
|
import { contentHash } from "../kernel/ids.js";
|
|
20
|
-
import {
|
|
20
|
+
import { LifecycleFold, planDecisions } from "../kernel/lifecycle.js";
|
|
21
21
|
import { scanInbox } from "../kernel/mailbox.js";
|
|
22
22
|
import { orchInbox, pinnedDir } from "../paths.js";
|
|
23
23
|
import { SESSION_ID, requestId, specDigest } from "../requests.js";
|
|
@@ -185,8 +185,10 @@ export class Engine {
|
|
|
185
185
|
if (wf.journal.closed)
|
|
186
186
|
return;
|
|
187
187
|
const quiet = wf.journal.resting = this.quiescent(wf);
|
|
188
|
-
if (quiet)
|
|
188
|
+
if (quiet) {
|
|
189
189
|
this.recordSettled(wf);
|
|
190
|
+
this.store.releasePins(wf);
|
|
191
|
+
}
|
|
190
192
|
}
|
|
191
193
|
/** Journal lengths of the workflows whose settled record (settled.ts) was last written or found not due. */
|
|
192
194
|
settledAt = new Map();
|
|
@@ -221,7 +223,53 @@ export class Engine {
|
|
|
221
223
|
}
|
|
222
224
|
started = Date.now();
|
|
223
225
|
terminal(wf) { return lazy(wf) ? wf.settled.done : terminalEntry(revisionEntries(wf)); }
|
|
224
|
-
|
|
226
|
+
intakeFold = new LifecycleFold();
|
|
227
|
+
intakeSeen = 0;
|
|
228
|
+
/** Journal positions preserve retained-envelope order, even for repeated request entries. */
|
|
229
|
+
retained = new Map();
|
|
230
|
+
retainedAt = new Map();
|
|
231
|
+
sends = new Map();
|
|
232
|
+
rejectedStages = new Set();
|
|
233
|
+
withdrawnStages = new Set();
|
|
234
|
+
/** One writer appends committed entries; folds never advance past an uncommitted append or an awaited decision. */
|
|
235
|
+
lifecycle() {
|
|
236
|
+
const entries = this.ledgers.orch.committed?.() ?? this.ledgers.orch.entries();
|
|
237
|
+
for (; this.intakeSeen < entries.length; this.intakeSeen++) {
|
|
238
|
+
const entry = entries[this.intakeSeen];
|
|
239
|
+
if (entry.type === 'request') {
|
|
240
|
+
const request = entry.request;
|
|
241
|
+
if (request.kind === 'send') {
|
|
242
|
+
const sent = this.sends.get(request.rid) ?? [];
|
|
243
|
+
sent.push({ at: this.intakeSeen, request });
|
|
244
|
+
this.sends.set(request.rid, sent);
|
|
245
|
+
}
|
|
246
|
+
if (!this.intakeFold.resolved.has(request.rid)) {
|
|
247
|
+
this.retained.set(this.intakeSeen, request);
|
|
248
|
+
const positions = this.retainedAt.get(request.rid) ?? new Set();
|
|
249
|
+
positions.add(this.intakeSeen);
|
|
250
|
+
this.retainedAt.set(request.rid, positions);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
else if (['admitted', 'applied', 'rejected', 'withdrawn'].includes(entry.type)) {
|
|
254
|
+
const record = entry;
|
|
255
|
+
this.intakeFold.apply(record);
|
|
256
|
+
if (record.type === 'withdrawn')
|
|
257
|
+
for (const rid of record.rids)
|
|
258
|
+
this.withdrawnStages.add(rid);
|
|
259
|
+
else {
|
|
260
|
+
const resolution = this.intakeFold.resolved.get(record.rid);
|
|
261
|
+
if (resolution) {
|
|
262
|
+
for (const at of this.retainedAt.get(record.rid) ?? [])
|
|
263
|
+
this.retained.delete(at);
|
|
264
|
+
this.retainedAt.delete(record.rid);
|
|
265
|
+
if (resolution.type === 'rejected' && ['run', 'revise'].includes(this.intakeFold.admitted.get(record.rid)?.kind ?? ''))
|
|
266
|
+
this.rejectedStages.add(record.rid);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return this.intakeFold;
|
|
272
|
+
}
|
|
225
273
|
/** A2, P10: Recover executor authority before replaying each unfinished workflow. Returns what it recovered: the
|
|
226
274
|
* workflows, the calls the executor read and repaired, and those it skipped as already recovered. */
|
|
227
275
|
async recover() {
|
|
@@ -342,11 +390,9 @@ export class Engine {
|
|
|
342
390
|
async startWorkflow(wf) {
|
|
343
391
|
if (this.terminal(wf))
|
|
344
392
|
return;
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
return;
|
|
349
|
-
}
|
|
393
|
+
await this.store.ready(wf);
|
|
394
|
+
if (this.terminal(wf))
|
|
395
|
+
return;
|
|
350
396
|
wf.journal.resting = false;
|
|
351
397
|
await this.resolveFinished(wf);
|
|
352
398
|
const log = revisionEntries(wf);
|
|
@@ -365,18 +411,17 @@ export class Engine {
|
|
|
365
411
|
const files = await readdir(orchInbox(this.ledgers.home)).catch(error => { if (error.code === 'ENOENT')
|
|
366
412
|
return []; throw error; });
|
|
367
413
|
const last = this.consumed;
|
|
368
|
-
|
|
414
|
+
const length = this.ledgers.orch.count?.() ?? (this.ledgers.orch.committed?.() ?? this.ledgers.orch.entries()).length;
|
|
415
|
+
if (!files.length && last && !last.pending && last.length === length)
|
|
369
416
|
return;
|
|
370
417
|
await this.consume();
|
|
371
418
|
}
|
|
372
419
|
async consume() {
|
|
373
420
|
this.passes.push(Date.now());
|
|
374
421
|
const scanned = (await scanInbox(orchInbox(this.ledgers.home))).filter(r => r.to === 'orch');
|
|
375
|
-
const before =
|
|
376
|
-
//
|
|
377
|
-
|
|
378
|
-
const retained = this.ledgers.orch.entries().filter(e => e.type === 'request' && !before.resolved.has(e.request.rid)).map(e => e.request);
|
|
379
|
-
const candidates = [...retained, ...scanned];
|
|
422
|
+
const before = this.lifecycle(), staged = new Set();
|
|
423
|
+
// The watermark index removes envelopes only after a committed terminal resolution.
|
|
424
|
+
const candidates = [...this.retained.values(), ...scanned];
|
|
380
425
|
for (const request of candidates) {
|
|
381
426
|
if (!['run', 'revise'].includes(request.kind) || before.admitted.has(request.rid) || before.tombstones.has(request.rid) || staged.has(request.rid))
|
|
382
427
|
continue;
|
|
@@ -410,21 +455,20 @@ export class Engine {
|
|
|
410
455
|
for (const { type, ...fields } of resolution)
|
|
411
456
|
await this.ledgers.orch.append(type, fields);
|
|
412
457
|
}
|
|
413
|
-
const view =
|
|
414
|
-
for (const [
|
|
415
|
-
|
|
458
|
+
const view = this.lifecycle();
|
|
459
|
+
for (const pending of [this.rejectedStages, this.withdrawnStages]) {
|
|
460
|
+
for (const rid of pending) {
|
|
416
461
|
await this.store.discardStage(rid);
|
|
462
|
+
pending.delete(rid);
|
|
463
|
+
}
|
|
417
464
|
}
|
|
418
|
-
for (const rid of view.tombstones)
|
|
419
|
-
await this.store.discardStage(rid);
|
|
420
465
|
for (const req of scanned) {
|
|
421
466
|
if (view.resolved.has(req.rid) || (view.admitted.has(req.rid) && view.admitted.get(req.rid).hash !== contentHash(req))) {
|
|
422
467
|
await unlink(join(orchInbox(this.ledgers.home), `${req.rid}.json`)).catch(error => { if (error.code !== 'ENOENT')
|
|
423
468
|
throw error; });
|
|
424
469
|
}
|
|
425
470
|
}
|
|
426
|
-
|
|
427
|
-
this.consumed = { length: this.ledgers.orch.entries().length, pending: [...after.admitted.keys()].some(rid => !after.resolved.has(rid)) };
|
|
471
|
+
this.consumed = { length: this.intakeSeen, pending: view.open.size > 0 };
|
|
428
472
|
}
|
|
429
473
|
findCall(to, bareWid = false) {
|
|
430
474
|
for (const wf of this.store.workflows.values()) {
|
|
@@ -451,9 +495,9 @@ export class Engine {
|
|
|
451
495
|
context(wf, entry) { return { journal: wf.journal, widRev: `${wf.wid}@${wf.revision}`, key: entry.key, gen: entry.gen }; }
|
|
452
496
|
async withdraw(req) {
|
|
453
497
|
const rids = req.body.rids;
|
|
498
|
+
this.lifecycle();
|
|
499
|
+
const sent = [...new Set(rids)].flatMap(rid => this.sends.get(rid) ?? []).sort((a, b) => a.at - b.at).map(item => item.request);
|
|
454
500
|
for (const wf of this.store.workflows.values()) {
|
|
455
|
-
const requests = this.ledgers.orch.entries().filter(e => e.type === 'request').map(e => e.request);
|
|
456
|
-
const sent = requests.filter(r => r.kind === 'send' && rids.includes(r.rid));
|
|
457
501
|
const visited = new Set();
|
|
458
502
|
for (const target of sent) {
|
|
459
503
|
const found = this.findCall(target.body.to, true);
|
|
@@ -623,7 +667,7 @@ export class Engine {
|
|
|
623
667
|
// them): a changed file refuses the resume before anything is recorded.
|
|
624
668
|
for (const wf of this.store.workflows.values()) {
|
|
625
669
|
const done = this.terminal(wf);
|
|
626
|
-
if (!inScope(wf) ||
|
|
670
|
+
if (!inScope(wf) || !(done?.status === 'parked' || (releasing && !done)))
|
|
627
671
|
continue;
|
|
628
672
|
try {
|
|
629
673
|
await this.store.ready(wf);
|
|
@@ -834,15 +878,19 @@ export class Engine {
|
|
|
834
878
|
this.opening.delete(wid);
|
|
835
879
|
}
|
|
836
880
|
}
|
|
837
|
-
dispatchGeneration(wf, entry, refusal) {
|
|
881
|
+
dispatchGeneration(wf, entry, refusal, checked = false) {
|
|
882
|
+
const id = `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`;
|
|
883
|
+
if (this.generations.has(id) || this.held(wf.wid) || wf.journal.entries().some(e => e.type === 'retired' && e.call === id))
|
|
884
|
+
return;
|
|
838
885
|
// A finished workflow's pinned files are verified before a generation of it runs (the ticket names its origin); a
|
|
839
886
|
// sealed generation's run only repeats post-seal steps, which read no pinned file. When they do not verify, the
|
|
840
887
|
// generation is sealed failed (`pin-failed: …`) without a child, like any call that cannot be prepared: the engine
|
|
841
888
|
// goes on, the workflow ends again, and a later follow-up verifies the files again.
|
|
842
|
-
|
|
889
|
+
// Released pins (not resident) take the same asynchronous path: a getter must never throw out of this method.
|
|
890
|
+
if (refusal === undefined && !checked && !(this.store.verified(wf.wid) && this.store.pinsResident(wf)) && !callEntries(wf.journal, `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`).some(e => e.type === JT.sealed)) {
|
|
843
891
|
const revision = wf.revision, current = () => wf.revision === revision && this.store.workflows.get(wf.wid) === wf && !this.closed;
|
|
844
892
|
void this.store.ready(wf).then(() => { if (current())
|
|
845
|
-
this.dispatchGeneration(wf, entry); }, error => {
|
|
893
|
+
this.dispatchGeneration(wf, entry, undefined, true); }, error => {
|
|
846
894
|
if (!current())
|
|
847
895
|
return;
|
|
848
896
|
const reason = `pin-failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
@@ -857,10 +905,19 @@ export class Engine {
|
|
|
857
905
|
}
|
|
858
906
|
// Pins not verified (a refusal, or the post-seal steps of a sealed generation): the ticket comes from the journal's
|
|
859
907
|
// entry alone, so a damaged pinned record cannot keep the call from sealing.
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
908
|
+
// After ready, pins released again before this dispatch reload through the checked getter; a load that fails
|
|
909
|
+
// seals this generation alone (`pin-failed: …`), so no getter error escapes and ready is not retried in a loop.
|
|
910
|
+
let ticket;
|
|
911
|
+
if (refusal !== undefined || !this.store.verified(wf.wid))
|
|
912
|
+
ticket = { ...this.unpinnedTicket(wf, entry), ...(refusal !== undefined ? { refusal } : {}) };
|
|
913
|
+
else
|
|
914
|
+
try {
|
|
915
|
+
ticket = this.ticket({ wf }, entry);
|
|
916
|
+
}
|
|
917
|
+
catch (error) {
|
|
918
|
+
refusal = `pin-failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
919
|
+
ticket = { ...this.unpinnedTicket(wf, entry), refusal };
|
|
920
|
+
}
|
|
864
921
|
this.generations.add(id);
|
|
865
922
|
wf.journal.resting = false;
|
|
866
923
|
void this.executor.run(ticket).then(result => this.background(async () => {
|
|
@@ -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
|
}
|
|
@@ -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 ?? "");
|
|
@@ -2,12 +2,16 @@
|
|
|
2
2
|
import { forgetJournalSnapshot, readJournalFold } from "../kernel/journal.js";
|
|
3
3
|
import { orchLedger } from "../paths.js";
|
|
4
4
|
import { JT } from "../types.js";
|
|
5
|
-
import { applyLedger, emptyLedger } from "./ledger.js";
|
|
5
|
+
import { LEDGER_ENTRY_TYPES, applyLedger, emptyLedger } from "./ledger.js";
|
|
6
6
|
import { labelsOf } from "../events/derive.js";
|
|
7
7
|
export function emptyReaderLedger() {
|
|
8
8
|
return { created: new Map(), origins: new Map(), intents: new Map(), revisions: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), sessions: new Map(), runSessions: new Map(),
|
|
9
9
|
byWid: new Map(), byOrigin: new Map(), state: emptyLedger(), createdRids: new Map(), decisions: new Map(), resolutions: new Map(), sendNotes: new Map() };
|
|
10
10
|
}
|
|
11
|
+
/** Reader-only projections, combined with applyLedger's type list by the byte filter. */
|
|
12
|
+
export const READER_ENTRY_TYPES = [JT.created, 'create-intent', 'revise-intent', 'request', 'pruned', 'drain', 'undrain',
|
|
13
|
+
JT.applied, JT.rejected, 'send-note'];
|
|
14
|
+
const discardedLedgerTypes = ['switch-observed', 'skip', 'writer-hold', 'writer-release'];
|
|
11
15
|
export function applyReaderLedger(ix, e) {
|
|
12
16
|
if (e.type === JT.created) {
|
|
13
17
|
if (!ix.created.has(e.wid))
|
|
@@ -78,7 +82,7 @@ export function applyReaderLedger(ix, e) {
|
|
|
78
82
|
// A holder needs only pool/slot/exec, not any extra payload the entry might carry.
|
|
79
83
|
if (e.type === "hold")
|
|
80
84
|
applyLedger(ix.state, { seq: e.seq, ts: e.ts, type: e.type, pool: e.pool, slot: e.slot, exec: e.exec });
|
|
81
|
-
else if (
|
|
85
|
+
else if (!discardedLedgerTypes.includes(e.type))
|
|
82
86
|
applyLedger(ix.state, e);
|
|
83
87
|
ix.state.seen++;
|
|
84
88
|
}
|
|
@@ -89,13 +93,19 @@ export function readerHold(ix, wid, origin) {
|
|
|
89
93
|
return last?.type === "drain" && (!created || created.seq < last.seq) ? last : undefined;
|
|
90
94
|
}
|
|
91
95
|
const readers = new Map();
|
|
96
|
+
// Canonical writer JSON: these are exactly the types that affect reader projections or applyLedger below.
|
|
97
|
+
const needles = [...new Set([...READER_ENTRY_TYPES.filter(type => type !== 'request'),
|
|
98
|
+
...LEDGER_ENTRY_TYPES.filter(type => !discardedLedgerTypes.includes(type))])].map(type => `"type":${JSON.stringify(type)}`);
|
|
99
|
+
// Request records only affect labels/session for runs; the other request kinds have no reader projection.
|
|
100
|
+
needles.push('"kind":"run"');
|
|
92
101
|
export function readerLedger(home) {
|
|
93
102
|
const path = orchLedger(home);
|
|
94
103
|
// Drop any raw snapshot loaded by another read path in this process. This reader never creates one itself.
|
|
95
104
|
forgetJournalSnapshot(path);
|
|
96
105
|
try {
|
|
97
|
-
const record = readJournalFold(path, readers.get(path), emptyReaderLedger, applyReaderLedger);
|
|
106
|
+
const record = readJournalFold(path, readers.get(path), emptyReaderLedger, applyReaderLedger, { needles });
|
|
98
107
|
if (record) {
|
|
108
|
+
record.state.state.seen = record.seen;
|
|
99
109
|
readers.set(path, record);
|
|
100
110
|
return record;
|
|
101
111
|
}
|
|
@@ -107,9 +107,17 @@ export function readSettled(home, wid) {
|
|
|
107
107
|
return undefined;
|
|
108
108
|
if (!record.journal || typeof record.journal.size !== "number" || !record.done || typeof record.revision !== "number" || !Array.isArray(record.sweep) || !Array.isArray(record.resumed))
|
|
109
109
|
return undefined;
|
|
110
|
-
|
|
111
|
-
|
|
110
|
+
// Version 2 records held fenced tags with obsolete pid/start lineage. Keep their tags only; no rebuild is needed.
|
|
111
|
+
const tags = [];
|
|
112
|
+
for (const s of record.sweep) {
|
|
113
|
+
if (typeof s === "string")
|
|
114
|
+
tags.push(s);
|
|
115
|
+
else if (s && typeof s === "object" && typeof s.exec === "string")
|
|
116
|
+
tags.push(s.exec);
|
|
117
|
+
else
|
|
112
118
|
return undefined;
|
|
119
|
+
}
|
|
120
|
+
record.sweep = tags;
|
|
113
121
|
return record;
|
|
114
122
|
}
|
|
115
123
|
/** Write the record of a settled workflow from its decoded journal (best effort: a failure only costs a decode at the
|
|
@@ -771,6 +771,8 @@ function forgetRemovedWorkflows(home, names, pruned) {
|
|
|
771
771
|
paths.delete(wid);
|
|
772
772
|
}
|
|
773
773
|
}
|
|
774
|
+
/** Ledger types that determine holdOf/heldIn (other ledgerIndex projections do not affect holds). */
|
|
775
|
+
export const HOLD_ENTRY_TYPES = [JT.created, 'drain', 'undrain'];
|
|
774
776
|
/** Drain: the one hold rule. drain/undrain entries apply to every workflow (no scope), one session's (`origin`) or one
|
|
775
777
|
* workflow (`wid`). A workflow is held when the newest entry that applies to it is a drain recorded after it was created. */
|
|
776
778
|
export function holdOf(ledger, wid, origin) {
|