Repository navigation
Expand file tree
/
Copy pathEventSink.ts
More file actions
1279 lines (1234 loc) · 50.2 KB
/
Copy pathEventSink.ts
File metadata and controls
1279 lines (1234 loc) · 50.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
CommandId,
type OrchestrationV2Run,
OrchestrationV2DomainEvent,
type OrchestrationV2ProviderThread,
type OrchestrationV2Subagent,
type OrchestrationV2TurnItem,
OrchestrationV2StoredEvent,
ProviderThreadId,
RunAttemptId,
RunId,
RuntimeRequestId,
NodeId,
type ProjectId,
ThreadId,
} from "@t3tools/contracts";
import * as ProviderCommitBatch from "./ProviderCommitBatch.ts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Semaphore from "effect/Semaphore";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/sql/SqlClient";
import * as SqlError from "effect/sql/SqlError";
import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts";
import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts";
import { projectStoredEventForWire } from "./WireProjection.ts";
import { makeRunOutcomeRecorder, type RunOutcome } from "./RunMetrics.ts";
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
import * as EffectOutbox from "./EffectOutbox.ts";
import * as EventStore from "./EventStore.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProjectStore from "./ProjectStore.ts";
import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";
export class EventSinkWriteError extends Schema.TaggedError<EventSinkWriteError>()(
"EventSinkWriteError",
{
eventCount: Schema.Number,
commandId: Schema.optional(CommandId),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to write ${this.eventCount} orchestration V2 event(s).`;
}
}
export class EventSinkStreamError extends Schema.TaggedError<EventSinkStreamError>()(
"EventSinkStreamError",
{
threadId: Schema.optional(ThreadId),
afterSequence: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
return this.threadId === undefined
? "Failed to stream orchestration V2 events."
: `Failed to stream orchestration V2 events for thread ${this.threadId}.`;
}
}
export const EventSinkV2Error = Schema.Union([EventSinkWriteError, EventSinkStreamError]);
export type EventSinkV2Error = typeof EventSinkV2Error.Type;
interface ProviderBatchPublication {
readonly publish: Array<Effect.Effect<void>>;
eventCount: number;
}
const CurrentProviderBatch = Context.Reference<ProviderBatchPublication | undefined>(
"t3/orchestration-v2/EventSink/CurrentProviderBatch",
{ defaultValue: () => undefined },
);
export interface EventSinkV2Shape {
/** Items that are not provider snapshots, such as a consumer's own control items, never batch. */
readonly consumeProviderEvents: <A extends { readonly type: string }, E, R, E2, R2>(
source: Stream.Stream<A, E, R>,
process: (event: A) => Effect.Effect<void, E2, R2>,
after: Effect.Effect<boolean, E2, R2>,
canBatch: Effect.Effect<boolean, never, R2>,
) => Effect.Effect<
void,
E | E2 | ProviderCommitBatch.CommitBatchError | Schema.SchemaError,
R | R2
>;
/** Normalize and persist an ordered group against one transaction; publish after its commit. */
readonly withProviderBatch: <A, E, R>(
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E | EventSinkV2Error, R>;
readonly write: (input: {
/** Return no events if another thread owns this native session at commit time. */
readonly unlessNativeThreadOwned?: Pick<
OrchestrationV2ProviderThread,
"driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
>;
readonly guardPendingUserInputCancellations?: boolean;
readonly commandId?: CommandId;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
readonly writeWithEffects: (input: {
/**
* Rebuilds each run.updated from the stored row with only its delegatedCompletion replaced.
* The batch must not also change that run's lifecycle.
*/
readonly updateDelegatedCompletionOnly?: boolean;
readonly unlessNativeThreadOwned?: Pick<
OrchestrationV2ProviderThread,
"driver" | "providerInstanceId" | "appThreadId" | "nativeThreadRef"
>;
readonly guardPendingUserInputCancellations?: boolean;
readonly commandId?: CommandId;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
readonly writeIfRunCurrent: (input: {
readonly guardPendingUserInputCancellations?: boolean;
readonly commandId?: CommandId;
readonly threadId: ThreadId;
readonly runId: RunId;
readonly activeAttemptId: RunAttemptId;
readonly expectedStatus: OrchestrationV2Run["status"];
/** Also refuse while this run interrupt request is stored without its result. */
readonly unlessInterruptRequested?: {
readonly requestId: OrchestrationV2TurnItem["id"];
readonly resultId: OrchestrationV2TurnItem["id"];
};
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
readonly effects?: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
}) => Effect.Effect<
{
readonly committed: boolean;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
},
EventSinkV2Error
>;
/** Commits only if the expected attempt and ordinal still own the provider thread, protecting newer attempts. */
readonly writeIfProviderThreadOwner: (input: {
readonly guardPendingUserInputCancellations?: boolean;
readonly commandId?: CommandId;
readonly providerThreadId: ProviderThreadId;
readonly runId: RunId;
readonly activeAttemptId: RunAttemptId;
readonly expectedLastRunOrdinal: number;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
}) => Effect.Effect<
{
readonly committed: boolean;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
},
EventSinkV2Error
>;
/** Commits only if the full provider row equals expected; some writers do not advance updatedAt. */
readonly writeIfProviderThreadUnchanged: (input: {
readonly expected: OrchestrationV2ProviderThread;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
}) => Effect.Effect<
{
readonly committed: boolean;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
},
EventSinkV2Error
>;
/** Commits only if the stored turn item still equals expected. */
readonly writeIfTurnItemUnchanged: (input: {
readonly expected: OrchestrationV2TurnItem;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
}) => Effect.Effect<
{
readonly committed: boolean;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
},
EventSinkV2Error
>;
/** Commits only if the stored subagent still equals expected. */
readonly writeIfSubagentUnchanged: (input: {
readonly expected: OrchestrationV2Subagent;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
}) => Effect.Effect<
{
readonly committed: boolean;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
},
EventSinkV2Error
>;
readonly commitCommand: (input: {
readonly commandId: CommandId;
readonly threadId: ThreadId;
readonly commandType: string;
readonly acceptedAt: DateTime.Utc;
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
readonly effects: ReadonlyArray<EffectOutbox.PendingOrchestrationEffectV2>;
readonly cancelUnsettledEffects?: {
readonly effectTypes: ReadonlyArray<EffectOutbox.OrchestrationEffectRequestV2["type"]>;
readonly reason: string;
};
/** Like writeWithEffects' updateDelegatedCompletionOnly, for this run's run.updated only. */
readonly updateDelegatedCompletionOnlyRunId?: RunId;
}) => Effect.Effect<
{
readonly receipt: CommandReceiptStore.CommandReceiptV2;
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
readonly committed: boolean;
readonly cancelledEffectCount: number;
},
EventSinkV2Error
>;
readonly commitRejectedCommand: (input: {
readonly commandId: CommandId;
readonly threadId: ThreadId;
readonly commandType: string;
readonly rejectedAt: DateTime.Utc;
readonly error: string;
}) => Effect.Effect<CommandReceiptStore.CommandReceiptV2, EventSinkV2Error>;
readonly commitProjectCommand: (input: {
readonly commandId: CommandId;
readonly projectId: ProjectId;
readonly commandType: string;
readonly acceptedAt: DateTime.Utc;
readonly event: UnsequencedProjectEvent;
}) => Effect.Effect<
{ readonly receipt: CommandReceiptStore.ProjectCommandReceiptV2; readonly committed: boolean },
EventSinkV2Error
>;
readonly commitRejectedProjectCommand: (input: {
readonly commandId: CommandId;
readonly projectId: ProjectId;
readonly commandType: string;
readonly rejectedAt: DateTime.Utc;
readonly error: string;
}) => Effect.Effect<CommandReceiptStore.ProjectCommandReceiptV2, EventSinkV2Error>;
readonly stream: (input?: {
readonly threadId?: ThreadId;
readonly afterSequence?: number;
readonly eventType?: OrchestrationV2DomainEvent["type"];
/** Bound RPC subscribers; internal workers must not drop their subscription under load. */
readonly bounded?: boolean;
}) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
readonly latestSequence: (input?: {
readonly threadId?: ThreadId;
}) => Effect.Effect<number, EventSinkV2Error>;
readonly readByCommandId: (input: {
readonly commandId: CommandId;
}) => Stream.Stream<OrchestrationV2StoredEvent, EventSinkV2Error>;
}
export class EventSinkV2 extends Context.Service<EventSinkV2, EventSinkV2Shape>()(
"t3/orchestration-v2/EventSink/EventSinkV2",
) {}
const layerBase: Layer.Layer<
EventSinkV2,
never,
| CommandReceiptStore.CommandReceiptStoreV2
| EffectOutbox.EffectOutboxV2
| EventStore.EventStoreV2
| ProjectionStore.ProjectionStoreV2
| ProjectStore.ProjectStoreV2
| SqlClient.SqlClient
| TurnItemPositionStore.TurnItemPositionStoreV2
> = Layer.effect(
EventSinkV2,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const commandReceipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
const effectOutbox = yield* EffectOutbox.EffectOutboxV2;
const eventStore = yield* EventStore.EventStoreV2;
const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
const projectStore = yield* ProjectStore.ProjectStoreV2;
const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
const liveEvents = yield* PubSub.unbounded<OrchestrationV2StoredEvent>();
const liveEventsByType = new Map<
OrchestrationV2DomainEvent["type"],
PubSub.PubSub<OrchestrationV2StoredEvent>
>();
const publishLiveEvents =
/* This helper runs for individual orchestration events; the enclosing operation owns the span. */
Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2StoredEvent>) {
yield* PubSub.publishAll(liveEvents, events);
for (const [type, pubsub] of liveEventsByType) {
yield* PubSub.publishAll(
pubsub,
events.filter((stored) => stored.event.type === type),
);
}
});
const runOutcomes = makeRunOutcomeRecorder((threadId) =>
// One payload row; unlike the shell, it still resolves a deleted child thread.
projectionStore
.getThread(threadId)
.pipe(Effect.map((thread) => thread.lineage.relationshipToParent === "subagent")),
);
// Recorded before publication, so an interrupted publish cannot lose a committed outcome.
const publishStoredEvents = (
events: ReadonlyArray<OrchestrationV2StoredEvent>,
outcomes: ReadonlyArray<RunOutcome>,
) =>
runOutcomes
.record(outcomes)
.pipe(
Effect.andThen(eventStore.publishCommitted(events)),
Effect.andThen(publishLiveEvents(events)),
);
// Serialize commit and publish; reordered publication makes clients drop earlier sequences.
const publishLane = yield* Semaphore.make(1);
const commitThenPublishNow = <A, E, R>(
transaction: Effect.Effect<A, E, R>,
publish: (committed: A) => Effect.Effect<void>,
) =>
Effect.uninterruptibleMask((restore) => {
let holdsLane = false;
const takeLane = publishLane.take(1).pipe(
Effect.andThen(
Effect.sync(() => {
holdsLane = true;
}),
),
Effect.uninterruptible,
);
// Cancellation may roll back the transaction's work. Once it commits,
// every subscriber must hear about it before this writer can exit.
// Otherwise a failed child run can leave its parent's task running.
return sql
.withTransaction(Effect.tap(restore(transaction), () => takeLane))
.pipe(
Effect.tap(publish),
Effect.ensuring(
Effect.suspend(() => (holdsLane ? publishLane.release(1) : Effect.void)),
),
);
});
// A user can answer after terminal normalization reads the pending request.
// Recheck inside the write transaction so stale cleanup cannot erase answers.
const guardUserInputCancellations =
/* This helper runs for individual orchestration events; the enclosing operation owns the span. */
Effect.fnUntraced(function* (events: ReadonlyArray<OrchestrationV2DomainEvent>) {
const staleRequests = new Set<RuntimeRequestId>();
const staleNodes = new Set<NodeId>();
for (const event of events) {
if (
event.type !== "runtime-request.updated" ||
event.payload.kind !== "user_input" ||
event.payload.status !== "cancelled"
)
continue;
const current = yield* projectionStore.getRuntimeRequest(
event.threadId,
event.payload.id,
);
if (
current?.status !== "pending" ||
current.kind !== "user_input" ||
current.providerTurnId !== event.payload.providerTurnId ||
current.responseCapability.type === "message"
) {
staleRequests.add(event.payload.id);
staleNodes.add(event.payload.nodeId);
}
}
return events.filter((event) => {
switch (event.type) {
case "runtime-request.updated":
return event.payload.status !== "cancelled" || !staleRequests.has(event.payload.id);
case "node.updated":
return event.payload.status !== "cancelled" || !staleNodes.has(event.payload.id);
case "turn-item.updated":
return (
event.payload.type !== "user_input_request" ||
event.payload.status !== "cancelled" ||
!staleRequests.has(event.payload.requestId)
);
default:
return true;
}
});
});
const normalizeEvents = (events: ReadonlyArray<OrchestrationV2DomainEvent>) => {
const runOrdinals = new Map(
events.flatMap((event) =>
event.type === "run.created" || event.type === "run.updated"
? [[event.payload.id, event.payload.ordinal] as const]
: [],
),
);
return Effect.forEach(
events,
(event): Effect.Effect<OrchestrationV2DomainEvent, unknown> =>
event.type === "turn-item.updated"
? turnItemPositions
.normalize(
event.payload,
event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId),
)
.pipe(Effect.map((payload) => ({ ...event, payload })))
: Effect.succeed(event),
{ concurrency: 1 },
);
};
const applyStoredEvents =
/* This helper runs for individual orchestration events; the enclosing operation owns the span. */
Effect.fnUntraced(function* (storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>) {
yield* Effect.forEach(storedEvents, (stored) => projectionStore.apply(stored.event), {
concurrency: 1,
});
const sequence = storedEvents.at(-1)?.sequence;
if (sequence !== undefined) {
const now = DateTime.formatIso(yield* DateTime.now);
yield* sql`
INSERT INTO orchestration_v2_projection_metadata (
projection_name,
schema_version,
last_sequence,
updated_at
)
VALUES (
'thread-projections',
${ProjectionStore.ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION},
${sequence},
${now}
)
ON CONFLICT(projection_name)
DO UPDATE SET
schema_version = excluded.schema_version,
last_sequence = excluded.last_sequence,
updated_at = excluded.updated_at
`;
}
// Read lineage here, on the connection this transaction holds; see makeRunOutcomeRecorder.
return yield* runOutcomes.prepare(storedEvents);
});
// The enclosing write or commit span already traces this per-event projection merge.
const updateDelegatedCompletionOnly = Effect.fnUntraced(function* (
events: ReadonlyArray<OrchestrationV2DomainEvent>,
includesRun: (runId: RunId) => boolean,
) {
return yield* Effect.forEach(events, (event) =>
Effect.gen(function* () {
if (event.type !== "run.updated" || !includesRun(event.payload.id)) return event;
const { runs } = yield* projectionStore.getThreadRecords(event.threadId, ["runs"], {
runIds: [event.payload.id],
});
const current = runs[0];
return current === undefined
? event
: {
...event,
payload: { ...current, delegatedCompletion: event.payload.delegatedCompletion },
};
}),
);
});
const writeEffect = Effect.fn("orchestrationV2.EventSink.write")(function* (
input: Parameters<EventSinkV2Shape["writeWithEffects"]>[0],
) {
yield* Effect.annotateCurrentSpan({
"orchestration_v2.command_id": input.commandId ?? null,
"orchestration_v2.event_count": input.events.length,
"orchestration_v2.thread_id": input.events[0]?.threadId ?? null,
});
const batch = yield* CurrentProviderBatch;
if (batch !== undefined) batch.eventCount += input.events.length;
const { committed } = yield* commitThenPublish(
Effect.gen(function* () {
// Check ownership in the same transaction that claims the native session.
const imported = input.unlessNativeThreadOwned;
if (imported?.nativeThreadRef != null) {
const owners = yield* sql`
SELECT provider_thread_id
FROM orchestration_v2_projection_provider_threads
WHERE driver = ${imported.driver}
AND provider_instance_id = ${imported.providerInstanceId}
AND thread_id IS NOT ${imported.appThreadId}
AND json_extract(payload_json, '$.nativeThreadRef.nativeId') = ${imported.nativeThreadRef.nativeId}
LIMIT 1
`;
if (owners.length > 0) return { committed: [], outcomes: [] };
}
// Checkpoint capture can finish after a cohort writer reads its parent run.
// Merge in this transaction so the event log and projection keep that completion.
const events = input.updateDelegatedCompletionOnly
? yield* updateDelegatedCompletionOnly(input.events, () => true)
: input.events;
const normalized = yield* normalizeEvents(
input.guardPendingUserInputCancellations === true
? yield* guardUserInputCancellations(events)
: events,
);
const committed = yield* eventStore.append({
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
events: normalized,
});
const outcomes = yield* applyStoredEvents(committed);
yield* effectOutbox.enqueue(input.effects);
return { committed, outcomes };
}).pipe(Effect.withTracerEnabled(false)),
({ committed, outcomes }) =>
Effect.gen(function* () {
if (input.effects.length > 0) {
yield* effectOutbox.notifyAvailable(input.effects.length);
}
yield* publishStoredEvents(committed, outcomes);
}),
);
return committed;
});
const writeIfRunCurrentEffect = Effect.fn("orchestrationV2.EventSink.writeIfRunCurrent")(
function* (input: Parameters<EventSinkV2Shape["writeIfRunCurrent"]>[0]) {
yield* Effect.annotateCurrentSpan({
"orchestration_v2.command_id": input.commandId ?? null,
"orchestration_v2.event_count": input.events.length,
"orchestration_v2.run_id": input.runId,
"orchestration_v2.thread_id": input.threadId,
});
return yield* commitThenPublish(
Effect.gen(function* () {
const rows = yield* sql<{
readonly status: string;
readonly active_attempt_id: string | null;
}>`
SELECT
status,
json_extract(payload_json, '$.activeAttemptId') AS active_attempt_id
FROM orchestration_v2_projection_runs
WHERE run_id = ${input.runId}
AND thread_id = ${input.threadId}
LIMIT 1
`;
const current = rows[0];
if (
current === undefined ||
current.status !== input.expectedStatus ||
current.active_attempt_id !== input.activeAttemptId
) {
return {
committed: false as const,
storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
};
}
if (input.unlessInterruptRequested !== undefined) {
const { requestId, resultId } = input.unlessInterruptRequested;
const pending = yield* sql<{ readonly pending: number }>`
SELECT EXISTS (
SELECT 1 FROM orchestration_v2_projection_turn_items
WHERE thread_id = ${input.threadId} AND turn_item_id = ${requestId}
) AND NOT EXISTS (
SELECT 1 FROM orchestration_v2_projection_turn_items
WHERE thread_id = ${input.threadId} AND turn_item_id = ${resultId}
) AS pending
`;
if (pending[0]?.pending === 1) {
return {
committed: false as const,
storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
};
}
}
const normalized = yield* normalizeEvents(
input.guardPendingUserInputCancellations === true
? yield* guardUserInputCancellations(input.events)
: input.events,
);
const storedEvents = yield* eventStore.append({
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
events: normalized,
});
const outcomes = yield* applyStoredEvents(storedEvents);
yield* effectOutbox.enqueue(input.effects ?? []);
return { committed: true as const, storedEvents, outcomes };
}),
(result) =>
Effect.gen(function* () {
if (!result.committed) return;
if (input.effects !== undefined && input.effects.length > 0) {
yield* effectOutbox.notifyAvailable(input.effects.length);
}
yield* publishStoredEvents(result.storedEvents, result.outcomes);
}),
);
},
);
const writeIfProviderThreadOwnerEffect = Effect.fn(
"orchestrationV2.EventSink.writeIfProviderThreadOwner",
)(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadOwner"]>[0]) {
yield* Effect.annotateCurrentSpan({
"orchestration_v2.command_id": input.commandId ?? null,
"orchestration_v2.event_count": input.events.length,
"orchestration_v2.provider_thread_id": input.providerThreadId,
"orchestration_v2.run_id": input.runId,
"orchestration_v2.active_attempt_id": input.activeAttemptId,
"orchestration_v2.expected_last_run_ordinal": input.expectedLastRunOrdinal,
});
return yield* commitThenPublish(
Effect.gen(function* () {
const rows = yield* sql<{
readonly active_attempt_id: string | null;
readonly last_run_ordinal: number | null;
}>`
SELECT
json_extract(r.payload_json, '$.activeAttemptId') AS active_attempt_id,
p.last_run_ordinal
FROM orchestration_v2_projection_provider_threads p
JOIN orchestration_v2_projection_runs r
ON r.run_id = ${input.runId}
AND r.thread_id = p.thread_id
WHERE p.provider_thread_id = ${input.providerThreadId}
LIMIT 1
`;
const current = rows[0];
if (
current === undefined ||
current.active_attempt_id !== input.activeAttemptId ||
current.last_run_ordinal !== input.expectedLastRunOrdinal
) {
return {
committed: false as const,
storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
};
}
const normalized = yield* normalizeEvents(
input.guardPendingUserInputCancellations === true
? yield* guardUserInputCancellations(input.events)
: input.events,
);
const storedEvents = yield* eventStore.append({
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
events: normalized,
});
const outcomes = yield* applyStoredEvents(storedEvents);
return { committed: true as const, storedEvents, outcomes };
}),
(result) =>
result.committed
? publishStoredEvents(result.storedEvents, result.outcomes)
: Effect.void,
);
});
// Appends the events only if the stored payload still matches, in one transaction.
const writeIfStoredPayloadMatches = <E>(
readStoredPayload: Effect.Effect<ReadonlyArray<{ readonly payload_json: string }>, E>,
expectedJson: string,
events: ReadonlyArray<OrchestrationV2DomainEvent>,
) =>
commitThenPublish(
Effect.gen(function* () {
const rows = yield* readStoredPayload;
if (rows[0]?.payload_json !== expectedJson) {
return {
committed: false as const,
storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
};
}
const normalized = yield* normalizeEvents(events);
const storedEvents = yield* eventStore.append({ events: normalized });
const outcomes = yield* applyStoredEvents(storedEvents);
return { committed: true as const, storedEvents, outcomes };
}),
(result) =>
result.committed
? publishStoredEvents(result.storedEvents, result.outcomes)
: Effect.void,
);
const writeIfProviderThreadUnchangedEffect = Effect.fn(
"orchestrationV2.EventSink.writeIfProviderThreadUnchanged",
)(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadUnchanged"]>[0]) {
yield* Effect.annotateCurrentSpan({
"orchestration_v2.event_count": input.events.length,
"orchestration_v2.provider_thread_id": input.expected.id,
});
const expectedJson = yield* ProjectionStore.encodeProviderThreadPayload(input.expected);
return yield* writeIfStoredPayloadMatches(
sql<{ readonly payload_json: string }>`
SELECT payload_json
FROM orchestration_v2_projection_provider_threads
WHERE provider_thread_id = ${input.expected.id}
LIMIT 1
`,
expectedJson,
input.events,
);
});
const writeIfTurnItemUnchangedEffect = Effect.fn(
"orchestrationV2.EventSink.writeIfTurnItemUnchanged",
)(function* (input: Parameters<EventSinkV2Shape["writeIfTurnItemUnchanged"]>[0]) {
yield* Effect.annotateCurrentSpan({
"orchestration_v2.event_count": input.events.length,
"orchestration_v2.turn_item_id": input.expected.id,
});
const expectedJson = yield* ProjectionStore.encodeTurnItemPayload(input.expected);
return yield* writeIfStoredPayloadMatches(
sql<{ readonly payload_json: string }>`
SELECT payload_json
FROM orchestration_v2_projection_turn_items
WHERE turn_item_id = ${input.expected.id}
LIMIT 1
`,
expectedJson,
input.events,
);
});
const writeIfSubagentUnchangedEffect = Effect.fn(
"orchestrationV2.EventSink.writeIfSubagentUnchanged",
)(function* (input: Parameters<EventSinkV2Shape["writeIfSubagentUnchanged"]>[0]) {
yield* Effect.annotateCurrentSpan({
"orchestration_v2.event_count": input.events.length,
"orchestration_v2.subagent_id": input.expected.id,
});
const expectedJson = yield* ProjectionStore.encodeSubagentPayload(input.expected);
return yield* writeIfStoredPayloadMatches(
sql<{ readonly payload_json: string }>`
SELECT payload_json
FROM orchestration_v2_projection_subagents
WHERE subagent_id = ${input.expected.id}
LIMIT 1
`,
expectedJson,
input.events,
);
});
const existingCommandResult =
/* This helper runs for individual orchestration events; the enclosing operation owns the span. */
Effect.fnUntraced(function* (commandId: CommandId) {
const existing = yield* commandReceipts.getByCommandId(commandId);
if (Option.isNone(existing)) {
return yield* Effect.die(
new Error(`Command receipt ${commandId} disappeared during its transaction.`),
);
}
const storedEvents = yield* eventStore.readByCommandId({ commandId }).pipe(
Stream.runCollect,
Effect.map((events): ReadonlyArray<OrchestrationV2StoredEvent> => Array.from(events)),
);
return { receipt: existing.value, storedEvents };
});
const commitCommandEffect = Effect.fn("orchestrationV2.EventSink.commitCommand")(function* (
input: Parameters<EventSinkV2Shape["commitCommand"]>[0],
) {
const result = yield* commitThenPublish(
Effect.gen(function* () {
const reserved = yield* commandReceipts.insertIfAbsent({
commandId: input.commandId,
threadId: input.threadId,
commandType: input.commandType,
acceptedAt: input.acceptedAt,
resultSequence: 0,
status: "accepted",
error: null,
});
if (!reserved) {
const existing = yield* existingCommandResult(input.commandId);
return { ...existing, committed: false as const, cancelledEffectIds: [] };
}
// Planning does not lock the source. Once deletion commits, maintenance
// can remove its checkpoints, so a new fork must not revive that history.
if (input.commandType === "thread.fork") {
for (const event of input.events) {
if (event.type !== "thread.created" || event.payload.forkedFrom?.type !== "run")
continue;
const sourceId = event.payload.forkedFrom.threadId;
const source = yield* sql`
SELECT 1 FROM orchestration_v2_projection_threads
WHERE thread_id = ${sourceId} AND deleted_at IS NULL
`;
if (source.length === 0) {
const receipt: CommandReceiptStore.CommandReceiptV2 = {
commandId: input.commandId,
threadId: input.threadId,
commandType: input.commandType,
acceptedAt: input.acceptedAt,
resultSequence: yield* eventStore.latestSequence({ threadId: input.threadId }),
status: "rejected",
error: "Cannot fork a missing or deleted thread.",
};
yield* commandReceipts.upsert(receipt);
return {
receipt,
storedEvents: [],
committed: false as const,
cancelledEffectIds: [],
};
}
}
}
const runId = input.updateDelegatedCompletionOnlyRunId;
const normalized = yield* normalizeEvents(
runId === undefined
? input.events
: yield* updateDelegatedCompletionOnly(input.events, (id) => id === runId),
);
const storedEvents = yield* eventStore.append({
commandId: input.commandId,
events: normalized,
});
// A Stop that changes nothing can still queue the stop of its delegated tasks.
const sequence =
storedEvents.at(-1)?.sequence ??
(input.effects.length === 0
? undefined
: yield* eventStore.latestSequence({ threadId: input.threadId }));
if (sequence === undefined) {
return yield* Effect.die(
new Error(`Command ${input.commandId} produced no orchestration events.`),
);
}
const outcomes = yield* applyStoredEvents(storedEvents);
yield* effectOutbox.enqueue(input.effects);
const receipt: CommandReceiptStore.CommandReceiptV2 = {
commandId: input.commandId,
threadId: input.threadId,
commandType: input.commandType,
acceptedAt: input.acceptedAt,
resultSequence: sequence,
status: "accepted",
error: null,
};
yield* commandReceipts.upsert(receipt);
const cancelledEffectIds =
input.cancelUnsettledEffects === undefined
? []
: yield* effectOutbox.cancelUnsettled({
threadId: input.threadId,
...input.cancelUnsettledEffects,
});
return { receipt, storedEvents, outcomes, committed: true as const, cancelledEffectIds };
}),
(result) =>
Effect.gen(function* () {
yield* effectOutbox.signalCancellations(result.cancelledEffectIds);
if (result.committed && input.effects.length > 0) {
yield* effectOutbox.notifyAvailable(input.effects.length);
}
if (result.committed) yield* publishStoredEvents(result.storedEvents, result.outcomes);
}),
);
return {
receipt: result.receipt,
storedEvents: result.storedEvents,
committed: result.committed,
cancelledEffectCount: result.cancelledEffectIds.length,
};
});
const commitRejectedCommandEffect = Effect.fn(
"orchestrationV2.EventSink.commitRejectedCommand",
)(function* (input: Parameters<EventSinkV2Shape["commitRejectedCommand"]>[0]) {
return yield* sql.withTransaction(
Effect.gen(function* () {
const sequence = yield* eventStore.latestSequence({ threadId: input.threadId });
const receipt: CommandReceiptStore.CommandReceiptV2 = {
commandId: input.commandId,
threadId: input.threadId,
commandType: input.commandType,
acceptedAt: input.rejectedAt,
resultSequence: sequence,
status: "rejected",
error: input.error,
};
const inserted = yield* commandReceipts.insertIfAbsent(receipt);
if (inserted) {
return receipt;
}
const existing = yield* commandReceipts.getByCommandId(input.commandId);
return Option.getOrElse(existing, () => receipt);
}),
);
});
const existingProjectReceipt = (commandId: CommandId) =>
commandReceipts.getProjectByCommandId(commandId).pipe(
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(`Command ${commandId} was already used by a thread command.` as const),
onSome: Effect.succeed,
}),
),
);
const commitProjectCommandEffect = Effect.fn("orchestrationV2.EventSink.commitProjectCommand")(
function* (input: Parameters<EventSinkV2Shape["commitProjectCommand"]>[0]) {
const result = yield* commitThenPublish(
Effect.gen(function* () {
const reserved: CommandReceiptStore.ProjectCommandReceiptV2 = {
commandId: input.commandId,
projectId: input.projectId,
commandType: input.commandType,
acceptedAt: input.acceptedAt,
resultSequence: 0,
status: "accepted",
error: null,
};
if (!(yield* commandReceipts.insertIfAbsent(reserved))) {
return { receipt: yield* existingProjectReceipt(input.commandId), event: undefined };
}
const event = yield* eventStore.appendProjectEvent(input.event);
yield* projectStore.apply(event);
const receipt = { ...reserved, resultSequence: event.sequence };
yield* commandReceipts.upsert(receipt);
return { receipt, event };
}),
(result) =>
result.event === undefined ? Effect.void : eventStore.publishCommitted([result.event]),
);
return { receipt: result.receipt, committed: result.event !== undefined };
},
);
const commitRejectedProjectCommandEffect = Effect.fn(
"orchestrationV2.EventSink.commitRejectedProjectCommand",
)(function* (input: Parameters<EventSinkV2Shape["commitRejectedProjectCommand"]>[0]) {
return yield* sql.withTransaction(
Effect.gen(function* () {
const receipt: CommandReceiptStore.ProjectCommandReceiptV2 = {
commandId: input.commandId,
projectId: input.projectId,
commandType: input.commandType,
acceptedAt: input.rejectedAt,
resultSequence: yield* eventStore.latestApplicationSequence,
status: "rejected",
error: input.error,
};
return (yield* commandReceipts.insertIfAbsent(receipt))
? receipt
: yield* existingProjectReceipt(input.commandId);
}),
);
});
const catchUp = (input: {
readonly afterSequence: number;
readonly throughSequence: number;
readonly threadId?: ThreadId;
readonly eventType?: OrchestrationV2DomainEvent["type"];
}): Stream.Stream<OrchestrationV2StoredEvent, unknown> => {
const pageSize = 256;
const loop = (afterSequence: number): Stream.Stream<OrchestrationV2StoredEvent, unknown> =>
Stream.unwrap(
eventStore
.read({
afterSequence,
throughSequence: input.throughSequence,
...(input.threadId === undefined ? {} : { threadId: input.threadId }),
...(input.eventType === undefined ? {} : { eventType: input.eventType }),
limit: pageSize,
})
.pipe(
Stream.runCollect,
Effect.map((chunk) => Array.from(chunk)),
Effect.map((events) => {
if (events.length === 0) {
return Stream.empty;
}
const current = Stream.fromIterable(events);
const last = events.at(-1)?.sequence ?? input.throughSequence;
return events.length < pageSize || last >= input.throughSequence
? current
: Stream.concat(current, loop(last));
}),
),
);
return loop(input.afterSequence);
};
const stream = (input?: Parameters<EventSinkV2Shape["stream"]>[0]) => {
const afterSequence = input?.afterSequence ?? 0;
const matches = (stored: OrchestrationV2StoredEvent) =>
(input?.threadId === undefined || stored.event.threadId === input.threadId) &&
(input?.eventType === undefined || stored.event.type === input.eventType);
const replay = (throughSequence: number) =>
catchUp({