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 @@ -54,6 +54,7 @@ import * as ProviderTurnStart from "./ProviderTurnStartService.ts";
import * as RunExecutionService from "./RunExecutionService.ts";
import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";
import * as RuntimePolicy from "./RuntimePolicy.ts";
import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";

const isDomainEvent = Schema.is(OrchestrationV2DomainEvent);

Expand Down Expand Up @@ -137,6 +138,7 @@ function startWithMissingWorktree(
Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}),
Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }),
IdAllocator.layer,
Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}),
Layer.succeed(FileSystem.FileSystem, {
exists: () => Effect.succeed(false),
realPath: (target: string) =>
Expand Down Expand Up @@ -948,6 +950,7 @@ function makeLocalCommandHarness(input: {
}),
}),
IdAllocator.layer,
Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({}),
layerWorktreeLocation(input.worktreesDir),
input.fileSystem === undefined
? FileSystem.layerNoop({ exists: () => Effect.succeed(true) })
Expand Down
63 changes: 63 additions & 0 deletions apps/server/src/orchestration-v2/ProviderTurnStartService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import {
} from "@t3tools/provider-core/server/failure";
import * as RunExecutionService from "./RunExecutionService.ts";
import * as RuntimePolicy from "./RuntimePolicy.ts";
import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";
import {
isRestartNoteContinuation,
pendingRestartCancelledBackgroundWork,
Expand Down Expand Up @@ -145,6 +146,7 @@ export const layer: Layer.Layer<
| ProviderSessionManager.ProviderSessionManagerV2
| RunExecutionService.RunExecutionServiceV2
| RuntimePolicy.RuntimePolicyV2
| TurnItemPositionStore.TurnItemPositionStoreV2
> = Layer.effect(
ProviderTurnStartServiceV2,
Effect.gen(function* () {
Expand All @@ -161,6 +163,7 @@ export const layer: Layer.Layer<
const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
const runExecution = yield* RunExecutionService.RunExecutionServiceV2;
const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2;
const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
const isManagedWorktreePath = yield* makeIsManagedWorktreePath;

const resolveRecreateBase = Effect.fn("ProviderTurnStartService.resolveRecreateBase")(
Expand Down Expand Up @@ -1115,6 +1118,7 @@ export const layer: Layer.Layer<
let resumedRetryHandoff: ReadonlyArray<OrchestrationV2ContextHandoff> | undefined;
let resumedHandoffContext: ReturnType<typeof handoffContextForThread> | undefined;
let portableForkFallback: OrchestrationV2ContextHandoff | undefined;
let recoveryTurnItem: OrchestrationV2TurnItem | undefined;
const loadedProviderThread = yield* Effect.gen(function* () {
if (nativeForkTransfer !== undefined) {
const sourceProjection = yield* projectionStore.getThreadRecords(
Expand Down Expand Up @@ -1369,6 +1373,50 @@ export const layer: Layer.Layer<
const { handoff, transferId, createdAt } = yield* recoveryHandoff;
effectiveHandoffs = withRecoveryHandoff(handoff);
resumeFellBack = true;
const previousRun = projection.runs.findLast(
(candidate) =>
candidate.providerThreadId === providerThread.id &&
candidate.ordinal < run.ordinal &&
candidate.startedAt !== null,
);
// Stable per run so a retried start reuses the reserved run-start position.
const handoffTurnItemId = idAllocator.derive.runSignalTurnItem({
runId,
signal: "resume-fallback-handoff",
});
const handoffTurnItem: OrchestrationV2TurnItem = {
id: handoffTurnItemId,
threadId: projection.thread.id,
runId,
nodeId: rootNode.id,
providerThreadId: providerThread.id,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
// The summary is delivered ahead of this run's own handoffs and message.
ordinal: yield* turnItemPositions.allocate({
threadId: projection.thread.id,
turnItemId: handoffTurnItemId,
runId,
runOrdinal: run.ordinal,
placement: "run_start",
}),
status: "completed",
title: "Recovered context",
startedAt: createdAt,
completedAt: createdAt,
updatedAt: createdAt,
type: "handoff",
contextHandoffId: handoff.id,
fromProviderThreadIds: handoff.fromProviderThreadIds,
toProviderThreadId: handoff.toProviderThreadId,
fromProviderInstanceIds: [providerThread.providerInstanceId],
toProviderInstanceId: run.providerInstanceId,
fromModelSelections: previousRun === undefined ? [] : [previousRun.modelSelection],
toModel: run.modelSelection.model,
strategy: handoff.strategy,
summary: handoff.summaryText,
};
yield* eventSink.write({
events: [
{
Expand Down Expand Up @@ -1408,6 +1456,7 @@ export const layer: Layer.Layer<
},
],
});
recoveryTurnItem = handoffTurnItem;
return replacement;
});
if (loadedProviderThread === undefined) return;
Expand Down Expand Up @@ -1514,6 +1563,20 @@ export const layer: Layer.Layer<
},
},
]),
// Shown only once the replacement session commits with the running transition.
...(recoveryTurnItem === undefined
? []
: [
{
id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
type: "turn-item.updated" as const,
threadId: projection.thread.id,
runId: run.id,
providerInstanceId: run.providerInstanceId,
occurredAt: now,
payload: recoveryTurnItem,
},
]),
{
id: yield* idAllocator.allocate.event({ threadId: projection.thread.id }),
type: "run.updated",
Expand Down
21 changes: 21 additions & 0 deletions apps/server/src/orchestration-v2/TurnItemPositionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,24 @@ it.effect("reuses an item's position without attempting another allocation inser
);
}).pipe(Effect.provide(layerTest)),
);

it.effect("places a run-start item ahead of the run's items, then appends once taken", () =>
Effect.gen(function* () {
const positions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
const threadId = ThreadId.make("thread:run-start");
const allocate = (id: string, placement?: "run_start") =>
positions.allocate({
threadId,
turnItemId: TurnItemId.make(id),
runId: RunId.make("run:2"),
runOrdinal: 2,
...(placement === undefined ? {} : { placement }),
});
const message = yield* allocate("item:message");
const recovery = yield* allocate("item:recovery", "run_start");
assert.isBelow(recovery, message);
assert.isAbove(recovery, 1_999_999);
assert.equal(yield* allocate("item:retry-recovery", "run_start"), message + 1);
assert.equal(yield* allocate("item:reply"), message + 2);
}).pipe(Effect.provide(layerTest)),
);
16 changes: 14 additions & 2 deletions apps/server/src/orchestration-v2/TurnItemPositionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export interface TurnItemPositionStoreV2Shape {
readonly turnItemId: TurnItemId;
readonly runId: RunId | null;
readonly runOrdinal?: number;
// `run_start` takes the run's unused first slot, ahead of its items, and appends once it is taken.
readonly placement?: "append" | "run_start";
}) => Effect.Effect<number, TurnItemPositionStoreError>;
readonly normalize: (
item: OrchestrationV2TurnItem,
Expand All @@ -42,7 +44,13 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlCli
const allocate: TurnItemPositionStoreV2Shape["allocate"] =
/* This helper runs for individual orchestration events; the enclosing operation owns the span. */
Effect.fnUntraced(
function* ({ threadId, turnItemId, runId, runOrdinal: suppliedRunOrdinal }) {
function* ({
threadId,
turnItemId,
runId,
runOrdinal: suppliedRunOrdinal,
placement = "append",
}) {
const existing = yield* sql<{ readonly ordinal: number }>`
SELECT ordinal
FROM orchestration_v2_turn_item_positions
Expand All @@ -68,7 +76,11 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlCli
SELECT
${threadId},
${turnItemId},
COALESCE(MAX(ordinal), ${lowerBound}) + 1
${
placement === "run_start"
? sql`CASE WHEN COALESCE(MIN(ordinal), ${upperBound}) > ${lowerBound} THEN ${lowerBound} ELSE MAX(ordinal) + 1 END`
: sql`COALESCE(MAX(ordinal), ${lowerBound}) + 1`
}
FROM orchestration_v2_turn_item_positions
WHERE thread_id = ${threadId}
AND ordinal >= ${lowerBound}
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/orchestration-v2/runtimeLayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ const layerProviderTurnStartServiceProvided = ProviderTurnStartService.layer.pip
layerProviderAuthServiceProvided,
layerRunExecutionServiceProvided,
layerRuntimePolicyProvided,
TurnItemPositionStore.layer,
),
),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1335,6 +1335,20 @@ describe("orchestration v2 provider switching", () => {
assert.isFalse(turns[1]?.nativeThreadHasTurns);
assert.equal(turns[2]?.nativeThreadId, turns[1]?.nativeThreadId);
assert.isTrue(turns[2]?.nativeThreadHasTurns);

const projection = yield* orchestrator.getThreadProjection(threadId);
const run2 = projection.runs[1]!;
const handoff = projection.contextHandoffs.find(
(candidate) => candidate.targetRunId === run2.id,
);
assert.deepEqual(
projection.turnItems
.filter((item) => item.runId === run2.id)
.toSorted((left, right) => left.ordinal - right.ordinal)
.slice(0, 2)
.map((item) => (item.type === "handoff" ? item.contextHandoffId : item.type)),
[handoff?.id, "user_message"],
);
}).pipe(
Effect.provide(
ProviderReplayHarness.layerWithRegistry(
Expand Down
Loading