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

ThreadLiveEventCoalescer.ts

244 lines8.2 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 coalescibleUpdateKey(input: ThreadLiveEvent): string | null {
25 const { event } = input;
26 const prefix = `${event.threadId}\u0000${event.runId ?? ""}\u0000${event.type}`;
27 if (event.type === "message.updated") {
28 return event.payload.role === "assistant" && event.payload.streaming
29 ? `${prefix}\u0000${event.payload.id}`
30 : null;
31 }
32 if (event.type !== "turn-item.updated" || event.payload.status !== "running") return null;
33 switch (event.payload.type) {
34 case "assistant_message":
35 case "reasoning":
36 if (!event.payload.streaming) return null;
37 break;
38 case "command_execution":
39 case "file_change":
40 case "file_search":
41 case "web_search":
42 case "dynamic_tool":
43 break;
44 default:
45 return null;
46 }
47 return `${prefix}\u0000${event.payload.type}\u0000${event.payload.id}`;
49​
50// These events replace whole entities. Keep each survivor at its original
51// position/sequence so a resume cursor cannot skip an unrelated earlier update.
52export function coalesceLiveUpdatedEvents(
53 events: ReadonlyArray<ThreadLiveEvent>,
54): ReadonlyArray<ThreadLiveEvent> {
55 const latestUpdates = new Map<string, number>();
56 const superseded = new Set<number>();
57 const pendingKeys = new Map<ThreadLiveEvent["event"]["type"], string>();
58​
59 for (const [index, event] of events.entries()) {
60 const key = coalescibleUpdateKey(event);
61 if (key === null) {
62 latestUpdates.clear();
63 pendingKeys.clear();
64 continue;
65 }
66 // Both entity families use insertion order; partial timelines also reject
67 // unseen items below their watermark. Keep identity switches within each
68 // family, while allowing paired message/item updates to coalesce.
69 const pendingKey = pendingKeys.get(event.event.type);
70 if (pendingKey !== undefined && pendingKey !== key) latestUpdates.clear();
71 pendingKeys.set(event.event.type, key);
72 const previous = latestUpdates.get(key);
73 if (previous !== undefined) superseded.add(previous);
74 latestUpdates.set(key, index);
75 }
76 return events.filter((_, index) => !superseded.has(index));
78​
79export const makeThreadLiveEventCoalescer = Effect.fn(
80 "ThreadLiveEventCoalescer.makeThreadLiveEventCoalescer",
81)(function* <E = never>(options?: {
82 readonly coalesceWindow?: Duration.Input;
83 readonly maxItems?: number;
84 readonly maxSerializedBytes?: number;
85}) {
86 const coalescerScope = yield* Effect.scope;
87 const budget = yield* makeLiveStreamBudget(options);
88 const cleanupComplete = yield* Deferred.make<void>();
89 const output = yield* Queue.unbounded<
90 RetainedLiveItem<ThreadLiveInput>,
91 E | LiveStreamBufferError | Cause.Done
92 >();
93 const mutex = yield* Semaphore.make(1);
94 const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;
95 let pendingUpdates: Array<RetainedLiveItem<ThreadLiveEvent>> = [];
96 let windowGeneration = 0;
97 let windowFiber: Fiber.Fiber<void, never> | null = null;
98 let closed = false;
99​
100 const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {
101 const fiber = windowFiber;
102 if (!fiber) {
103 return;
104 }
105 windowFiber = null;
106 yield* Fiber.interrupt(fiber);
107 });
108​
109 const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* () {
110 if (pendingUpdates.length === 0) {
111 return;
112 }
113 const items = yield* budget.replace(
114 pendingUpdates,
115 coalesceLiveUpdatedEvents(pendingUpdates.map((item) => item.value)),
116 );
117 pendingUpdates = [];
118 yield* Queue.offerAll(output, items);
119 }, Effect.uninterruptible);
120​
121 const flushWindow = (generation: number) =>
122 Effect.sleep(coalesceWindow).pipe(
123 Effect.andThen(
124 mutex.withPermits(1)(
125 Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),
126 ),
127 ),
128 Effect.ensuring(
129 Effect.sync(() => {
130 if (generation === windowGeneration) {
131 windowFiber = null;
132 }
133 }),
134 ),
135 Effect.catchTags({ LiveStreamBufferError: () => Effect.void }),
136 );
137​
138 // Keep each source batch together so a synchronization marker cannot pass
139 // events already pulled from PubSub but still being coalesced.
140 const offerAll = Effect.fn("ThreadLiveEventCoalescer.offerAll")(function* (
141 inputs: ReadonlyArray<ThreadLiveInput>,
142 ) {
143 yield* mutex.withPermits(1)(
144 Effect.forEach(
145 inputs,
146 (input) =>
147 Effect.gen(function* () {
148 yield* budget.check;
149 if (input.kind === "event") {
150 yield* budget.retain(input).pipe(
151 Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
152 Effect.uninterruptible,
153 );
154 }
155 if (input.kind === "event" && coalescibleUpdateKey(input) !== null) {
156 if (pendingUpdates.length === 1) {
157 const generation = ++windowGeneration;
158 windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);
159 }
160 if (pendingUpdates.length >= MAX_PENDING_UPDATES) {
161 yield* cancelWindow();
162 windowGeneration += 1;
163 yield* flushPending();
164 }
165 return;
166 }
167​
168 yield* cancelWindow();
169 windowGeneration += 1;
170 yield* flushPending();
171 if (input.kind === "synchronized") {
172 yield* budget.retain({ kind: "synchronized" as const }).pipe(
173 Effect.flatMap((marker) => Queue.offer(output, marker)),
174 Effect.uninterruptible,
175 );
176 }
177 }),
178 { discard: true },
179 ),
180 );
181 });
182​
183 const close = (cause?: Cause.Cause<E | LiveStreamBufferError>) =>
184 mutex.withPermits(1)(
185 Effect.gen(function* () {
186 if (closed) {
187 return;
188 }
189 closed = true;
190 windowGeneration += 1;
191 yield* cancelWindow();
192 budget.release(pendingUpdates);
193 pendingUpdates = [];
194 budget.release(yield* Queue.clear(output).pipe(Effect.orElseSucceed(() => [])));
195 if (cause) {
196 yield* Queue.failCause(output, cause);
197 }
198 yield* Queue.shutdown(output);
199 yield* Deferred.succeed(cleanupComplete, undefined);
200 }),
201 );
202​
203 yield* Effect.addFinalizer(() => close());
204 yield* budget.failed.pipe(
205 Effect.catchTags({ LiveStreamBufferError: (error) => close(Cause.fail(error)) }),
206 Effect.forkScoped,
207 );
208​
209 return {
210 offer: (input: ThreadLiveInput) => offerAll([input]),
211 close,
212 end: mutex.withPermits(1)(
213 Effect.gen(function* () {
214 yield* cancelWindow();
215 windowGeneration += 1;
216 yield* flushPending();
217 yield* Queue.end(output);
218 }),
219 ),
220 offerAll,
221 stream: budget.deliver(Stream.fromQueue(output)),
222 failed: budget.failed,
223 closed: Deferred.await(cleanupComplete),
224 usage: budget.usage,
225 } as const;
226});
227​
228export const coalesceThreadLiveStream = <E, R>(source: Stream.Stream<ThreadLiveEvent, E, R>) =>
229 Stream.unwrap(
230 Effect.gen(function* () {
231 const coalescer = yield* makeThreadLiveEventCoalescer<E>();
232 yield* source.pipe(
233 Stream.runForEachArray(coalescer.offerAll),
234 Effect.andThen(coalescer.end),
235 Effect.raceFirst(coalescer.failed),
236 Effect.exit,
237 Effect.flatMap((exit) =>
238 Exit.isFailure(exit) ? coalescer.close(exit.cause) : Effect.void,
239 ),
240 Effect.forkScoped({ startImmediately: true }),
241 );
242 return coalescer.stream;
243 }),
244 );