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

ProviderTurnStartMemory.fixture.mjs

232 lines8.0 KB

1import * as NodeModule from "node:module";
2import * as NodeURL from "node:url";
3import * as NodeCrypto from "node:crypto";
4import * as NodeAssert from "node:assert/strict";
5const root = process.argv[2];
6const mode = process.argv[3];
7const withHandoff = mode.startsWith("handoff");
8const require = NodeModule.createRequire(root + "/apps/server/package.json");
9const load = (name) => import(NodeURL.pathToFileURL(require.resolve("effect/" + name)));
10const [Effect, Layer, FileSystem, Path] = await Promise.all([
11 load("Effect"),
12 load("Layer"),
13 load("FileSystem"),
14 load("Path"),
15]);
16const app = (file) => import(NodeURL.pathToFileURL(root + "/apps/server/src/" + file + ".ts"));
17const providerCore = (file) =>
18 import(NodeURL.pathToFileURL(root + "/packages/provider-core/src/server/" + file + ".ts"));
19const [
20 Start,
21 Projection,
22 Run,
23 Sessions,
24 Policy,
25 Id,
26 Sink,
27 Handoff,
28 Git,
29 Project,
30 Auth,
31 Config,
32 Settings,
33] = await Promise.all([
34 app("orchestration-v2/ProviderTurnStartService"),
35 app("orchestration-v2/ProjectionStore"),
36 app("orchestration-v2/RunExecutionService"),
37 app("orchestration-v2/ProviderSessionManager"),
38 app("orchestration-v2/RuntimePolicy"),
39 providerCore("IdAllocator"),
40 app("orchestration-v2/EventSink"),
41 app("orchestration-v2/ContextHandoffService"),
42 app("git/GitWorkflowService"),
43 app("project/ProjectService"),
44 app("provider/ProviderAuthService"),
45 app("config"),
46 app("serverSettings"),
47]);
48let current;
49let fullReads = 0;
50let threadReads = 0;
51const liveRuns = [];
52const refs = [];
53const checkpoints = [];
54const count = Number(process.argv[4] ?? 4);
55const bytes = Number(process.argv[5] ?? 32768);
56const session = {
57 driver: "codex",
58 providerSession: { id: "session", driver: "codex" },
59 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
60 startTurn: () =>
61 mode === "handoff-failure" ? Effect.fail("Synthetic startup failure") : Effect.void,
62 compactThread: () => Effect.void,
63};
64const dependencies = Layer.mergeAll(
65 Layer.mock(Handoff.ContextHandoffServiceV2)({}),
66 Id.layer,
67 FileSystem.layerNoop({}),
68 Path.layer,
69 Layer.mock(Git.GitWorkflowService)({}),
70 Layer.mock(Project.ProjectService)({}),
71 Layer.mock(Auth.ProviderAuthService)({}),
72 Layer.mock(Config.ServerConfig)({ worktreesDir: "/synthetic-worktrees" }),
73 Settings.layerTest(),
74 Layer.mock(Projection.ProjectionStoreV2)({
75 getThreadProjection: () =>
76 Effect.sync(() => {
77 fullReads++;
78 throw new Error("full transcript read");
79 }),
80 hasUnpairedRunInterruptRequest: () => Effect.succeed(false),
81 getThreadRecords: (threadId, fields) =>
82 Effect.sync(() => {
83 NodeAssert.equal(threadId, current.thread.id);
84 NodeAssert.deepEqual(fields, []);
85 threadReads++;
86 return { thread: current.thread };
87 }),
88 getTurnStartContext: () =>
89 Effect.sync(() => {
90 fullReads++;
91 return { ...current, hasConversation: true };
92 }),
93 getTurnStartHistory: () => Effect.sync(() => current.turnItems),
94 getRuntimeRecoveryProjection: () => Effect.sync(() => current),
95 }),
96 Layer.mock(Sessions.ProviderSessionManagerV2)({ open: () => Effect.succeed(session) }),
97 Layer.mock(Policy.RuntimePolicyV2)({
98 resolve: () =>
99 Effect.succeed({ cwd: "/synthetic", interactionMode: "default", runtimeMode: "full-access" }),
100 }),
101 Layer.mock(Run.RunExecutionServiceV2)({
102 startRootRun: (input) =>
103 Effect.gen(function* () {
104 liveRuns.push(input);
105 const turnInput = { ...input, message: input.message };
106 const result = yield* Effect.exit(
107 mode === "handoff-compact"
108 ? input.session.compactThread(turnInput)
109 : input.session.startTurn(turnInput),
110 );
111 NodeAssert.equal(result._tag, mode === "handoff-failure" ? "Failure" : "Success");
112 }),
113 }),
114 Layer.mock(Sink.EventSinkV2)({
115 write: () => Effect.succeed([]),
116 writeIfRunCurrent: ({ events }) =>
117 Effect.sync(() => {
118 for (const event of events)
119 if (event.type === "run.updated") current.runs = [event.payload];
120 return { committed: true, storedEvents: [] };
121 }),
122 }),
123);
124function fixture(index) {
125 const runId = "run:" + index;
126 const history = JSON.parse(
127 JSON.stringify({
128 id: "historical:" + index,
129 threadId: "thread",
130 runId: null,
131 providerThreadId: "provider",
132 status: "completed",
133 type: "command_execution",
134 output: NodeCrypto.randomBytes(bytes).toString("hex"),
135 }),
136 );
137 refs.push(new WeakRef(history));
138 return {
139 thread: { id: "thread", projectId: "project", branch: null, worktreePath: null },
140 runs: [
141 {
142 id: runId,
143 threadId: "thread",
144 ordinal: 1,
145 providerInstanceId: "instance",
146 modelSelection: { instanceId: "instance", model: "synthetic" },
147 providerThreadId: "provider",
148 userMessageId: "message",
149 rootNodeId: "root",
150 activeAttemptId: "attempt",
151 status: "starting",
152 startedAt: null,
153 },
154 ],
155 nodes: [{ id: "root", checkpointScopeId: "scope" }],
156 attempts: [{ id: "attempt", runId, providerThreadId: "provider" }],
157 providerThreads: [
158 {
159 id: "provider",
160 driver: "codex",
161 providerSessionId: "session",
162 nativeThreadRef: { nativeId: "native", driver: "codex", strength: "strong" },
163 contextUsage: { usedTokens: 0, maxTokens: 128000 },
164 handoffIds: [],
165 },
166 ],
167 messages: [{ id: "message", text: "Continue", attachments: [] }],
168 checkpointScopes: [{ id: "scope" }],
169 contextHandoffs: withHandoff
170 ? [
171 {
172 id: "handoff",
173 threadId: "thread",
174 targetRunId: runId,
175 toProviderThreadId: "provider",
176 fromProviderThreadIds: ["provider"],
177 coveredRunOrdinals: { from: 1, to: 1 },
178 status: "ready",
179 strategy: "full_thread_summary",
180 summaryText: "Synthetic summary",
181 handoffIds: [],
182 },
183 ]
184 : [],
185 contextTransfers: [],
186 providerSessions: [],
187 providerTurns: [],
188 subagents: [],
189 turnItems: [history],
190 };
192await Effect.runPromise(
193 Effect.gen(function* () {
194 const service = yield* Start.ProviderTurnStartServiceV2;
195 for (let i = 0; i < count; i++) {
196 current = fixture(i);
197 yield* service.start({ threadId: "thread", runId: "run:" + i });
198 const controls = liveRuns.at(-1);
199 current = { ...current, turnItems: [] };
200 NodeAssert.equal(yield* controls.shouldStartProviderTurn(), true);
201 NodeAssert.equal(yield* controls.shouldFinalizeRun(), true);
202 const liveRun = current.runs[0];
203 current = { ...current, runs: [{ ...liveRun, activeAttemptId: "replacement" }] };
204 NodeAssert.equal(yield* controls.shouldStartProviderTurn(), false);
205 NodeAssert.equal(yield* controls.shouldFinalizeRun(), false);
206 current = { ...current, runs: [{ ...liveRun, status: "completed" }] };
207 NodeAssert.equal(yield* controls.shouldFinalizeRun(), false);
208 NodeAssert.deepEqual(yield* controls.loadInheritedBackgroundTurnItems(), []);
209 NodeAssert.equal(fullReads, i + 1);
210 NodeAssert.equal(threadReads, i + 1);
211 NodeAssert.equal(yield* controls.hasUnpairedRunInterruptRequest(), false);
212 NodeAssert.equal(fullReads, i + 1);
213 NodeAssert.equal(threadReads, i + 1);
214 current = null;
215 if (i === Math.floor(count / 2) - 1 || i === count - 1) {
216 yield* Effect.promise(async () => {
217 for (let j = 0; j < 3; j++) {
218 await new Promise(setImmediate);
219 global.gc();
220 }
221 checkpoints.push({
222 runs: liveRuns.length,
223 payloadMiB: ((i + 1) * bytes * 2) / 1048576,
224 retained: refs.filter((ref) => ref.deref()).length,
225 heapMiB: Math.round(process.memoryUsage().heapUsed / 1048576),
226 });
227 });
228 }
229 }
230 }).pipe(Effect.provide(Start.layer.pipe(Layer.provide(dependencies)))),
231);
232console.log(JSON.stringify({ checkpoints }));