perf(server): skip plan bodies in thread summaries (#10341)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-09-06 02:21:03 -07:00
1 parent 076d753ae6
commit eb8ed80300
5 files changed
+280 -36

No files matched your search

@@ -2697,7 +2697,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("maintains shell summaries without reading message bodies", () =>
it.effect("maintains shell summaries without decoding message or plan bodies", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
@@ -2923,12 +2923,13 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
('summary-other-thread', 'thread-shell-summary-other', NULL, 'pending', NULL,
'2026-03-01T08:00:06.000Z', NULL)
`;
// Empty markdown must not be decoded when the shell only needs plan status.
yield* sql`
INSERT INTO projection_thread_proposed_plans (
plan_id, thread_id, turn_id, plan_markdown, implemented_at,
implementation_thread_id, created_at, updated_at
) VALUES (
'summary-plan', 'thread-shell-summary', 'turn-shell-summary-1', '# Plan', NULL,
'summary-plan', 'thread-shell-summary', 'turn-shell-summary-1', '', NULL,
NULL, '2026-03-01T08:00:06.000Z', '2026-03-01T08:00:06.000Z'
)
`;
@@ -197,33 +197,6 @@ function derivePendingUserInputCountFromActivities(
return openRequestIds.size;
}
function deriveHasActionableProposedPlan(input: {
readonly latestTurnId: string | null;
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
}): boolean {
const sorted = [...input.proposedPlans].toSorted(
(left, right) =>
left.updatedAt.localeCompare(right.updatedAt) || left.planId.localeCompare(right.planId),
);
let latestForTurn: ProjectionThreadProposedPlan | null = null;
if (input.latestTurnId !== null) {
for (let index = sorted.length - 1; index >= 0; index -= 1) {
const plan = sorted[index];
if (plan?.turnId === input.latestTurnId) {
latestForTurn = plan;
break;
}
}
}
if (latestForTurn !== null) {
return latestForTurn.implementedAt === null;
}
const latestPlan = sorted.at(-1) ?? null;
return latestPlan !== null && latestPlan.implementedAt === null;
}
function retainProjectionMessagesAfterRevert(
messages: ReadonlyArray<ProjectionThreadMessage>,
turns: ReadonlyArray<ProjectionTurn>,
@@ -595,19 +568,18 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
const [latestUserMessageAt, proposedPlans, activities, pendingApprovalCount] =
const [latestUserMessageAt, hasActionableProposedPlan, activities, pendingApprovalCount] =
yield* Effect.all([
projectionThreadMessageRepository.getLatestUserMessageAt({ threadId }),
projectionThreadProposedPlanRepository.listByThreadId({ threadId }),
projectionThreadProposedPlanRepository.hasActionableByThreadId({
threadId,
latestTurnId: existingRow.value.latestTurnId,
}),
projectionThreadActivityRepository.listUserInputLifecycleByThreadId({ threadId }),
projectionPendingApprovalRepository.countPendingByThreadId({ threadId }),
]);
const pendingUserInputCount = derivePendingUserInputCountFromActivities(activities);
const hasActionableProposedPlan = deriveHasActionableProposedPlan({
latestTurnId: existingRow.value.latestTurnId,
proposedPlans,
});
yield* projectionThreadRepository.upsert({
...existingRow.value,
@@ -1,25 +1,234 @@
import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
import { ProjectId, ThreadId, TurnId, ProviderInstanceId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Statement from "effect/unstable/sql/Statement";
import { SqlitePersistenceMemory } from "./Sqlite.ts";
import { ProjectionProjectRepositoryLive } from "./ProjectionProjects.ts";
import { ProjectionThreadRepositoryLive } from "./ProjectionThreads.ts";
import { ProjectionThreadProposedPlanRepositoryLive } from "./ProjectionThreadProposedPlans.ts";
import { ProjectionProjectRepository } from "../Services/ProjectionProjects.ts";
import { ProjectionThreadRepository } from "../Services/ProjectionThreads.ts";
import { ProjectionThreadProposedPlanRepository } from "../Services/ProjectionThreadProposedPlans.ts";
const projectionRepositoriesLayer = it.layer(
Layer.mergeAll(
ProjectionProjectRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
ProjectionThreadRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
ProjectionThreadProposedPlanRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
SqlitePersistenceMemory,
),
);
projectionRepositoriesLayer("Projection repositories", (it) => {
it.effect("selects the latest-turn plan before checking implementation status", () =>
Effect.gen(function* () {
const plans = yield* ProjectionThreadProposedPlanRepository;
const threadId = ThreadId.make("thread-plan-status");
const latestTurnId = TurnId.make("turn-plan-status-current");
const firstPlan = {
planId: "plan-status-first",
threadId,
turnId: latestTurnId,
planMarkdown: "# First plan",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-03-24T00:00:01.000Z",
updatedAt: "2026-03-24T00:00:01.000Z",
};
yield* plans.upsert(firstPlan);
yield* plans.upsert({
...firstPlan,
planId: "plan-status-implemented",
implementedAt: "2026-03-24T00:00:02.000Z",
createdAt: "2026-03-24T00:00:02.000Z",
updatedAt: "2026-03-24T00:00:02.000Z",
});
yield* plans.upsert({
...firstPlan,
planId: "plan-status-other-turn",
turnId: TurnId.make("turn-plan-status-old"),
updatedAt: "2026-03-24T00:00:10.000Z",
});
assert.isFalse(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }));
yield* plans.upsert({ ...firstPlan, updatedAt: "2026-03-24T00:00:03.000Z" });
assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
}),
);
it.effect("falls back within the thread when the latest turn has no plan", () =>
Effect.gen(function* () {
const plans = yield* ProjectionThreadProposedPlanRepository;
const threadId = ThreadId.make("thread-plan-fallback");
const latestTurnId = TurnId.make("turn-plan-fallback-missing");
assert.isFalse(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
assert.isFalse(yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }));
const firstPlan = {
planId: "plan-fallback-without-turn",
threadId,
turnId: null,
planMarkdown: "# Old plan",
implementedAt: "2026-03-24T00:00:01.000Z",
implementationThreadId: null,
createdAt: "2026-03-24T00:00:01.000Z",
updatedAt: "2026-03-24T00:00:01.000Z",
};
yield* plans.upsert(firstPlan);
yield* plans.upsert({
...firstPlan,
planId: "plan-fallback-with-turn",
turnId: TurnId.make("turn-plan-fallback-old"),
implementedAt: null,
updatedAt: "2026-03-24T00:00:02.000Z",
});
yield* plans.upsert({
...firstPlan,
planId: "plan-fallback-other-thread",
threadId: ThreadId.make("thread-plan-fallback-other"),
turnId: latestTurnId,
updatedAt: "2026-03-24T00:00:03.000Z",
});
assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId }));
assert.isTrue(yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }));
}),
);
it.effect("preserves locale ordering and stable ties when selecting plan status", () =>
Effect.gen(function* () {
const plans = yield* ProjectionThreadProposedPlanRepository;
const timestamp = "2026-03-24T00:00:00.000Z";
const cases = [
{
name: "mixed-case-ids",
expected: "plan-A".localeCompare("plan-a") > 0,
rows: [
{
planId: "plan-a",
implementedAt: timestamp,
createdAt: timestamp,
updatedAt: timestamp,
},
{ planId: "plan-A", implementedAt: null, createdAt: timestamp, updatedAt: timestamp },
],
},
{
name: "equivalent-ids",
expected: true,
rows: [
{
planId: "plan-\u00e9",
implementedAt: timestamp,
createdAt: timestamp,
updatedAt: timestamp,
},
{
planId: "plan-e\u0301",
implementedAt: null,
createdAt: "2026-03-24T00:00:01.000Z",
updatedAt: timestamp,
},
],
},
{
name: "timestamp-formats",
expected: "2026-03-24T00:00:00+00:00".localeCompare("2026-03-24T00:00:00-01:00") > 0,
rows: [
{
planId: "plan-minus",
implementedAt: timestamp,
createdAt: timestamp,
updatedAt: "2026-03-24T00:00:00-01:00",
},
{
planId: "plan-plus",
implementedAt: null,
createdAt: timestamp,
updatedAt: "2026-03-24T00:00:00+00:00",
},
],
},
];
for (const testCase of cases) {
const threadId = ThreadId.make(`thread-plan-order-${testCase.name}`);
const latestTurnId = TurnId.make(`turn-plan-order-${testCase.name}`);
for (const plan of testCase.rows) {
yield* plans.upsert({
...plan,
planId: `${testCase.name}-${plan.planId}`,
threadId,
turnId: latestTurnId,
planMarkdown: "# Plan",
implementationThreadId: null,
});
}
assert.strictEqual(
yield* plans.hasActionableByThreadId({ threadId, latestTurnId }),
testCase.expected,
testCase.name,
);
assert.strictEqual(
yield* plans.hasActionableByThreadId({ threadId, latestTurnId: null }),
testCase.expected,
testCase.name,
);
}
}),
);
it.effect("returns only current-turn status metadata when old plans have large bodies", () =>
Effect.gen(function* () {
const plans = yield* ProjectionThreadProposedPlanRepository;
const sql = yield* SqlClient.SqlClient;
const threadId = ThreadId.make("thread-plan-metadata");
const latestTurnId = TurnId.make("turn-plan-metadata-current");
const updatedAt = "2026-03-24T00:00:00.000Z";
yield* sql`
WITH RECURSIVE history(n) AS (
SELECT 1 UNION ALL SELECT n + 1 FROM history WHERE n < 256
)
INSERT INTO projection_thread_proposed_plans (
plan_id, thread_id, turn_id, plan_markdown, implemented_at,
implementation_thread_id, created_at, updated_at
)
SELECT 'plan-metadata-old-' || n, ${threadId}, 'turn-plan-metadata-old',
${"# Old plan\n".repeat(1024)}, ${updatedAt}, NULL, ${updatedAt}, ${updatedAt}
FROM history
`;
yield* plans.upsert({
planId: "plan-metadata-current",
threadId,
turnId: latestTurnId,
planMarkdown: "# Current plan",
implementedAt: null,
implementationThreadId: null,
createdAt: updatedAt,
updatedAt,
});
const statements: Array<Statement.Statement<unknown>> = [];
const actionable = yield* plans.hasActionableByThreadId({ threadId, latestTurnId }).pipe(
Effect.provideService(Statement.CurrentTransformer, (statement) => {
statements.push(statement);
return Effect.succeed(statement);
}),
);
assert.isTrue(actionable);
assert.strictEqual(statements.length, 1);
const statement = statements[0];
if (statement === undefined) return yield* Effect.die("Expected a plan status query.");
assert.deepEqual(yield* statement, [
{ planId: "plan-metadata-current", implementedAt: null, updatedAt },
]);
}),
);
it.effect("stores SQL NULL for missing project model options", () =>
Effect.gen(function* () {
const projects = yield* ProjectionProjectRepository;
@@ -1,11 +1,13 @@
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { toPersistenceSqlError } from "../Errors.ts";
import {
DeleteProjectionThreadProposedPlansInput,
HasActionableProjectionThreadProposedPlanInput,
ListProjectionThreadProposedPlansInput,
ProjectionThreadProposedPlan,
ProjectionThreadProposedPlanRepository,
@@ -77,6 +79,55 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
`,
});
const listPlanStatusCandidates = SqlSchema.findAll({
Request: HasActionableProjectionThreadProposedPlanInput,
Result: Schema.Struct({
planId: ProjectionThreadProposedPlan.fields.planId,
implementedAt: ProjectionThreadProposedPlan.fields.implementedAt,
updatedAt: ProjectionThreadProposedPlan.fields.updatedAt,
}),
execute: ({ threadId, latestTurnId }) => sql`
SELECT
plan_id AS "planId",
implemented_at AS "implementedAt",
updated_at AS "updatedAt"
FROM projection_thread_proposed_plans
WHERE thread_id = ${threadId}
AND (
turn_id = ${latestTurnId}
OR NOT EXISTS (
SELECT 1 FROM projection_thread_proposed_plans
WHERE thread_id = ${threadId} AND turn_id = ${latestTurnId}
)
)
ORDER BY created_at ASC, plan_id ASC
`,
});
const hasActionableByThreadId = Effect.fn(
"ProjectionThreadProposedPlanRepository.hasActionableByThreadId",
)(
function* (input: HasActionableProjectionThreadProposedPlanInput) {
const candidates = yield* listPlanStatusCandidates(input);
let selected: (typeof candidates)[number] | undefined;
// Timestamps and IDs use localeCompare, not SQLite byte order. Replace
// equal candidates to preserve the stable order of listByThreadId.
for (const candidate of candidates) {
if (
selected === undefined ||
(candidate.updatedAt.localeCompare(selected.updatedAt) ||
candidate.planId.localeCompare(selected.planId)) >= 0
) {
selected = candidate;
}
}
return selected?.implementedAt === null;
},
Effect.mapError(
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.hasActionableByThreadId:query"),
),
);
const upsert: ProjectionThreadProposedPlanRepositoryShape["upsert"] = (row) =>
upsertProjectionThreadProposedPlanRow(row).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query")),
@@ -101,6 +152,7 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
return {
upsert,
listByThreadId,
hasActionableByThreadId,
deleteByThreadId,
} satisfies ProjectionThreadProposedPlanRepositoryShape;
});
@@ -29,6 +29,13 @@ export const ListProjectionThreadProposedPlansInput = Schema.Struct({
export type ListProjectionThreadProposedPlansInput =
typeof ListProjectionThreadProposedPlansInput.Type;
export const HasActionableProjectionThreadProposedPlanInput = Schema.Struct({
threadId: ThreadId,
latestTurnId: Schema.NullOr(TurnId),
});
export type HasActionableProjectionThreadProposedPlanInput =
typeof HasActionableProjectionThreadProposedPlanInput.Type;
export const DeleteProjectionThreadProposedPlansInput = Schema.Struct({
threadId: ThreadId,
});
@@ -42,6 +49,9 @@ export interface ProjectionThreadProposedPlanRepositoryShape {
readonly listByThreadId: (
input: ListProjectionThreadProposedPlansInput,
) => Effect.Effect<ReadonlyArray<ProjectionThreadProposedPlan>, ProjectionRepositoryError>;
readonly hasActionableByThreadId: (
input: HasActionableProjectionThreadProposedPlanInput,
) => Effect.Effect<boolean, ProjectionRepositoryError>;
readonly deleteByThreadId: (
input: DeleteProjectionThreadProposedPlansInput,
) => Effect.Effect<void, ProjectionRepositoryError>;