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

ThreadLiveEventCoalescer.ts

242 lines8.1 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 maxItems?: number;
83 readonly maxSerializedBytes?: number;
84}) {
85 const coalescerScope = yield* Effect.scope;
86 const budget = yield* makeLiveStreamBudget(options);
87 const cleanupComplete = yield* Deferred.make<void>();
88 const output = yield* Queue.unbounded<
89 RetainedLiveItem<ThreadLiveInput>,
90 E | LiveStreamBufferError | Cause.Done
91 >();
92 const mutex = yield* Semaphore.make(1);
93 let pendingUpdates: Array<RetainedLiveItem<ThreadLiveEvent>> = [];
94 let windowGeneration = 0;
95 let windowFiber: Fiber.Fiber<void, never> | null = null;
96 let closed = false;
97​
98 const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {
99 const fiber = windowFiber;
100 if (!fiber) {
101 return;
102 }
103 windowFiber = null;
104 yield* Fiber.interrupt(fiber);
105 });
106​
107 const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* () {
108 if (pendingUpdates.length === 0) {
109 return;
110 }
111 const items = yield* budget.replace(
112 pendingUpdates,
113 coalesceLiveUpdatedEvents(pendingUpdates.map((item) => item.value)),
114 );
115 pendingUpdates = [];
116 yield* Queue.offerAll(output, items);
117 }, Effect.uninterruptible);
118​
119 const flushWindow = (generation: number) =>
120 Effect.sleep(COALESCE_WINDOW).pipe(
121 Effect.andThen(
122 mutex.withPermits(1)(
123 Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),
124 ),
125 ),
126 Effect.ensuring(
127 Effect.sync(() => {
128 if (generation === windowGeneration) {
129 windowFiber = null;
130 }
131 }),
132 ),
133 Effect.catchTags({ LiveStreamBufferError: () => Effect.void }),
134 );
135​
136 // Keep each source batch together so a synchronization marker cannot pass
137 // events already pulled from PubSub but still being coalesced.
138 const offerAll = Effect.fn("ThreadLiveEventCoalescer.offerAll")(function* (
139 inputs: ReadonlyArray<ThreadLiveInput>,
140 ) {
141 yield* mutex.withPermits(1)(
142 Effect.forEach(
143 inputs,
144 (input) =>
145 Effect.gen(function* () {
146 yield* budget.check;
147 if (input.kind === "event") {
148 yield* budget.retain(input).pipe(
149 Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
150 Effect.uninterruptible,
151 );
152 }
153 if (input.kind === "event" && coalescibleUpdateKey(input) !== null) {
154 if (pendingUpdates.length === 1) {
155 const generation = ++windowGeneration;
156 windowFiber = yield* Effect.forkIn(flushWindow(generation), coalescerScope);
157 }
158 if (pendingUpdates.length >= MAX_PENDING_UPDATES) {
159 yield* cancelWindow();
160 windowGeneration += 1;
161 yield* flushPending();
162 }
163 return;
164 }
165​
166 yield* cancelWindow();
167 windowGeneration += 1;
168 yield* flushPending();
169 if (input.kind === "synchronized") {
170 yield* budget.retain({ kind: "synchronized" as const }).pipe(
171 Effect.flatMap((marker) => Queue.offer(output, marker)),
172 Effect.uninterruptible,
173 );
174 }
175 }),
176 { discard: true },
177 ),
178 );
179 });
180​
181 const close = (cause?: Cause.Cause<E | LiveStreamBufferError>) =>
182 mutex.withPermits(1)(
183 Effect.gen(function* () {
184 if (closed) {
185 return;
186 }
187 closed = true;
188 windowGeneration += 1;
189 yield* cancelWindow();
190 budget.release(pendingUpdates);
191 pendingUpdates = [];
192 budget.release(yield* Queue.clear(output).pipe(Effect.orElseSucceed(() => [])));
193 if (cause) {
194 yield* Queue.failCause(output, cause);
195 }
196 yield* Queue.shutdown(output);
197 yield* Deferred.succeed(cleanupComplete, undefined);
198 }),
199 );
200​
201 yield* Effect.addFinalizer(() => close());
202 yield* budget.failed.pipe(
203 Effect.catchTags({ LiveStreamBufferError: (error) => close(Cause.fail(error)) }),
204 Effect.forkScoped,
205 );
206​
207 return {
208 offer: (input: ThreadLiveInput) => offerAll([input]),
209 close,
210 end: mutex.withPermits(1)(
211 Effect.gen(function* () {
212 yield* cancelWindow();
213 windowGeneration += 1;
214 yield* flushPending();
215 yield* Queue.end(output);
216 }),
217 ),
218 offerAll,
219 stream: budget.deliver(Stream.fromQueue(output)),
220 failed: budget.failed,
221 closed: Deferred.await(cleanupComplete),
222 usage: budget.usage,
223 } as const;
224});
225​
226export const coalesceThreadLiveStream = <E, R>(source: Stream.Stream<ThreadLiveEvent, E, R>) =>
227 Stream.unwrap(
228 Effect.gen(function* () {
229 const coalescer = yield* makeThreadLiveEventCoalescer<E>();
230 yield* source.pipe(
231 Stream.runForEachArray(coalescer.offerAll),
232 Effect.andThen(coalescer.end),
233 Effect.raceFirst(coalescer.failed),
234 Effect.exit,
235 Effect.flatMap((exit) =>
236 Exit.isFailure(exit) ? coalescer.close(exit.cause) : Effect.void,
237 ),
238 Effect.forkScoped({ startImmediately: true }),
239 );
240 return coalescer.stream;
241 }),
242 );