fix(server): bound + paginate thread activity reads to stop heap OOM

A busy SQLite database materialised hundreds of MB of activity payloads into the
Node heap and crashed the server. Bound the reads and add an on-demand
pagination path so deep history is still recoverable.

- /api/orchestration/snapshot and the `t3` CLI offline path called getSnapshot(),
  loading every thread's full activity/message/checkpoint history even though
  they only read `.projects`. Point both at getCommandReadModel() (same shape,
  without the heavy per-thread tables).
- getThreadDetailById windows activities to the most recent 500 (it fetches
  WINDOW+1 to detect truncation and sets `hasMoreActivities` so clients can
  lazy-load). Live activities still stream in via the event subscription.
- New orchestration.getThreadActivities RPC pages older activities on demand:
  cursor is {beforeSequence} for sequenced rows or {beforeCreatedAt,
  beforeActivityId} for legacy unsequenced (NULL) rows, output {activities,
  hasMore}. The sequenced query orders by `sequence DESC` with
  `(sequence < ? OR sequence IS NULL)` so the (thread_id, sequence, created_at,
  activity_id) index satisfies the ORDER BY instead of a filesort. Unsequenced
  rows page by a (created_at, activity_id) cursor consistent with the window's
  ordering.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
olafuraandClaude Opus 4.8 authored and Julius Marminge committed 2026-07-20 17:25:59 +02:00
1 parent 5d34f9ff23
commit 9382e9024c
13 files changed
+446 -29

No files matched your search

@@ -77,6 +77,8 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -185,6 +187,8 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -268,6 +272,8 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -336,6 +342,8 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
@@ -389,6 +397,8 @@ describe("CheckpointDiffQuery.layer", () => {
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getThreadActivitiesPage: () =>
Effect.die("CheckpointDiffQuery should not request thread activities"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
+3 -1
View File
@@ -337,7 +337,9 @@ const dispatchLiveOrchestrationCommand = (
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
return yield* projectionSnapshotQuery.getSnapshot();
// Project resolution only reads `.projects`; the command read model returns the
// same shape without loading the heavy per-thread activity/message tables.
return yield* projectionSnapshotQuery.getCommandReadModel();
});
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
@@ -201,6 +201,7 @@ describe("OrchestrationEngine", () => {
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
),
Layer.provide(
@@ -342,6 +342,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
createdAt: "2026-02-24T00:00:06.000Z",
},
],
hasMoreActivities: false,
checkpoints: [
{
turnId: asTurnId("turn-1"),
@@ -974,6 +975,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
assert.equal(threadDetail._tag, "Some");
if (threadDetail._tag === "Some") {
assert.deepEqual(threadDetail.value.activities, snapshot.threads[0]?.activities ?? []);
// Well under the window — nothing older to lazy-load.
assert.equal(threadDetail.value.hasMoreActivities, false);
}
assert.deepEqual(snapshot.threads[0]?.activities ?? [], [
@@ -1153,6 +1156,159 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
}),
);
it.effect(
"windows thread-detail activities to the most recent 500 and pages older on demand",
() =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, default_model_selection_json,
scripts_json, created_at, updated_at, deleted_at
)
VALUES (
'project-1', 'Project 1', '/tmp/project-1',
'{"provider":"codex","model":"gpt-5-codex"}', '[]',
'2026-04-01T00:00:00.000Z', '2026-04-01T00:00:01.000Z', NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode,
interaction_mode, branch, worktree_path, latest_turn_id,
latest_user_message_at, pending_approval_count, pending_user_input_count,
has_actionable_proposed_plan, created_at, updated_at, archived_at, deleted_at
)
VALUES (
'thread-1', 'project-1', 'Thread 1',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
NULL, NULL, NULL, NULL, 0, 0, 0,
'2026-04-01T00:00:02.000Z', '2026-04-01T00:00:03.000Z', NULL, NULL
)
`;
// 600 activities (sequence 1..600); the detail load must return only the
// most recent 500 (sequence 101..600), re-sorted ascending for display.
const total = 600;
yield* Effect.forEach(
Array.from({ length: total }, (_unused, index) => index + 1),
(seq) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
)
VALUES (
${`activity-${String(seq).padStart(4, "0")}`}, 'thread-1', NULL,
'info', 'runtime.note', ${`act-${seq}`}, '{}', ${seq},
'2026-04-01T00:01:00.000Z'
)
`,
{ discard: true },
);
const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1"));
assert.equal(threadDetail._tag, "Some");
if (threadDetail._tag === "Some") {
const activities = threadDetail.value.activities;
assert.equal(activities.length, 500);
assert.equal(activities[0]?.summary, "act-101");
assert.equal(activities[0]?.sequence, 101);
assert.equal(activities.at(-1)?.summary, "act-600");
// 600 > window, so the client is told older history can be lazy-loaded.
assert.equal(threadDetail.value.hasMoreActivities, true);
}
// Lazy-load the page immediately older than the windowed view (cursor =
// oldest loaded sequence, 101): sequences 1..100, ascending, no more left.
const olderPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeSequence: 101,
limit: 500,
});
assert.equal(olderPage.activities.length, 100);
assert.equal(olderPage.activities[0]?.summary, "act-1");
assert.equal(olderPage.activities.at(-1)?.summary, "act-100");
assert.equal(olderPage.hasMore, false);
// A bounded page returns the newest `limit` of the older set and reports
// that more remain (sequences 401..600, with 1..400 still older).
const boundedPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeSequence: 601,
limit: 200,
});
assert.equal(boundedPage.activities.length, 200);
assert.equal(boundedPage.activities[0]?.summary, "act-401");
assert.equal(boundedPage.activities.at(-1)?.summary, "act-600");
assert.equal(boundedPage.hasMore, true);
yield* sql`DELETE FROM projection_thread_activities`;
// Legacy rows may not have a sequence. They are still windowed in the
// detail load and must remain pageable by the deterministic created/id
// ordering used by the snapshot query.
yield* Effect.forEach(
Array.from({ length: total }, (_unused, index) => index + 1),
(seq) =>
sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json,
sequence, created_at
)
VALUES (
${`unsequenced-${String(seq).padStart(4, "0")}`}, 'thread-1', NULL,
'info', 'runtime.note', ${`legacy-act-${seq}`}, '{}', NULL,
'2026-04-01T00:01:00.000Z'
)
`,
{ discard: true },
);
const legacyThreadDetail = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-1"),
);
assert.equal(legacyThreadDetail._tag, "Some");
if (legacyThreadDetail._tag === "Some") {
const activities = legacyThreadDetail.value.activities;
assert.equal(activities.length, 500);
assert.equal(activities[0]?.summary, "legacy-act-101");
assert.equal(activities[0]?.sequence, undefined);
assert.equal(activities.at(-1)?.summary, "legacy-act-600");
const legacyOlderPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeCreatedAt: activities[0]?.createdAt ?? "2026-04-01T00:01:00.000Z",
beforeActivityId: activities[0]?.id ?? asEventId("unsequenced-0101"),
limit: 500,
});
assert.equal(legacyOlderPage.activities.length, 100);
assert.equal(legacyOlderPage.activities[0]?.summary, "legacy-act-1");
assert.equal(legacyOlderPage.activities.at(-1)?.summary, "legacy-act-100");
assert.equal(legacyOlderPage.hasMore, false);
}
const legacyBoundedPage = yield* snapshotQuery.getThreadActivitiesPage({
threadId: ThreadId.make("thread-1"),
beforeCreatedAt: "2026-04-01T00:01:00.000Z",
beforeActivityId: asEventId("unsequenced-0601"),
limit: 200,
});
assert.equal(legacyBoundedPage.activities.length, 200);
assert.equal(legacyBoundedPage.activities[0]?.summary, "legacy-act-401");
assert.equal(legacyBoundedPage.activities.at(-1)?.summary, "legacy-act-600");
assert.equal(legacyBoundedPage.hasMore, true);
}),
);
it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
@@ -1,6 +1,7 @@
import {
ChatAttachment,
CheckpointRef,
EventId,
IsoDateTime,
MessageId,
NonNegativeInt,
@@ -117,6 +118,25 @@ const ProjectIdLookupInput = Schema.Struct({
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
/**
* Maximum number of most-recent activities loaded into a thread-detail snapshot.
* Bounds peak memory when opening a long-lived thread; older activities are
* fetched on demand (lazy-load, planned) and live ones stream in via events.
*/
const THREAD_DETAIL_ACTIVITY_WINDOW = 500;
const ThreadActivitiesBeforeSequenceInput = Schema.Struct({
threadId: ThreadId,
beforeSequence: Schema.Number,
limit: Schema.Number,
});
const ThreadActivitiesBeforeActivityInput = Schema.Struct({
threadId: ThreadId,
beforeCreatedAt: IsoDateTime,
beforeActivityId: EventId,
limit: Schema.Number,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
@@ -254,6 +274,23 @@ function mapProposedPlanRow(
};
}
function mapThreadActivityRow(
row: Schema.Schema.Type<typeof ProjectionThreadActivityDbRowSchema>,
): OrchestrationThreadActivity {
const activity = {
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
createdAt: row.createdAt,
};
// `sequence` is the pagination cursor; omit it when the (legacy) row is
// unsequenced so the optional contract field stays absent.
return row.sequence !== null ? Object.assign(activity, { sequence: row.sequence }) : activity;
}
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown): ProjectionRepositoryError =>
Schema.isSchemaError(cause)
@@ -808,6 +845,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// The thread-detail timeline loads only the most recent window of activities so a
// long-lived thread (tens of thousands of activities, hundreds of MB of payload)
// can't blow the server heap. New activities still stream in live via the event
// subscription; older history will be fetched on demand once lazy-load lands.
// Select the most recent N (sequence DESC) then re-sort ascending for display.
const listThreadActivityRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionThreadActivityDbRowSchema,
@@ -823,8 +865,17 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM projection_thread_activities
WHERE thread_id = ${threadId}
FROM (
SELECT *
FROM projection_thread_activities
WHERE thread_id = ${threadId}
ORDER BY
sequence DESC,
created_at DESC,
activity_id DESC
-- One extra beyond the window so the caller can report hasMoreActivities.
LIMIT ${THREAD_DETAIL_ACTIVITY_WINDOW + 1}
)
ORDER BY
sequence ASC,
created_at ASC,
@@ -832,6 +883,81 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// Older-than-cursor page for lazy-load. Returns rows newest-first (DESC) so a
// simple LIMIT yields the page adjacent to the cursor; the caller reverses to
// ascending. `sequence IS NULL` (legacy unsequenced) rows sort last under
// `sequence DESC` (SQLite orders NULLs last in DESC) — the very oldest — so
// paging eventually reaches them. `beforeSequence` is a NonNegativeInt, so
// `(sequence < beforeSequence OR sequence IS NULL)` is equivalent to the old
// `COALESCE(sequence, -1) < beforeSequence` but lets the
// (thread_id, sequence, created_at, activity_id) index satisfy the ORDER BY
// directly instead of forcing a filesort over the whole thread.
const listThreadActivityRowsBeforeSequence = SqlSchema.findAll({
Request: ThreadActivitiesBeforeSequenceInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, beforeSequence, limit }) =>
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 (sequence < ${beforeSequence} OR sequence IS NULL)
ORDER BY
sequence DESC,
created_at DESC,
activity_id DESC
LIMIT ${limit}
`,
});
// Legacy unsequenced (sequence NULL) rows are paged by a (created_at,
// activity_id) cursor. created_at is compared lexicographically as TEXT, which
// equals chronological order only because timestamps are canonical ISO-8601
// (always UTC `Z`, fixed millisecond precision) — the same invariant every
// `ORDER BY created_at` in this layer (including the detail window above)
// already relies on, so the cursor stays consistent with how rows are
// displayed. activity_id breaks created_at ties; its ordering is arbitrary but
// matches the window's `activity_id` tiebreak, so pages never skip or repeat.
const listUnsequencedThreadActivityRowsBeforeActivity = SqlSchema.findAll({
Request: ThreadActivitiesBeforeActivityInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, beforeCreatedAt, beforeActivityId, limit }) =>
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 sequence IS NULL
AND (
created_at < ${beforeCreatedAt}
OR (
created_at = ${beforeCreatedAt}
AND activity_id < ${beforeActivityId}
)
)
ORDER BY
created_at DESC,
activity_id DESC
LIMIT ${limit}
`,
});
const getThreadSessionRowByThread = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadSessionDbRowSchema,
@@ -1076,16 +1202,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
for (const row of activityRows) {
updatedAt = maxIso(updatedAt, row.createdAt);
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
threadActivities.push({
id: row.activityId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
...(row.sequence !== null ? { sequence: row.sequence } : {}),
createdAt: row.createdAt,
});
threadActivities.push(mapThreadActivityRow(row));
activitiesByThread.set(row.threadId, threadActivities);
}
@@ -1190,6 +1307,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
// The full snapshot is unwindowed, so there is never more to load.
hasMoreActivities: false,
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
@@ -1998,21 +2117,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
return message;
}),
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
activities: activityRows.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;
}),
// The query fetches WINDOW+1 ascending rows; if it returned the extra
// one, older activities exist beyond the window — drop that oldest row
// and flag it so clients can lazy-load older history.
activities: (activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW
? activityRows.slice(activityRows.length - THREAD_DETAIL_ACTIVITY_WINDOW)
: activityRows
).map(mapThreadActivityRow),
hasMoreActivities: activityRows.length > THREAD_DETAIL_ACTIVITY_WINDOW,
checkpoints: checkpointRows.map((row) => ({
turnId: row.turnId,
checkpointTurnCount: row.checkpointTurnCount,
@@ -2063,6 +2175,43 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
);
const getThreadActivitiesPage: ProjectionSnapshotQueryShape["getThreadActivitiesPage"] = (
input,
) =>
Effect.gen(function* () {
const limit = Math.min(
Math.max(1, input.limit ?? THREAD_DETAIL_ACTIVITY_WINDOW),
THREAD_DETAIL_ACTIVITY_WINDOW,
);
// Fetch one extra to detect whether older activities remain.
const rowsEffect =
"beforeSequence" in input
? listThreadActivityRowsBeforeSequence({
threadId: input.threadId,
beforeSequence: input.beforeSequence,
limit: limit + 1,
})
: listUnsequencedThreadActivityRowsBeforeActivity({
threadId: input.threadId,
beforeCreatedAt: input.beforeCreatedAt,
beforeActivityId: input.beforeActivityId,
limit: limit + 1,
});
const rows = yield* rowsEffect.pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadActivitiesPage:query",
"ProjectionSnapshotQuery.getThreadActivitiesPage:decodeRows",
),
),
);
const hasMore = rows.length > limit;
// Rows are newest-first; keep the page closest to the cursor, then reverse
// to ascending for display.
const page = (hasMore ? rows.slice(0, limit) : rows).map(mapThreadActivityRow).toReversed();
return { activities: page, hasMore };
});
return {
getCommandReadModel,
getSnapshot,
@@ -2078,6 +2227,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getThreadShellById,
getThreadDetailById,
getThreadDetailSnapshot,
getThreadActivitiesPage,
} satisfies ProjectionSnapshotQueryShape;
});
@@ -9,6 +9,8 @@
import type {
CheckpointRef,
OrchestrationCheckpointSummary,
OrchestrationGetThreadActivitiesInput,
OrchestrationGetThreadActivitiesResult,
OrchestrationProject,
OrchestrationProjectShell,
OrchestrationReadModel,
@@ -168,6 +170,16 @@ export interface ProjectionSnapshotQueryShape {
readonly getThreadDetailSnapshot: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
/**
* Cursor-paginated load of a thread's older activities (lazy-load / infinite
* scroll). Returns the page of activities immediately older than the provided
* sequence or unsequenced activity cursor, ascending, plus whether older ones
* remain.
*/
readonly getThreadActivitiesPage: (
input: OrchestrationGetThreadActivitiesInput,
) => Effect.Effect<OrchestrationGetThreadActivitiesResult, ProjectionRepositoryError>;
}
/**
+5 -1
View File
@@ -31,8 +31,12 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
Effect.fn("environment.orchestration.snapshot")(function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
// The only consumer (the `t3` CLI project resolver) reads just
// `.projects`, so use the command read model — it returns the same
// OrchestrationReadModel shape but never materialises the per-thread
// activity/message/checkpoint tables (490MB+ on a busy DB → heap OOM).
return yield* projectionSnapshotQuery
.getSnapshot()
.getCommandReadModel()
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_snapshot_failed", cause),
@@ -27,6 +27,7 @@ const makeProject = (scripts: OrchestrationProject["scripts"]): OrchestrationPro
const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
@@ -210,6 +210,7 @@ describe("ProviderSessionReaper", () => {
),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
),
Layer.provideMerge(NodeServices.layer),
@@ -97,6 +97,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(AnalyticsService.AnalyticsService, {
record: () => Effect.void,
@@ -160,6 +161,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -204,6 +206,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
@@ -254,6 +257,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
getThreadActivitiesPage: () => Effect.die("unused"),
}),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
+16
View File
@@ -34,6 +34,7 @@ import {
type OrchestrationThreadStreamItem,
OrchestrationGetFullThreadDiffError,
OrchestrationGetSnapshotError,
OrchestrationGetThreadActivitiesError,
OrchestrationGetTurnDiffError,
ORCHESTRATION_WS_METHODS,
type ProjectId,
@@ -287,6 +288,7 @@ const SHELL_RESUME_MAX_GAP = 1_000;
const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[ORCHESTRATION_WS_METHODS.dispatchCommand, AuthOrchestrationOperateScope],
[ORCHESTRATION_WS_METHODS.getTurnDiff, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getThreadActivities, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getFullThreadDiff, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],
@@ -1183,6 +1185,20 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getThreadActivities]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getThreadActivities,
projectionSnapshotQuery.getThreadActivitiesPage(input).pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetThreadActivitiesError({
message: "Failed to load thread activities page",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
+48
View File
@@ -25,6 +25,7 @@ import { ProviderInstanceId } from "./providerInstance.ts";
export const ORCHESTRATION_WS_METHODS = {
dispatchCommand: "orchestration.dispatchCommand",
getTurnDiff: "orchestration.getTurnDiff",
getThreadActivities: "orchestration.getThreadActivities",
getFullThreadDiff: "orchestration.getFullThreadDiff",
replayEvents: "orchestration.replayEvents",
getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",
@@ -362,6 +363,10 @@ export const OrchestrationThread = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed([])),
),
activities: Schema.Array(OrchestrationThreadActivity),
// The detail snapshot windows `activities` to the most recent page; this is
// true when older activities exist beyond the window and can be lazy-loaded
// via the getThreadActivities RPC. Absent on lightweight (shell) threads.
hasMoreActivities: Schema.optional(Schema.Boolean),
checkpoints: Schema.Array(OrchestrationCheckpointSummary),
session: Schema.NullOr(OrchestrationSession),
});
@@ -1238,6 +1243,37 @@ export type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput
export const OrchestrationGetTurnDiffResult = ThreadTurnDiff;
export type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type;
/**
* Cursor-paginated load of a thread's OLDER activities (lazy-load / infinite
* scroll). Sequenced activity uses `beforeSequence`, the `sequence` of the
* oldest activity the client currently holds. Legacy unsequenced activity uses
* the `(beforeCreatedAt, beforeActivityId)` pair from the oldest loaded
* activity. The server returns the page of activities immediately older than the
* cursor (chronological ascending) plus whether any remain beyond that.
*/
export const OrchestrationGetThreadActivitiesInput = Schema.Union([
Schema.Struct({
threadId: ThreadId,
beforeSequence: NonNegativeInt,
limit: Schema.optional(NonNegativeInt),
}),
Schema.Struct({
threadId: ThreadId,
beforeCreatedAt: IsoDateTime,
beforeActivityId: EventId,
limit: Schema.optional(NonNegativeInt),
}),
]);
export type OrchestrationGetThreadActivitiesInput =
typeof OrchestrationGetThreadActivitiesInput.Type;
export const OrchestrationGetThreadActivitiesResult = Schema.Struct({
activities: Schema.Array(OrchestrationThreadActivity),
hasMore: Schema.Boolean,
});
export type OrchestrationGetThreadActivitiesResult =
typeof OrchestrationGetThreadActivitiesResult.Type;
export const OrchestrationGetFullThreadDiffInput = Schema.Struct({
threadId: ThreadId,
toTurnCount: NonNegativeInt,
@@ -1265,6 +1301,10 @@ export const OrchestrationRpcSchemas = {
input: OrchestrationGetTurnDiffInput,
output: OrchestrationGetTurnDiffResult,
},
getThreadActivities: {
input: OrchestrationGetThreadActivitiesInput,
output: OrchestrationGetThreadActivitiesResult,
},
getFullThreadDiff: {
input: OrchestrationGetFullThreadDiffInput,
output: OrchestrationGetFullThreadDiffResult,
@@ -1311,6 +1351,14 @@ export class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass<Orche
},
) {}
export class OrchestrationGetThreadActivitiesError extends Schema.TaggedErrorClass<OrchestrationGetThreadActivitiesError>()(
"OrchestrationGetThreadActivitiesError",
{
message: TrimmedNonEmptyString,
cause: Schema.optional(Schema.Defect()),
},
) {}
export class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass<OrchestrationGetFullThreadDiffError>()(
"OrchestrationGetFullThreadDiffError",
{
+12
View File
@@ -52,6 +52,8 @@ import {
OrchestrationGetFullThreadDiffError,
OrchestrationGetFullThreadDiffInput,
OrchestrationGetSnapshotError,
OrchestrationGetThreadActivitiesError,
OrchestrationGetThreadActivitiesInput,
OrchestrationGetTurnDiffError,
OrchestrationGetTurnDiffInput,
OrchestrationReplayEventsError,
@@ -612,6 +614,15 @@ export const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.g
error: Schema.Union([OrchestrationGetTurnDiffError, EnvironmentAuthorizationError]),
});
export const WsOrchestrationGetThreadActivitiesRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getThreadActivities,
{
payload: OrchestrationGetThreadActivitiesInput,
success: OrchestrationRpcSchemas.getThreadActivities.output,
error: Schema.Union([OrchestrationGetThreadActivitiesError, EnvironmentAuthorizationError]),
},
);
export const WsOrchestrationGetFullThreadDiffRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getFullThreadDiff,
{
@@ -753,6 +764,7 @@ export const WsRpcGroup = RpcGroup.make(
WsSubscribeAuthAccessRpc,
WsOrchestrationDispatchCommandRpc,
WsOrchestrationGetTurnDiffRpc,
WsOrchestrationGetThreadActivitiesRpc,
WsOrchestrationGetFullThreadDiffRpc,
WsOrchestrationReplayEventsRpc,
WsOrchestrationGetArchivedShellSnapshotRpc,