From 749bb0fa93c6cad74a8119bbe371164a009eeb73 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Wed, 4 Nov 2026 19:39:12 -0800 Subject: [PATCH] fix(core): bound a subagent report to its own busy period Each busy period records where it began, on the clock that stamps event times, plus the child's newest answer at that moment. Settlement only reports an answer that completed during the period, excluding the starting answer by ID for millisecond ties and falling back to the timestamp alone when a committed revert deleted that row. --- .../src/session/execution/subagent-report.ts | 105 +++++++++++------- packages/core/test/subagent-lifetime.test.ts | 86 ++++++++++++++ 2 files changed, 153 insertions(+), 38 deletions(-) diff --git a/packages/core/src/session/execution/subagent-report.ts b/packages/core/src/session/execution/subagent-report.ts index 8b935e1d5c9..c0bb33626de 100644 --- a/packages/core/src/session/execution/subagent-report.ts +++ b/packages/core/src/session/execution/subagent-report.ts @@ -1,6 +1,6 @@ export * as SubagentReport from "./subagent-report.js" -import { Effect, Fiber, Scope } from "effect" +import { Clock, DateTime, Effect, Fiber, Scope } from "effect" import type { Job } from "../../job.js" import { SessionInbox } from "../inbox.js" import { SessionMessage } from "../message.js" @@ -36,8 +36,21 @@ export type Snapshot = { * its cancelled caller already owns the result. */ readonly owned: boolean - /** The child's newest answer when the period began; undefined when that was never read. */ - readonly baseline: { readonly id: SessionMessage.ID | undefined } | undefined + /** Where this period began; undefined when `started` never recorded it. */ + readonly start: Start | undefined +} + +/** + * Where a busy period began: the clock reading when it started and the child's newest answer at + * that moment. Both are needed. The reading alone misses an answer that completes in the same + * millisecond the next period starts, and the answer alone fails once a committed revert deletes + * that row. + */ +export type Start = { + /** Clock reading on the same clock that stamps event and assistant completion times. */ + readonly at: number + /** The child's newest answer when the period began, if it had one. */ + readonly answer: SessionMessage.ID | undefined } export type Deps = { @@ -57,24 +70,36 @@ export type Deps = { * same notification ID, so first admission wins and the parent sees one message. */ export const make = (deps: Deps) => { - // The job generation running when a busy period began. Its watcher records that generation's - // terminal when it settles within the period, because only a cancellation there owns the - // period's report: completion or failure is settling an earlier period. Dropped at settlement. - const periods = new Map() - // Children whose last succeeded period held its report for background work. Process-local: after - // a restart, recovery and background notices wake the child instead. - const held = new Set() - // A child's newest answer when its busy period began, so settlement can tell a period that - // produced no new answer. Process-local, like held. - const baselines = new Map() + // The job generation running when a busy period began, and where that period began. Its watcher + // records that generation's terminal when it settles within the period, because only a + // cancellation there owns the period's report: completion or failure is settling an earlier + // period. Dropped at settlement. + const periods = new Map() + // Children whose last succeeded period held its report for background work, with the start of the + // earliest period still owed. Process-local: after a restart, recovery and background notices wake + // the child instead. + const held = new Map() - // The same assistant message the SubagentJob run and restart recovery read: the newest - // completed assistant answer, whose text becomes the report body. - const lastAssistant = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) { - const messages = yield* deps.store.messages({ sessionID, order: "desc", limit: 20 }) - return messages.find( - (message) => message.type === "assistant" && message.time.completed !== undefined && message.error === undefined, - ) + /** + * The newest answer that completed at or after the busy period began. `since` comes from the + * period's start, so an answer the parent already has, or one that finished before this period, + * never reports again. A period with no recorded start falls back to unbounded. + */ + const lastAssistant = Effect.fnUntraced(function* (sessionID: SessionSchema.ID, since: Start | undefined) { + const messages = yield* deps.store.messages({ sessionID, order: "desc", limit: 20, type: "assistant" }) + // The answer a period starts with can complete in the same millisecond the next period starts, + // so it is excluded by ID as well as by time. A committed revert can delete that row mid-period: + // a missing anchor then bounds by time alone, never as a store cursor, which would read []. + const end = messages.findIndex((message) => message.id === since?.answer) + return messages + .slice(0, end === -1 ? undefined : end) + .find( + (message) => + message.type === "assistant" && + message.time.completed !== undefined && + message.error === undefined && + (since === undefined || DateTime.toEpochMillis(message.time.completed) >= since.at), + ) }) const started = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) { @@ -85,15 +110,22 @@ export const make = (deps: Deps) => { periods.delete(sessionID) if (leftover.job?.fiber) yield* Fiber.interrupt(leftover.job.fiber) } + // Read the clock before any step runs: the start must be on the clock that stamps every event + // and assistant completion. + const at = yield* Clock.currentTimeMillis + const child = yield* deps.store.get(sessionID) + // Only children report, so a top-level period costs no message read. + const answer = child?.parentID ? (yield* lastAssistant(sessionID, undefined))?.id : undefined + const start: Start = { at, answer } const job = yield* deps.jobs.get(sessionID) // A finished entry from an earlier generation must not make a re-prompt silently reconcile. - if (job?.status !== "running") periods.set(sessionID, { job: undefined }) + if (job?.status !== "running") periods.set(sessionID, { job: undefined, start }) else { const bound: Bound = { generation: job.started_at, settled: undefined, fiber: undefined } // Record before forking: startImmediately can run the watcher inline when this generation // already settled. Every write is guarded by the record, so an old watcher cannot mark a // later period. - periods.set(sessionID, { job: bound }) + periods.set(sessionID, { job: bound, start }) bound.fiber = yield* deps.jobs.wait({ id: sessionID }).pipe( Effect.flatMap((result) => Effect.sync(() => { @@ -106,9 +138,6 @@ export const make = (deps: Deps) => { Effect.forkIn(deps.scope, { startImmediately: true }), ) } - baselines.delete(sessionID) - if (!(yield* deps.store.get(sessionID))?.parentID) return - baselines.set(sessionID, (yield* lastAssistant(sessionID))?.id) }) const snapshot = Effect.fnUntraced(function* (sessionID: SessionSchema.ID): Effect.fn.Return { @@ -125,22 +154,23 @@ export const make = (deps: Deps) => { : undefined) // Read the watcher's write before interrupting it, or a resumed continuation loses it. if (bound?.fiber) yield* Fiber.interrupt(bound.fiber) - const baseline = baselines.has(sessionID) ? { id: baselines.get(sessionID) } : undefined - baselines.delete(sessionID) return { blocked: yield* deps.jobs.isBlocked(sessionID), job, recovery: yield* deps.jobs.recovery(sessionID), owned: settled?.status === "cancelled", - baseline, + start: period?.start, } }) const report = Effect.fnUntraced(function* (sessionID: SessionSchema.ID, outcome: Outcome, snap: Snapshot) { // Shutdown keeps the claim, and restart owns the report that resumes it. if (outcome.type === "interrupted" && outcome.reason === "shutdown") return - // Every settlement decides afresh; a period that holds again re-adds the child below. - const owed = held.delete(sessionID) + // Every settlement decides afresh; a period that holds again re-adds the child below, keeping + // the start it first owed. + const owed = held.has(sessionID) + const since = owed ? held.get(sessionID) : snap.start + held.delete(sessionID) const child = yield* deps.store.get(sessionID) if (!child?.parentID) return const parentID = child.parentID @@ -171,21 +201,20 @@ export const make = (deps: Deps) => { // final state. Failures and user interrupts report now. Mark held before asking, so a silent // descendant settling meanwhile still wakes this child; a spurious wake sends nothing. if (outcome.type === "succeeded") { - held.add(child.id) + // Keep the start this child first owed, so a later hold still reports that answer or a newer + // one rather than losing it to a period that produced nothing. + if (!held.has(child.id)) held.set(child.id, since) if (yield* deps.pending(child.id)) return held.delete(child.id) } const recovery = subagentRecovery(live?.notificationID ? snap.recovery : undefined, child, parentID) const status = outcome.type === "succeeded" ? "completed" : outcome.type === "interrupted" ? "cancelled" : "error" - const assistant = status === "completed" ? yield* lastAssistant(child.id) : undefined - // A period that succeeded without finishing an assistant message was not a turn: a move, a - // compaction or a recovered notice settles that way, and a spawn that never ran reports - // through the tool's inline error instead. + const assistant = status === "completed" ? yield* lastAssistant(child.id, since) : undefined + // A period that succeeded without finishing an answer of its own was not a turn: a move, a + // compaction, a recovered notice or a no-input wake settles that way, and a spawn that never ran + // reports through the tool's inline error instead. if (status === "completed" && assistant === undefined) return - // A no-input wake (a silent descendant's release, or a resume) runs no model step and must not - // re-send an answer the parent already has. - if (status === "completed" && !owed && snap.baseline !== undefined && snap.baseline.id === assistant?.id) return const output = status === "completed" ? SubagentCompletion.text(assistant) : undefined const error = outcome.type === "failed" ? outcome.error.message : undefined const notificationID = live?.notificationID diff --git a/packages/core/test/subagent-lifetime.test.ts b/packages/core/test/subagent-lifetime.test.ts index 9f0f0c836f5..781c9e109f9 100644 --- a/packages/core/test/subagent-lifetime.test.ts +++ b/packages/core/test/subagent-lifetime.test.ts @@ -498,4 +498,90 @@ describe("subagent observer lifetime", () => { expect(yield* llm.requests()).toHaveLength(requests) }), ) + + it.live("a re-prompted child reports only the answer from that busy period", () => + Effect.gen(function* () { + const llm = yield* TestLLM.Test + const f = yield* family() + yield* llm.push( + TestLLM.text("first", "first"), + TestLLM.text("Parent heard the first report", "parent-first"), + TestLLM.text("second", "second"), + TestLLM.text("Parent heard the second report", "parent-second"), + ) + + yield* f.sessions.prompt({ sessionID: f.child.id, text: "Check the tests" }) + yield* f.sessions.wait(f.child.id) + yield* f.sessions.wait(f.parent.id) + const opening = yield* reports(f.parent.id) + expect(opening).toHaveLength(1) + expect(opening[0]?.text).toContain("first") + + yield* f.sessions.prompt({ sessionID: f.child.id, text: "Check them again" }) + yield* f.sessions.wait(f.child.id) + yield* f.sessions.wait(f.parent.id) + const notices = yield* reports(f.parent.id) + expect(notices).toHaveLength(2) + expect(notices[1]).toMatchObject({ metadata: { source: "subagent", childID: f.child.id, state: "completed" } }) + expect(notices[1]?.text).toContain("second") + expect(notices[1]?.text).not.toContain("first") + }), + ) + + it.live("a reverted and re-prompted child reports its new answer", () => + Effect.gen(function* () { + const llm = yield* TestLLM.Test + const f = yield* family() + yield* llm.push( + TestLLM.text("first", "first"), + TestLLM.text("Parent heard the first report", "parent-first"), + TestLLM.text("second", "second"), + TestLLM.text("Parent heard the second report", "parent-second"), + ) + + const opening = yield* f.sessions.prompt({ sessionID: f.child.id, text: "Check the tests" }) + yield* f.sessions.wait(f.child.id) + yield* f.sessions.wait(f.parent.id) + expect(yield* reports(f.parent.id)).toHaveLength(1) + + // A committed revert deletes this period's anchor row; the next period must still report. + yield* f.sessions.revert.stage({ sessionID: f.child.id, messageID: opening.id, files: false }) + yield* f.sessions.revert.commit(f.child.id) + yield* f.sessions.prompt({ sessionID: f.child.id, text: "Check them again" }) + yield* f.sessions.wait(f.child.id) + yield* f.sessions.wait(f.parent.id) + const notices = yield* reports(f.parent.id) + expect(notices).toHaveLength(2) + expect(notices[1]).toMatchObject({ metadata: { source: "subagent", childID: f.child.id, state: "completed" } }) + expect(notices[1]?.text).toContain("second") + expect(notices[1]?.text).not.toContain("first") + }), + ) + + it.live("a failed follow-up does not re-send the earlier answer", () => + Effect.gen(function* () { + const llm = yield* TestLLM.Test + const f = yield* family() + yield* llm.push( + TestLLM.text("first", "first"), + TestLLM.text("Parent heard the first report", "parent-first"), + Stream.die(new Error("follow-up failed")), + TestLLM.text("Parent heard the failure", "parent-failure"), + ) + + yield* f.sessions.prompt({ sessionID: f.child.id, text: "Check the tests" }) + yield* f.sessions.wait(f.child.id) + yield* f.sessions.wait(f.parent.id) + expect(yield* reports(f.parent.id)).toHaveLength(1) + + yield* f.sessions.prompt({ sessionID: f.child.id, text: "Check them again" }) + yield* f.sessions.wait(f.child.id) + yield* f.sessions.wait(f.parent.id) + const notices = yield* reports(f.parent.id) + expect(notices).toHaveLength(2) + expect(notices[1]).toMatchObject({ metadata: { source: "subagent", childID: f.child.id, state: "error" } }) + expect(notices[1]?.text).toContain("follow-up failed") + expect(notices[1]?.text).not.toContain("first") + }), + ) })