Skip to content

Commit 52aeac1

Browse files
committed
fix(server): prevent agent session import races
1 parent 6ce81b5 commit 52aeac1

8 files changed

Lines changed: 362 additions & 78 deletions

File tree

‎apps/server/src/orchestration/decider.import.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,4 +178,81 @@ it.layer(NodeServices.layer)("thread history import", (it) => {
178178
expect(result).toMatchObject({ type: "thread.settled" });
179179
}),
180180
);
181+
182+
it.effect("rejects history import after a client message reaches the thread", () =>
183+
Effect.gen(function* () {
184+
const createdAt = "2026-08-24T10:00:00.000Z";
185+
const liveMessageAt = "2026-08-24T10:02:00.000Z";
186+
const threadId = ThreadId.make("import:codex:client-race");
187+
const withThread = yield* projectEvent(createEmptyReadModel(createdAt), {
188+
sequence: 1,
189+
eventId: EventId.make("event-client-race-thread-created"),
190+
aggregateKind: "thread",
191+
aggregateId: threadId,
192+
type: "thread.created",
193+
occurredAt: createdAt,
194+
commandId: CommandId.make("command-client-race-thread-created"),
195+
causationEventId: null,
196+
correlationId: CommandId.make("command-client-race-thread-created"),
197+
metadata: {},
198+
payload: {
199+
threadId,
200+
projectId: ProjectId.make("project-1"),
201+
title: "Imported thread",
202+
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
203+
runtimeMode: "full-access",
204+
interactionMode: "default",
205+
branch: null,
206+
worktreePath: null,
207+
createdAt,
208+
updatedAt: createdAt,
209+
},
210+
});
211+
const readModel = yield* projectEvent(withThread, {
212+
sequence: 2,
213+
eventId: EventId.make("event-client-race-message"),
214+
aggregateKind: "thread",
215+
aggregateId: threadId,
216+
type: "thread.message-sent",
217+
occurredAt: liveMessageAt,
218+
commandId: CommandId.make("command-client-race-message"),
219+
causationEventId: null,
220+
correlationId: CommandId.make("command-client-race-message"),
221+
metadata: {},
222+
payload: {
223+
threadId,
224+
messageId: MessageId.make("client-race-message"),
225+
role: "user",
226+
text: "Start live work",
227+
turnId: null,
228+
streaming: false,
229+
createdAt: liveMessageAt,
230+
updatedAt: liveMessageAt,
231+
},
232+
});
233+
234+
const error = yield* Effect.flip(
235+
decideOrchestrationCommand({
236+
command: {
237+
type: "thread.history.import",
238+
commandId: CommandId.make("command-client-race-import"),
239+
threadId,
240+
messages: [
241+
{
242+
messageId: MessageId.make(`${threadId}:000000`),
243+
role: "user",
244+
text: "Old work",
245+
createdAt,
246+
},
247+
],
248+
},
249+
readModel,
250+
}),
251+
);
252+
253+
expect(error._tag).toBe("OrchestrationCommandInvariantError");
254+
expect(error.message).toContain("must be active and empty");
255+
expect(readModel.threads[0]?.updatedAt).toBe(liveMessageAt);
256+
}),
257+
);
181258
});

‎apps/server/src/orchestration/decider.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1290,11 +1290,23 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
12901290
}
12911291

12921292
case "thread.history.import": {
1293-
yield* requireThread({
1293+
const thread = yield* requireThread({
12941294
readModel,
12951295
command,
12961296
threadId: command.threadId,
12971297
});
1298+
if (
1299+
thread.deletedAt !== null ||
1300+
thread.archivedAt !== null ||
1301+
thread.messages.length > 0 ||
1302+
thread.latestTurn !== null ||
1303+
thread.session !== null
1304+
) {
1305+
return yield* new OrchestrationCommandInvariantError({
1306+
commandType: command.type,
1307+
detail: `Thread '${command.threadId}' must be active and empty before history can be imported.`,
1308+
});
1309+
}
12981310
const firstMessage = command.messages[0];
12991311
if (firstMessage === undefined) {
13001312
return yield* new OrchestrationCommandInvariantError({

‎apps/server/src/persistence/ProviderSessionRuntime.ts‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInp
5858
export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
5959
export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
6060

61+
export interface ProviderSessionRuntimeUpsertOptions {
62+
readonly onConflict?: "update" | "ignore";
63+
}
64+
6165
/**
6266
* ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
6367
*/
@@ -71,6 +75,7 @@ export class ProviderSessionRuntimeRepository extends Context.Service<
7175
*/
7276
readonly upsert: (
7377
runtime: ProviderSessionRuntime,
78+
options?: ProviderSessionRuntimeUpsertOptions,
7479
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
7580

7681
/**
@@ -186,6 +191,36 @@ export const make = Effect.gen(function* () {
186191
`,
187192
});
188193

194+
const insertRuntimeRow = SqlSchema.void({
195+
Request: ProviderSessionRuntimeDbRowSchema,
196+
execute: (runtime) =>
197+
sql`
198+
INSERT INTO provider_session_runtime (
199+
thread_id,
200+
provider_name,
201+
provider_instance_id,
202+
adapter_key,
203+
runtime_mode,
204+
status,
205+
last_seen_at,
206+
resume_cursor_json,
207+
runtime_payload_json
208+
)
209+
VALUES (
210+
${runtime.threadId},
211+
${runtime.providerName},
212+
${runtime.providerInstanceId},
213+
${runtime.adapterKey},
214+
${runtime.runtimeMode},
215+
${runtime.status},
216+
${runtime.lastSeenAt},
217+
${runtime.resumeCursor},
218+
${runtime.runtimePayload}
219+
)
220+
ON CONFLICT (thread_id) DO NOTHING
221+
`,
222+
});
223+
189224
const getRuntimeRowByThreadId = SqlSchema.findOneOption({
190225
Request: GetRuntimeRequestSchema,
191226
Result: ProviderSessionRuntimeRawDbRowSchema,
@@ -235,8 +270,8 @@ export const make = Effect.gen(function* () {
235270
`,
236271
});
237272

238-
const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime) =>
239-
upsertRuntimeRow(runtime).pipe(
273+
const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime, options) =>
274+
(options?.onConflict === "ignore" ? insertRuntimeRow(runtime) : upsertRuntimeRow(runtime)).pipe(
240275
Effect.mapError(
241276
toPersistenceSqlOrDecodeError(
242277
"ProviderSessionRuntimeRepository.upsert:query",

‎apps/server/src/project/AgentSessionImporter.test.ts‎

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import {
1212
type OrchestrationThread,
1313
} from "@t3tools/contracts";
1414
import * as Effect from "effect/Effect";
15+
import * as Deferred from "effect/Deferred";
16+
import * as Fiber from "effect/Fiber";
1517
import * as Layer from "effect/Layer";
1618
import * as Option from "effect/Option";
1719
import * as Stream from "effect/Stream";
@@ -29,7 +31,10 @@ import * as ThreadBackgroundLiveness from "../orchestration/ThreadBackgroundLive
2931
import * as ThreadPlanProgress from "../orchestration/ThreadPlanProgress.ts";
3032
import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
3133
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
32-
import { ProviderSessionDirectoryLive } from "../provider/Layers/ProviderSessionDirectory.ts";
34+
import {
35+
makeProviderSessionDirectoryLive,
36+
ProviderSessionDirectoryLive,
37+
} from "../provider/Layers/ProviderSessionDirectory.ts";
3338
import { ProviderSessionDirectoryPersistenceError } from "../provider/Errors.ts";
3439
import * as ProviderSessionDirectory from "../provider/Services/ProviderSessionDirectory.ts";
3540
import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts";
@@ -428,6 +433,7 @@ const integrationLayer = Layer.mergeAll(
428433
Layer.provide(OrchestrationProjectionPipelineLive),
429434
),
430435
OrchestrationProjectionSnapshotQueryLive,
436+
integrationRuntimeRepository,
431437
ProviderSessionDirectoryLive.pipe(Layer.provide(integrationRuntimeRepository)),
432438
Layer.succeed(AgentSessionScanner.AgentSessionScanner, integrationScanner),
433439
).pipe(
@@ -505,4 +511,95 @@ it.layer(integrationLayer)("AgentSessionImporter integration", (it) => {
505511
);
506512
}),
507513
);
514+
515+
it.effect("keeps a binding created while an import is in progress", () =>
516+
Effect.gen(function* () {
517+
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
518+
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
519+
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
520+
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
521+
const projectId = ProjectId.make("project-import-binding-race");
522+
const workspaceRoot = "/tmp/project-import-binding-race";
523+
const providerSessionId = "codex-binding-race";
524+
const threadId = ThreadId.make(`import:codex:${providerSessionId}`);
525+
const scanner = AgentSessionScanner.AgentSessionScanner.of({
526+
scan: Effect.die("unused"),
527+
recentThreads: () =>
528+
Stream.succeed({ ...integrationThread, providerSessionId, title: "Binding race" }),
529+
});
530+
const importerAtBindingWrite = yield* Deferred.make<void>();
531+
const releaseImporter = yield* Deferred.make<void>();
532+
const importerRepository = ProviderSessionRuntime.ProviderSessionRuntimeRepository.of({
533+
...repository,
534+
upsert: (runtime, options) =>
535+
options?.onConflict === "ignore"
536+
? Deferred.succeed(importerAtBindingWrite, undefined).pipe(
537+
Effect.andThen(Deferred.await(releaseImporter)),
538+
Effect.andThen(repository.upsert(runtime, options)),
539+
)
540+
: repository.upsert(runtime, options),
541+
});
542+
const importerDirectory = yield* ProviderSessionDirectory.ProviderSessionDirectory.pipe(
543+
Effect.provide(
544+
makeProviderSessionDirectoryLive().pipe(
545+
Layer.provide(
546+
Layer.succeed(
547+
ProviderSessionRuntime.ProviderSessionRuntimeRepository,
548+
importerRepository,
549+
),
550+
),
551+
),
552+
),
553+
);
554+
555+
yield* engine.dispatch({
556+
type: "project.create",
557+
commandId: CommandId.make("create-import-binding-race-project"),
558+
projectId,
559+
title: "Binding race",
560+
workspaceRoot,
561+
defaultModelSelection: null,
562+
createdAt: "2026-08-24T09:00:00.000Z",
563+
});
564+
565+
const importFiber = yield* importRecentAgentThreads({ projectId }).pipe(
566+
Effect.provideService(AgentSessionScanner.AgentSessionScanner, scanner),
567+
Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, importerDirectory),
568+
Effect.forkChild,
569+
);
570+
571+
yield* Effect.raceFirst(
572+
Deferred.await(importerAtBindingWrite),
573+
Fiber.join(importFiber).pipe(
574+
Effect.flatMap((result) =>
575+
Effect.die(
576+
new Error(`Import completed before the binding write: ${JSON.stringify(result)}`),
577+
),
578+
),
579+
),
580+
);
581+
expect(
582+
Option.getOrThrow(yield* snapshots.getThreadDetailById(threadId)).messages.map(
583+
(message) => message.text,
584+
),
585+
).toEqual(integrationThread.messages.map((message) => message.text));
586+
587+
yield* directory.upsert({
588+
threadId,
589+
provider: ProviderDriverKind.make("codex"),
590+
providerInstanceId: ProviderInstanceId.make("codex"),
591+
status: "running",
592+
resumeCursor: { threadId: "active-client-session" },
593+
runtimePayload: { cwd: workspaceRoot, activeTurnId: "turn-active" },
594+
});
595+
yield* Deferred.succeed(releaseImporter, undefined);
596+
597+
expect(yield* Fiber.join(importFiber)).toEqual({ importedCount: 1, skippedCount: 0 });
598+
expect(Option.getOrThrow(yield* directory.getBinding(threadId))).toMatchObject({
599+
status: "running",
600+
resumeCursor: { threadId: "active-client-session" },
601+
runtimePayload: { cwd: workspaceRoot, activeTurnId: "turn-active" },
602+
});
603+
}),
604+
);
508605
});

‎apps/server/src/project/AgentSessionImporter.ts‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -149,18 +149,21 @@ export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(fu
149149
}
150150

151151
if (Option.isNone(existingBinding)) {
152-
yield* directory.upsert({
153-
threadId,
154-
provider,
155-
providerInstanceId: thread.providerInstanceId,
156-
status: "stopped",
157-
runtimeMode: DEFAULT_RUNTIME_MODE,
158-
resumeCursor:
159-
thread.source === "codex"
160-
? { threadId: thread.providerSessionId }
161-
: { threadId, resume: thread.providerSessionId },
162-
runtimePayload: { cwd: workspaceRoot },
163-
});
152+
yield* directory.upsert(
153+
{
154+
threadId,
155+
provider,
156+
providerInstanceId: thread.providerInstanceId,
157+
status: "stopped",
158+
runtimeMode: DEFAULT_RUNTIME_MODE,
159+
resumeCursor:
160+
thread.source === "codex"
161+
? { threadId: thread.providerSessionId }
162+
: { threadId, resume: thread.providerSessionId },
163+
runtimePayload: { cwd: workspaceRoot },
164+
},
165+
{ onConflict: "ignore" },
166+
);
164167
}
165168

166169
return true;

0 commit comments

Comments
 (0)