pi-durable-subagents 1.0.41 → 1.0.42
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 +22 -0
- package/README.md +29 -1
- package/dist/agent/main.js +1 -1
- package/dist/cli/main.js +13 -3
- package/dist/events/pump.js +6 -2
- package/dist/events/waiting.js +3 -0
- package/dist/kernel/journal.js +189 -36
- package/dist/kernel/mailbox.js +2 -0
- package/dist/orchestrator/engine.js +154 -18
- 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 +17 -1
- package/dist/orchestrator/ledger.js +8 -3
- package/dist/orchestrator/main.js +5 -2
- package/dist/orchestrator/settled.js +134 -0
- package/dist/orchestrator/snapshot.js +89 -11
- package/dist/orchestrator/store.js +131 -22
- package/dist/ui/tool.js +5 -3
- package/dist/ui/view.js +20 -8
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.0.42
|
|
4
|
+
|
|
5
|
+
- The orchestrator starts in seconds on a large home. Measured on a copy of a real home (2084 workflows, 432 MB of
|
|
6
|
+
journals): a restart reached the evaluator after 82 s in 1.0.41 and after 3.5 s now; peak memory fell from 1.5 GiB
|
|
7
|
+
to about 710 MiB. Recovery records a receipt per recovered call and skips calls whose receipt is still current;
|
|
8
|
+
lookups that scanned every journal per call are indexed; pinned files of terminal workflows are checked when a
|
|
9
|
+
request needs them rather than at every start.
|
|
10
|
+
- Settled workflows open without decoding their journals. A rebuildable record under `cache/settled/` (validated
|
|
11
|
+
against the journal's inode, size, entry count and last line; any mismatch takes the full path and rewrites it)
|
|
12
|
+
stands in until something reads or appends to the journal, which then decodes it in full. Only terminal workflows
|
|
13
|
+
with nothing left for recovery to do are eligible.
|
|
14
|
+
- The first start after upgrading does a one-time pass that writes the receipts and records (about 40 s on the home
|
|
15
|
+
above).
|
|
16
|
+
- A pinned file that changed no longer stops the orchestrator or leaves a generation hanging: the generation's call
|
|
17
|
+
is sealed `failed` with `pin-failed: <file>` without starting a child, and a follow-up runs again once the file is
|
|
18
|
+
restored. Resume, revise and follow-up of such a workflow are refused with `pin-failed`.
|
|
19
|
+
- `status` says why a queued call does not move: `orchestrator starting (<age>)` while the orchestrator recovers
|
|
20
|
+
(also on the orchestrator line), the writer lock, a full provider (`waiting for a free slot (<provider> n/n)`) or a
|
|
21
|
+
used-up usage window. Without evidence it says only `queued`; an answered asker shows `queued (answered)`.
|
|
22
|
+
- The orchestrator ledger records `recovery: true` on its start entry and a `recovered` entry with the recovery time
|
|
23
|
+
and counts.
|
|
24
|
+
|
|
3
25
|
## 1.0.41
|
|
4
26
|
|
|
5
27
|
- An answer that races the planned hibernation no longer strands its call. In 1.0.40 the parent forwarded an answer,
|
package/README.md
CHANGED
|
@@ -228,6 +228,20 @@ script run from its bash tool): pi exports `DSA_SESSION`, and `run` names that
|
|
|
228
228
|
session (see `--session` below). Other sessions' and a terminal's runs are
|
|
229
229
|
not shown.
|
|
230
230
|
|
|
231
|
+
A queued subagent says why it does not start, as far as the orchestrator has
|
|
232
|
+
recorded it, and `queued` alone when nothing is known:
|
|
233
|
+
|
|
234
|
+
| phrase | meaning |
|
|
235
|
+
| --- | --- |
|
|
236
|
+
| `queued: orchestrator starting (12s)` | the orchestrator is still recovering workflows after a start; nothing is dispatched yet (`status` shows `orchestrator: <version> (pid N, starting 12s)`, the summary line `3 queued: orchestrator starting (12s)`) |
|
|
237
|
+
| `queued: <provider> usage window used up` | every provider it can start on is used up |
|
|
238
|
+
| `queued: waiting for the writer lock of <root>` | another call writes in the same worktree |
|
|
239
|
+
| `queued: waiting for a free slot (<provider> 4/4)` | every provider it can start on is full |
|
|
240
|
+
| `queued (answered)` / `queued (answered): <reason>` | an answered asker waiting to run again, with the reason when one is recorded (as above) |
|
|
241
|
+
| `paused · r resumes` | a drained workflow |
|
|
242
|
+
|
|
243
|
+
The CLI and the tool's status (`queued` per call) say the same.
|
|
244
|
+
|
|
231
245
|
The list is also where you act. The footer shows the keys for the selected
|
|
232
246
|
row: `Enter` watch, `s` steer, `f` follow-up, `x` stop (asks `y` first),
|
|
233
247
|
`m` model, `a` answer. A one-line input opens at the bottom (paste works),
|
|
@@ -901,7 +915,21 @@ subagent only watching it.
|
|
|
901
915
|
The restart ledger records the reason and initiator; after the next start,
|
|
902
916
|
`status` shows who forced it and why for 24 hours.
|
|
903
917
|
|
|
904
|
-
An orchestrator reads requests only after it has recovered its workflows
|
|
918
|
+
An orchestrator reads requests only after it has recovered its workflows. Its
|
|
919
|
+
start costs the unfinished work plus a small check per finished workflow, not
|
|
920
|
+
the size of finished history: a call whose recovery completed is recorded in its
|
|
921
|
+
journal and not read again until something concerns it, and a settled workflow
|
|
922
|
+
(ended, nothing open) opens without decoding its journal, from a rebuildable
|
|
923
|
+
record in `DSA_HOME/cache/settled`; the journal is read when a request needs it.
|
|
924
|
+
Pinned files of a finished workflow are verified when a resume, revise or
|
|
925
|
+
follow-up uses them; a changed file refuses that request (`pin-failed`). A
|
|
926
|
+
follow-up generation that is already open when its files no longer verify (at a
|
|
927
|
+
restart, say) is sealed `failed` without starting a subagent, with an error
|
|
928
|
+
starting `pin-failed: ` that names the file; the workflow ends again, and once
|
|
929
|
+
the file is restored a later follow-up runs. The first start after upgrading
|
|
930
|
+
makes a one-time pass that writes these records and receipts (tens of seconds
|
|
931
|
+
on a large home). The ledger's `orchestrator` entry has `recovery: true`, and a
|
|
932
|
+
`recovered` entry with the time taken follows when recovery ends. So
|
|
905
933
|
a `restart` sent to one that just started waits for it (and says so); if no
|
|
906
934
|
orchestrator reaches the request in time, `restart` exits 75 and the request
|
|
907
935
|
stays pending — it is decided later, so do not send another.
|
package/dist/agent/main.js
CHANGED
|
@@ -439,7 +439,7 @@ export function registerMain(pi, ui) {
|
|
|
439
439
|
"run (action optional for exactly one launch form): agent+task; tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
|
|
440
440
|
"agents: list names, descriptions, default models and source for this cwd; use these names for run.",
|
|
441
441
|
"send to:'<wid>/<key>' (bare '<wid>' only for a single-call workflow): steer on a running call delivers at the next safe point (receipt in status/UI); a steer to a call waiting on its question interrupts the question and the subagent usually asks again — use answer to answer it; sealed → finished:<status> — use kind 'follow-up'. notify tells a call a decision without disturbing it; the reply's delivery says how: steered (running: it gets the note at its next safe point), held-until-answer (waiting on its question: never interrupts it, delivered after the answer) or noted (not running: nothing starts; the note is recorded and the call's next follow-up opens with every pending note; status shows notesPending). to may list several calls for steer, notify, follow-up and model: one request per call, each decided on its own, one result line per target (request:<id> sends <id>:1...<id>:n; a retry with the same list is safe). follow-up continues a sealed call as generation g+1 (reply generation) or queues after a running turn (reply delivery forwarded; if that turn ends without taking it, it opens g+1); follow-up model:'provider/id' or a pool name runs that generation on it. answer: give the qid (or just the call, or nothing when one question is open); to and rev are filled in. A question that needs the user's decision goes to the user; if you answer one yourself, tell the user what you chose. model ('provider/id' or a pool name — its first model not used up): a running call switches at its next provider request; an asking, hibernated or queued call launches on it when it runs again; the reply's model/effect (next-request|next-execution|next-generation) says which. status model = model actually used by the last request; switching = requested, not used yet; switchFailed = refused. A provider content refusal (ToS/usage policy) fails the call at once, not retried. Unknown targets list valid addresses. replaces:[rid] supersedes an earlier send.",
|
|
442
|
-
"stop target:<wid|<wid>/<key>> is terminal stopped (usage and partial edits kept); a sealed call → already-sealed:<status>, a finished workflow → terminal:<status>. drain holds existing workflows reversibly (new runs unaffected); resume [wid] releases held workflows. restart (after an update) replaces the orchestrator with the installed version: refused with busy:<running executions> while any runs. Never force without the user's explicit approval: show the user the refusal's list first, then supply force:'<token>' and reason. Subagents cannot force; hibernated askers and queued calls do not block it. Never kill the orchestrator process. Commands that need the machine (benchmarks, timing) take a lease: tell the subagent to run them as `pi-durable-subagents hold machine [--shared] -- <command>` (FIFO; `hold <name> --slots N` admits N at a time; status lists lease holders and waiters). status: without wid, what runs (with its run labels, clipped), asks (with its answer address; hibernated:true holds no slot) or failed, writerWait: a call queued for its git worktree's writer lock (one call whose tools include edit/write runs per worktree; spec writer:false or isolation:'worktree' opts out), sharedWorktree names calls sharing observed edit/write roots (reminder), lease: a call holding or waiting for a resource lease, finished workflows one line each, provider slots held/limit, the config in effect and providers whose usage window is used up (avoided until a probe finds them answering again), and the orchestrator version (versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+tail:N: the last N lines of each call's result, wid+grep:'<regex>': only its matching lines (a JS regex run in-process: avoid nested quantifiers like (a+)+; first 2000 chars of a line, last 5000 lines; both: grep, then tail; at most 4000 chars per call); wid+key: one call's full result; full:true: everything. A run reply names calls already queued behind a writer lock (writerWait). A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
|
|
442
|
+
"stop target:<wid|<wid>/<key>> is terminal stopped (usage and partial edits kept); a sealed call → already-sealed:<status>, a finished workflow → terminal:<status>. drain holds existing workflows reversibly (new runs unaffected); resume [wid] releases held workflows. restart (after an update) replaces the orchestrator with the installed version: refused with busy:<running executions> while any runs. Never force without the user's explicit approval: show the user the refusal's list first, then supply force:'<token>' and reason. Subagents cannot force; hibernated askers and queued calls do not block it. Never kill the orchestrator process. Commands that need the machine (benchmarks, timing) take a lease: tell the subagent to run them as `pi-durable-subagents hold machine [--shared] -- <command>` (FIFO; `hold <name> --slots N` admits N at a time; status lists lease holders and waiters). status: without wid, what runs (with its run labels, clipped), asks (with its answer address; hibernated:true holds no slot) or failed, writerWait: a call queued for its git worktree's writer lock (one call whose tools include edit/write runs per worktree; spec writer:false or isolation:'worktree' opts out), sharedWorktree names calls sharing observed edit/write roots (reminder), lease: a call holding or waiting for a resource lease, queued: why a queued call does not start (orchestrator starting while it recovers after a start, a used-up provider, a writer lock, full providers; absent when not known), finished workflows one line each, provider slots held/limit, the config in effect and providers whose usage window is used up (avoided until a probe finds them answering again), and the orchestrator version (with ', starting <age>' while it recovers; versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+tail:N: the last N lines of each call's result, wid+grep:'<regex>': only its matching lines (a JS regex run in-process: avoid nested quantifiers like (a+)+; first 2000 chars of a line, last 5000 lines; both: grep, then tail; at most 4000 chars per call); wid+key: one call's full result; full:true: everything. A run reply names calls already queued behind a writer lock (writerWait). A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
|
|
443
443
|
"Control replies are {applied:true,rid} or {applied:false,reason,rid} when decided; otherwise {submitted:{rid}} after 10s.",
|
|
444
444
|
...(agents ? [`Available agents: ${agents}.`] : []),
|
|
445
445
|
"User sees a summary line above the editor; ↓ on an empty editor (or /subagents) opens the list, Enter watches live OR finished calls (finished transcripts remain on disk) and expands finished workflows. List keys: s steer (paste-capable input), x stop (confirm y), m model, a answer when asked, f follow-up on finished calls; action feedback appears in footer.",
|
package/dist/cli/main.js
CHANGED
|
@@ -7,7 +7,7 @@ import { setTimeout as delay } from "node:timers/promises";
|
|
|
7
7
|
import { dsaHome } from "../paths.js";
|
|
8
8
|
import { readJournalSnapshot } from "../kernel/journal.js";
|
|
9
9
|
import { journalPath, orchLedger } from "../paths.js";
|
|
10
|
-
import { answerForwardedNote, modelStatusText, allWorkflows, eventsFromEntries, heldWorkflows, isLive, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, labelsText, outputSelect, statusCompactDetail } from "../orchestrator/snapshot.js";
|
|
10
|
+
import { answerForwardedNote, modelStatusText, queuedText, allWorkflows, eventsFromEntries, heldWorkflows, isLive, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, labelsText, outputSelect, statusCompactDetail } from "../orchestrator/snapshot.js";
|
|
11
11
|
import { statsLine } from "../orchestrator/stats.js";
|
|
12
12
|
import { resolution, start, startOrchestrator, submit } from "./control.js";
|
|
13
13
|
import { doctor, renderDoctor, size } from "./doctor.js";
|
|
@@ -101,10 +101,20 @@ export function parseArgs(args) {
|
|
|
101
101
|
const clip = (text, n) => text.length > n ? `${text.slice(0, n)}…` : text;
|
|
102
102
|
/** Notes recorded for a call that is not running (send kind "notify"); its next follow-up carries them. */
|
|
103
103
|
const notesLine = (n) => n ? ` · ${n} note${n > 1 ? "s" : ""} pending` : "";
|
|
104
|
-
/**
|
|
104
|
+
/** Why a queued call does not start, when the orchestrator ledger says so (an answered asker: "(answered)" first); nothing
|
|
105
|
+
* while a drain holds its workflow (it waits for resume, as the UI says). A writer-lock wait has its own suffix. */
|
|
105
106
|
const answeredNote = (c, paused) => {
|
|
106
107
|
const forwarded = answerForwardedNote(c);
|
|
107
|
-
|
|
108
|
+
if (forwarded)
|
|
109
|
+
return `: ${forwarded}`;
|
|
110
|
+
if (c.phase !== "queued" || paused)
|
|
111
|
+
return "";
|
|
112
|
+
const why = c.queued ?? (c.queuedFor ? queuedText(c.queuedFor) : undefined);
|
|
113
|
+
if (c.writerWait && why === `waiting for the writer lock of ${c.writerWait.root}`)
|
|
114
|
+
return c.answered ? " (answered)" : ""; // its own suffix says it
|
|
115
|
+
if (c.answered)
|
|
116
|
+
return why ? ` (answered): ${why}` : " (answered)"; // no slot claim without a full provider
|
|
117
|
+
return why ? `: ${why}` : "";
|
|
108
118
|
};
|
|
109
119
|
/** P25, T10: Render journal-derived status (one line per call, last output line only) without live orchestrator memory. */
|
|
110
120
|
export function renderStatus(wf) {
|
package/dist/events/pump.js
CHANGED
|
@@ -290,7 +290,11 @@ export class EventPump {
|
|
|
290
290
|
const wf = this.options.store.workflows.get(wid);
|
|
291
291
|
if (!wf)
|
|
292
292
|
continue;
|
|
293
|
-
const
|
|
293
|
+
const start = this.marks.get(wid) ?? 0;
|
|
294
|
+
// A journal not decoded (a settled workflow) is decoded only when it has entries not derived yet.
|
|
295
|
+
if (wf.journal.loaded === false && (wf.journal.count?.() ?? Infinity) <= start)
|
|
296
|
+
continue;
|
|
297
|
+
const entries = committed(wf.journal);
|
|
294
298
|
if (entries.length <= start)
|
|
295
299
|
continue;
|
|
296
300
|
const id = this.identity(wid);
|
|
@@ -332,7 +336,7 @@ export class EventPump {
|
|
|
332
336
|
let v = verdicts.get(wid);
|
|
333
337
|
if (v === undefined) {
|
|
334
338
|
const wf = this.options.store.workflows.get(wid);
|
|
335
|
-
v = wf ? quiet(wid, committed(wf.journal)) : pruned.has(wid);
|
|
339
|
+
v = wf ? (wf.journal.loaded === false && wf.settled ? wf.settled.quiet : quiet(wid, committed(wf.journal))) : pruned.has(wid);
|
|
336
340
|
verdicts.set(wid, v);
|
|
337
341
|
}
|
|
338
342
|
return v;
|
package/dist/events/waiting.js
CHANGED
|
@@ -419,6 +419,9 @@ export function waitCollector(src) {
|
|
|
419
419
|
const current = new Map(), meta = new Map(), present = new Set();
|
|
420
420
|
for (const wf of src.workflows()) {
|
|
421
421
|
present.add(wf.wid);
|
|
422
|
+
// A journal not decoded is a settled workflow's (orchestrator/settled.ts): it has no live call, so no wait.
|
|
423
|
+
if (wf.journal.loaded === false)
|
|
424
|
+
continue;
|
|
422
425
|
const entries = wf.journal.entries();
|
|
423
426
|
let hit = folds.get(wf.wid);
|
|
424
427
|
if (hit?.entries !== entries) {
|
package/dist/kernel/journal.js
CHANGED
|
@@ -1,23 +1,43 @@
|
|
|
1
1
|
import { open, mkdir } from 'node:fs/promises';
|
|
2
|
-
import { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs';
|
|
2
|
+
import { closeSync, constants, fstatSync, fsyncSync, ftruncateSync, openSync, readFileSync, readSync } from 'node:fs';
|
|
3
3
|
import { dirname } from 'node:path';
|
|
4
|
+
import * as zlib from 'node:zlib';
|
|
4
5
|
const TABLE = new Uint32Array(256).map((_, n) => { let c = n; for (let k = 0; k < 8; k++)
|
|
5
6
|
c = (c & 1) ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
|
|
7
|
+
/** The CRC-32 (IEEE) of `bytes` as an unsigned number: node's native one when it has it (22.2+), else a table. */
|
|
8
|
+
const crcValue = typeof zlib.crc32 === 'function'
|
|
9
|
+
? bytes => zlib.crc32(bytes)
|
|
10
|
+
: bytes => {
|
|
11
|
+
let crc = 0xffffffff;
|
|
12
|
+
for (let i = 0; i < bytes.length; i++)
|
|
13
|
+
crc = TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
|
|
14
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
15
|
+
};
|
|
6
16
|
/** C11: the CRC-32 (IEEE) of a record, 8 lowercase hex digits: the frame of every journal line. */
|
|
7
17
|
export function crc32(bytes) {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
18
|
+
return crcValue(bytes).toString(16).padStart(8, '0');
|
|
19
|
+
}
|
|
20
|
+
/** The value of the 8 lowercase hex digits at `bytes[0..8)` followed by a space, or -1 when they are not that. */
|
|
21
|
+
function frameHead(bytes) {
|
|
22
|
+
if (bytes.length < 9 || bytes[8] !== 32)
|
|
23
|
+
return -1;
|
|
24
|
+
let value = 0;
|
|
25
|
+
for (let i = 0; i < 8; i++) {
|
|
26
|
+
const c = bytes[i], digit = c >= 48 && c <= 57 ? c - 48 : c >= 97 && c <= 102 ? c - 87 : -1;
|
|
27
|
+
if (digit < 0)
|
|
28
|
+
return -1;
|
|
29
|
+
value = value * 16 + digit;
|
|
30
|
+
}
|
|
31
|
+
return value;
|
|
12
32
|
}
|
|
13
33
|
/** C11: One framed line `<crc32 hex 8> <json>\n` (the journal format; the event log uses it too). */
|
|
14
34
|
export function frameLine(json) { return `${crc32(Buffer.from(json))} ${json}\n`; }
|
|
15
35
|
/** C11: The JSON text of one framed line (without its newline), or undefined when its frame or checksum is wrong. */
|
|
16
36
|
export function unframeLine(line) {
|
|
17
|
-
if (line.length < 10
|
|
37
|
+
if (line.length < 10)
|
|
18
38
|
return undefined;
|
|
19
|
-
const head =
|
|
20
|
-
return
|
|
39
|
+
const head = frameHead(line), json = line.subarray(9);
|
|
40
|
+
return head >= 0 && crcValue(json) === head ? Buffer.from(json.buffer, json.byteOffset, json.byteLength).toString() : undefined;
|
|
21
41
|
}
|
|
22
42
|
/** Entries are immutable history (A1): freeze them so shared snapshots can be handed out without copying. */
|
|
23
43
|
function freeze(value) {
|
|
@@ -36,10 +56,10 @@ function decode(bytes, prior = []) {
|
|
|
36
56
|
if (end < 0)
|
|
37
57
|
break;
|
|
38
58
|
try {
|
|
39
|
-
const line = bytes.subarray(offset, end), json = line.subarray(9);
|
|
40
|
-
if (
|
|
59
|
+
const line = bytes.subarray(offset, end), json = line.subarray(9), head = frameHead(line);
|
|
60
|
+
if (head < 0 || crcValue(json) !== head)
|
|
41
61
|
throw new Error('CRC');
|
|
42
|
-
const entry = JSON.parse(
|
|
62
|
+
const entry = JSON.parse(bytes.toString('utf8', offset + 9, end));
|
|
43
63
|
if (entry.seq !== entries.length + 1 || !Number.isFinite(entry.ts) || typeof entry.type !== 'string')
|
|
44
64
|
throw new Error('Envelope');
|
|
45
65
|
entries.push(freeze(entry));
|
|
@@ -214,35 +234,165 @@ export function openJournalDescriptors() { return descriptors; }
|
|
|
214
234
|
/** A1, C11: Repair only the tail, then serialize durable framed appends. A resting handle (`resting = true`) closes its
|
|
215
235
|
* descriptor once its appends are done and reopens it for the next append; its entries stay in memory. */
|
|
216
236
|
export async function openJournal(path) {
|
|
217
|
-
await
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
237
|
+
return (await openHandle(path));
|
|
238
|
+
}
|
|
239
|
+
/** The expectation a journal handle meets now (its committed bytes, read back from the file), for a later lazy open;
|
|
240
|
+
* undefined when the file has no complete entry or does not end at the committed length. */
|
|
241
|
+
export function journalExpectation(journal) {
|
|
242
|
+
const entries = journal.committed?.() ?? journal.entries(), count = entries.length;
|
|
243
|
+
if (!count)
|
|
244
|
+
return undefined;
|
|
245
|
+
let fd;
|
|
225
246
|
try {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
247
|
+
fd = openSync(journal.path, 'r');
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
const { ino, size } = fstatSync(fd), tail = lastLine(fd, size);
|
|
254
|
+
if (!tail)
|
|
255
|
+
return undefined;
|
|
256
|
+
// The last line must be the last committed entry (a torn tail is truncated by every open, never trusted).
|
|
257
|
+
const json = unframeLine(tail.subarray(0, tail.length - 1));
|
|
258
|
+
if (json === undefined || JSON.parse(json).seq !== count)
|
|
259
|
+
return undefined;
|
|
260
|
+
return { ino, size, count, tail: crc32(tail), tailLength: tail.length };
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return undefined;
|
|
264
|
+
}
|
|
265
|
+
finally {
|
|
266
|
+
closeSync(fd);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/** The last line of the file (with its newline), when the file ends with one. Reads from the end in chunks. */
|
|
270
|
+
function lastLine(fd, size) {
|
|
271
|
+
if (!size)
|
|
272
|
+
return undefined;
|
|
273
|
+
let chunk = 4096, buffer = Buffer.alloc(0);
|
|
274
|
+
for (let end = size;;) {
|
|
275
|
+
const start = Math.max(0, end - chunk), part = Buffer.alloc(end - start);
|
|
276
|
+
for (let read = 0; read < part.length;) {
|
|
277
|
+
const n = readSync(fd, part, read, part.length - read, start + read);
|
|
278
|
+
if (!n)
|
|
279
|
+
return undefined;
|
|
280
|
+
read += n;
|
|
281
|
+
}
|
|
282
|
+
buffer = Buffer.concat([part, buffer]);
|
|
283
|
+
if (buffer[buffer.length - 1] !== 10)
|
|
284
|
+
return undefined;
|
|
285
|
+
const previous = buffer.lastIndexOf(10, buffer.length - 2);
|
|
286
|
+
if (previous >= 0)
|
|
287
|
+
return buffer.subarray(previous + 1);
|
|
288
|
+
if (start === 0)
|
|
289
|
+
return buffer;
|
|
290
|
+
end = start;
|
|
291
|
+
chunk *= 2;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** A1, C11: A journal handle that decodes nothing yet: when the file still is what `expect` describes (same inode and
|
|
295
|
+
* size, the same last line), the handle reports `loaded: false` and `count()` from it, and decodes the whole file
|
|
296
|
+
* (verifying it as openJournal does) on the first access to its entries or the first append. Undefined when the file
|
|
297
|
+
* is not what was expected: the caller opens it eagerly. Decoding later finds the same bytes or throws (one writer). */
|
|
298
|
+
export async function openLazyJournal(path, expect) {
|
|
299
|
+
let fd;
|
|
300
|
+
try {
|
|
301
|
+
fd = openSync(path, 'r');
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
try {
|
|
307
|
+
const { ino, size } = fstatSync(fd);
|
|
308
|
+
if (ino !== expect.ino || size !== expect.size || expect.count < 1 || expect.tailLength < 10 || expect.tailLength > size)
|
|
309
|
+
return undefined;
|
|
310
|
+
const tail = Buffer.alloc(expect.tailLength);
|
|
311
|
+
for (let read = 0; read < tail.length;) {
|
|
312
|
+
const n = readSync(fd, tail, read, tail.length - read, size - tail.length + read);
|
|
313
|
+
if (!n)
|
|
314
|
+
return undefined;
|
|
315
|
+
read += n;
|
|
232
316
|
}
|
|
233
|
-
if (
|
|
234
|
-
|
|
235
|
-
|
|
317
|
+
if (tail[tail.length - 1] !== 10 || tail.indexOf(10) !== tail.length - 1 || crc32(tail) !== expect.tail)
|
|
318
|
+
return undefined;
|
|
319
|
+
if (size > tail.length) {
|
|
320
|
+
const before = Buffer.alloc(1);
|
|
321
|
+
if (readSync(fd, before, 0, 1, size - tail.length - 1) !== 1 || before[0] !== 10)
|
|
322
|
+
return undefined;
|
|
236
323
|
}
|
|
237
324
|
}
|
|
238
|
-
catch
|
|
239
|
-
|
|
240
|
-
|
|
325
|
+
catch {
|
|
326
|
+
return undefined;
|
|
327
|
+
}
|
|
328
|
+
finally {
|
|
329
|
+
closeSync(fd);
|
|
241
330
|
}
|
|
242
|
-
|
|
243
|
-
|
|
331
|
+
return openHandle(path, expect);
|
|
332
|
+
}
|
|
333
|
+
/** Decode a journal synchronously as openJournal does (a torn tail is truncated), for a lazy handle's first access. */
|
|
334
|
+
function loadSync(path, expect) {
|
|
335
|
+
const fd = openSync(path, 'r+');
|
|
336
|
+
try {
|
|
337
|
+
const { ino, size } = fstatSync(fd);
|
|
338
|
+
if (ino !== expect.ino || size !== expect.size)
|
|
339
|
+
throw new Error(`Journal changed while not loaded: ${path} has ${size} bytes, ${expect.size} expected`);
|
|
340
|
+
const bytes = readFileSync(fd), decoded = decode(bytes);
|
|
341
|
+
if (decoded.entries.length !== expect.count)
|
|
342
|
+
throw new Error(`Journal changed while not loaded: ${path} has ${decoded.entries.length} entries, ${expect.count} expected`);
|
|
343
|
+
if (decoded.length !== bytes.length) {
|
|
344
|
+
ftruncateSync(fd, decoded.length);
|
|
345
|
+
fsyncSync(fd);
|
|
346
|
+
}
|
|
347
|
+
return { entries: decoded.entries, size: decoded.length };
|
|
348
|
+
}
|
|
349
|
+
finally {
|
|
350
|
+
closeSync(fd);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
async function openHandle(path, lazy) {
|
|
354
|
+
let entries, size, file;
|
|
355
|
+
if (lazy)
|
|
356
|
+
size = lazy.size;
|
|
357
|
+
else {
|
|
358
|
+
await mkdir(dirname(path), { recursive: true });
|
|
359
|
+
let created = false;
|
|
360
|
+
const first = await open(path, 'ax+').then(f => { created = true; return f; }, async (error) => {
|
|
361
|
+
if (error.code !== 'EEXIST')
|
|
362
|
+
throw error;
|
|
363
|
+
return open(path, 'a+');
|
|
364
|
+
});
|
|
365
|
+
try {
|
|
366
|
+
const bytes = await first.readFile(), decoded = decode(bytes);
|
|
367
|
+
entries = decoded.entries;
|
|
368
|
+
size = decoded.length;
|
|
369
|
+
if (decoded.length !== bytes.length) {
|
|
370
|
+
await first.truncate(decoded.length);
|
|
371
|
+
await first.sync();
|
|
372
|
+
}
|
|
373
|
+
if (created) {
|
|
374
|
+
await first.sync();
|
|
375
|
+
await syncDirectory(dirname(path));
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
await first.close();
|
|
380
|
+
throw error;
|
|
381
|
+
}
|
|
382
|
+
file = first;
|
|
383
|
+
descriptors++;
|
|
384
|
+
}
|
|
385
|
+
/** The entries, decoding a lazy handle's file first. */
|
|
386
|
+
const all = () => {
|
|
387
|
+
if (!entries) {
|
|
388
|
+
const loaded = loadSync(path, lazy);
|
|
389
|
+
entries = loaded.entries;
|
|
390
|
+
size = loaded.size;
|
|
391
|
+
}
|
|
392
|
+
return entries;
|
|
393
|
+
};
|
|
244
394
|
let queue = Promise.resolve(), closed = false, failed, view;
|
|
245
|
-
let resting =
|
|
395
|
+
let resting = lazy !== undefined, restTimer;
|
|
246
396
|
// Only this process writes the file (A2): a reopened file that is not exactly what was committed was changed by
|
|
247
397
|
// someone else, and appending to it could interleave records.
|
|
248
398
|
const reopen = async () => {
|
|
@@ -283,10 +433,12 @@ export async function openJournal(path) {
|
|
|
283
433
|
const handle = {
|
|
284
434
|
path,
|
|
285
435
|
// Shared frozen view, rebuilt only after an append (entries are immutable, see freeze()).
|
|
286
|
-
entries: () => view ??= Object.freeze(
|
|
436
|
+
entries: () => view ??= Object.freeze(all().slice()),
|
|
287
437
|
// The growing array itself (no copy): it is only ever appended to, so a reader may keep it and read below a length
|
|
288
438
|
// it saw (the event pump reads new entries per tick without copying the journal).
|
|
289
|
-
committed: () =>
|
|
439
|
+
committed: () => all(),
|
|
440
|
+
get loaded() { return entries !== undefined; },
|
|
441
|
+
count: () => entries ? entries.length : lazy.count,
|
|
290
442
|
onAppend: undefined,
|
|
291
443
|
append(type, fields) {
|
|
292
444
|
if (closed)
|
|
@@ -295,6 +447,7 @@ export async function openJournal(path) {
|
|
|
295
447
|
const operation = queue.then(async () => {
|
|
296
448
|
if (failed)
|
|
297
449
|
throw failed;
|
|
450
|
+
const entries = all();
|
|
298
451
|
const entry = { ...frozen, seq: entries.length + 1, ts: Date.now(), type };
|
|
299
452
|
const json = JSON.stringify(entry), bytes = Buffer.from(json), line = `${crc32(bytes)} ${json}\n`;
|
|
300
453
|
let target;
|
package/dist/kernel/mailbox.js
CHANGED
|
@@ -138,6 +138,8 @@ export class Outbox {
|
|
|
138
138
|
}
|
|
139
139
|
/** The envelope recorded as sent under `rid`, if any. */
|
|
140
140
|
recorded(rid) { const req = this.sent.get(rid); return req && structuredClone(req); }
|
|
141
|
+
/** The recipients of unresolved envelopes. */
|
|
142
|
+
pendingDestinations() { return new Set([...this.pending.values()].map(req => req.to)); }
|
|
141
143
|
/** P38: Re-publish every unresolved envelope under its original identity. */
|
|
142
144
|
republishPending() { return this.serial(async () => { for (const req of this.pending.values())
|
|
143
145
|
await this.publish(req); }); }
|