Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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", () =>
Expand Down
14 changes: 8 additions & 6 deletions apps/server/src/orchestration-v2/IssueWorkCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<never>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
command: OrchestrationV2ServerCommand,
Expand Down Expand Up @@ -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));
}
});
Expand Down
63 changes: 36 additions & 27 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"], {
Expand All @@ -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;
}
Expand Down Expand Up @@ -9746,21 +9745,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
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,
);
Expand Down Expand Up @@ -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) {
Expand Down
8 changes: 8 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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: {
Expand Down
8 changes: 5 additions & 3 deletions apps/server/src/orchestration-v2/ProjectionStore.fork.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -900,16 +900,18 @@ 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(
(row) => row.id === threadId,
),
);
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(
Expand Down Expand Up @@ -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=?)",
),
),
);
Expand Down
6 changes: 4 additions & 2 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3828,9 +3828,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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)}
Expand Down Expand Up @@ -5088,7 +5088,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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'
))
Expand Down