Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TurnItemPositionStore.ts

163 lines6.2 KB

1import { OrchestrationV2TurnItem, RunId, ThreadId, TurnItemId } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Schema from "effect/Schema";
6import * as SqlClient from "effect/sql/SqlClient";
7​
8export class TurnItemPositionStoreError extends Schema.TaggedError<TurnItemPositionStoreError>()(
9 "TurnItemPositionStoreError",
10 {
11 threadId: ThreadId,
12 turnItemId: TurnItemId,
13 cause: Schema.optional(Schema.Defect()),
14 },
15) {}
16​
17const isTurnItemPositionStoreError = Schema.is(TurnItemPositionStoreError);
18​
19export interface TurnItemPositionStoreV2Shape {
20 readonly allocate: (input: {
21 readonly threadId: ThreadId;
22 readonly turnItemId: TurnItemId;
23 readonly runId: RunId | null;
24 readonly runOrdinal?: number;
25 // `run_start` takes the run's unused first slot, ahead of its items, and appends once it is taken.
26 readonly placement?: "append" | "run_start";
27 // Keep an existing position even when it lies outside the run's range.
28 readonly keepExisting?: boolean;
29 readonly moveToEnd?: boolean;
30 }) => Effect.Effect<number, TurnItemPositionStoreError>;
31 readonly normalize: (
32 item: OrchestrationV2TurnItem,
33 runOrdinal?: number,
34 moveToEnd?: boolean,
35 ) => Effect.Effect<OrchestrationV2TurnItem, TurnItemPositionStoreError>;
37​
38export class TurnItemPositionStoreV2 extends Context.Service<
39 TurnItemPositionStoreV2,
40 TurnItemPositionStoreV2Shape
41>()("t3/orchestration-v2/TurnItemPositionStore/TurnItemPositionStoreV2") {}
42​
43export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlClient> = Layer.effect(
44 TurnItemPositionStoreV2,
45 Effect.gen(function* () {
46 const sql = yield* SqlClient.SqlClient;
47​
48 const allocate: TurnItemPositionStoreV2Shape["allocate"] =
49 /* This helper runs for individual orchestration events; the enclosing operation owns the span. */
50 Effect.fnUntraced(
51 function* ({
52 threadId,
53 turnItemId,
54 runId,
55 runOrdinal: suppliedRunOrdinal,
56 placement = "append",
57 keepExisting = false,
58 moveToEnd = false,
59 }) {
60 const existing = yield* sql<{ readonly ordinal: number }>`
61 SELECT ordinal
62 FROM orchestration_v2_turn_item_positions
63 WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
64 LIMIT 1
65 `;
66 const runRows =
67 runId === null || suppliedRunOrdinal !== undefined
68 ? []
69 : yield* sql<{ readonly ordinal: number }>`
70 SELECT ordinal
71 FROM orchestration_v2_projection_runs
72 WHERE thread_id = ${threadId} AND run_id = ${runId}
73 LIMIT 1
74 `;
75 const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;
76 const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;
77 const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;
78 const current = existing[0]?.ordinal;
79 if (current !== undefined) {
80 // A steer that missed its turn starts the next run; it moves into that run's range.
81 if (
82 !moveToEnd &&
83 (keepExisting ||
84 runOrdinal === null ||
85 (current >= lowerBound && current <= upperBound))
86 ) {
87 return current;
88 }
89 yield* sql`
90 UPDATE orchestration_v2_turn_item_positions
91 SET ordinal = (
92 SELECT CASE
93 WHEN MAX(ordinal) = ${current} THEN ${current}
94 ELSE COALESCE(MAX(ordinal), ${lowerBound}) + 1
95 END
96 FROM orchestration_v2_turn_item_positions
97 WHERE thread_id = ${threadId}
98 AND ordinal >= ${lowerBound}
99 AND ordinal <= ${upperBound}
100 )
101 WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
102 `;
103 } else {
104 yield* sql`
105 INSERT INTO orchestration_v2_turn_item_positions (thread_id, turn_item_id, ordinal)
106 SELECT
107 ${threadId},
108 ${turnItemId},
109 ${
110 placement === "run_start"
111 ? sql`CASE WHEN COALESCE(MIN(ordinal), ${upperBound}) > ${lowerBound} THEN ${lowerBound} ELSE MAX(ordinal) + 1 END`
112 : sql`COALESCE(MAX(ordinal), ${lowerBound}) + 1`
113 }
114 FROM orchestration_v2_turn_item_positions
115 WHERE thread_id = ${threadId}
116 AND ordinal >= ${lowerBound}
117 AND ordinal <= ${upperBound}
118 ON CONFLICT(thread_id, turn_item_id) DO NOTHING
119 `;
120 }
121 const rows = yield* sql<{ readonly ordinal: number }>`
122 SELECT ordinal
123 FROM orchestration_v2_turn_item_positions
124 WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
125 LIMIT 1
126 `;
127 const ordinal = rows[0]?.ordinal;
128 if (ordinal === undefined) {
129 return yield* new TurnItemPositionStoreError({
130 threadId,
131 turnItemId,
132 cause: "Position allocation returned no row.",
133 });
134 }
135 return ordinal;
136 },
137 (effect, { threadId, turnItemId }) =>
138 effect.pipe(
139 Effect.mapError((cause) =>
140 isTurnItemPositionStoreError(cause)
141 ? cause
142 : new TurnItemPositionStoreError({ threadId, turnItemId, cause }),
143 ),
144 ),
145 );
146​
147 return TurnItemPositionStoreV2.of({
148 allocate,
149 // Per-event normalization shares the enclosing orchestration span.
150 normalize: Effect.fnUntraced(function* (item, runOrdinal, moveToEnd = false) {
151 return yield* allocate({
152 threadId: item.threadId,
153 turnItemId: item.id,
154 runId: item.runId,
155 // Queued steers keep their submission order until their run starts (see Orchestrator).
156 keepExisting: item.status === "pending",
157 moveToEnd,
158 ...(runOrdinal === undefined ? {} : { runOrdinal }),
159 }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal })));
160 }),
161 });
162 }),
163);