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

ThreadLiveEventCoalescer.ts

241 lines8.1 KB

1import type {
2 OrchestrationEvent,
3 OrchestrationGetSnapshotError,
4 OrchestrationThreadStreamItem,
5} from "@t3tools/contracts";
6import * as Deferred from "effect/Deferred";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as Predicate from "effect/Predicate";
11import * as Queue from "effect/Queue";
12import * as Semaphore from "effect/Semaphore";
13import * as Stream from "effect/Stream";
14​
15import { projectActivityEvent } from "./ActivityPayloadProjection.ts";
16import { makeLiveStreamBudget, type RetainedLiveItem } from "./LiveStreamBudget.ts";
17​
18const COALESCE_WINDOW = Duration.millis(50);
19const MAX_PENDING_UPDATES = 512;
20​
21export type ThreadLiveInput =
22 | { readonly kind: "event"; readonly event: OrchestrationEvent }
23 | { readonly kind: "synchronized" };
24​
25function isToolUpdated(event: OrchestrationEvent): boolean {
26 return (
27 event.type === "thread.activity-appended" && event.payload.activity.kind === "tool.updated"
28 );
30​
31function asTrimmedString(value: unknown): string | null {
32 if (!Predicate.isString(value)) {
33 return null;
34 }
35 const trimmed = value.trim();
36 return trimmed.length > 0 ? trimmed : null;
38​
39function stableToolCallIdentity(event: OrchestrationEvent): string | null {
40 if (event.type !== "thread.activity-appended") {
41 return null;
42 }
43 const payload = event.payload.activity.payload;
44 if (!Predicate.isObject(payload)) {
45 return null;
46 }
47 const data = Predicate.isObject(payload.data) ? payload.data : null;
48 return asTrimmedString(payload.toolCallId) ?? asTrimmedString(data?.toolCallId);
50​
51/**
52 * Retain only the latest in-flight update for each stable tool-call id in a
53 * live run. Anonymous calls pass through because labels are not unique when
54 * tools execute in parallel. Survivors remain in sequence order.
55 */
56export function coalesceLiveToolUpdatedEvents(
57 events: ReadonlyArray<OrchestrationEvent>,
58): ReadonlyArray<OrchestrationEvent> {
59 const survivors: Array<OrchestrationEvent> = [];
60 let pendingUpdates: Array<OrchestrationEvent> = [];
61​
62 const flushUpdates = () => {
63 const seen = new Set<string>();
64 const latestUpdates: Array<OrchestrationEvent> = [];
65 for (let index = pendingUpdates.length - 1; index >= 0; index -= 1) {
66 const event = pendingUpdates[index]!;
67 const identity = stableToolCallIdentity(event);
68 const activity =
69 event.type === "thread.activity-appended" ? event.payload.activity : undefined;
70 const key = identity ? `${activity?.turnId ?? ""}\u0000${identity}` : null;
71 if (key && seen.has(key)) {
72 continue;
73 }
74 if (key) {
75 seen.add(key);
76 }
77 latestUpdates.push(event);
78 }
79 latestUpdates.reverse();
80 survivors.push(...latestUpdates);
81 pendingUpdates = [];
82 };
83​
84 for (const event of events) {
85 if (isToolUpdated(event)) {
86 pendingUpdates.push(event);
87 continue;
88 }
89 flushUpdates();
90 survivors.push(event);
91 }
92 flushUpdates();
93 return survivors;
95​
96export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoalescer")(
97 function* (options?: {
98 readonly coalesceWindow?: Duration.Input;
99 readonly maxItems?: number;
100 readonly maxSerializedBytes?: number;
101 }) {
102 const coalescerScope = yield* Effect.scope;
103 const budget = yield* makeLiveStreamBudget(options);
104 const cleanupComplete = yield* Deferred.make<void>();
105 const output = yield* Queue.unbounded<
106 RetainedLiveItem<OrchestrationThreadStreamItem>,
107 OrchestrationGetSnapshotError
108 >();
109 const mutex = yield* Semaphore.make(1);
110 const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;
111 let pendingUpdates: Array<RetainedLiveItem<OrchestrationEvent>> = [];
112 let windowGeneration = 0;
113 let windowFiber: Fiber.Fiber<void, never> | null = null;
114 let closed = false;
115​
116 const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {
117 const fiber = windowFiber;
118 if (!fiber) {
119 return;
120 }
121 windowFiber = null;
122 yield* Fiber.interrupt(fiber);
123 });
124​
125 const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* () {
126 if (pendingUpdates.length === 0) {
127 return;
128 }
129 const items = yield* budget.replace(
130 pendingUpdates,
131 coalesceLiveToolUpdatedEvents(pendingUpdates.map((item) => item.value)).map((event) => ({
132 kind: "event" as const,
133 event,
134 })),
135 (item) => item.event,
136 );
137 pendingUpdates = [];
138 yield* Queue.offerAll(output, items);
139 }, Effect.uninterruptible);
140​
141 const flushWindow = (generation: number) =>
142 Effect.sleep(coalesceWindow).pipe(
143 Effect.andThen(
144 mutex.withPermits(1)(
145 Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),
146 ),
147 ),
148 Effect.ensuring(
149 Effect.sync(() => {
150 if (generation === windowGeneration) {
151 windowFiber = null;
152 }
153 }),
154 ),
155 Effect.catchTags({ OrchestrationGetSnapshotError: () => Effect.void }),
156 );
157​
158 // Keep each source batch together so a synchronization marker cannot pass
159 // events already pulled from PubSub but still being coalesced.
160 const offerAll = Effect.fn("ThreadLiveEventCoalescer.offerAll")(function* (
161 inputs: ReadonlyArray<ThreadLiveInput>,
162 ) {
163 yield* mutex.withPermits(1)(
164 Effect.forEach(
165 inputs,
166 (input) =>
167 Effect.gen(function* () {
168 yield* budget.check;
169 if (input.kind === "event") {
170 // Retain only the client payload, not full persisted tool output.
171 yield* budget.retain(projectActivityEvent(input.event)).pipe(
172 Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
173 Effect.uninterruptible,
174 );
175 }
176 if (input.kind === "event" && isToolUpdated(input.event)) {
177 if (pendingUpdates.length === 1) {
178 const generation = ++windowGeneration;
179 windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);
180 }
181 if (pendingUpdates.length >= MAX_PENDING_UPDATES) {
182 yield* cancelWindow();
183 windowGeneration += 1;
184 yield* flushPending();
185 }
186 return;
187 }
188​
189 yield* cancelWindow();
190 windowGeneration += 1;
191 // A non-update event closes the run immediately. The coalescer keeps
192 // that boundary after the final update from the run.
193 yield* flushPending();
194 if (input.kind === "synchronized") {
195 yield* budget.retain({ kind: "synchronized" as const }).pipe(
196 Effect.flatMap((marker) => Queue.offer(output, marker)),
197 Effect.uninterruptible,
198 );
199 }
200 }),
201 { discard: true },
202 ),
203 );
204 });
205​
206 const close = (error?: OrchestrationGetSnapshotError) =>
207 mutex.withPermits(1)(
208 Effect.gen(function* () {
209 if (closed) {
210 return;
211 }
212 closed = true;
213 windowGeneration += 1;
214 yield* cancelWindow();
215 budget.release(pendingUpdates);
216 pendingUpdates = [];
217 budget.release(yield* Queue.clear(output).pipe(Effect.orDie));
218 if (error) {
219 yield* Queue.fail(output, error);
220 }
221 yield* Queue.shutdown(output);
222 yield* Deferred.succeed(cleanupComplete, undefined);
223 }),
224 );
225​
226 yield* Effect.addFinalizer(() => close());
227 yield* budget.failed.pipe(
228 Effect.catchTags({ OrchestrationGetSnapshotError: close }),
229 Effect.forkScoped,
230 );
231​
232 return {
233 offer: (input: ThreadLiveInput) => offerAll([input]),
234 offerAll,
235 stream: budget.deliver(Stream.fromQueue(output)),
236 failed: budget.failed,
237 closed: Deferred.await(cleanupComplete),
238 usage: budget.usage,
239 } as const;
240 },
241);