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

ProjectionControlReads.test.ts

316 lines10.9 KB

1import { assert, it } from "@effect/vitest";
2import {
3 EventId,
4 MessageId,
5 NodeId,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 ProviderSessionId,
10 ProviderThreadId,
11 ProviderTurnId,
12 RunAttemptId,
13 RunId,
14 RuntimeRequestId,
15 ThreadId,
16 type OrchestrationV2DomainEvent,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as SqlClient from "effect/unstable/sql/SqlClient";
23import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
24import {
25 ProjectionStoreV2,
26 ProjectionStoreThreadNotFoundError,
27 layer,
28 layerMemory,
29} from "./ProjectionStore.ts";
30import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
31import {
32 layer as controlLayer,
33 ProviderTurnControlServiceV2,
34} from "./ProviderTurnControlService.ts";
35import { layer as replyLayer, RuntimeRequestServiceV2 } from "./RuntimeRequestService.ts";
36​
37const threadId = ThreadId.make("thread:control-reads");
38const providerThreadId = ProviderThreadId.make("provider-thread:control-reads");
39const providerTurnId = ProviderTurnId.make("provider-turn:control-reads");
40const providerSessionId = ProviderSessionId.make("session:control-reads");
41const attemptId = RunAttemptId.make("attempt:control-reads");
42const runId = RunId.make("run:control-reads");
43const messageId = MessageId.make("message:control-reads");
44const requestId = RuntimeRequestId.make("request:control-reads");
45const nodeId = NodeId.make("node:control-reads");
46const providerInstanceId = ProviderInstanceId.make("codex");
47const driver = ProviderDriverKind.make("codex");
48const modelSelection = { instanceId: providerInstanceId, model: "gpt-6" };
49​
50function fixtureEvents(now: DateTime.Utc): ReadonlyArray<OrchestrationV2DomainEvent> {
51 const common = { threadId, occurredAt: now };
52 return [
53 {
54 ...common,
55 id: EventId.make("control:thread"),
56 type: "thread.created",
57 payload: {
58 id: threadId,
59 projectId: ProjectId.make("project:control-reads"),
60 title: "Control reads",
61 providerInstanceId,
62 modelSelection,
63 createdBy: "user",
64 creationSource: "web",
65 runtimeMode: "full-access",
66 interactionMode: "default",
67 branch: null,
68 worktreePath: "/workspace",
69 activeProviderThreadId: providerThreadId,
70 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
71 forkedFrom: null,
72 createdAt: now,
73 updatedAt: now,
74 archivedAt: null,
75 settledOverride: null,
76 settledAt: null,
77 lastVisitedAt: null,
78 deletedAt: null,
79 },
80 },
81 {
82 ...common,
83 id: EventId.make("control:provider-thread"),
84 type: "provider-thread.updated",
85 payload: {
86 id: providerThreadId,
87 driver,
88 providerInstanceId,
89 providerSessionId,
90 appThreadId: threadId,
91 ownerNodeId: null,
92 nativeThreadRef: { driver, nativeId: "native-control-thread", strength: "strong" },
93 nativeConversationHeadRef: null,
94 status: "active",
95 firstRunOrdinal: 1,
96 lastRunOrdinal: 1,
97 handoffIds: [],
98 forkedFrom: null,
99 createdAt: now,
100 updatedAt: now,
101 },
102 },
103 {
104 ...common,
105 id: EventId.make("control:run"),
106 type: "run.created",
107 payload: {
108 id: runId,
109 threadId,
110 ordinal: 1,
111 providerInstanceId,
112 modelSelection,
113 providerThreadId,
114 userMessageId: messageId,
115 rootNodeId: nodeId,
116 activeAttemptId: attemptId,
117 status: "running",
118 requestedAt: now,
119 startedAt: now,
120 completedAt: null,
121 checkpointId: null,
122 contextHandoffId: null,
123 },
124 },
125 {
126 ...common,
127 id: EventId.make("control:attempt"),
128 type: "run-attempt.created",
129 payload: {
130 id: attemptId,
131 runId,
132 attemptOrdinal: 1,
133 rootNodeId: nodeId,
134 providerInstanceId,
135 providerThreadId,
136 providerTurnId,
137 reason: "initial",
138 status: "running",
139 startedAt: now,
140 completedAt: null,
141 },
142 },
143 {
144 ...common,
145 id: EventId.make("control:turn"),
146 type: "provider-turn.updated",
147 payload: {
148 id: providerTurnId,
149 providerThreadId,
150 nodeId,
151 runAttemptId: attemptId,
152 nativeTurnRef: { driver, nativeId: "native-control-turn", strength: "strong" },
153 ordinal: 1,
154 status: "running",
155 startedAt: now,
156 completedAt: null,
157 },
158 },
159 {
160 ...common,
161 id: EventId.make("control:message"),
162 type: "message.updated",
163 payload: {
164 id: messageId,
165 threadId,
166 runId,
167 nodeId,
168 role: "user",
169 text: "Use the smaller fix.",
170 attachments: [],
171 streaming: false,
172 createdBy: "user",
173 creationSource: "web",
174 createdAt: now,
175 updatedAt: now,
176 },
177 },
178 {
179 ...common,
180 id: EventId.make("control:request"),
181 type: "runtime-request.updated",
182 payload: {
183 id: requestId,
184 nodeId,
185 providerTurnId,
186 nativeRequestRef: null,
187 kind: "command",
188 status: "resolved",
189 responseCapability: { type: "live", providerSessionId },
190 createdAt: now,
191 resolvedAt: now,
192 },
193 },
194 ];
196​
197for (const storage of ["sqlite", "memory"] as const) {
198 const storeLayer =
199 storage === "sqlite" ? layer.pipe(Layer.provideMerge(SqlitePersistenceMemory)) : layerMemory;
200 it.effect(`${storage}: controls and replies read only their exact durable targets`, () =>
201 Effect.gen(function* () {
202 const store = yield* ProjectionStoreV2;
203 const now = yield* DateTime.now;
204 const events = fixtureEvents(now);
205 yield* Effect.forEach(events, (event) => store.apply(event), { discard: true });
206 if (storage === "sqlite") {
207 const sql = yield* SqlClient.SqlClient;
208 yield* sql`INSERT INTO orchestration_v2_projection_messages
209 (message_id, thread_id, run_id, node_id, role, streaming, created_at, updated_at, payload_json)
210 VALUES ('message:unrelated-obsolete', ${threadId}, ${runId}, ${nodeId}, 'assistant', 0,
211 ${DateTime.formatIso(now)}, ${DateTime.formatIso(now)}, '{"obsolete":"transcript"}')`;
212 assert.equal((yield* Effect.exit(store.getThreadProjection(threadId)))._tag, "Failure");
213 const queryPlan = yield* sql<{ detail: string }>`EXPLAIN QUERY PLAN
214 SELECT payload_json FROM orchestration_v2_projection_turn_items
215 WHERE thread_id = ${threadId} AND node_id = ${nodeId}
216 AND type IN ('approval_request', 'user_input_request')
217 AND json_extract(payload_json, '$.requestId') = ${requestId}
218 ORDER BY ordinal ASC LIMIT 1`;
219 assert.isTrue(queryPlan.some((row) => row.detail.includes("turn_items_node_ordinal_idx")));
220 }
221 const running = yield* store.getRunningTurnContext(threadId);
222 assert.equal(running.run?.id, runId);
223 assert.equal(running.providerThread?.id, providerThreadId);
224 assert.equal(running.providerTurn?.id, providerTurnId);
225 const providerContext = yield* store.getThreadProviderContext(threadId, providerInstanceId);
226 assert.equal(providerContext.thread.id, threadId);
227 assert.deepEqual(
228 providerContext.providerThreads.map((thread) => thread.id),
229 [providerThreadId],
230 );
231 const responseContext = yield* store.getRuntimeResponseContext(threadId, requestId);
232 assert.equal(responseContext.request?.id, requestId);
233 const target = { providerThreadId, providerTurnId, attemptId, messageId };
234 const context = yield* store.getProviderControlContext(threadId, target);
235 assert.equal(context.providerThread?.id, providerThreadId);
236 assert.equal(context.providerTurn?.id, providerTurnId);
237 assert.equal(context.attempt?.id, attemptId);
238 assert.equal(context.message?.text, "Use the smaller fix.");
239 assert.equal(context.run?.id, runId);
240 assert.equal((yield* store.getRuntimeRequest(threadId, requestId))?.status, "resolved");
241 assert.isUndefined(
242 yield* store.getRuntimeRequest(threadId, RuntimeRequestId.make("request:missing")),
243 );
244 const absent = yield* store.getProviderControlContext(threadId, {
245 providerThreadId: ProviderThreadId.make("provider-thread:missing"),
246 providerTurnId: ProviderTurnId.make("provider-turn:missing"),
247 });
248 assert.isUndefined(absent.providerThread);
249 assert.isUndefined(absent.providerTurn);
250 const missingThread = yield* store
251 .getRuntimeRequest(ThreadId.make("thread:missing"), requestId)
252 .pipe(Effect.flip);
253 assert.instanceOf(missingThread, ProjectionStoreThreadNotFoundError);
254​
255 const calls: string[] = [];
256 const sessions = Layer.mock(ProviderSessionManagerV2)({
257 get: () =>
258 Effect.succeed(
259 Option.some({
260 interruptTurn: () =>
261 Effect.sync(() => {
262 calls.push("interrupt");
263 }),
264 steerTurn: (input: { message: { text: string }; runId: RunId }) =>
265 Effect.sync(() => {
266 assert.equal(input.runId, runId);
267 calls.push(input.message.text);
268 }),
269 respondToRuntimeRequest: () =>
270 Effect.sync(() => {
271 calls.push("reply");
272 }),
273 } as never),
274 ),
275 });
276 yield* Effect.gen(function* () {
277 const control = yield* ProviderTurnControlServiceV2;
278 const reply = yield* RuntimeRequestServiceV2;
279 yield* control.interrupt({ threadId, providerThreadId, providerTurnId, providerSessionId });
280 yield* control.steer({
281 threadId,
282 providerThreadId,
283 providerTurnId,
284 providerSessionId,
285 messageId,
286 });
287 yield* reply.respond({ threadId, providerSessionId, requestId, decision: "accept" });
288 assert.deepEqual(calls, ["interrupt", "Use the smaller fix.", "reply"]);
289 const wrongSession = ProviderSessionId.make("session:wrong");
290 assert.equal(
291 (yield* Effect.exit(
292 control.interrupt({
293 threadId,
294 providerThreadId,
295 providerTurnId,
296 providerSessionId: wrongSession,
297 }),
298 ))._tag,
299 "Failure",
300 );
301 assert.equal(
302 (yield* Effect.exit(
303 reply.respond({
304 threadId,
305 providerSessionId: wrongSession,
306 requestId,
307 decision: "accept",
308 }),
309 ))._tag,
310 "Failure",
311 );
312 assert.lengthOf(calls, 3);
313 }).pipe(Effect.provide(Layer.merge(controlLayer, replyLayer).pipe(Layer.provide(sessions))));
314 }).pipe(Effect.provide(Layer.merge(storeLayer, SqlitePersistenceMemory))),
315 );