From 376ee7a0be737bb95ef35a470f6aea7c364a2a90 Mon Sep 17 00:00:00 2001 From: Tanner Polley <42780259+tannerpolley@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:26:21 -0700 Subject: [PATCH] fix(server): restore the reads and test isolation the 20261116 sync merge dropped The sync merge 721ba11236 (#428) kept fork code where upstream had narrowed reads, and dropped one fork test isolation, so 14 server tests failed on main: - FoundationPersistence: a fork test lost Layer.fresh, so its run.silence.check effects leaked into later shared-database tests. - control-reads: delegated tasks read the parent's whole history again (upstream getRunProviderRecords, subagentChildThreadIds and run-scoped completion delivery reads were dropped); fork continueAdmissions and EndedRunTurnItems walked the thread. - ProjectionStore.fork: the subagent usage-limit lookup lost its partial index to upstream's new type index; two fork tests asserted fork-only details upstream replaced (archived_at column, type-index plan). Closes #449 Co-Authored-By: Claude Opus 5.5 --- .../FoundationPersistence.test.ts | 2 +- .../src/orchestration-v2/IssueWorkCommands.ts | 14 +++-- .../src/orchestration-v2/Orchestrator.ts | 63 +++++++++++-------- .../ProjectionSettlement.test.ts | 8 +++ .../ProjectionStore.fork.test.ts | 8 ++- .../src/orchestration-v2/ProjectionStore.ts | 6 +- 6 files changed, 62 insertions(+), 39 deletions(-) diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index f9721a1fc4857..6392ff81e37f4 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -1363,7 +1363,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { (yield* pull).map((stored) => stored.sequence), live.map((stored) => stored.sequence), ); - }), + }).pipe(Effect.scoped, Effect.provide(Layer.fresh(layerTest))), ); it.effect("paginates catch-up beyond the event-store read limit", () => diff --git a/apps/server/src/orchestration-v2/IssueWorkCommands.ts b/apps/server/src/orchestration-v2/IssueWorkCommands.ts index 2420ea9930a99..c0a431fbb0d1f 100644 --- a/apps/server/src/orchestration-v2/IssueWorkCommands.ts +++ b/apps/server/src/orchestration-v2/IssueWorkCommands.ts @@ -338,9 +338,7 @@ export function makeIssueWorkCommands({ const reuseManagedChild = Effect.fn("reuseManagedChild")(function* ( request: DelegatedTaskRequest, - parentProjection: ProjectionRecords< - "runs" | "nodes" | "subagents" | "providerThreads" | "providerTurns" | "attempts" - >, + parentProjection: ProjectionRecords, events: Ref.Ref>, effects: Ref.Ref>, command: OrchestrationV2ServerCommand, @@ -490,10 +488,14 @@ export function makeIssueWorkCommands({ ) { for (const stored of storedEvents) { if (stored.event.type !== "run.created" || stored.event.payload.status !== "queued") continue; - const shell = yield* projectionStore - .getThreadShell(stored.event.threadId) + // The thread row alone: a shell read walks the thread's history for fields unused here. + const thread = yield* projectionStore + .getThread(stored.event.threadId) .pipe(mapDispatchError(command)); - if (shell?.linkedIssue !== undefined || (shell !== null && isReadOnlyIssueRole(shell.role))) + if ( + thread.deletedAt === null && + (thread.linkedIssue !== undefined || isReadOnlyIssueRole(thread.role)) + ) yield* mapDispatchError(command)(startNextQueuedRun(stored.event.threadId)); } }); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e651e6128f8da..ceddd90b9b993 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -2098,20 +2098,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const offerDelegatedCompletionDelivery = /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ Effect.fnUntraced(function* (threadId: ThreadId, parentRunId: RunId | null) { - const projection = yield* projectionStore.getThreadRecords(threadId, [ - "runs", - "providerThreads", - ]); - const parentRun = projection.runs.find((candidate) => candidate.id === parentRunId); - const cohort = completionCohort(projection, parentRunId); + const controls = yield* projectionStore.getThreadRecords(threadId, ["runs"], { + runIds: parentRunId === null ? [] : [parentRunId], + }); + const parentRun = controls.runs[0]; + const cohort = completionCohort(controls, parentRunId); const delivery = cohort?.delivery; if ( (parentRunId !== null && parentRun === undefined) || cohort?.disposition !== "open" || delivery == null || delivery.taskIds.length === 0 || - projection.thread.archivedAt !== null || - projection.thread.deletedAt !== null + controls.thread.archivedAt !== null || + controls.thread.deletedAt !== null ) return; const messages = yield* projectionStore.getThreadRecords(threadId, ["messages"], { @@ -2133,9 +2132,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const providerThread = parentRun?.providerThreadId == null ? undefined - : projection.providerThreads.find( - (candidate) => candidate.id === parentRun.providerThreadId, - ); + : (yield* projectionStore.getThreadRecords(threadId, ["providerThreads"], { + providerThreadIds: [parentRun.providerThreadId], + })).providerThreads[0]; if (parentRunId !== null && providerThread === undefined) { return; } @@ -9746,21 +9745,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio effects: Ref.Ref>, command: OrchestrationV2ServerCommand, ) { - const parentProjection = yield* projectionStore - .getThreadRecords( - request.parentThreadId, - ["runs", "nodes", "subagents", "providerThreads", "providerTurns", "attempts"], - { omitSettledLeafNodes: true }, - ) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProjectionError({ - threadId: request.parentThreadId, - cause, - }), - ), - ); + // A run-less delegation (fork) has no run to scope the read to. + const parentProjection = yield* ( + request.parentRunId === null || request.parentNodeId === null + ? projectionStore.getThreadRecords( + request.parentThreadId, + ["runs", "nodes", "providerThreads", "providerTurns", "attempts"], + { omitSettledLeafNodes: true }, + ) + : projectionStore.getRunProviderRecords( + request.parentThreadId, + request.parentRunId, + request.parentNodeId, + ) + ).pipe( + Effect.mapError( + (cause) => + new OrchestratorProjectionError({ + threadId: request.parentThreadId, + cause, + }), + ), + ); const parentRun = parentProjection.runs.find( (candidate) => candidate.id === request.parentRunId, ); @@ -15122,7 +15128,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio pendingBackgroundTasks: childShell?.pendingBackgroundTasks ?? [], }); yield* forkDelegatedCompletion.publishUntaggedIssueCloseout(childControls, progress, options); - const parent = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"]); + // Each task of this child names it, so the parent's other tasks stay unread. + const parent = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], { + subagentChildThreadIds: [childThreadId], + }); const closed = childControls.thread.archivedAt !== null || childControls.thread.deletedAt !== null; for (const task of parent.subagents) { diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts index 86a4c6c77375d..292a0edc628de 100644 --- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts @@ -18,6 +18,7 @@ import { import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -509,6 +510,13 @@ it.effect("sql: a subagent thread becomes a candidate once its parent is done", payload: { ...parentThread, ...overrides, updatedAt: now }, }); assert.deepEqual(yield* ids(), [child]); + // Active-thread reads filter on the column, so the event must write it, not only the payload. + if (type === "thread.archived") { + const [row] = yield* (yield* SqlClient.SqlClient)<{ + readonly archived_at: string | null; + }>`SELECT archived_at FROM orchestration_v2_projection_threads WHERE thread_id = ${parent}`; + assert.equal(row?.archived_at, DateTime.formatIso(now)); + } } const orphan = yield* createThread("orphan", { lineage: { diff --git a/apps/server/src/orchestration-v2/ProjectionStore.fork.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.fork.test.ts index ca71531c8e858..dd14457ec1d09 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.fork.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.fork.test.ts @@ -900,8 +900,10 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ["archivedAt", DateTime.formatIso(now)], ["settledOverride", "settled"], ]) { + // A real archive writes the archived_at column along with the payload. yield* sql`UPDATE orchestration_v2_projection_threads - SET payload_json = json_set(payload_json, ${`$.${field}`}, ${value}) + SET payload_json = json_set(payload_json, ${`$.${field}`}, ${value}), + archived_at = ${field === "archivedAt" ? value : null} WHERE thread_id = ${threadId}`; assert.isUndefined( (yield* store.getLimitRecoveryCandidates({ now, autoResume: true, snooze: false })).find( @@ -909,7 +911,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ), ); yield* sql`UPDATE orchestration_v2_projection_threads - SET payload_json = ${originalRow!.payload_json} WHERE thread_id = ${threadId}`; + SET payload_json = ${originalRow!.payload_json}, archived_at = NULL WHERE thread_id = ${threadId}`; } yield* sql`UPDATE orchestration_v2_projection_threads SET deleted_at = ${DateTime.formatIso(now)} WHERE thread_id = ${threadId}`; assert.isUndefined( @@ -1222,7 +1224,7 @@ it.effect("live command records search the recovery index and retain filtering a assert.ok( plan.some((row) => row.detail.includes( - "SEARCH orchestration_v2_projection_turn_items USING INDEX orchestration_v2_projection_turn_items_recovery_idx (thread_id=?)", + "SEARCH orchestration_v2_projection_turn_items USING COVERING INDEX orchestration_v2_projection_turn_items_thread_type_idx (thread_id=? AND type=? AND status=?)", ), ), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 6208341d8ba53..c2224076a2e0c 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -3828,9 +3828,9 @@ export const layer: Layer.Layer = SELECT payload_json FROM orchestration_v2_projection_turn_items ${ - filter?.turnItemTypes === undefined + filter?.turnItemTypes === undefined && filter?.turnItemRunId === undefined ? sql`WHERE ${turnItemMatch(threadId, filter)}` - : // Seeks the type index. Sorted, SQLite would walk the thread by ordinal instead. + : // Seeks the type or run index. Sorted, SQLite would walk the thread by ordinal instead. sql`WHERE rowid IN ( SELECT rowid FROM orchestration_v2_projection_turn_items WHERE ${turnItemMatch(threadId, filter)} @@ -5088,7 +5088,9 @@ export const layer: Layer.Layer = ORDER BY ordinal DESC LIMIT 1 ) IN ('completed', 'interrupted', 'failed', 'cancelled', 'rolled_back') OR EXISTS ( + -- The type index would read every error of the thread to find a usage limit. SELECT 1 FROM orchestration_v2_projection_turn_items error + INDEXED BY orchestration_v2_projection_turn_items_usage_limit_idx WHERE error.thread_id = child.thread_id AND error.type = 'error' AND CASE WHEN json_valid(error.payload_json) THEN json_extract(error.payload_json, '$.failure.class') END = 'usage_limit' ))