The best way to control Claude Code, Codex and more from any computer or phone
run in transaction
Julius Marminge committed
Feb 25, 2026 at 20:40 UTC
5a08b9dd64e5f13a9ad88c910e9f34cb7598199a
3 files changed
+172
-37
.plans/16c-pr89-remediation-checklist.md
+2
-2
@@ -154,8 +154,8 @@ Counts: active `53` (`valid=34`, `partially-valid=19`), closed-invalid `5`
154
155
### Phase 2
156
157
-- [ ] `C001` Non-atomic event appending can corrupt state on retry. If an error occurs mid-loop (lines 96-102) after some events are persisted but before the receipt is written, the command appears to fail. A retry generates new UUIDs via `crypto.randomUUID()` in the decider, appending duplicate events. Consider wrapping the loop in a transaction or using deterministic event IDs derived from `commandId`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
158
- - Status: `TODO`
157
+- [x] `C001` Non-atomic event appending can corrupt state on retry. If an error occurs mid-loop (lines 96-102) after some events are persisted but before the receipt is written, the command appears to fail. A retry generates new UUIDs via `crypto.randomUUID()` in the decider, appending duplicate events. Consider wrapping the loop in a transaction or using deterministic event IDs derived from `commandId`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
158
+ - Status: `DONE`
159
- Verdict: `valid`
160
- Severity: `High`
161
- Area: `Event ordering and state consistency`
apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts
renamed
+119
-8
@@ -10,17 +10,21 @@ import {
10
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
11
import { describe, expect, it } from "vitest";
12
13
-import { PersistenceSqlError } from "../persistence/Errors.ts";
14
-import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
15
-import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
16
-import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
13
+import { PersistenceSqlError } from "../../persistence/Errors.ts";
14
+import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
15
+import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
16
+import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
17
import {
18
OrchestrationEventStore,
19
type OrchestrationEventStoreShape,
20
-} from "../persistence/Services/OrchestrationEventStore.ts";
21
-import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
22
-import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
23
-import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
20
+} from "../../persistence/Services/OrchestrationEventStore.ts";
21
+import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
22
+import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
23
+import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
24
+import {
25
+ OrchestrationProjectionPipeline,
26
+ type OrchestrationProjectionPipelineShape,
27
+} from "../Services/ProjectionPipeline.ts";
28
29
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
30
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
@@ -356,6 +360,113 @@ describe("OrchestrationEngine", () => {
360
await runtime.dispose();
361
});
362
363
+ it("rolls back all events for a multi-event command when projection fails mid-dispatch", async () => {
364
+ let shouldFailRequestedProjection = true;
365
+ const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
366
+ bootstrap: Effect.void,
367
+ projectEvent: (event) => {
368
+ if (
369
+ shouldFailRequestedProjection &&
370
+ event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") &&
371
+ event.type === "thread.turn-start-requested"
372
+ ) {
373
+ shouldFailRequestedProjection = false;
374
+ return Effect.fail(
375
+ new PersistenceSqlError({
376
+ operation: "test.projection",
377
+ detail: "projection failed",
378
+ }),
379
+ );
380
+ }
381
+ return Effect.void;
382
+ },
383
+ };
384
+
385
+ const runtime = ManagedRuntime.make(
386
+ OrchestrationEngineLive.pipe(
387
+ Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
388
+ Layer.provide(OrchestrationEventStoreLive),
389
+ Layer.provide(OrchestrationCommandReceiptRepositoryLive),
390
+ Layer.provide(SqlitePersistenceMemory),
391
+ ),
392
+ );
393
+ const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
394
+ const createdAt = now();
395
+
396
+ await runtime.runPromise(
397
+ engine.dispatch({
398
+ type: "project.create",
399
+ commandId: CommandId.makeUnsafe("cmd-project-atomic-create"),
400
+ projectId: asProjectId("project-atomic"),
401
+ title: "Atomic Project",
402
+ workspaceRoot: "/tmp/project-atomic",
403
+ defaultModel: "gpt-5-codex",
404
+ createdAt,
405
+ }),
406
+ );
407
+ await runtime.runPromise(
408
+ engine.dispatch({
409
+ type: "thread.create",
410
+ commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"),
411
+ threadId: ThreadId.makeUnsafe("thread-atomic"),
412
+ projectId: asProjectId("project-atomic"),
413
+ title: "atomic",
414
+ model: "gpt-5-codex",
415
+ branch: null,
416
+ worktreePath: null,
417
+ createdAt,
418
+ }),
419
+ );
420
+
421
+ const turnStartCommand = {
422
+ type: "thread.turn.start" as const,
423
+ commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"),
424
+ threadId: ThreadId.makeUnsafe("thread-atomic"),
425
+ message: {
426
+ messageId: asMessageId("msg-atomic-1"),
427
+ role: "user" as const,
428
+ text: "hello",
429
+ attachments: [],
430
+ },
431
+ createdAt,
432
+ };
433
+
434
+ await expect(runtime.runPromise(engine.dispatch(turnStartCommand))).rejects.toThrow(
435
+ "projection failed",
436
+ );
437
+
438
+ const eventsAfterFailure = await runtime.runPromise(
439
+ Stream.runCollect(engine.readEvents(0)).pipe(
440
+ Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
441
+ ),
442
+ );
443
+ expect(eventsAfterFailure.map((event) => event.type)).toEqual([
444
+ "project.created",
445
+ "thread.created",
446
+ ]);
447
+ expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
448
+
449
+ const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
450
+ expect(retryResult.sequence).toBe(4);
451
+
452
+ const eventsAfterRetry = await runtime.runPromise(
453
+ Stream.runCollect(engine.readEvents(0)).pipe(
454
+ Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
455
+ ),
456
+ );
457
+ expect(eventsAfterRetry.map((event) => event.type)).toEqual([
458
+ "project.created",
459
+ "thread.created",
460
+ "thread.message-sent",
461
+ "thread.turn-start-requested",
462
+ ]);
463
+ expect(
464
+ eventsAfterRetry.filter((event) => event.commandId === turnStartCommand.commandId),
465
+ ).toHaveLength(2);
466
+
467
+ await runtime.dispose();
468
+ });
469
+
470
it("fails command dispatch when command invariants are violated", async () => {
471
const system = await createOrchestrationSystem();
472
const { engine } = system;
apps/server/src/orchestration/Layers/OrchestrationEngine.ts
+51
-27
@@ -6,7 +6,9 @@ import type {
6
} from "@t3tools/contracts";
7
import { OrchestrationCommand } from "@t3tools/contracts";
8
import { Deferred, Effect, Layer, Option, PubSub, Queue, Stream } from "effect";
9
+import * as SqlClient from "effect/unstable/sql/SqlClient";
10
11
+import { toPersistenceSqlError } from "../../persistence/Errors.ts";
12
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
13
import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
14
import {
@@ -55,6 +57,7 @@ function formatDispatchError(error: OrchestrationDispatchError): string {
57
}
58
59
const makeOrchestrationEngine = Effect.gen(function* () {
60
+ const sql = yield* SqlClient.SqlClient;
61
const eventStore = yield* OrchestrationEventStore;
62
const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
63
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -91,36 +94,57 @@ const makeOrchestrationEngine = Effect.gen(function* () {
94
readModel,
95
});
96
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
94
- let lastSavedEvent = null as OrchestrationEvent | null;
95
-
96
- for (const nextEvent of eventBases) {
97
- const savedEvent = yield* eventStore.append(nextEvent);
98
- yield* projectionPipeline.projectEvent(savedEvent);
99
- readModel = yield* projectEvent(readModel, savedEvent);
100
- yield* PubSub.publish(eventPubSub, savedEvent);
101
- lastSavedEvent = savedEvent;
102
- }
103
-
104
- if (lastSavedEvent === null) {
105
- return yield* Deferred.fail(
106
- envelope.result,
107
- new OrchestrationCommandInvariantError({
108
- commandType: envelope.command.type,
109
- detail: "Command produced no events.",
97
+ const committedCommand = yield* sql
98
+ .withTransaction(
99
+ Effect.gen(function* () {
100
+ const committedEvents: OrchestrationEvent[] = [];
101
+ let nextReadModel = readModel;
102
+
103
+ for (const nextEvent of eventBases) {
104
+ const savedEvent = yield* eventStore.append(nextEvent);
105
+ yield* projectionPipeline.projectEvent(savedEvent);
106
+ nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
107
+ committedEvents.push(savedEvent);
108
+ }
109
+
110
+ const lastSavedEvent = committedEvents.at(-1) ?? null;
111
+ if (lastSavedEvent === null) {
112
+ return yield* new OrchestrationCommandInvariantError({
113
+ commandType: envelope.command.type,
114
+ detail: "Command produced no events.",
115
+ });
116
+ }
117
+
118
+ yield* commandReceiptRepository.upsert({
119
+ commandId: envelope.command.commandId,
120
+ aggregateKind: lastSavedEvent.aggregateKind,
121
+ aggregateId: lastSavedEvent.aggregateId,
122
+ acceptedAt: lastSavedEvent.occurredAt,
123
+ resultSequence: lastSavedEvent.sequence,
124
+ status: "accepted",
125
+ error: null,
126
+ });
127
+
128
+ return {
129
+ committedEvents,
130
+ lastSequence: lastSavedEvent.sequence,
131
+ nextReadModel,
132
+ } as const;
133
}),
134
+ )
135
+ .pipe(
136
+ Effect.catchTag("SqlError", (sqlError) =>
137
+ Effect.fail(
138
+ toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
139
+ ),
140
+ ),
141
);
112
- }
142
114
- yield* commandReceiptRepository.upsert({
115
- commandId: envelope.command.commandId,
116
- aggregateKind: lastSavedEvent.aggregateKind,
117
- aggregateId: lastSavedEvent.aggregateId,
118
- acceptedAt: lastSavedEvent.occurredAt,
119
- resultSequence: lastSavedEvent.sequence,
120
- status: "accepted",
121
- error: null,
122
- });
123
- yield* Deferred.succeed(envelope.result, { sequence: lastSavedEvent.sequence });
143
+ readModel = committedCommand.nextReadModel;
144
+ for (const event of committedCommand.committedEvents) {
145
+ yield* PubSub.publish(eventPubSub, event);
146
+ }
147
+ yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence });
148
}).pipe(
149
Effect.catch((error) =>
150
Effect.gen(function* () {