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 Semaphore from "effect/Semaphore";
11import * as Stream from "effect/Stream";
12
13const MAX_EVENTS = 64;
14const MAX_BYTES = 1024 * 1024;
15// While another write waits, a shared transaction stops taking jobs after this long.
16const MAX_HOLD_NANOS = 100_000_000n;
17// A stream waiting this long ranks like a main thread, so subagents cannot starve.
18const STARVATION_MILLIS = 30_000;
19// Bounds snapshots held across stream queues; a full backlog makes streams wait to read more.
20const MAX_QUEUED = 4 * MAX_EVENTS;
21const encodeQueue = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
22
23export const enabled = Config.Boolean("T3CODE_PROVIDER_COMMIT_BATCHING").pipe(
24 Config.withDefault(true),
25 Effect.orDie,
26);
27
28type Snapshot =
29 | {
30 readonly type: "node.updated";
31 readonly node: { readonly id: string; readonly threadId: string };
32 }
33 | {
34 readonly type: "message.updated";
35 readonly message: { readonly id: string; readonly threadId: string };
36 }
37 | {
38 readonly type: "turn_item.updated";
39 readonly turnItem: { readonly id: string; readonly threadId: string };
40 }
41 | {
42 readonly type: "plan.updated";
43 readonly plan: { readonly id: string; readonly threadId: string };
44 };
45const isSnapshot = (event: { readonly type: string }): event is Snapshot =>
46 event.type === "node.updated" ||
47 event.type === "message.updated" ||
48 event.type === "turn_item.updated" ||
49 event.type === "plan.updated";
50const snapshotEntity = (event: Snapshot) => {
51 const entity =
52 event.type === "node.updated"
53 ? event.node
54 : event.type === "message.updated"
55 ? event.message
56 : event.type === "turn_item.updated"
57 ? event.turnItem
58 : event.plan;
59 return { key: `${event.type}:${entity.id}`, threadId: entity.threadId };
60};
61
62/** Who a provider stream writes for; ranks its snapshots against other streams'. */
63export interface StreamPriority {
64 readonly threadId: string;
65 /** A subagent or delegated task, which yields to main threads. */
66 readonly delegated: boolean;
67}
68
69export class CommitBatchError extends Schema.TaggedError<CommitBatchError>()("CommitBatchError", {
70 cause: Schema.Defect(),
71}) {}
72export const isCommitBatchError = Schema.is(CommitBatchError);
73
74interface StreamState {
75 readonly owner: { active: boolean };
76 readonly priority: StreamPriority | undefined;
77 /** Queued snapshots not yet taken into a batch, in stream order. */
78 readonly jobs: Array<Job>;
79 unsettled: number;
80 servedAt: number;
81 /** A control, failure or EOF of this stream waits for its queued snapshots. */
82 finishing: boolean;
83}
84interface Job {
85 readonly stream: StreamState;
86 /** Still in its stream's queue, holding one of the backlog's `MAX_QUEUED` slots. */
87 queued: boolean;
88 readonly key: string;
89 readonly threadId: string;
90 readonly queuedAt: number;
91 readonly bytes: number;
92 readonly execute: Effect.Effect<void, CommitBatchError>;
93 readonly settle: (
94 exit: Exit.Exit<void, CommitBatchError>,
95 preserveFailure: boolean,
96 ) => Effect.Effect<void>;
97 /** Settles a job a later snapshot of the same entity replaced, with that snapshot's outcome. */
98 readonly skip: (exit: Exit.Exit<void, CommitBatchError>) => Effect.Effect<void>;
99 readonly cancel: Effect.Effect<void>;
100 readonly settled: Effect.Effect<void>;
101}
102interface Unit {
103 readonly job: Job;
104 readonly superseded: ReadonlyArray<Job>;
105}
106interface Batch {
107 readonly units: ReadonlyArray<Unit>;
108 readonly reason: "ready" | "limit";
109 readonly dequeued: number;
110}
111
112/**
113 * Snapshots carry an entity's full state, so an earlier one is dropped when a later one of the
114 * same entity follows it in this stream with no first appearance of another entity in between.
115 * Kept jobs stay in stream order, and entities first appear in the same order as before.
116 */
117function coalesce(jobs: ReadonlyArray<Job>): Array<Unit> {
118 const firstSeen = new Map<string, number>();
119 jobs.forEach((job, index) => {
120 if (!firstSeen.has(job.key)) firstSeen.set(job.key, index);
121 });
122 const survivor: Array<number> = Array.from({ length: jobs.length }, (_, index) => index);
123 const nextOfKey = new Map<string, number>();
124 for (let index = jobs.length - 1; index >= 0; index--) {
125 const job = jobs[index]!;
126 const next = nextOfKey.get(job.key);
127 nextOfKey.set(job.key, index);
128 if (next === undefined) continue;
129 let replaced = true;
130 for (let between = index + 1; replaced && between < next; between++) {
131 if (firstSeen.get(jobs[between]!.key)! > index) replaced = false;
132 }
133 if (replaced) survivor[index] = survivor[next]!;
134 }
135 const superseded = new Map<number, Array<Job>>();
136 jobs.forEach((job, index) => {
137 const kept = survivor[index]!;
138 if (kept !== index) superseded.set(kept, [...(superseded.get(kept) ?? []), job]);
139 });
140 return jobs.flatMap((job, index) =>
141 survivor[index] === index ? [{ job, superseded: superseded.get(index) ?? [] }] : [],
142 );
143}
144
145const CurrentWorker = Context.Reference<number | undefined>(
146 "t3/ProviderCommitBatch/CurrentWorker",
147 {
148 defaultValue: () => undefined,
149 },
150);
151
152export const make = Effect.fn("ProviderCommitBatch.make")(function* (
153 commit: (work: Effect.Effect<void, CommitBatchError>) => Effect.Effect<void, CommitBatchError>,
154 enabled: boolean,
155 isolate: (
156 work: Effect.Effect<void, CommitBatchError>,
157 ) => Effect.Effect<void, CommitBatchError> = (work) => work,
158 /** Whether a client has the thread open; its streams rank first. */
159 isViewed: (threadId: string) => boolean = () => false,
160) {
161 const wake = yield* Queue.sliding<void>(1);
162 const backlog = yield* Semaphore.make(MAX_QUEUED);
163 const streams = new Set<StreamState>();
164 const pending = new Set<Job>();
165 let closed = false;
166 let servings = 0;
167 // The snapshots each unfinished `barrier` write waits on.
168 const waitingWrites = new Set<ReadonlySet<Job>>();
169 const shutdown = Effect.gen(function* () {
170 closed = true;
171 yield* Queue.shutdown(wake);
172 for (const job of pending) yield* job.cancel;
173 yield* backlog.releaseAll;
174 });
175 yield* Effect.addFinalizer(() => shutdown);
176 // These helpers run once per raw event; the shared transaction owns the tracing span.
177 const enqueue = Effect.fnUntraced(function* <A, E, R>(
178 effect: Effect.Effect<A, E, R>,
179 stream: StreamState,
180 entity: { readonly key: string; readonly threadId: string },
181 bytes: number,
182 skipped: A,
183 ) {
184 const caller = yield* Effect.context<R>();
185 const reply = yield* Deferred.make<A, E | CommitBatchError>();
186 let ownFailure: Cause.Cause<E> | undefined;
187 let result: A;
188 const release = () => {
189 if (pending.delete(job)) stream.unsettled--;
190 };
191 const job: Job = {
192 stream,
193 queued: false,
194 key: entity.key,
195 threadId: entity.threadId,
196 queuedAt: yield* Clock.currentTimeMillis,
197 bytes,
198 execute: effect.pipe(
199 Effect.tapCause((cause) =>
200 Effect.sync(() => {
201 ownFailure = cause;
202 }),
203 ),
204 Effect.mapError((cause) => new CommitBatchError({ cause })),
205 Effect.provideContext(caller),
206 Effect.tap((value) =>
207 Effect.sync(() => {
208 result = value;
209 }),
210 ),
211 Effect.asVoid,
212 ),
213 settle: Effect.fnUntraced(function* (
214 exit: Exit.Exit<void, CommitBatchError>,
215 preserveFailure: boolean,
216 ) {
217 release();
218 if (Exit.isFailure(exit)) {
219 stream.owner.active = false;
220 yield* Deferred.failCause(
221 reply,
222 preserveFailure && ownFailure !== undefined ? ownFailure : exit.cause,
223 );
224 } else yield* Deferred.succeed(reply, result);
225 }),
226 skip: (exit) =>
227 Exit.isFailure(exit)
228 ? job.settle(exit, false)
229 : Effect.suspend(() => {
230 release();
231 return Deferred.succeed(reply, skipped);
232 }),
233 cancel: Effect.suspend(() => {
234 release();
235 const dequeued = job.queued;
236 job.queued = false;
237 return Deferred.interrupt(reply).pipe(
238 Effect.andThen(dequeued ? backlog.release(1) : Effect.void),
239 );
240 }),
241 settled: Deferred.await(reply).pipe(Effect.exit, Effect.asVoid),
242 };
243 yield* Effect.uninterruptibleMask((restore) =>
244 Effect.gen(function* () {
245 if (closed) return yield* Deferred.interrupt(reply);
246 yield* restore(backlog.take(1));
247 if (closed) {
248 yield* backlog.release(1);
249 return yield* Deferred.interrupt(reply);
250 }
251 job.queued = true;
252 pending.add(job);
253 stream.unsettled++;
254 stream.jobs.push(job);
255 yield* Queue.offer(wake, undefined);
256 }),
257 );
258 return Deferred.await(reply);
259 });
260 const rank = (stream: StreamState, now: number) => {
261 const tier =
262 stream.priority === undefined
263 ? 1
264 : isViewed(stream.priority.threadId)
265 ? 0
266 : stream.priority.delegated
267 ? 2
268 : 1;
269 const starved = now - stream.jobs[0]!.queuedAt >= STARVATION_MILLIS;
270 return [starved ? Math.min(tier, 1) : tier, stream.finishing ? 0 : 1, stream.servedAt];
271 };
272 // Viewed streams first, then main threads, then subagents; within a tier, streams finishing a
273 // control first, then the stream served longest ago.
274 const nextBatch = (now: number): Batch | undefined => {
275 const ready = Array.from(streams, (stream) =>
276 stream.jobs.length === 0 ? [] : [{ stream, rank: rank(stream, now) }],
277 )
278 .flat()
279 .sort((left, right) => {
280 for (let index = 0; index < left.rank.length; index++) {
281 const order = left.rank[index]! - right.rank[index]!;
282 if (order !== 0) return order;
283 }
284 return 0;
285 });
286 if (ready.length === 0) return undefined;
287 const units: Array<Unit> = [];
288 let bytes = 0;
289 let dequeued = 0;
290 let reason: Batch["reason"] = "ready";
291 for (const { stream } of ready) {
292 let take = 0;
293 while (take < stream.jobs.length && take < MAX_EVENTS - units.length) {
294 const next = stream.jobs[take]!.bytes;
295 if (units.length + take > 0 && bytes + next > MAX_BYTES) break;
296 bytes += next;
297 take++;
298 }
299 if (take < stream.jobs.length) reason = "limit";
300 if (take === 0) break;
301 const taken = stream.jobs.splice(0, take);
302 for (const job of taken) job.queued = false;
303 dequeued += take;
304 units.push(...coalesce(taken));
305 stream.servedAt = ++servings;
306 if (units.length >= MAX_EVENTS || bytes >= MAX_BYTES) break;
307 }
308 return { units, reason, dequeued };
309 };
310 // Commits a prefix of `units` in one transaction and returns how many it took.
311 const commitPrefix = (units: ReadonlyArray<Unit>, reason: Batch["reason"]) =>
312 Effect.uninterruptibleMask((restore) =>
313 Effect.gen(function* () {
314 const outcomes = new Map<Job, Exit.Exit<void, CommitBatchError>>();
315 let taken = 0;
316 const work = Effect.gen(function* () {
317 // A retried transaction runs this again from the first unit.
318 outcomes.clear();
319 taken = 0;
320 const startedAt = yield* Clock.monotonicTimeNanos;
321 for (const { job, superseded } of units) {
322 // Cutting only helps a write that needs none of the units still to run.
323 if (
324 taken > 0 &&
325 waitingWrites.size > 0 &&
326 (yield* Clock.monotonicTimeNanos) - startedAt >= MAX_HOLD_NANOS &&
327 Array.from(waitingWrites).some((jobs) =>
328 units
329 .slice(taken)
330 .every(
331 (unit) => !jobs.has(unit.job) && !unit.superseded.some((j) => jobs.has(j)),
332 ),
333 )
334 )
335 return;
336 taken++;
337 if (!job.stream.owner.active) {
338 yield* job.cancel;
339 for (const replaced of superseded) yield* replaced.cancel;
340 continue;
341 }
342 const outcome = yield* (units.length > 1 ? isolate(job.execute) : job.execute).pipe(
343 Effect.exit,
344 );
345 outcomes.set(job, outcome);
346 if (Exit.isFailure(outcome)) {
347 job.stream.owner.active = false;
348 if (units.length === 1) return yield* Effect.failCause(outcome.cause);
349 }
350 }
351 });
352 const exit = yield* restore(
353 commit(work).pipe(Effect.provideService(CurrentWorker, yield* Effect.fiberId)),
354 ).pipe(Effect.exit);
355 const committed = taken === 0 ? units : units.slice(0, taken);
356 const jobs = committed.flatMap((unit) => [unit.job, ...unit.superseded]);
357 yield* Effect.annotateCurrentSpan({
358 "orchestration_v2.work_item_count": committed.length,
359 "orchestration_v2.coalesced_work_item_count": jobs.length - committed.length,
360 "orchestration_v2.deferred_work_item_count": units.length - committed.length,
361 "orchestration_v2.consumer_count": new Set(jobs.map((job) => job.stream)).size,
362 "orchestration_v2.raw_json_bytes": jobs.reduce((bytes, job) => bytes + job.bytes, 0),
363 "orchestration_v2.batch_flush_reason": reason,
364 "orchestration_v2.backlog_batching": true,
365 "orchestration_v2.batch_wait_ms":
366 (yield* Clock.currentTimeMillis) - Math.min(...jobs.map((job) => job.queuedAt)),
367 });
368 for (const { job, superseded } of committed) {
369 const outcome = outcomes.get(job) ?? Exit.void;
370 const final = Exit.isSuccess(exit) ? outcome : exit;
371 yield* job.settle(
372 final,
373 Exit.isSuccess(exit) ||
374 (Exit.isFailure(exit) &&
375 Exit.isFailure(outcome) &&
376 Cause.squash(exit.cause) === Cause.squash(outcome.cause)),
377 );
378 for (const replaced of superseded) yield* replaced.skip(final);
379 }
380 return committed.length;
381 }),
382 ).pipe(Effect.withSpan("orchestrationV2.ProviderCommitBatch.flush"));
383 if (enabled) {
384 yield* Effect.forever(
385 Effect.gen(function* () {
386 const batch = nextBatch(yield* Clock.currentTimeMillis);
387 if (batch === undefined) return yield* Queue.take(wake);
388 yield* backlog.release(batch.dequeued);
389 let units = batch.units;
390 while (units.length > 0) units = units.slice(yield* commitPrefix(units, batch.reason));
391 }),
392 ).pipe(Effect.ensuring(shutdown), Effect.forkScoped);
393 }
394 /**
395 * Runs `effect` after queued snapshots for `threadIds` commit; omitted, after every queued
396 * snapshot. Other threads' snapshots never delay it.
397 */
398 const barrier = Effect.fnUntraced(function* <A, E, R>(
399 effect: Effect.Effect<A, E, R>,
400 threadIds?: ReadonlyArray<string>,
401 ) {
402 if (closed) return yield* Effect.interrupt;
403 if (!enabled || (yield* CurrentWorker) === (yield* Effect.fiberId)) return yield* effect;
404 const jobs: ReadonlySet<Job> = new Set(
405 Array.from(pending).filter(
406 (job) => threadIds === undefined || threadIds.includes(job.threadId),
407 ),
408 );
409 return yield* Effect.uninterruptibleMask((restore) => {
410 waitingWrites.add(jobs);
411 return restore(
412 Effect.gen(function* () {
413 for (const job of jobs) yield* job.settled;
414 if (closed) return yield* Effect.interrupt;
415 return yield* effect;
416 }),
417 ).pipe(
418 Effect.ensuring(
419 Effect.sync(() => {
420 waitingWrites.delete(jobs);
421 }),
422 ),
423 );
424 });
425 });
426 const consume = Effect.fnUntraced(function* <A extends { readonly type: string }, E, R, E2, R2>(
427 source: Stream.Stream<A, E, R>,
428 process: (event: A) => Effect.Effect<void, E2, R2>,
429 after: Effect.Effect<boolean, E2, R2>,
430 canBatch: Effect.Effect<boolean, never, R2> = Effect.succeed(true),
431 priority?: StreamPriority,
432 ) {
433 if (!enabled)
434 return yield* source.pipe(
435 Stream.mapEffect((event) => process(event).pipe(Effect.andThen(after))),
436 Stream.takeUntil(Boolean),
437 Stream.runDrain,
438 );
439 const stream: StreamState = {
440 owner: { active: true },
441 priority,
442 jobs: [],
443 unsettled: 0,
444 servedAt: 0,
445 finishing: false,
446 };
447 streams.add(stream);
448 const signals = source.pipe(
449 Stream.map((event) => ({ _tag: "Event" as const, event })),
450 Stream.catchCause((cause) => Stream.succeed({ _tag: "Failure" as const, cause })),
451 Stream.concat(Stream.succeed({ _tag: "End" as const })),
452 );
453 let resume: Effect.Effect<void> = Effect.void;
454 // Replies run in order, so EOF, failures and controls follow this stream's earlier snapshots
455 // without waiting for other streams' work.
456 yield* signals.pipe(
457 Stream.mapEffect((signal) =>
458 Effect.gen(function* () {
459 yield* resume;
460 const processed = yield* Deferred.make<void>();
461 let reply: Effect.Effect<boolean, E | E2 | CommitBatchError, R2>;
462 let check = false;
463 const snapshot =
464 signal._tag === "Event" && isSnapshot(signal.event) && (yield* canBatch)
465 ? signal.event
466 : undefined;
467 if (snapshot !== undefined) {
468 const bytes = Buffer.byteLength(yield* encodeQueue(snapshot));
469 reply = yield* enqueue(
470 process(snapshot).pipe(Effect.as(false)),
471 stream,
472 snapshotEntity(snapshot),
473 bytes,
474 false,
475 );
476 } else {
477 if (stream.unsettled > 0) stream.finishing = true;
478 if (signal._tag === "End") reply = Effect.succeed(true);
479 else if (signal._tag === "Failure") reply = Effect.failCause(signal.cause);
480 else {
481 const event = signal.event;
482 reply = Effect.sync(() => {
483 stream.finishing = false;
484 }).pipe(Effect.andThen(process(event)), Effect.as(false));
485 check = true;
486 resume = Deferred.await(processed);
487 }
488 }
489 return { reply, processed, check };
490 }),
491 ),
492 Stream.buffer({ capacity: MAX_EVENTS }),
493 Stream.mapEffect(({ reply, processed, check }) =>
494 reply.pipe(
495 Effect.flatMap((end) =>
496 end ? Effect.succeed(true) : check ? after : Effect.succeed(false),
497 ),
498 Effect.tap((stop) =>
499 Effect.sync(() => {
500 if (stop) stream.owner.active = false;
501 }),
502 ),
503 Effect.ensuring(Deferred.succeed(processed, undefined)),
504 ),
505 ),
506 Stream.takeUntil(Boolean),
507 Stream.runDrain,
508 Effect.ensuring(
509 Effect.gen(function* () {
510 stream.owner.active = false;
511 streams.delete(stream);
512 for (const job of stream.jobs.splice(0)) yield* job.cancel;
513 }),
514 ),
515 );
516 });
517 return { barrier, consume };
518});