perf(server): bound snapshot activity payload memory (#9000)
This commit is contained in:
1 parent
73776d4e52
commit
a9ffb82796
5 files changed
+449
-94
No files matched your search
@@ -64,6 +64,28 @@ describe("projectActivityPayload", () => {
|
||||
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
|
||||
});
|
||||
|
||||
it("keeps preview normalization and fence-only fallback while scanning lines", () => {
|
||||
const preview = projectActivityPayload(
|
||||
activity({
|
||||
itemType: "command_execution",
|
||||
data: { rawOutput: `\`\`\`\n actual\tresult \n${"x".repeat(5000)}` },
|
||||
}),
|
||||
);
|
||||
const fences = projectActivityPayload(
|
||||
activity({
|
||||
itemType: "command_execution",
|
||||
data: { rawOutput: "```\r\n \t \n```\n" },
|
||||
}),
|
||||
);
|
||||
|
||||
expect((preview.payload as { data: { rawOutput: unknown } }).data.rawOutput).toEqual({
|
||||
content: "actual result",
|
||||
});
|
||||
expect((fences.payload as { data: { rawOutput: unknown } }).data.rawOutput).toEqual({
|
||||
content: "2 lines",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps bounded Claude and ACP command output summaries", () => {
|
||||
const claude = projectActivityPayload(
|
||||
activity({
|
||||
|
||||
@@ -144,22 +144,29 @@ function projectCommandValue(data: Record<string, unknown>): unknown {
|
||||
}
|
||||
|
||||
function summarizeToolTextOutput(value: string): string | null {
|
||||
const lines: string[] = [];
|
||||
for (const rawLine of value.split(/\r?\n/u)) {
|
||||
const line = rawLine.replace(/\s+/g, " ").trim();
|
||||
let meaningfulLineCount = 0;
|
||||
let offset = 0;
|
||||
|
||||
while (offset <= value.length) {
|
||||
const newlineIndex = value.indexOf("\n", offset);
|
||||
const lineEnd = newlineIndex === -1 ? value.length : newlineIndex;
|
||||
const line = value.slice(offset, lineEnd).replace(/\s+/g, " ").trim();
|
||||
if (line.length > 0) {
|
||||
lines.push(line);
|
||||
meaningfulLineCount += 1;
|
||||
if (line !== "```") {
|
||||
const summary = line.length <= 84 ? line : `${line.slice(0, 83).trimEnd()}…`;
|
||||
// V8 can retain the full tool output behind a short sliced string.
|
||||
// Join a tiny character array so the returned preview owns its bytes.
|
||||
return Array.from(summary).join("");
|
||||
}
|
||||
}
|
||||
if (newlineIndex === -1) {
|
||||
break;
|
||||
}
|
||||
offset = newlineIndex + 1;
|
||||
}
|
||||
|
||||
const firstLine = lines.find((line) => line !== "```");
|
||||
if (firstLine) {
|
||||
return firstLine.length <= 84 ? firstLine : `${firstLine.slice(0, 83).trimEnd()}…`;
|
||||
}
|
||||
if (lines.length > 1) {
|
||||
return `${lines.length.toLocaleString()} lines`;
|
||||
}
|
||||
return null;
|
||||
return meaningfulLineCount > 1 ? `${meaningfulLineCount.toLocaleString()} lines` : null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -21,6 +21,7 @@ import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
|
||||
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
import { encodeThreadDetailPageCursor } from "../threadDetailCursor.ts";
|
||||
import { projectThreadDetailSnapshot } from "../ActivityPayloadProjection.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.make(value);
|
||||
@@ -2389,9 +2390,84 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =
|
||||
'thread-w',
|
||||
'turn-5',
|
||||
'tool',
|
||||
'tool.completed',
|
||||
CASE
|
||||
WHEN sequence = 2 THEN 'tool.updated'
|
||||
WHEN sequence IN (3, 70) THEN 'context-window.updated'
|
||||
ELSE 'tool.completed'
|
||||
END,
|
||||
'ran tool',
|
||||
printf('{"sequence":%d}', sequence),
|
||||
CASE
|
||||
WHEN sequence IN (2, 80) THEN json_object(
|
||||
'itemType', 'command_execution',
|
||||
'toolCallId', 'cross-batch-call',
|
||||
'title', CASE WHEN sequence = 80 THEN 'Build completed' ELSE 'Build' END,
|
||||
'status', 'completed',
|
||||
'data', json_object(
|
||||
'toolCallId', 'cross-batch-call',
|
||||
'item', json_object(
|
||||
'command', 'vp test run',
|
||||
'aggregatedOutput', printf(
|
||||
'command output%s%s',
|
||||
char(10),
|
||||
replace(hex(zeroblob(8192)), '00', 'x')
|
||||
)
|
||||
),
|
||||
'rawOutput', printf(
|
||||
'raw output%s%s',
|
||||
char(10),
|
||||
replace(hex(zeroblob(8192)), '00', 'y')
|
||||
),
|
||||
'files', json_array(json_object('path', 'apps/server/src/snapshot.ts'))
|
||||
)
|
||||
)
|
||||
WHEN sequence = 10 THEN json_object(
|
||||
'itemType', 'mcp_tool_call',
|
||||
'status', 'completed',
|
||||
'data', json_object(
|
||||
'item', json_object(
|
||||
'type', 'mcpToolCall',
|
||||
'id', 'mcp-item-10',
|
||||
'tool', 'fetch_pr',
|
||||
'server', 'github',
|
||||
'status', 'completed',
|
||||
'arguments', json_object('pr', 42),
|
||||
'result', json_object(
|
||||
'content', json_array(json_object(
|
||||
'type', 'text',
|
||||
'text', printf(
|
||||
'PR body line one%s%s',
|
||||
char(10),
|
||||
replace(hex(zeroblob(8192)), '00', 'z')
|
||||
)
|
||||
))
|
||||
),
|
||||
'_meta', json_object('raw', replace(hex(zeroblob(8192)), '00', 'q'))
|
||||
)
|
||||
)
|
||||
)
|
||||
WHEN sequence = 11 THEN json_object(
|
||||
'itemType', 'command_execution',
|
||||
'status', 'completed',
|
||||
'data', json_object(
|
||||
'item', json_object(
|
||||
'status', 'failed',
|
||||
'command', 'vp test run',
|
||||
'aggregatedOutput', printf(
|
||||
'failed command%s%s',
|
||||
char(10),
|
||||
replace(hex(zeroblob(8192)), '00', 'w')
|
||||
)
|
||||
),
|
||||
'rawOutput', json_object('stdout', 'failed output'),
|
||||
'files', json_array(json_object('path', 'apps/server/src/failed.ts'))
|
||||
)
|
||||
)
|
||||
WHEN sequence IN (3, 70) THEN json_object(
|
||||
'usedTokens', sequence * 100,
|
||||
'modelContextWindow', 100000
|
||||
)
|
||||
ELSE json_object('sequence', sequence)
|
||||
END,
|
||||
sequence,
|
||||
'2026-03-01T00:04:00.000Z'
|
||||
FROM activity_rows
|
||||
@@ -2469,12 +2545,14 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =
|
||||
const detailWithPinnedRequests = yield* snapshotQuery.getThreadDetailById(threadW);
|
||||
assert.equal(detailWithPinnedRequests._tag, "Some");
|
||||
if (detailWithPinnedRequests._tag === "Some") {
|
||||
const ids = detailWithPinnedRequests.value.activities.map((activity) => activity.id);
|
||||
const ids = new Set(
|
||||
detailWithPinnedRequests.value.activities.map((activity) => activity.id),
|
||||
);
|
||||
assert.equal(detailWithPinnedRequests.value.activities.length, 503);
|
||||
assert.equal(ids.includes(asEventId("approval-old")), true);
|
||||
assert.equal(ids.includes(asEventId("user-input-old")), true);
|
||||
assert.equal(ids.includes(asEventId("user-input-closed")), false);
|
||||
assert.equal(ids.includes(asEventId("user-input-tied-z-request")), true);
|
||||
assert.equal(ids.has(asEventId("approval-old")), true);
|
||||
assert.equal(ids.has(asEventId("user-input-old")), true);
|
||||
assert.equal(ids.has(asEventId("user-input-closed")), false);
|
||||
assert.equal(ids.has(asEventId("user-input-tied-z-request")), true);
|
||||
}
|
||||
|
||||
const windowWithPinnedRequests = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
|
||||
@@ -2482,12 +2560,67 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =
|
||||
});
|
||||
assert.equal(windowWithPinnedRequests._tag, "Some");
|
||||
if (windowWithPinnedRequests._tag === "Some") {
|
||||
const ids = windowWithPinnedRequests.value.thread.activities.map((activity) => activity.id);
|
||||
const ids = new Set(
|
||||
windowWithPinnedRequests.value.thread.activities.map((activity) => activity.id),
|
||||
);
|
||||
assert.equal(windowWithPinnedRequests.value.thread.activities.length, 503);
|
||||
assert.equal(ids.includes(asEventId("approval-old")), true);
|
||||
assert.equal(ids.includes(asEventId("user-input-old")), true);
|
||||
assert.equal(ids.includes(asEventId("user-input-closed")), false);
|
||||
assert.equal(ids.includes(asEventId("user-input-tied-z-request")), true);
|
||||
assert.equal(ids.has(asEventId("approval-old")), true);
|
||||
assert.equal(ids.has(asEventId("user-input-old")), true);
|
||||
assert.equal(ids.has(asEventId("user-input-closed")), false);
|
||||
assert.equal(ids.has(asEventId("user-input-tied-z-request")), true);
|
||||
}
|
||||
|
||||
const fullSnapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW);
|
||||
assert.equal(fullSnapshot._tag, "Some");
|
||||
if (
|
||||
detailWithPinnedRequests._tag === "Some" &&
|
||||
fullSnapshot._tag === "Some" &&
|
||||
windowWithPinnedRequests._tag === "Some"
|
||||
) {
|
||||
const projectedFullSnapshot = projectThreadDetailSnapshot(fullSnapshot.value);
|
||||
const projectedRawBaseline = projectThreadDetailSnapshot({
|
||||
snapshotSequence: fullSnapshot.value.snapshotSequence,
|
||||
thread: detailWithPinnedRequests.value,
|
||||
});
|
||||
assert.deepStrictEqual(projectedFullSnapshot, projectedRawBaseline);
|
||||
|
||||
const rawActivitiesById = new Map(
|
||||
detailWithPinnedRequests.value.activities.map((activity) => [activity.id, activity]),
|
||||
);
|
||||
const projectedWindowSnapshot = projectThreadDetailSnapshot(windowWithPinnedRequests.value);
|
||||
const projectedWindowBaseline = projectThreadDetailSnapshot({
|
||||
...windowWithPinnedRequests.value,
|
||||
thread: {
|
||||
...windowWithPinnedRequests.value.thread,
|
||||
activities: windowWithPinnedRequests.value.thread.activities.map(
|
||||
(activity) => rawActivitiesById.get(activity.id) ?? activity,
|
||||
),
|
||||
},
|
||||
});
|
||||
assert.deepStrictEqual(projectedWindowSnapshot, projectedWindowBaseline);
|
||||
|
||||
const projectedIds = new Set(
|
||||
projectedFullSnapshot.thread.activities.map((activity) => activity.id),
|
||||
);
|
||||
assert.equal(projectedIds.has(asEventId("activity-0002")), false);
|
||||
assert.equal(projectedIds.has(asEventId("activity-0003")), false);
|
||||
assert.equal(projectedIds.has(asEventId("activity-0070")), true);
|
||||
|
||||
const failedCommand = projectedFullSnapshot.thread.activities.find(
|
||||
(activity) => activity.id === asEventId("activity-0011"),
|
||||
);
|
||||
assert.deepStrictEqual(failedCommand?.payload, {
|
||||
itemType: "command_execution",
|
||||
status: "failed",
|
||||
data: {
|
||||
item: {
|
||||
command: "vp test run",
|
||||
aggregatedOutput: "failed command",
|
||||
},
|
||||
files: [{ path: "apps/server/src/failed.ts" }],
|
||||
rawOutput: { content: "failed output" },
|
||||
},
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -57,6 +57,7 @@ import {
|
||||
decodeThreadDetailPageCursor,
|
||||
encodeThreadDetailPageCursor,
|
||||
} from "../threadDetailCursor.ts";
|
||||
import { projectActivityPayload } from "../ActivityPayloadProjection.ts";
|
||||
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
import {
|
||||
@@ -75,6 +76,9 @@ const decodeThread = Schema.decodeUnknownEffect(OrchestrationThread);
|
||||
// activity window. Applying the limit in SQL avoids decoding an unbounded
|
||||
// payload_json set before the projector can enforce that invariant.
|
||||
const THREAD_DETAIL_ACTIVITY_LIMIT = 500;
|
||||
// Snapshot payloads are decoded and projected in small sequential batches so
|
||||
// one client read does not retain the raw payloads for the full activity window.
|
||||
const THREAD_DETAIL_ACTIVITY_PAYLOAD_BATCH_SIZE = 25;
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
@@ -100,6 +104,9 @@ const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
sequence: Schema.NullOr(NonNegativeInt),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadActivityIdRowSchema = Schema.Struct({
|
||||
activityId: ProjectionThreadActivity.fields.activityId,
|
||||
});
|
||||
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
|
||||
const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
|
||||
Struct.assign({
|
||||
@@ -146,6 +153,9 @@ const ThreadActivityKindsLookupInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
activityKinds: Schema.Array(Schema.String),
|
||||
});
|
||||
const ThreadActivityIdsLookupInput = Schema.Struct({
|
||||
activityIds: Schema.Array(ProjectionThreadActivity.fields.activityId),
|
||||
});
|
||||
// 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
|
||||
@@ -349,6 +359,21 @@ function mapProposedPlanRow(
|
||||
};
|
||||
}
|
||||
|
||||
function mapThreadActivityRow(
|
||||
row: Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>,
|
||||
): OrchestrationThreadActivity {
|
||||
return {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
@@ -1060,6 +1085,44 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityIdsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityIdRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT activity_id AS "activityId"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY
|
||||
sequence DESC,
|
||||
created_at DESC,
|
||||
activity_id DESC
|
||||
LIMIT ${THREAD_DETAIL_ACTIVITY_LIMIT}
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRowsByIds = SqlSchema.findAll({
|
||||
Request: ThreadActivityIdsLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ activityIds }) =>
|
||||
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
|
||||
-- The selectors already scoped these globally unique ids to the
|
||||
-- thread inside this transaction. Keep this as a primary-key lookup.
|
||||
WHERE ${sql.in("activity_id", activityIds)}
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRowsByThreadAndKinds = SqlSchema.findAll({
|
||||
Request: ThreadActivityKindsLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
@@ -1310,15 +1373,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
// Blocking request payloads must remain available even if they predate the
|
||||
// recent activity window. Each CTE returns at most one unresolved row per
|
||||
// request, so the merge below stays bounded by actionable work.
|
||||
const listPinnedThreadActivityRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
WITH pending_approval_requests AS (
|
||||
const pinnedThreadActivityIdsCte = (threadId: string) => sql`
|
||||
pending_approval_requests AS (
|
||||
SELECT request_id, thread_id
|
||||
FROM projection_pending_approvals
|
||||
WHERE thread_id = ${threadId}
|
||||
@@ -1382,6 +1438,17 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
WHERE request_order = 1
|
||||
AND kind = 'user-input.requested'
|
||||
)
|
||||
`;
|
||||
|
||||
// Blocking request payloads must remain available even if they predate the
|
||||
// recent activity window. Each CTE returns at most one unresolved row per
|
||||
// request, so the merge below stays bounded by actionable work.
|
||||
const listPinnedThreadActivityRowsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
WITH ${pinnedThreadActivityIdsCte(threadId)}
|
||||
SELECT
|
||||
activity.activity_id AS "activityId",
|
||||
activity.thread_id AS "threadId",
|
||||
@@ -1399,6 +1466,17 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listPinnedThreadActivityIdsByThread = SqlSchema.findAll({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadActivityIdRowSchema,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
WITH ${pinnedThreadActivityIdsCte(threadId)}
|
||||
SELECT activity_id AS "activityId"
|
||||
FROM pinned_activity_ids
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRowsByThreadWindow = SqlSchema.findAll({
|
||||
Request: ThreadTurnRangeLookupInput,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
@@ -1466,6 +1544,48 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityIdsByThreadWindow = SqlSchema.findAll({
|
||||
Request: ThreadTurnRangeLookupInput,
|
||||
Result: ProjectionThreadActivityIdRowSchema,
|
||||
execute: ({ threadId, minAnchorAt, minTurnKey, beforeAnchorAt, beforeTurnKey }) =>
|
||||
sql`
|
||||
SELECT activity_id AS "activityId"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
AND (
|
||||
turn_id IN (
|
||||
SELECT turn_id FROM projection_turns
|
||||
WHERE thread_id = ${threadId}
|
||||
AND turn_id IS NOT NULL
|
||||
AND (
|
||||
requested_at > ${minAnchorAt}
|
||||
OR (
|
||||
requested_at = ${minAnchorAt}
|
||||
AND turn_id >= ${minTurnKey}
|
||||
)
|
||||
)
|
||||
AND (
|
||||
requested_at < ${beforeAnchorAt}
|
||||
OR (
|
||||
requested_at = ${beforeAnchorAt}
|
||||
AND turn_id < ${beforeTurnKey}
|
||||
)
|
||||
)
|
||||
)
|
||||
OR (
|
||||
turn_id IS NULL
|
||||
AND created_at >= ${minAnchorAt}
|
||||
AND created_at < ${beforeAnchorAt}
|
||||
)
|
||||
)
|
||||
ORDER BY
|
||||
sequence DESC,
|
||||
created_at DESC,
|
||||
activity_id DESC
|
||||
LIMIT ${THREAD_DETAIL_ACTIVITY_LIMIT}
|
||||
`,
|
||||
});
|
||||
|
||||
const getFullThreadDiffContextRow = SqlSchema.findOneOption({
|
||||
Request: FullThreadDiffContextLookupInput,
|
||||
Result: ProjectionFullThreadDiffContextRowSchema,
|
||||
@@ -2571,49 +2691,136 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
readonly beforeTurnKey: string;
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
type ThreadDetailActivityRead =
|
||||
| {
|
||||
readonly mode: "raw";
|
||||
readonly query?: ProjectionThreadDetailQuery;
|
||||
}
|
||||
| {
|
||||
readonly mode: "client";
|
||||
};
|
||||
|
||||
const listProjectedThreadActivities = Effect.fn(
|
||||
"ProjectionSnapshotQuery.listProjectedThreadActivities",
|
||||
)(function* (threadId: ThreadId, bounds: ThreadDetailBounds | undefined) {
|
||||
const [activityIdRows, pinnedActivityIdRows] = yield* Effect.all([
|
||||
(bounds === undefined
|
||||
? listThreadActivityIdsByThread({ threadId })
|
||||
: listThreadActivityIdsByThreadWindow({ threadId, ...bounds })
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivityIds:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivityIds:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listPinnedThreadActivityIdsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivityIds:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivityIds:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
const activityIds = [
|
||||
...new Set([...activityIdRows, ...pinnedActivityIdRows].map(({ activityId }) => activityId)),
|
||||
];
|
||||
const activities: OrchestrationThreadActivity[] = [];
|
||||
|
||||
for (
|
||||
let offset = 0;
|
||||
offset < activityIds.length;
|
||||
offset += THREAD_DETAIL_ACTIVITY_PAYLOAD_BATCH_SIZE
|
||||
) {
|
||||
const batchIds = activityIds.slice(
|
||||
offset,
|
||||
offset + THREAD_DETAIL_ACTIVITY_PAYLOAD_BATCH_SIZE,
|
||||
);
|
||||
const batchRows = yield* listThreadActivityRowsByIds({ activityIds: batchIds }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivityPayloadBatch:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivityPayloadBatch:decodeRows",
|
||||
),
|
||||
),
|
||||
);
|
||||
const pinnedActivityRowsEffect =
|
||||
query?.activityKinds === undefined
|
||||
? listPinnedThreadActivityRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:decodeRows",
|
||||
for (const row of batchRows) {
|
||||
activities.push(projectActivityPayload(mapThreadActivityRow(row)));
|
||||
}
|
||||
}
|
||||
|
||||
return activities.toSorted(
|
||||
(left, right) =>
|
||||
(left.sequence ?? -1) - (right.sequence ?? -1) ||
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.id.localeCompare(right.id),
|
||||
);
|
||||
});
|
||||
|
||||
const getThreadDetailByIdBounded = (
|
||||
threadId: ThreadId,
|
||||
bounds: ThreadDetailBounds | undefined,
|
||||
activityRead: ThreadDetailActivityRead = { mode: "raw" },
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const activitiesEffect =
|
||||
activityRead.mode === "client"
|
||||
? listProjectedThreadActivities(threadId, bounds)
|
||||
: Effect.all([
|
||||
(activityRead.query?.activityKinds === undefined
|
||||
? bounds === undefined
|
||||
? listThreadActivityRowsByThread({ threadId })
|
||||
: listThreadActivityRowsByThreadWindow({ threadId, ...bounds })
|
||||
: activityRead.query.activityKinds.length === 0
|
||||
? Effect.succeed([])
|
||||
: listThreadActivityRowsByThreadAndKinds({
|
||||
threadId,
|
||||
activityKinds: activityRead.query.activityKinds,
|
||||
})
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: Effect.succeed([]);
|
||||
activityRead.query?.activityKinds === undefined
|
||||
? listPinnedThreadActivityRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:query",
|
||||
"ProjectionSnapshotQuery.getThreadDetailById:listPinnedActivities:decodeRows",
|
||||
),
|
||||
),
|
||||
)
|
||||
: Effect.succeed([]),
|
||||
]).pipe(
|
||||
Effect.map(([activityRows, pinnedActivityRows]) =>
|
||||
[
|
||||
...new Map(
|
||||
[...activityRows, ...pinnedActivityRows].map(
|
||||
(row) => [row.activityId, row] as const,
|
||||
),
|
||||
).values(),
|
||||
]
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
(left.sequence ?? -1) - (right.sequence ?? -1) ||
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.activityId.localeCompare(right.activityId),
|
||||
)
|
||||
.map(mapThreadActivityRow),
|
||||
),
|
||||
);
|
||||
|
||||
const [
|
||||
threadRow,
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
pinnedActivityRows,
|
||||
activities,
|
||||
checkpointRows,
|
||||
latestTurnRow,
|
||||
sessionRow,
|
||||
@@ -2645,8 +2852,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
activityRowsEffect,
|
||||
pinnedActivityRowsEffect,
|
||||
activitiesEffect,
|
||||
listCheckpointRowsByThread({ threadId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -2677,17 +2883,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
return Option.none<OrchestrationThread>();
|
||||
}
|
||||
|
||||
const selectedActivityRows = [
|
||||
...new Map(
|
||||
[...activityRows, ...pinnedActivityRows].map((row) => [row.activityId, row] as const),
|
||||
).values(),
|
||||
].toSorted(
|
||||
(left, right) =>
|
||||
(left.sequence ?? -1) - (right.sequence ?? -1) ||
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.activityId.localeCompare(right.activityId),
|
||||
);
|
||||
|
||||
const thread = {
|
||||
id: threadRow.value.threadId,
|
||||
projectId: threadRow.value.projectId,
|
||||
@@ -2729,21 +2924,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
return message;
|
||||
}),
|
||||
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
|
||||
activities: selectedActivityRows.map((row) => {
|
||||
const activity = {
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
if (row.sequence !== null) {
|
||||
return Object.assign(activity, { sequence: row.sequence });
|
||||
}
|
||||
return activity;
|
||||
}),
|
||||
activities,
|
||||
checkpoints: checkpointRows.map((row) => ({
|
||||
turnId: row.turnId,
|
||||
checkpointTurnCount: row.checkpointTurnCount,
|
||||
@@ -2768,7 +2949,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (
|
||||
threadId,
|
||||
query,
|
||||
) => getThreadDetailByIdBounded(threadId, undefined, query);
|
||||
) =>
|
||||
getThreadDetailByIdBounded(threadId, undefined, {
|
||||
mode: "raw",
|
||||
...(query === 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
|
||||
@@ -2792,7 +2977,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
if (window?.turnLimit === undefined) {
|
||||
const thread = yield* getThreadDetailById(threadId);
|
||||
const thread = yield* getThreadDetailByIdBounded(threadId, undefined, {
|
||||
mode: "client",
|
||||
});
|
||||
if (Option.isNone(thread)) {
|
||||
return Option.none<OrchestrationThreadDetailSnapshot>();
|
||||
}
|
||||
@@ -2845,7 +3032,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
? { minAnchorAt: "", minTurnKey: "", beforeAnchorAt: "", beforeTurnKey: "" }
|
||||
: undefined;
|
||||
|
||||
const thread = yield* getThreadDetailByIdBounded(threadId, emptyBounds ?? bounds);
|
||||
const thread = yield* getThreadDetailByIdBounded(threadId, emptyBounds ?? bounds, {
|
||||
mode: "client",
|
||||
});
|
||||
if (Option.isNone(thread)) {
|
||||
return Option.none<OrchestrationThreadDetailSnapshot>();
|
||||
}
|
||||
|
||||
@@ -191,6 +191,10 @@ export interface ProjectionSnapshotQueryShape {
|
||||
* response carries `page` metadata (see `OrchestrationThreadDetailWindow`).
|
||||
* Without a window the full thread is returned with no `page` field —
|
||||
* pagination is strictly opt-in.
|
||||
*
|
||||
* Activity payloads are projected for clients as they are read in small
|
||||
* sequential batches. Callers still apply the full snapshot projector for
|
||||
* collection-level activity pruning.
|
||||
*/
|
||||
readonly getThreadDetailSnapshot: (
|
||||
threadId: ThreadId,
|
||||
|
||||
Reference in new issue
Block a user