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

ThreadLiveEventCoalescer.ts

248 lines7.8 KB

1import type { OrchestrationV2ThreadStreamItem } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as Queue from "effect/Queue";
9import * as Semaphore from "effect/Semaphore";
10import * as Stream from "effect/Stream";
11​
12import {
13 LiveStreamBufferError,
14 makeLiveStreamBudget,
15 type RetainedLiveItem,
16} from "./LiveStreamBudget.ts";
17​
18const COALESCE_WINDOW = Duration.millis(50);
19const MAX_PENDING_UPDATES = 512;
20​
21type ThreadLiveEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>;
22export type ThreadLiveInput = ThreadLiveEvent | { readonly kind: "synchronized" };
23​
24function isToolUpdated(input: ThreadLiveEvent): boolean {
25 if (input.event.type !== "turn-item.updated" || input.event.payload.status !== "running")
26 return false;
27 switch (input.event.payload.type) {
28 case "command_execution":
29 case "file_change":
30 case "file_search":
31 case "web_search":
32 case "dynamic_tool":
33 return true;
34 default:
35 return false;
36 }
38​
39function stableToolCallIdentity(input: ThreadLiveEvent): string | null {
40 return input.event.type === "turn-item.updated" ? input.event.payload.id : null;
42​
43export function coalesceLiveToolUpdatedEvents(
44 events: ReadonlyArray<ThreadLiveEvent>,
45): ReadonlyArray<ThreadLiveEvent> {
46 const survivors: Array<ThreadLiveEvent> = [];
47 let pendingUpdates: Array<ThreadLiveEvent> = [];
48​
49 const flushUpdates = () => {
50 const seen = new Set<string>();
51 const latestUpdates: Array<ThreadLiveEvent> = [];
52 for (let index = pendingUpdates.length - 1; index >= 0; index -= 1) {
53 const event = pendingUpdates[index]!;
54 const identity = stableToolCallIdentity(event);
55 const key = identity
56 ? `${event.event.threadId}\u0000${event.event.runId ?? ""}\u0000${identity}`
57 : null;
58 if (key && seen.has(key)) {
59 continue;
60 }
61 if (key) {
62 seen.add(key);
63 }
64 latestUpdates.push(event);
65 }
66 latestUpdates.reverse();
67 survivors.push(...latestUpdates);
68 pendingUpdates = [];
69 };
70​
71 for (const event of events) {
72 if (isToolUpdated(event)) {
73 pendingUpdates.push(event);
74 continue;
75 }
76 flushUpdates();
77 survivors.push(event);
78 }
79 flushUpdates();
80 return survivors;
82​
83export const makeThreadLiveEventCoalescer = Effect.fn(
84 "ThreadLiveEventCoalescer.makeThreadLiveEventCoalescer",
85)(function* <E = never>(options?: {
86 readonly coalesceWindow?: Duration.Input;
87 readonly maxItems?: number;
88 readonly maxSerializedBytes?: number;
89}) {
90 const coalescerScope = yield* Effect.scope;
91 const budget = yield* makeLiveStreamBudget(options);
92 const cleanupComplete = yield* Deferred.make<void>();
93 const output = yield* Queue.unbounded<
94 RetainedLiveItem<ThreadLiveInput>,
95 E | LiveStreamBufferError | Cause.Done
96 >();
97 const mutex = yield* Semaphore.make(1);
98 const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;
99 let pendingUpdates: Array<RetainedLiveItem<ThreadLiveEvent>> = [];
100 let windowGeneration = 0;
101 let windowFiber: Fiber.Fiber<void, never> | null = null;
102 let closed = false;
103​
104 const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {
105 const fiber = windowFiber;
106 if (!fiber) {
107 return;
108 }
109 windowFiber = null;
110 yield* Fiber.interrupt(fiber);
111 });
112​
113 const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* () {
114 if (pendingUpdates.length === 0) {
115 return;
116 }
117 const items = yield* budget.replace(
118 pendingUpdates,
119 coalesceLiveToolUpdatedEvents(pendingUpdates.map((item) => item.value)),
120 );
121 pendingUpdates = [];
122 yield* Queue.offerAll(output, items);
123 }, Effect.uninterruptible);
124​
125 const flushWindow = (generation: number) =>
126 Effect.sleep(coalesceWindow).pipe(
127 Effect.andThen(
128 mutex.withPermits(1)(
129 Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),
130 ),
131 ),
132 Effect.ensuring(
133 Effect.sync(() => {
134 if (generation === windowGeneration) {
135 windowFiber = null;
136 }
137 }),
138 ),
139 Effect.catchTags({ LiveStreamBufferError: () => Effect.void }),
140 );
141​
142 // Keep each source batch together so a synchronization marker cannot pass
143 // events already pulled from PubSub but still being coalesced.
144 const offerAll = Effect.fn("ThreadLiveEventCoalescer.offerAll")(function* (
145 inputs: ReadonlyArray<ThreadLiveInput>,
146 ) {
147 yield* mutex.withPermits(1)(
148 Effect.forEach(
149 inputs,
150 (input) =>
151 Effect.gen(function* () {
152 yield* budget.check;
153 if (input.kind === "event") {
154 yield* budget.retain(input).pipe(
155 Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
156 Effect.uninterruptible,
157 );
158 }
159 if (input.kind === "event" && isToolUpdated(input)) {
160 if (pendingUpdates.length === 1) {
161 const generation = ++windowGeneration;
162 windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);
163 }
164 if (pendingUpdates.length >= MAX_PENDING_UPDATES) {
165 yield* cancelWindow();
166 windowGeneration += 1;
167 yield* flushPending();
168 }
169 return;
170 }
171​
172 yield* cancelWindow();
173 windowGeneration += 1;
174 yield* flushPending();
175 if (input.kind === "synchronized") {
176 yield* budget.retain({ kind: "synchronized" as const }).pipe(
177 Effect.flatMap((marker) => Queue.offer(output, marker)),
178 Effect.uninterruptible,
179 );
180 }
181 }),
182 { discard: true },
183 ),
184 );
185 });
186​
187 const close = (cause?: Cause.Cause<E | LiveStreamBufferError>) =>
188 mutex.withPermits(1)(
189 Effect.gen(function* () {
190 if (closed) {
191 return;
192 }
193 closed = true;
194 windowGeneration += 1;
195 yield* cancelWindow();
196 budget.release(pendingUpdates);
197 pendingUpdates = [];
198 budget.release(yield* Queue.clear(output).pipe(Effect.orElseSucceed(() => [])));
199 if (cause) {
200 yield* Queue.failCause(output, cause);
201 }
202 yield* Queue.shutdown(output);
203 yield* Deferred.succeed(cleanupComplete, undefined);
204 }),
205 );
206​
207 yield* Effect.addFinalizer(() => close());
208 yield* budget.failed.pipe(
209 Effect.catchTags({ LiveStreamBufferError: (error) => close(Cause.fail(error)) }),
210 Effect.forkScoped,
211 );
212​
213 return {
214 offer: (input: ThreadLiveInput) => offerAll([input]),
215 close,
216 end: mutex.withPermits(1)(
217 Effect.gen(function* () {
218 yield* cancelWindow();
219 windowGeneration += 1;
220 yield* flushPending();
221 yield* Queue.end(output);
222 }),
223 ),
224 offerAll,
225 stream: budget.deliver(Stream.fromQueue(output)),
226 failed: budget.failed,
227 closed: Deferred.await(cleanupComplete),
228 usage: budget.usage,
229 } as const;
230});
231​
232export const coalesceThreadLiveStream = <E, R>(source: Stream.Stream<ThreadLiveEvent, E, R>) =>
233 Stream.unwrap(
234 Effect.gen(function* () {
235 const coalescer = yield* makeThreadLiveEventCoalescer<E>();
236 yield* source.pipe(
237 Stream.runForEachArray(coalescer.offerAll),
238 Effect.andThen(coalescer.end),
239 Effect.raceFirst(coalescer.failed),
240 Effect.exit,
241 Effect.flatMap((exit) =>
242 Exit.isFailure(exit) ? coalescer.close(exit.cause) : Effect.void,
243 ),
244 Effect.forkScoped({ startImmediately: true }),
245 );
246 return coalescer.stream;
247 }),
248 );