GeezerVison is showing github.com — fix(server): Claude subagent progress no longer re-stores the unchanged prompt by Gigioxx · Pull Request #18375 · pingdotgg/t3code
fix(server): Claude subagent progress no longer re-stores the unchanged prompt
#18375
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.ts
(3)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
fix(server): Claude subagent progress no longer re-stores the unchang…
…ed prompt
Store a subagent prompt once in orchestration_events and point later unchanged updates at that row. Reads and replay budgets restore it in SQL, so events, the wire, and clients are unchanged. Slim rows keep an empty prompt so older servers can still decode them.
Fixes #18204
Loading branch information
Uh oh!
There was an error while loading. Please reload this page.
commit 0eb17fc60712445c1ed06fef3802bb29ccaf477f
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -230,6 +230,7 @@ export const layer: Layer.Layer<
];
const supersedableThreadEventTypes = new Set(SUPERSEDABLE_THREAD_EVENT_TYPES);
// Keep subagent.updated and turn-item.updated rows: slimmed payloads reference their prompts.
const COMPACTION_PAGE_SIZE = 500;
/**
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3,7 +3,9 @@ import * as NodeV8 from "node:v8";
import {
CommandId,
EventId,
NodeId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
TurnItemId,
Expand Down
Expand Up
@@ -103,6 +105,199 @@ layer("OrchestrationEventStore", (it) => {
),
);
it.effect("stores an unchanged subagent prompt once and replays it on every update", () =>
Effect.gen(function* () {
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const afterSequence = yield* store.latestApplicationSequence;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread:subagent-prompt");
const id = NodeId.make("node:subagent-prompt");
const driver = ProviderDriverKind.make("claudeAgent");
const providerInstanceId = ProviderInstanceId.make("claudeAgent");
const prompt = "Audit the repository. ".repeat(200);
const subagent = (index: number, progress: string, nextPrompt = prompt) =>
({
id: EventId.make(`event:subagent-prompt:subagent:${index}`),
type: "subagent.updated",
threadId,
occurredAt: now,
payload: {
id,
threadId,
runId: null,
parentNodeId: NodeId.make("node:subagent-prompt-parent"),
origin: "provider_native",
createdBy: "agent",
driver,
providerInstanceId,
providerThreadId: null,
childThreadId: null,
nativeTaskRef: { driver, nativeId: "subagent-prompt", strength: "strong" },
prompt: nextPrompt,
progress,
title: "Audit",
model: null,
status: "running",
result: null,
startedAt: now,
completedAt: null,
updatedAt: now,
},
}) satisfies OrchestrationV2DomainEvent;
const item = (index: number, progress: string, nextPrompt = prompt) =>
({
id: EventId.make(`event:subagent-prompt:item:${index}`),
type: "turn-item.updated",
threadId,
occurredAt: now,
payload: {
id: TurnItemId.make("item:subagent-prompt"),
type: "subagent",
threadId,
runId: null,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
status: "running",
title: "Audit",
subagentId: id,
origin: "provider_native",
driver,
providerInstanceId,
childThreadId: null,
prompt: nextPrompt,
progress,
result: null,
startedAt: now,
completedAt: null,
updatedAt: now,
},
}) satisfies OrchestrationV2DomainEvent;
const events = [
subagent(0, "Reading files"),
item(0, "Reading files"),
subagent(1, "Running tests"),
item(1, "Running tests"),
subagent(2, "Writing report"),
item(2, "Writing report"),
subagent(3, "Retrying", "Audit again."),
item(3, "Retrying", "Audit again."),
];
yield* store.appendAgentEvents({ events });
const stored = yield* sql<{ readonly payload_json: string }>`
SELECT payload_json FROM orchestration_events
WHERE stream_id = ${threadId} ORDER BY sequence ASC
`;
assert.deepEqual(
stored.map((row) => row.payload_json.includes(prompt)),
[true, true, false, false, false, false, false, false],
);
const replayed = yield* store
.readAgentEvents({ threadId, afterSequence })
.pipe(Stream.runCollect);
assert.deepEqual(
replayed.map((entry) => entry.event),
events,
);
// Replay budgets measure the payloads replay decodes, not the slimmer stored rows.
const stats = yield* store.getAgentReplayStats({
threadId,
afterSequence,
throughSequence: yield* store.latestApplicationSequence,
maxEvents: events.length,
});
assert.isAbove(stats.rawPayloadBytes, prompt.length * 6);
const applicationStats = yield* store.getReplayStats({
afterSequence,
throughSequence: yield* store.latestApplicationSequence,
});
assert.isAbove(applicationStats.rawPayloadBytes, prompt.length * 6);
}),
);
it.effect("stores the full subagent prompt when its hint row was rolled back", () =>
Effect.gen(function* () {
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const afterSequence = yield* store.latestApplicationSequence;
const now = yield* DateTime.now;
const threadId = ThreadId.make("thread:subagent-rollback");
const event = {
id: EventId.make("event:subagent-rollback"),
type: "subagent.updated",
threadId,
occurredAt: now,
payload: {
id: NodeId.make("node:subagent-rollback"),
threadId,
runId: null,
parentNodeId: NodeId.make("node:subagent-rollback-parent"),
origin: "provider_native",
createdBy: "agent",
driver: ProviderDriverKind.make("claudeAgent"),
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
providerThreadId: null,
childThreadId: null,
nativeTaskRef: null,
prompt: "Audit the repository. ".repeat(200),
progress: "Reading files",
title: "Audit",
model: null,
status: "running",
result: null,
startedAt: now,
completedAt: null,
updatedAt: now,
},
} satisfies OrchestrationV2DomainEvent;
const rolledBack = yield* sql
.withTransaction(
store
.appendAgentEvents({ events: [event] })
.pipe(Effect.andThen(Effect.fail("rollback"))),
)
.pipe(Effect.flip);
assert.equal(rolledBack, "rollback");
const rowsAfterRollback = yield* sql`
SELECT sequence FROM orchestration_events WHERE stream_id = ${threadId}
`;
assert.deepEqual(rowsAfterRollback, []);
const events = [event, { ...event, id: EventId.make("event:subagent-after-rollback") }];
const appended = yield* store.appendAgentEvents({ events });
assert.deepEqual(
appended.map((entry) => entry.event),
events,
);
const stored = yield* sql<{
readonly prompt: string | null;
readonly prompt_sequence: number | null;
}>`
SELECT json_extract(payload_json, '$.prompt') AS prompt,
json_extract(payload_json, '$.promptSequence') AS prompt_sequence
FROM orchestration_events WHERE stream_id = ${threadId} ORDER BY sequence
`;
assert.deepEqual(stored, [
{ prompt: event.payload.prompt, prompt_sequence: null },
{ prompt: "", prompt_sequence: appended[0]!.sequence },
]);
const replayed = yield* store.readAgentEvents({ threadId }).pipe(Stream.runCollect);
assert.deepEqual(replayed, appended);
const applicationEvents = yield* store
.readApplicationEvents({
afterSequence,
throughSequence: appended[1]!.sequence,
})
.pipe(Stream.runCollect);
assert.deepEqual(applicationEvents, [...appended]);
}),
);
it.effect("stores json columns as strings and replays CLI-origin events", () =>
Effect.gen(function* () {
const eventStore = yield* OrchestrationEventStore.OrchestrationEventStore;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -296,6 +296,21 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
const makeEventStore = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const committedEvents = yield* PubSub.unbounded<ApplicationStoredEvent>();
// Sequence of the latest row storing each subagent's full prompt. The INSERT re-checks it.
const promptHints = new Map<string, number>();
// Puts back a subagent prompt that appendAgentEvents stored once, behind `promptSequence`.
const restoredPayloadJson = sql`CASE
WHEN orchestration_events.event_type IN ('subagent.updated', 'turn-item.updated')
AND json_type(orchestration_events.payload_json, '$.promptSequence') = 'integer'
THEN json_set(
json_remove(orchestration_events.payload_json, '$.promptSequence'),
'$.prompt',
(SELECT json_extract(anchor.payload_json, '$.prompt')
FROM orchestration_events AS anchor
WHERE anchor.sequence = json_extract(orchestration_events.payload_json, '$.promptSequence'))
)
ELSE orchestration_events.payload_json
END`;
const appendProjectEventRow = SqlSchema.findOne({
Request: AppendProjectEventRequestSchema,
Expand Down
Expand Up
@@ -400,7 +415,7 @@ const makeEventStore = Effect.gen(function* () {
stream_id,
event_type,
occurred_at,
payload_json,
${restoredPayloadJson} AS payload_json,
metadata_json,
application_event_version,
causation_event_id,
Expand Down
Expand Up
@@ -440,7 +455,33 @@ const makeEventStore = Effect.gen(function* () {
(event) =>
Effect.gen(function* () {
const encoded = yield* encodeV2EventJson(event);
const rows = yield* sql<{ readonly sequence: number }>`
const subagent =
encoded.type === "subagent.updated"
? encoded.payload
: encoded.type === "turn-item.updated" && encoded.payload.type === "subagent"
? encoded.payload
: undefined;
const promptKey = subagent === undefined ? undefined : `${event.type}:${subagent.id}`;
const hint = promptKey === undefined ? undefined : promptHints.get(promptKey);
const payloadJson = yield* encodeJson(encoded.payload);
// Progress ticks repeat an unchanged prompt, so store it once and point
// later rows at it. Keep an empty prompt so older servers still decode
// the row. ProjectionMaintenance never deletes these anchor rows. The
// hint is re-checked here because its transaction may have rolled back.
const storedPayload =
hint !== undefined && subagent !== undefined
? sql`CASE WHEN EXISTS (
SELECT 1 FROM orchestration_events
WHERE sequence = ${hint}
AND json_type(payload_json, '$.promptSequence') IS NULL
AND json_extract(payload_json, '$.prompt') = ${subagent.prompt}
) THEN json_set(${payloadJson}, '$.prompt', '', '$.promptSequence', CAST(${hint} AS INTEGER))
ELSE ${payloadJson} END`
: sql`${payloadJson}`;
const rows = yield* sql<{
readonly sequence: number;
readonly stores_full_prompt?: number;
}>`
INSERT INTO orchestration_events (
event_id,
aggregate_kind,
Expand Down
Expand Up
@@ -474,12 +515,29 @@ const makeEventStore = Effect.gen(function* () {
NULL,
${input.commandId ?? null},
${event.rawEventId === undefined ? "server" : "provider"},
${yield* encodeJson(encoded.payload) },
${storedPayload },
${yield* encodeJson(metadataForV2Event(event))},
2
)
RETURNING sequence
RETURNING sequence${
hint === undefined
? sql``
: sql`, json_type(payload_json, '$.promptSequence') IS NULL AS stores_full_prompt`
}
`;
const row = rows[0];
if (promptKey !== undefined && row !== undefined) {
// Delete first so Map order tracks recent use and eviction drops idle subagents.
promptHints.delete(promptKey);
promptHints.set(
promptKey,
hint === undefined || row.stores_full_prompt === 1 ? row.sequence : hint,
);
if (promptHints.size > 4096) {
const oldest = promptHints.keys().next().value;
if (oldest !== undefined) promptHints.delete(oldest);
}
}
return yield* decodeV2StoredEvent({
sequence: rows[0]?.sequence,
commandId: input.commandId ?? null,
Expand Down
Expand Up
@@ -555,7 +613,7 @@ const makeEventStore = Effect.gen(function* () {
COALESCE(SUM(octet_length(payload_json)), 0) AS "rawPayloadBytes",
COALESCE(MAX(event_type = 'thread.created'), 0) AS "hasCreateEvent"
FROM (
SELECT payload_json, event_type
SELECT ${restoredPayloadJson} AS payload_json, event_type
FROM orchestration_events
WHERE aggregate_kind = 'thread'
AND stream_id = ${input.threadId}
Expand All
@@ -578,7 +636,7 @@ const makeEventStore = Effect.gen(function* () {
sql<{ readonly eventCount: number; readonly rawPayloadBytes: number }>`
SELECT
COUNT(*) AS "eventCount",
COALESCE(SUM(octet_length(payload_json )), 0) AS "rawPayloadBytes"
COALESCE(SUM(octet_length(${restoredPayloadJson} )), 0) AS "rawPayloadBytes"
FROM orchestration_events INDEXED BY idx_orchestration_events_application_high_water
WHERE sequence > ${input.afterSequence}
AND sequence <= ${input.throughSequence}
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.