perf(server): reduce frequency of full tool call output being loaded into memory from db (#8988)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-08-31 20:36:53 -07:00
1 parent 42a8fd5103
commit b17cc3d1bf
10 files changed
+363 -98

No files matched your search

@@ -164,7 +164,7 @@ const make = Effect.gen(function* () {
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
return yield* projectionSnapshotQuery
.getThreadDetailById(threadId)
.getThreadDetailById(threadId, { activityKinds: [] })
.pipe(Effect.map(Option.getOrUndefined));
});
@@ -2235,7 +2235,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("clears stale pending user input from projected shell summaries", () =>
it.effect("reads only user-input activities when refreshing shell summaries", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
@@ -2293,70 +2293,128 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
},
});
// Invalid JSON proves the summary query filters tool rows before decoding payloads.
yield* sql`
INSERT INTO projection_thread_activities (
activity_id,
thread_id,
turn_id,
tone,
kind,
summary,
payload_json,
sequence,
created_at
)
VALUES
(
'activity-malformed-tool-output',
'thread-stale-user-input',
NULL,
'info',
'tool.completed',
'Tool completed',
'{not-json',
NULL,
'2026-02-26T12:35:02.000Z'
),
(
'activity-user-input-resolved-requested',
'thread-stale-user-input',
NULL,
'info',
'user-input.requested',
'User input requested',
json_object('requestId', 'user-input-resolved'),
NULL,
'2026-02-26T12:35:03.000Z'
),
(
'activity-user-input-resolved',
'thread-stale-user-input',
NULL,
'info',
'user-input.resolved',
'User input resolved',
json_object('requestId', 'user-input-resolved'),
NULL,
'2026-02-26T12:35:04.000Z'
),
(
'activity-user-input-stale-requested',
'thread-stale-user-input',
NULL,
'info',
'user-input.requested',
'User input requested',
json_object('requestId', 'user-input-stale'),
NULL,
'2026-02-26T12:35:05.000Z'
),
(
'activity-user-input-stale-failed',
'thread-stale-user-input',
NULL,
'error',
'provider.user-input.respond.failed',
'Provider user input response failed',
json_object(
'requestId',
'user-input-stale',
'detail',
'Unknown pending Codex user input request: user-input-stale'
),
NULL,
'2026-02-26T12:35:06.000Z'
),
(
'activity-user-input-active-requested',
'thread-stale-user-input',
NULL,
'info',
'user-input.requested',
'User input requested',
json_object('requestId', 'user-input-active'),
NULL,
'2026-02-26T12:35:07.000Z'
),
(
'activity-user-input-active-failed',
'thread-stale-user-input',
NULL,
'error',
'provider.user-input.respond.failed',
'Provider user input response failed',
json_object(
'requestId',
'user-input-active',
'detail',
'Provider is temporarily unavailable'
),
NULL,
'2026-02-26T12:35:08.000Z'
)
`;
yield* appendAndProject({
type: "thread.activity-appended",
type: "thread.message-sent",
eventId: EventId.make("evt-stale-user-input-3"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:02.000Z",
occurredAt: "2026-02-26T12:35:09.000Z",
commandId: CommandId.make("cmd-stale-user-input-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-3"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
activity: {
id: EventId.make("activity-stale-user-input-requested"),
tone: "info",
kind: "user-input.requested",
summary: "User input requested",
payload: {
requestId: "user-input-request-stale-1",
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
turnId: null,
createdAt: "2026-02-26T12:35:02.000Z",
},
},
});
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-stale-user-input-4"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:03.000Z",
commandId: CommandId.make("cmd-stale-user-input-4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-4"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
activity: {
id: EventId.make("activity-stale-user-input-failed"),
tone: "error",
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
payload: {
requestId: "user-input-request-stale-1",
detail:
"Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: user-input-request-stale-1",
},
turnId: null,
createdAt: "2026-02-26T12:35:03.000Z",
},
messageId: MessageId.make("message-stale-user-input"),
role: "user",
text: "Continue",
turnId: null,
streaming: false,
createdAt: "2026-02-26T12:35:09.000Z",
updatedAt: "2026-02-26T12:35:09.000Z",
},
});
@@ -2367,7 +2425,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
FROM projection_threads
WHERE thread_id = 'thread-stale-user-input'
`;
assert.deepEqual(threadRows, [{ pendingUserInputCount: 0 }]);
assert.deepEqual(threadRows, [{ pendingUserInputCount: 1 }]);
}),
);
@@ -130,7 +130,7 @@ function isStalePendingApprovalFailureDetail(detail: string | null): boolean {
);
}
// A full refresh loads all thread history, so skip events that cannot change the summary.
// A refresh reads each persisted summary source, so skip events that cannot change the result.
function shouldRefreshThreadShellSummary(event: OrchestrationEvent): boolean {
if (event.type === "thread.message-sent") {
return event.payload.role === "user";
@@ -588,7 +588,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const [messages, proposedPlans, activities, pendingApprovals] = yield* Effect.all([
projectionThreadMessageRepository.listByThreadId({ threadId }),
projectionThreadProposedPlanRepository.listByThreadId({ threadId }),
projectionThreadActivityRepository.listByThreadId({ threadId }),
projectionThreadActivityRepository.listUserInputLifecycleByThreadId({ threadId }),
projectionPendingApprovalRepository.listByThreadId({ threadId }),
]);
@@ -484,6 +484,77 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
if (threadDetail._tag === "Some") {
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
}
yield* sql`
INSERT INTO projection_thread_activities (
activity_id,
thread_id,
turn_id,
tone,
kind,
summary,
payload_json,
created_at
)
VALUES
(
'activity-task-started',
'thread-1',
'turn-1',
'info',
'task.started',
'Ship the query filter',
'{"taskId":"task-1","detail":"Ship the query filter"}',
'2026-02-24T00:00:06.100Z'
),
(
'activity-malformed-tool',
'thread-1',
'turn-1',
'info',
'tool.completed',
'Malformed tool output',
'not-json',
'2026-02-24T00:00:06.200Z'
)
`;
const detailWithoutActivities = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-1"),
{ activityKinds: [] },
);
assert.equal(detailWithoutActivities._tag, "Some");
if (detailWithoutActivities._tag === "Some") {
assert.deepEqual(detailWithoutActivities.value.activities, []);
assert.deepEqual(detailWithoutActivities.value.messages, snapshot.threads[0]?.messages);
assert.deepEqual(
detailWithoutActivities.value.proposedPlans,
snapshot.threads[0]?.proposedPlans,
);
assert.deepEqual(
detailWithoutActivities.value.checkpoints,
snapshot.threads[0]?.checkpoints,
);
}
const detailWithTaskActivities = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-1"),
{ activityKinds: ["task.started", "task.progress"] },
);
assert.equal(detailWithTaskActivities._tag, "Some");
if (detailWithTaskActivities._tag === "Some") {
assert.deepEqual(detailWithTaskActivities.value.activities, [
{
id: asEventId("activity-task-started"),
tone: "info",
kind: "task.started",
summary: "Ship the query filter",
payload: { taskId: "task-1", detail: "Ship the query filter" },
turnId: asTurnId("turn-1"),
createdAt: "2026-02-24T00:00:06.100Z",
},
]);
}
}),
);
@@ -64,6 +64,7 @@ import {
type ProjectionFullThreadDiffContext,
type ProjectionSnapshotCounts,
type ProjectionThreadCheckpointContext,
type ProjectionThreadDetailQuery,
type ProjectionSnapshotQueryShape,
} from "../Services/ProjectionSnapshotQuery.ts";
@@ -141,6 +142,10 @@ const ProjectIdLookupInput = Schema.Struct({
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
const ThreadActivityKindsLookupInput = Schema.Struct({
threadId: ThreadId,
activityKinds: Schema.Array(Schema.String),
});
// Windowed reads order turns by the stable keyset (anchor, turn key), where
// anchor is requested_at and turn key is
// COALESCE(turn_id, ''). Both are event-derived, so cursors survive the
@@ -1055,6 +1060,48 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listThreadActivityRowsByThreadAndKinds = SqlSchema.findAll({
Request: ThreadActivityKindsLookupInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, activityKinds }) =>
sql`
SELECT
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
tone,
kind,
summary,
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM (
SELECT
activity_id,
thread_id,
turn_id,
tone,
kind,
summary,
payload_json,
sequence,
created_at
FROM projection_thread_activities
WHERE thread_id = ${threadId}
AND ${sql.in("kind", activityKinds)}
ORDER BY
sequence DESC,
created_at DESC,
activity_id DESC
LIMIT ${THREAD_DETAIL_ACTIVITY_LIMIT}
) AS recent_activities
ORDER BY
sequence ASC,
created_at ASC,
activity_id ASC
`,
});
const getThreadSessionRowByThread = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadSessionDbRowSchema,
@@ -2524,8 +2571,43 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
readonly beforeTurnKey: string;
}
const getThreadDetailByIdBounded = (threadId: ThreadId, bounds: ThreadDetailBounds | undefined) =>
const getThreadDetailByIdBounded = (
threadId: ThreadId,
bounds: ThreadDetailBounds | undefined,
query: ProjectionThreadDetailQuery | undefined = undefined,
) =>
Effect.gen(function* () {
const activityRowsEffect = (
query?.activityKinds === undefined
? bounds === undefined
? listThreadActivityRowsByThread({ threadId })
: listThreadActivityRowsByThreadWindow({ threadId, ...bounds })
: query.activityKinds.length === 0
? Effect.succeed([])
: listThreadActivityRowsByThreadAndKinds({
threadId,
activityKinds: query.activityKinds,
})
).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows",
),
),
);
const pinnedActivityRowsEffect =
query?.activityKinds === undefined
? listPinnedThreadActivityRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:query",
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:decodeRows",
),
),
)
: Effect.succeed([]);
const [
threadRow,
messageRows,
@@ -2563,25 +2645,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
(bounds === undefined
? listThreadActivityRowsByThread({ threadId })
: listThreadActivityRowsByThreadWindow({ threadId, ...bounds })
).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows",
),
),
),
listPinnedThreadActivityRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:query",
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:decodeRows",
),
),
),
activityRowsEffect,
pinnedActivityRowsEffect,
listCheckpointRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -2700,8 +2765,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
);
});
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
getThreadDetailByIdBounded(threadId, undefined);
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (
threadId,
query,
) => getThreadDetailByIdBounded(threadId, undefined, query);
// Bounds pathological fan-out: one user turn that spawned hundreds of
// subagent turns still pages in bounded chunks, at the cost of splitting the
@@ -481,7 +481,7 @@ const make = Effect.gen(function* () {
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
return yield* projectionSnapshotQuery
.getThreadDetailById(threadId)
.getThreadDetailById(threadId, { activityKinds: [] })
.pipe(Effect.map(Option.getOrUndefined));
});
@@ -48,6 +48,7 @@ import { canReplaceThreadTitle } from "../threadTitles.ts";
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
const TASK_TITLE_ACTIVITY_KINDS = ["task.started", "task.progress"] as const;
// Fallback when the in-memory description cache no longer has the task name
// (server restart, session-exit sweep, TTL/capacity eviction): earlier
@@ -949,9 +950,12 @@ const make = Effect.gen(function* () {
),
);
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (
threadId: ThreadId,
activityKinds: ReadonlyArray<string> = [],
) {
return yield* projectionSnapshotQuery
.getThreadDetailById(threadId)
.getThreadDetailById(threadId, { activityKinds })
.pipe(Effect.map(Option.getOrUndefined));
});
@@ -2022,7 +2026,7 @@ const make = Effect.gen(function* () {
if (event.type === "task.completed") {
taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId);
if (!taskTitle) {
const threadDetail = yield* getLoadedThreadDetail();
const threadDetail = yield* resolveThreadDetail(thread.id, TASK_TITLE_ACTIVITY_KINDS);
taskTitle = findTaskTitleInActivities(threadDetail?.activities, event.payload.taskId);
}
}
@@ -54,6 +54,15 @@ export interface ProjectionFullThreadDiffContext {
readonly toCheckpointRef: CheckpointRef | null;
}
export interface ProjectionThreadDetailQuery {
/**
* Limit activities before SQLite returns and decodes their payloads.
* Any explicit filter omits pinned-request reads. An empty list also skips
* the activity query. Omit this option to preserve the full detail response.
*/
readonly activityKinds?: ReadonlyArray<string>;
}
/**
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
*/
@@ -168,6 +177,7 @@ export interface ProjectionSnapshotQueryShape {
*/
readonly getThreadDetailById: (
threadId: ThreadId,
query?: ProjectionThreadDetailQuery,
) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;
/**
@@ -23,6 +23,21 @@ const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
}),
);
const mapActivityRows = (
rows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>>,
): ReadonlyArray<ProjectionThreadActivity> =>
rows.map((row) => ({
activityId: row.activityId,
threadId: row.threadId,
turnId: row.turnId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
...(row.sequence !== null ? { sequence: row.sequence } : {}),
createdAt: row.createdAt,
}));
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown) =>
Schema.isSchemaError(cause)
@@ -97,6 +112,36 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
`,
});
const listUserInputLifecycleActivityRows = SqlSchema.findAll({
Request: ListProjectionThreadActivitiesInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
tone,
kind,
summary,
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM projection_thread_activities
WHERE thread_id = ${threadId}
AND kind IN (
'user-input.requested',
'user-input.resolved',
'provider.user-input.respond.failed'
)
ORDER BY
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
sequence ASC,
created_at ASC,
activity_id ASC
`,
});
const deleteProjectionThreadActivityRows = SqlSchema.void({
Request: DeleteProjectionThreadActivitiesInput,
execute: ({ threadId }) =>
@@ -124,21 +169,21 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
"ProjectionThreadActivityRepository.listByThreadId:decodeRows",
),
),
Effect.map((rows) =>
rows.map((row) => ({
activityId: row.activityId,
threadId: row.threadId,
turnId: row.turnId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
...(row.sequence !== null ? { sequence: row.sequence } : {}),
createdAt: row.createdAt,
})),
),
Effect.map(mapActivityRows),
);
const listUserInputLifecycleByThreadId: ProjectionThreadActivityRepositoryShape["listUserInputLifecycleByThreadId"] =
(input) =>
listUserInputLifecycleActivityRows(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionThreadActivityRepository.listUserInputLifecycleByThreadId:query",
"ProjectionThreadActivityRepository.listUserInputLifecycleByThreadId:decodeRows",
),
),
Effect.map(mapActivityRows),
);
const deleteByThreadId: ProjectionThreadActivityRepositoryShape["deleteByThreadId"] = (input) =>
deleteProjectionThreadActivityRows(input).pipe(
Effect.mapError(
@@ -149,6 +194,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
return {
upsert,
listByThreadId,
listUserInputLifecycleByThreadId,
deleteByThreadId,
} satisfies ProjectionThreadActivityRepositoryShape;
});
@@ -67,6 +67,15 @@ export interface ProjectionThreadActivityRepositoryShape {
input: ListProjectionThreadActivitiesInput,
) => Effect.Effect<ReadonlyArray<ProjectionThreadActivity>, ProjectionRepositoryError>;
/**
* List activity rows used to derive pending user-input state.
*
* Filters in SQLite so unrelated payloads do not enter server memory.
*/
readonly listUserInputLifecycleByThreadId: (
input: ListProjectionThreadActivitiesInput,
) => Effect.Effect<ReadonlyArray<ProjectionThreadActivity>, ProjectionRepositoryError>;
/**
* Delete projected thread activity rows by thread.
*/