Coalesce streamed ACP subagent assistant deltas before persistence

ACP streams a subagent's result per token, and emitSubagentAssistant
persisted a full-row message.updated + turn-item.updated event pair per
chunk — one 6KB grok subagent result amplified into ~2700 stored events,
14% of a whole session's event table (audit plan #10). Streamed chunks
now accumulate and emit at most once per 100ms window; the final text is
always flushed immediately on task completion, so the projection stays
exact. The grok_subagent_lineage fixture now asserts each child result
persists a single coalesced message.updated event (was one per chunk).

App-checked: a real streaming ACP result (4190 chars) persisted 4
message.updated events instead of thousands.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 committed 2026-07-12 11:52:08 +02:00
1 parent d17635201c
commit 63b64f489c
2 files changed
+78 -11

No files matched your search

@@ -26,6 +26,7 @@ import { modelSelectionsEqual } from "@t3tools/shared/model";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
@@ -84,6 +85,13 @@ import {
export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const;
/**
* Window for coalescing streamed subagent assistant deltas into one persisted
* snapshot. Matches the codex agent-message coalescer cadence; the final text
* is always flushed on task completion regardless of this interval.
*/
const SUBAGENT_STREAM_FLUSH_INTERVAL_MS = 100;
export interface AcpAdapterV2RuntimeInput {
readonly cwd: string;
readonly mcpServers: ReadonlyArray<EffectAcpSchema.McpServer>;
@@ -576,6 +584,12 @@ interface ActiveAcpSubagent {
childSessionId: string | null;
assistantText: string;
nextChildOrdinal: number;
// Streaming-emit throttle: ACP streams the subagent result per token, so a
// full-row event pair per chunk amplified one 6KB result into ~2700 stored
// events (audit plan #10). We coalesce intermediate emits and always flush
// the final text.
streamFlushScheduled: boolean;
streamPendingText: boolean;
}
type PendingRuntimeRequest = {
@@ -842,12 +856,10 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
yield* emitTextSegment(context, kind, false);
});
const emitSubagentAssistant = Effect.fnUntraced(function* (
const emitSubagentAssistantSnapshot = Effect.fnUntraced(function* (
subagent: ActiveAcpSubagent,
text: string,
) {
if (text.length === 0) return;
subagent.assistantText += text;
if (subagent.assistantText.length === 0) return;
const now = yield* DateTime.now;
const nativeItemId = `${subagent.task.nativeTaskRef?.nativeId ?? subagent.task.id}:result`;
const artifacts = makeSubagentConversationArtifacts({
@@ -871,13 +883,48 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
});
});
// Streaming append: accumulate and emit at most once per flush window.
const streamSubagentAssistant = Effect.fnUntraced(function* (
subagent: ActiveAcpSubagent,
text: string,
) {
if (text.length === 0) return;
subagent.assistantText += text;
subagent.streamPendingText = true;
if (subagent.streamFlushScheduled) return;
subagent.streamFlushScheduled = true;
yield* Effect.sleep(Duration.millis(SUBAGENT_STREAM_FLUSH_INTERVAL_MS)).pipe(
Effect.andThen(
Effect.suspend(() => {
subagent.streamFlushScheduled = false;
if (!subagent.streamPendingText) return Effect.void;
subagent.streamPendingText = false;
return emitSubagentAssistantSnapshot(subagent);
}),
),
Effect.forkIn(sessionScope),
);
});
// Terminal/one-shot emit: always persists the final text immediately.
const flushSubagentAssistant = Effect.fnUntraced(function* (
subagent: ActiveAcpSubagent,
finalText?: string,
) {
if (finalText !== undefined && finalText.length > 0) {
subagent.assistantText += finalText;
}
subagent.streamPendingText = false;
yield* emitSubagentAssistantSnapshot(subagent);
});
const projectSubagentNotification = Effect.fnUntraced(function* (
subagent: ActiveAcpSubagent,
notification: EffectAcpSchema.SessionNotification,
) {
const update = notification.update;
if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
yield* emitSubagentAssistant(subagent, update.content.text);
yield* streamSubagentAssistant(subagent, update.content.text);
}
});
@@ -952,6 +999,8 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
childSessionId: null,
assistantText: "",
nextChildOrdinal: 101,
streamFlushScheduled: false,
streamPendingText: false,
};
subagent.task = task;
context.subagents.set(update.nativeTaskId, subagent);
@@ -1044,12 +1093,15 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV
);
}
if (
taskStatus !== "running" &&
subagent.assistantText.length === 0 &&
update.result !== null
) {
yield* emitSubagentAssistant(subagent, update.result);
if (taskStatus !== "running") {
// Terminal: flush the final text immediately (adopting the
// one-shot result when nothing streamed) instead of leaving the
// last throttled snapshot possibly unemitted.
if (subagent.assistantText.length === 0 && update.result !== null) {
yield* flushSubagentAssistant(subagent, update.result);
} else if (subagent.streamPendingText) {
yield* flushSubagentAssistant(subagent);
}
}
const result = subagent.assistantText || update.result;
subagent.task = {
@@ -82,6 +82,21 @@ export function assertGrokSubagentLineageOutput(
const assistant = child.messages.find((message) => message.role === "assistant");
assert.isDefined(assistant);
assert.isBelow(assistant.text.indexOf(expected.first), assistant.text.indexOf(expected.second));
// Coalescing (audit plan #10): the subagent streamed a progress chunk and
// a result chunk into this one result message. Without coalescing each
// chunk persisted its own full-row message.updated event; the throttle
// collapses intermediate emits so the final text lands in a single flush.
const resultMessageEvents = result.storedEvents.filter((stored) => {
if (stored.event.type !== "message.updated") return false;
const payload = stored.event.payload as { readonly id?: unknown; readonly threadId?: unknown };
return payload.threadId === subagent.childThreadId && payload.id === assistant.id;
});
assert.lengthOf(
resultMessageEvents,
1,
`expected coalesced subagent result for ${expected.title}, got ${resultMessageEvents.length} message.updated events`,
);
for (const other of EXPECTED_CHILDREN) {
if (other.sessionId !== expected.sessionId) {
assert.notInclude(