Skip to content

Commit 77b31fe

Browse files
author
trajn
committed
Protect task continuity and first report delivery
1 parent af4333a commit 77b31fe

14 files changed

Lines changed: 225 additions & 93 deletions

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ A wait only observes. It ends with a reply or failure, when its task pauses, at
4242

4343
Replies and failures arrive on their own. At the next safe turn boundary, or once when the parent is idle, pi-sub batches unannounced ones into one message; a complete tool return already counts as delivery. Each completed execution has an immutable report ID. Serialized reports up to 2 KiB are inline; larger ones include a reference, a response preview of at most 512 bytes and an error preview of at most 240 bytes. A result or batch is at most 8 KiB; an oversized batch is cached as a report with a summary and reference.
4444

45-
Page a report with `sub_result({ report: "<report-id>", offset: 0, limit: 4096 })`. This returns plain text and the next offset without executing a child. Offsets are zero-based UTF-8 byte boundaries; limits are bytes, default 4096, minimum 4 and maximum 4096. The parent runtime has one 16 MiB FIFO cache of UTF-8 report payloads; reads do not refresh it. Eviction returns “Report no longer available”, without recreating the report. A single report over 16 MiB spills to a private temporary file until runtime teardown. A batch also spills if caching it would evict a report it references; later FIFO eviction is unchanged. The budget excludes JS heap, native history, pending input and journals. Session switch, fork, reload or shutdown tears down the runtime; preserve relevant findings before leaving.
45+
Page a report with `sub_result({ report: "<report-id>", offset: 0, limit: 4096 })`. This returns plain text and the next offset without executing a child. Offsets are zero-based UTF-8 byte boundaries; limits are bytes, default 4096, minimum 4 and maximum 4096. The parent runtime has one 16 MiB FIFO cache of UTF-8 report payloads; reads do not refresh it. If FIFO eviction reaches a task’s current report before its first handoff, the cache keeps a temporary disk copy. After handoff or replacement by the task’s next execution, later writes may evict it. An expired reference returns “Report no longer available”. A single report over 16 MiB spills to a private temporary file until runtime teardown. A batch also spills if caching it would evict a report it references; later FIFO eviction is unchanged. The budget excludes JS heap, native history, pending input and journals. Session switch, fork, reload or shutdown tears down the runtime; preserve relevant findings before leaving.
4646

4747
## Pause and continue
4848

‎docs/decisions/0007-bounded-report-cache.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ Each completed execution produces an immutable report with its own ID. A parent
88

99
Acceptance or stop removes the task, not its cached reports. First delivery includes the inline result or preview and reference; accepting a previously delivered result returns only the task ID, status and available report ID. Operator stop notifications include final report IDs. There are no idempotent task receipts. Evicted reports fail explicitly with “Report no longer available”; they are not silently recreated. Reports and spill files expire at runtime teardown. Full reports are not retained unbounded in the coordinator or native message details.
1010

11-
A serialized report of at most 2 KiB is inline. Larger reports carry a reference, a response preview of at most 512 bytes and an error preview of at most 240 bytes. The entire model-facing result or batch is at most 8 KiB; an oversized batch is itself cached as a report and delivered as a summary and reference. If inserting the envelope would evict a referenced report, spill the envelope without changing the FIFO. This protects the handoff, not subsequent reads. Delivery of an inline report or reference is independent of reading and task acceptance.
11+
A serialized report of at most 2 KiB is inline. Larger reports carry a reference, a response preview of at most 512 bytes and an error preview of at most 240 bytes. The entire model-facing result or batch is at most 8 KiB; an oversized batch is itself cached as a report and delivered as a summary and reference. If inserting the envelope would evict a referenced report, spill the envelope without changing the FIFO. FIFO displacement before first delivery spills the task's current report instead of dropping it. Once handed off or superseded, a displaced copy is deleted on the next insertion that does not reference it. This protects the first handoff, including acceptance or stop, not subsequent reads. Delivery of an inline report or reference is independent of reading and task acceptance.
1212

1313
`sub_result` accepts either `{id, wait?, timeout?, finish?}` for task observation and acceptance, or `{report, offset?, limit?}` for report paging, never both. Paging returns plain text and the next offset without starting a child execution. Offsets are zero-based UTF-8 byte boundaries; the limit is in bytes, defaults to 4096 and is between 4 and 4096 inclusive.
1414

‎index.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ export default function piSub(pi: ExtensionAPI): void {
7979
.filter((task) => isSettled(task.status) && !task.delivered);
8080
if (!tasks.length) return;
8181
hand(replyBatch(tasks, coordinator.reports));
82-
for (const task of tasks) coordinator.markDelivered(task.id);
82+
for (const task of tasks) coordinator.markDelivered(task);
8383
};
8484
/** An idle parent is woken once per event-loop turn, however many replies arrived in it. */
8585
const scheduleReplies = () => {
@@ -103,7 +103,7 @@ export default function piSub(pi: ExtensionAPI): void {
103103
};
104104
const respond = (value: TaskView | TaskView[]) => {
105105
const result = toolResult(value, coordinator.reports);
106-
for (const task of [value].flat()) coordinator.markDelivered(task.id);
106+
for (const task of [value].flat()) coordinator.markDelivered(task);
107107
return charged(result);
108108
};
109109
const failed = (error: unknown) =>
@@ -255,6 +255,7 @@ export default function piSub(pi: ExtensionAPI): void {
255255
pi.sendMessage(stoppedNotice(stopped, coordinator.reports), {
256256
triggerTurn: false,
257257
});
258+
for (const task of stopped) coordinator.markDelivered(task);
258259
} catch (error) {
259260
notify(reason(error), "error");
260261
}

‎src/coordinator.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@ export class Coordinator {
226226
t.activity = "";
227227
t.response = "";
228228
t.error = undefined;
229+
if (t.report) this.reports.release(t.report.id); // Superseded without a handoff.
229230
t.report = undefined;
230231
t.delivered = false;
231232
this.status(t, "active");
@@ -392,9 +393,17 @@ export class Coordinator {
392393
this.remove(t);
393394
return this.view(t, "accepted");
394395
}
395-
markDelivered(id: string): void {
396-
const t = this.tasks.get(id);
397-
if (!t || !isSettled(t.status) || t.delivered) return;
396+
markDelivered(view: TaskView): void {
397+
if (view.report) this.reports.release(view.report.id);
398+
const t = this.tasks.get(view.id);
399+
if (
400+
!t ||
401+
!isSettled(view.status) ||
402+
!isSettled(t.status) ||
403+
t.delivered ||
404+
t.report?.id !== view.report?.id
405+
)
406+
return;
398407
t.delivered = true;
399408
this.emit();
400409
}

‎src/report-store.ts‎

Lines changed: 52 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,46 +19,82 @@ export interface ReportRef {
1919
file?: string;
2020
}
2121

22-
type Entry =
23-
{ bytes: number; buffer: Buffer } | { bytes: number; file: string };
22+
type Buffered = { bytes: number; buffer: Buffer; pending: boolean };
23+
type Entry = Buffered | { bytes: number; file: string; displaced?: true };
2424

2525
export class ReportStore {
2626
private readonly entries = new Map<string, Entry>();
27+
// Displaced reports outlive their FIFO slot only through the first handoff.
28+
private readonly released = new Map<string, string>();
2729
private memoryBytes = 0;
2830
private directory?: string;
2931
private disposed = false;
3032

31-
/** An envelope must not evict the reports it hands off. No lasting pins. */
32-
put(text: string, references?: ReadonlySet<string>): ReportRef {
33+
private spill(id: string, buffer: Buffer): string {
34+
this.directory ??= mkdtempSync(join(tmpdir(), "pi-sub-reports-"));
35+
const file = join(this.directory, id);
36+
try {
37+
writeFileSync(file, buffer, { mode: 0o600, flag: "wx" });
38+
} catch (error) {
39+
if ((error as NodeJS.ErrnoException).code !== "EEXIST")
40+
rmSync(file, { force: true });
41+
throw error;
42+
}
43+
return file;
44+
}
45+
46+
/** End first-handoff protection, without invalidating the reference just returned. */
47+
release(id: string): void {
48+
const entry = this.entries.get(id);
49+
if (!entry) return;
50+
if ("buffer" in entry) entry.pending = false;
51+
else if (entry.displaced) this.released.set(id, entry.file);
52+
}
53+
54+
put(
55+
text: string,
56+
{
57+
pending = false,
58+
references,
59+
}: {
60+
pending?: boolean;
61+
references?: ReadonlySet<string>;
62+
} = {},
63+
): ReportRef {
3364
if (this.disposed) throw new Error("Report store disposed");
65+
for (const [oldId, file] of this.released) {
66+
if (references?.has(oldId)) continue;
67+
rmSync(file, { force: true });
68+
this.entries.delete(oldId);
69+
this.released.delete(oldId);
70+
}
3471
const buffer = Buffer.from(text, "utf8");
3572
const bytes = buffer.length;
3673
const id = `report-${randomUUID()}`;
3774
let excess = this.memoryBytes + bytes - REPORT_CACHE_BYTES;
38-
const victims: string[] = [];
75+
const victims: [string, Buffered][] = [];
3976
if (bytes <= REPORT_CACHE_BYTES && excess > 0) {
4077
for (const [oldId, entry] of this.entries) {
4178
if (!("buffer" in entry)) continue;
4279
if (references?.has(oldId)) break; // Spill instead of breaking FIFO.
43-
victims.push(oldId);
80+
victims.push([oldId, entry]);
4481
excess -= entry.bytes;
4582
if (excess <= 0) break;
4683
}
4784
}
4885
if (excess > 0) {
49-
this.directory ??= mkdtempSync(join(tmpdir(), "pi-sub-reports-"));
50-
const file = join(this.directory, id);
51-
// Publish only after the write succeeds. The private directory also
52-
// owns any partial file left by a failed write until teardown.
53-
writeFileSync(file, buffer, { mode: 0o600, flag: "wx" });
86+
const file = this.spill(id, buffer);
5487
this.entries.set(id, { bytes, file });
5588
return { id, bytes, file };
5689
}
57-
for (const oldId of victims) {
58-
this.memoryBytes -= this.entries.get(oldId)!.bytes;
59-
this.entries.delete(oldId);
90+
for (const [oldId, entry] of victims) {
91+
if (entry.pending) {
92+
const file = this.spill(oldId, entry.buffer);
93+
this.entries.set(oldId, { bytes: entry.bytes, file, displaced: true });
94+
} else this.entries.delete(oldId);
95+
this.memoryBytes -= entry.bytes;
6096
}
61-
this.entries.set(id, { bytes, buffer });
97+
this.entries.set(id, { bytes, buffer, pending });
6298
this.memoryBytes += bytes;
6399
return { id, bytes };
64100
}
@@ -118,6 +154,7 @@ export class ReportStore {
118154
if (this.directory)
119155
rmSync(this.directory, { recursive: true, force: true });
120156
this.entries.clear();
157+
this.released.clear();
121158
this.memoryBytes = 0;
122159
this.disposed = true;
123160
}

‎src/reports.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ function snapshot(task: TaskView) {
4040
}
4141

4242
export function captureReport(task: TaskView, store: ReportStore) {
43-
const report = store.put(JSON.stringify(snapshot(task), null, 2));
43+
const report = store.put(JSON.stringify(snapshot(task), null, 2), {
44+
pending: true,
45+
});
4446
const { response, error } = task;
4547
if (report.bytes <= INLINE_BYTES) return { response, error, report };
4648
return {
@@ -91,7 +93,7 @@ function envelope(
9193
const references = new Set(
9294
tasks.flatMap((task) => (task.report ? [task.report.id] : [])),
9395
);
94-
const report = store.put(text, references);
96+
const report = store.put(text, { references });
9597
return { content: JSON.stringify({ summary, report }), report };
9698
}
9799

‎src/views.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ function rows(lines: () => Line[], theme: Theme, pad: number): Component {
5353
const room = Math.floor(width) - padding.length * 2;
5454
if (room < 1) return [];
5555
return lines().map(({ text, style }) => {
56-
const line = truncateToWidth(text, room);
56+
const line = truncateToWidth(oneLine(text, 4096), room);
5757
return (
5858
padding +
5959
(style === "title"
@@ -87,9 +87,11 @@ function summary(task: TaskDetails, replied: boolean): Line[] {
8787
text: `${labels[task.status] ?? "Task"} · ${task.description || task.id.slice(0, 8)}`,
8888
style: "title",
8989
},
90-
...(task.error ? [{ text: task.error, style: "error" as const }] : []),
90+
...(typeof task.error === "string" && task.error
91+
? [{ text: task.error, style: "error" as const }]
92+
: []),
9193
// A task at work may still hold its previous execution's text.
92-
...(replied && !working && task.preview
94+
...(replied && !working && typeof task.preview === "string" && task.preview
9395
? [{ text: task.preview, style: "muted" as const }]
9496
: []),
9597
...(task.unsent && task.status !== "queued" && task.status !== "active"

‎src/widget.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,12 @@ import type {
33
Theme,
44
} from "@earendil-works/pi-coding-agent";
55
import { truncateToWidth } from "@earendil-works/pi-tui";
6-
import type { Coordinator, Summary, TaskView } from "./coordinator.ts";
6+
import {
7+
isSettled,
8+
type Coordinator,
9+
type Summary,
10+
type TaskView,
11+
} from "./coordinator.ts";
712
import { oneLine } from "./reports.ts";
813

914
const maxRows = 8;
@@ -47,7 +52,9 @@ export function renderWidget(
4752
): string[] {
4853
width = Math.floor(width);
4954
if (width < 1 || (!tasks.length && !summary.inputTokens)) return [];
50-
const open = tasks.filter((task) => !task.delivered);
55+
const open = tasks.filter(
56+
(task) => !task.delivered || !isSettled(task.status),
57+
);
5158
const shown =
5259
open.length > maxRows
5360
? open

‎src/worker.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@ export interface WorkerReport {
3030
interrupted: boolean;
3131
/** The session gained a user message, so the input need not be sent again. */
3232
inputPersisted: boolean;
33-
/** A session file exists: the next execution continues it. */
33+
/** A readable session header exists: the next execution continues it. */
3434
saved: boolean;
35-
/** A session that existed is gone: nothing can continue it. */
35+
/** A session that existed is gone or truncated: nothing can continue it. */
3636
sessionLost: boolean;
3737
}
3838
export interface Worker {
@@ -102,7 +102,7 @@ export function createWorker(
102102
try {
103103
const before = await readSession(sessionFile);
104104
if (continues && !before) {
105-
fail("Native session file is missing");
105+
fail("Native session file is missing or truncated");
106106
return report(before, undefined, true);
107107
}
108108
const known = new Set(before?.map((entry) => entry.id));
@@ -214,7 +214,7 @@ export function createWorker(
214214
const after = await readSession(sessionFile);
215215
// An interrupted first start may not have saved anything yet.
216216
if (!after && (before || !stopRequested))
217-
fail("Native session file is missing");
217+
fail("Native session file is missing or truncated");
218218
return report(after, known, !!before && !after);
219219
} catch (cause) {
220220
fail(cause instanceof Error ? cause.message : String(cause));
@@ -251,7 +251,12 @@ async function readSession(file: string): Promise<SessionEntry[] | undefined> {
251251
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
252252
throw error;
253253
}
254-
return parseSessionEntries(contents).filter(
254+
const entries = parseSessionEntries(contents);
255+
// Native Pi initializes an empty file as a fresh session. Never do that for
256+
// a continuation whose header has disappeared, even if the path still exists.
257+
if (entries[0]?.type !== "session" || typeof entries[0].id !== "string")
258+
return undefined;
259+
return entries.filter(
255260
(entry): entry is SessionEntry =>
256261
entry.type !== "session" && typeof entry.id === "string",
257262
);

‎test/coordinator.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { describe, expect, it, vi } from "vitest";
22
import type { Usage } from "@earendil-works/pi-ai";
33
import { Coordinator } from "../src/coordinator.ts";
4+
import { REPORT_CACHE_BYTES } from "../src/report-store.ts";
5+
import { toolResult } from "../src/reports.ts";
46
import type {
57
Worker,
68
WorkerEvent,
@@ -197,6 +199,44 @@ describe("synchronous races", () => {
197199
});
198200
});
199201

202+
it("keeps every report readable through its first handoff, even after FIFO displacement or task removal", async () => {
203+
const count = 20;
204+
const { c, workers, start } = setup(count);
205+
try {
206+
const tasks = await Promise.all(
207+
Array.from({ length: count }, (_, i) => {
208+
const id = start();
209+
workers[i]!.close({ text: "x".repeat(2500) + i });
210+
return c.wait(id);
211+
}),
212+
);
213+
const store = c.reports;
214+
store.put(
215+
"f".repeat(
216+
REPORT_CACHE_BYTES - tasks.reduce((n, t) => n + t.report!.bytes, 0),
217+
),
218+
);
219+
store.put("z"); // FIFO displaces the oldest report before anything has been delivered.
220+
tasks[0] = c.accept(tasks[0]!.id);
221+
const result = toolResult(tasks, store);
222+
for (const task of tasks) c.markDelivered(task);
223+
const batch = JSON.parse(result.content[0]!.text).report;
224+
expect(batch.file).toBeDefined(); // The envelope must not evict its own references.
225+
expect(store.read(batch.id).text).toContain(tasks[0]!.report!.id);
226+
for (const [i, task] of tasks.entries())
227+
expect(JSON.parse(store.read(task.report!.id).text).response).toBe(
228+
"x".repeat(2500) + i,
229+
);
230+
231+
store.put("z");
232+
expect(() => store.read(tasks[0]!.report!.id)).toThrow(
233+
/no longer available/,
234+
);
235+
} finally {
236+
await c.dispose();
237+
}
238+
});
239+
200240
describe("usage", () => {
201241
it("charges the growth of each session snapshot once and keeps totals of removed tasks", async () => {
202242
const { c, workers, start } = setup();

0 commit comments

Comments
 (0)