Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Clock from "effect/Clock";
3import * as Config from "effect/Config";
4import * as Effect from "effect/Effect";
5import * as Context from "effect/Context";
6import * as Deferred from "effect/Deferred";
7import * as Exit from "effect/Exit";
8import * as Queue from "effect/Queue";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11
12const MAX_EVENTS = 64;
13const MAX_BYTES = 1024 * 1024;
14// While another write waits, a shared transaction stops taking jobs after this long.
15const MAX_HOLD_NANOS = 100_000_000n;
16const encodeQueue = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
17
18export const enabled = Config.Boolean("T3CODE_PROVIDER_COMMIT_BATCHING").pipe(
19 Config.withDefault(true),
20 Effect.orDie,
21);
22
23type Snapshot =
24 | { readonly type: "node.updated"; readonly node: { readonly threadId: string } }
25 | { readonly type: "message.updated"; readonly message: { readonly threadId: string } }
26 | { readonly type: "turn_item.updated"; readonly turnItem: { readonly threadId: string } }
27 | { readonly type: "plan.updated"; readonly plan: { readonly threadId: string } };
28const isSnapshot = (event: { readonly type: string }): event is Snapshot =>
29 event.type === "node.updated" ||
30 event.type === "message.updated" ||
31 event.type === "turn_item.updated" ||
32 event.type === "plan.updated";
33const snapshotThreadId = (event: Snapshot) => {
34 switch (event.type) {
35 case "node.updated":
36 return event.node.threadId;
37 case "message.updated":
38 return event.message.threadId;
39 case "turn_item.updated":
40 return event.turnItem.threadId;
41 case "plan.updated":
42 return event.plan.threadId;
43 }
44};
45
46export class CommitBatchError extends Schema.TaggedError<CommitBatchError>()("CommitBatchError", {
47 cause: Schema.Defect(),
48}) {}
49export const isCommitBatchError = Schema.is(CommitBatchError);
50
51interface Job {
52 readonly owner: { active: boolean };
53 readonly threadId: string;
54 readonly queuedAt: number;
55 readonly bytes: number;
56 readonly execute: Effect.Effect<void, CommitBatchError>;
57 readonly settle: (
58 exit: Exit.Exit<void, CommitBatchError>,
59 preserveFailure: boolean,
60 ) => Effect.Effect<void>;
61 readonly cancel: Effect.Effect<void>;
62 readonly settled: Effect.Effect<void>;
63}
64interface Batch {
65 readonly events: ReadonlyArray<Job>;
66 readonly reason: "ready" | "limit";
67}
68
69function collect(queue: Queue.Queue<Job>) {
70 return Stream.fromEffectRepeat(Queue.takeBetween(queue, 1, MAX_EVENTS)).pipe(
71 Stream.flatMap((ready) => {
72 const batches: Array<Batch> = [];
73 let events: Array<Job> = [];
74 let bytes = 0;
75 const flush = (reason: Batch["reason"]) => {
76 if (events.length > 0) batches.push({ events, reason });
77 events = [];
78 bytes = 0;
79 };
80 for (const job of ready) {
81 if (events.length > 0 && bytes + job.bytes > MAX_BYTES) flush("limit");
82 events.push(job);
83 bytes += job.bytes;
84 if (events.length >= MAX_EVENTS || bytes >= MAX_BYTES) flush("limit");
85 }
86 flush("ready");
87 return Stream.fromArray(batches);
88 }),
89 );
90}
91
92const CurrentWorker = Context.Reference<number | undefined>(
93 "t3/ProviderCommitBatch/CurrentWorker",
94 {
95 defaultValue: () => undefined,
96 },
97);
98
99export const make = Effect.fn("ProviderCommitBatch.make")(function* (
100 commit: (work: Effect.Effect<void, CommitBatchError>) => Effect.Effect<void, CommitBatchError>,
101 enabled: boolean,
102 isolate: (
103 work: Effect.Effect<void, CommitBatchError>,
104 ) => Effect.Effect<void, CommitBatchError> = (work) => work,
105) {
106 const queue = yield* Queue.bounded<Job>(MAX_EVENTS);
107 const pending = new Set<Job>();
108 let closed = false;
109 // Writes in `barrier` that have not finished; they wait on the batch or the writer it holds.
110 let waitingWriters = 0;
111 const shutdown = Effect.gen(function* () {
112 closed = true;
113 yield* Queue.shutdown(queue);
114 for (const job of pending) yield* job.cancel;
115 });
116 yield* Effect.addFinalizer(() => shutdown);
117 // These helpers run once per raw event; the shared transaction owns the tracing span.
118 const enqueue = Effect.fnUntraced(function* <A, E, R>(
119 effect: Effect.Effect<A, E, R>,
120 token: { active: boolean },
121 threadId: string,
122 bytes: number,
123 ) {
124 const caller = yield* Effect.context<R>();
125 const reply = yield* Deferred.make<A, E | CommitBatchError>();
126 let ownFailure: Cause.Cause<E> | undefined;
127 let result: A;
128 const job: Job = {
129 owner: token,
130 threadId,
131 queuedAt: yield* Clock.currentTimeMillis,
132 bytes,
133 execute: effect.pipe(
134 Effect.tapCause((cause) =>
135 Effect.sync(() => {
136 ownFailure = cause;
137 }),
138 ),
139 Effect.mapError((cause) => new CommitBatchError({ cause })),
140 Effect.provideContext(caller),
141 Effect.tap((value) =>
142 Effect.sync(() => {
143 result = value;
144 }),
145 ),
146 Effect.asVoid,
147 ),
148 settle: Effect.fnUntraced(function* (
149 exit: Exit.Exit<void, CommitBatchError>,
150 preserveFailure: boolean,
151 ) {
152 pending.delete(job);
153 if (Exit.isFailure(exit)) {
154 token.active = false;
155 yield* Deferred.failCause(
156 reply,
157 preserveFailure && ownFailure !== undefined ? ownFailure : exit.cause,
158 );
159 } else yield* Deferred.succeed(reply, result);
160 }),
161 cancel: Effect.gen(function* () {
162 pending.delete(job);
163 yield* Deferred.interrupt(reply);
164 }),
165 settled: Deferred.await(reply).pipe(Effect.exit, Effect.asVoid),
166 };
167 yield* Effect.uninterruptibleMask((restore) =>
168 Effect.gen(function* () {
169 pending.add(job);
170 const accepted = yield* restore(Queue.offer(queue, job)).pipe(
171 Effect.onError(() => job.cancel),
172 );
173 if (!accepted) yield* job.cancel;
174 }),
175 );
176 return Deferred.await(reply);
177 });
178 // Commits a prefix of `jobs` in one transaction and returns how many it took.
179 const commitPrefix = (jobs: ReadonlyArray<Job>, reason: Batch["reason"]) =>
180 Effect.uninterruptibleMask((restore) =>
181 Effect.gen(function* () {
182 const outcomes = new Map<Job, Exit.Exit<void, CommitBatchError>>();
183 let taken = 0;
184 const work = Effect.gen(function* () {
185 // A retried transaction runs this again from the first job.
186 outcomes.clear();
187 taken = 0;
188 const startedAt = yield* Clock.monotonicTimeNanos;
189 for (const job of jobs) {
190 if (
191 taken > 0 &&
192 waitingWriters > 0 &&
193 (yield* Clock.monotonicTimeNanos) - startedAt >= MAX_HOLD_NANOS
194 )
195 return;
196 taken++;
197 if (!job.owner.active) {
198 yield* job.cancel;
199 continue;
200 }
201 const outcome = yield* (jobs.length > 1 ? isolate(job.execute) : job.execute).pipe(
202 Effect.exit,
203 );
204 outcomes.set(job, outcome);
205 if (Exit.isFailure(outcome)) {
206 job.owner.active = false;
207 if (jobs.length === 1) return yield* Effect.failCause(outcome.cause);
208 }
209 }
210 });
211 const exit = yield* restore(
212 commit(work).pipe(Effect.provideService(CurrentWorker, yield* Effect.fiberId)),
213 ).pipe(Effect.exit);
214 const committed = taken === 0 ? jobs : jobs.slice(0, taken);
215 yield* Effect.annotateCurrentSpan({
216 "orchestration_v2.work_item_count": committed.length,
217 "orchestration_v2.deferred_work_item_count": jobs.length - committed.length,
218 "orchestration_v2.consumer_count": new Set(committed.map((job) => job.owner)).size,
219 "orchestration_v2.raw_json_bytes": committed.reduce((bytes, job) => bytes + job.bytes, 0),
220 "orchestration_v2.batch_flush_reason": reason,
221 "orchestration_v2.backlog_batching": true,
222 "orchestration_v2.batch_wait_ms":
223 (yield* Clock.currentTimeMillis) - Math.min(...committed.map((job) => job.queuedAt)),
224 });
225 for (const job of committed) {
226 const outcome = outcomes.get(job) ?? Exit.void;
227 yield* job.settle(
228 Exit.isSuccess(exit) ? outcome : exit,
229 Exit.isSuccess(exit) ||
230 (Exit.isFailure(exit) &&
231 Exit.isFailure(outcome) &&
232 Cause.squash(exit.cause) === Cause.squash(outcome.cause)),
233 );
234 }
235 return committed.length;
236 }),
237 ).pipe(Effect.withSpan("orchestrationV2.ProviderCommitBatch.flush"));
238 if (enabled) {
239 yield* collect(queue).pipe(
240 Stream.runForEach(
241 Effect.fnUntraced(function* (batch: Batch) {
242 let jobs = batch.events;
243 while (jobs.length > 0) {
244 for (const job of jobs) if (!job.owner.active) yield* job.cancel;
245 jobs = jobs.filter((job) => job.owner.active);
246 if (jobs.length === 0) return;
247 jobs = jobs.slice(yield* commitPrefix(jobs, batch.reason));
248 }
249 }),
250 ),
251 Effect.ensuring(shutdown),
252 Effect.forkScoped,
253 );
254 }
255 /**
256 * Runs `effect` after queued snapshots for `threadIds` commit; omitted, after every queued
257 * snapshot. Other threads' snapshots never delay it.
258 */
259 const barrier = Effect.fnUntraced(function* <A, E, R>(
260 effect: Effect.Effect<A, E, R>,
261 threadIds?: ReadonlyArray<string>,
262 ) {
263 if (closed) return yield* Effect.interrupt;
264 if (!enabled || (yield* CurrentWorker) === (yield* Effect.fiberId)) return yield* effect;
265 return yield* Effect.uninterruptibleMask((restore) => {
266 waitingWriters++;
267 return restore(
268 Effect.gen(function* () {
269 for (const job of Array.from(pending)) {
270 if (threadIds === undefined || threadIds.includes(job.threadId)) yield* job.settled;
271 }
272 if (closed) return yield* Effect.interrupt;
273 return yield* effect;
274 }),
275 ).pipe(
276 Effect.ensuring(
277 Effect.sync(() => {
278 waitingWriters--;
279 }),
280 ),
281 );
282 });
283 });
284 const consume = Effect.fnUntraced(function* <A extends { readonly type: string }, E, R, E2, R2>(
285 source: Stream.Stream<A, E, R>,
286 process: (event: A) => Effect.Effect<void, E2, R2>,
287 after: Effect.Effect<boolean, E2, R2>,
288 canBatch: Effect.Effect<boolean, never, R2> = Effect.succeed(true),
289 ) {
290 if (!enabled)
291 return yield* source.pipe(
292 Stream.mapEffect((event) => process(event).pipe(Effect.andThen(after))),
293 Stream.takeUntil(Boolean),
294 Stream.runDrain,
295 );
296 const token = { active: true };
297 const signals = source.pipe(
298 Stream.map((event) => ({ _tag: "Event" as const, event })),
299 Stream.catchCause((cause) => Stream.succeed({ _tag: "Failure" as const, cause })),
300 Stream.concat(Stream.succeed({ _tag: "End" as const })),
301 );
302 let resume: Effect.Effect<void> = Effect.void;
303 // Replies run in order, so EOF, failures and controls follow this stream's earlier snapshots
304 // without waiting for other streams' work.
305 yield* signals.pipe(
306 Stream.mapEffect((signal) =>
307 Effect.gen(function* () {
308 yield* resume;
309 const processed = yield* Deferred.make<void>();
310 let reply: Effect.Effect<boolean, E | E2 | CommitBatchError, R2>;
311 let check = false;
312 if (signal._tag === "End") reply = Effect.succeed(true);
313 else if (signal._tag === "Failure") reply = Effect.failCause(signal.cause);
314 else if (isSnapshot(signal.event) && (yield* canBatch)) {
315 const bytes = Buffer.byteLength(yield* encodeQueue(signal.event));
316 reply = yield* enqueue(
317 process(signal.event).pipe(Effect.as(false)),
318 token,
319 snapshotThreadId(signal.event),
320 bytes,
321 );
322 } else {
323 reply = process(signal.event).pipe(Effect.as(false));
324 check = true;
325 resume = Deferred.await(processed);
326 }
327 return { reply, processed, check };
328 }),
329 ),
330 Stream.buffer({ capacity: MAX_EVENTS }),
331 Stream.mapEffect(({ reply, processed, check }) =>
332 reply.pipe(
333 Effect.flatMap((end) =>
334 end ? Effect.succeed(true) : check ? after : Effect.succeed(false),
335 ),
336 Effect.tap((stop) =>
337 Effect.sync(() => {
338 if (stop) token.active = false;
339 }),
340 ),
341 Effect.ensuring(Deferred.succeed(processed, undefined)),
342 ),
343 ),
344 Stream.takeUntil(Boolean),
345 Stream.runDrain,
346 Effect.ensuring(
347 Effect.sync(() => {
348 token.active = false;
349 }),
350 ),
351 );
352 });
353 return { barrier, consume };
354});