Open History to see the last commit
1import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
2import * as Cause from "effect/Cause";
3import * as Clock from "effect/Clock";
4import * as Config from "effect/Config";
5import * as Effect from "effect/Effect";
6import * as Context from "effect/Context";
7import * as Deferred from "effect/Deferred";
8import * as Exit from "effect/Exit";
9import * as Queue from "effect/Queue";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12
13const MAX_EVENTS = 64;
14const MAX_BYTES = 1024 * 1024;
15const encodeQueue = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
16
17export const enabled = Config.Boolean("T3CODE_PROVIDER_COMMIT_BATCHING").pipe(
18 Config.withDefault(true),
19 Effect.orDie,
20);
21
22type Event = ProviderAdapter.ProviderAdapterV2Event;
23const isSnapshot = (event: Event) =>
24 event.type === "node.updated" ||
25 event.type === "message.updated" ||
26 event.type === "turn_item.updated" ||
27 event.type === "plan.updated";
28
29export class CommitBatchError extends Schema.TaggedError<CommitBatchError>()("CommitBatchError", {
30 cause: Schema.Defect(),
31}) {}
32export const isCommitBatchError = Schema.is(CommitBatchError);
33
34interface Job {
35 readonly owner: { active: boolean };
36 readonly queuedAt: number;
37 readonly snapshot: boolean;
38 readonly bytes: number;
39 readonly execute: Effect.Effect<void, CommitBatchError>;
40 readonly settle: (
41 exit: Exit.Exit<void, CommitBatchError>,
42 preserveFailure: boolean,
43 ) => Effect.Effect<void>;
44 readonly cancel: Effect.Effect<void>;
45}
46interface Batch {
47 readonly events: ReadonlyArray<Job>;
48 readonly bytes: number;
49 readonly reason: "ready" | "limit" | "control";
50}
51
52function collect(queue: Queue.Queue<Job>) {
53 return Stream.fromEffectRepeat(Queue.takeBetween(queue, 1, MAX_EVENTS)).pipe(
54 Stream.flatMap((ready) => {
55 const batches: Array<Batch> = [];
56 let events: Array<Job> = [];
57 let bytes = 0;
58 const flush = (reason: Batch["reason"]) => {
59 if (events.length > 0) batches.push({ events, bytes, reason });
60 events = [];
61 bytes = 0;
62 };
63 for (const job of ready) {
64 if (!job.snapshot) {
65 flush("control");
66 batches.push({ events: [job], bytes: 0, reason: "control" });
67 } else {
68 if (events.length > 0 && bytes + job.bytes > MAX_BYTES) flush("limit");
69 events.push(job);
70 bytes += job.bytes;
71 if (events.length >= MAX_EVENTS || bytes >= MAX_BYTES) flush("limit");
72 }
73 }
74 flush("ready");
75 return Stream.fromArray(batches);
76 }),
77 );
78}
79
80const CurrentWorker = Context.Reference<number | undefined>(
81 "t3/ProviderCommitBatch/CurrentWorker",
82 {
83 defaultValue: () => undefined,
84 },
85);
86
87export const make = Effect.fn("ProviderCommitBatch.make")(function* (
88 commit: (work: Effect.Effect<void, CommitBatchError>) => Effect.Effect<void, CommitBatchError>,
89 enabled: boolean,
90 isolate: (
91 work: Effect.Effect<void, CommitBatchError>,
92 ) => Effect.Effect<void, CommitBatchError> = (work) => work,
93) {
94 const queue = yield* Queue.bounded<Job>(MAX_EVENTS);
95 const pending = new Set<Job>();
96 let closed = false;
97 const shutdown = Effect.gen(function* () {
98 closed = true;
99 yield* Queue.shutdown(queue);
100 for (const job of pending) yield* job.cancel;
101 });
102 yield* Effect.addFinalizer(() => shutdown);
103 // These helpers run once per raw event; the shared transaction owns the tracing span.
104 const enqueue = Effect.fnUntraced(function* <A, E, R>(
105 effect: Effect.Effect<A, E, R>,
106 token: { active: boolean },
107 snapshot: boolean,
108 bytes: number,
109 ) {
110 const caller = yield* Effect.context<R>();
111 const reply = yield* Deferred.make<A, E | CommitBatchError>();
112 let ownFailure: Cause.Cause<E> | undefined;
113 let result: A;
114 const job: Job = {
115 owner: token,
116 queuedAt: yield* Clock.currentTimeMillis,
117 snapshot,
118 bytes,
119 execute: effect.pipe(
120 Effect.tapCause((cause) =>
121 Effect.sync(() => {
122 ownFailure = cause;
123 }),
124 ),
125 Effect.mapError((cause) => new CommitBatchError({ cause })),
126 Effect.provideContext(caller),
127 Effect.tap((value) =>
128 Effect.sync(() => {
129 result = value;
130 }),
131 ),
132 Effect.asVoid,
133 ),
134 settle: Effect.fnUntraced(function* (
135 exit: Exit.Exit<void, CommitBatchError>,
136 preserveFailure: boolean,
137 ) {
138 pending.delete(job);
139 if (Exit.isFailure(exit)) {
140 token.active = false;
141 yield* Deferred.failCause(
142 reply,
143 preserveFailure && ownFailure !== undefined ? ownFailure : exit.cause,
144 );
145 } else yield* Deferred.succeed(reply, result);
146 }),
147 cancel: Effect.gen(function* () {
148 pending.delete(job);
149 yield* Deferred.interrupt(reply);
150 }),
151 };
152 yield* Effect.uninterruptibleMask((restore) =>
153 Effect.gen(function* () {
154 pending.add(job);
155 const accepted = yield* restore(Queue.offer(queue, job)).pipe(
156 Effect.onError(() => job.cancel),
157 );
158 if (!accepted) yield* job.cancel;
159 }),
160 );
161 return Deferred.await(reply);
162 });
163 if (enabled) {
164 yield* collect(queue).pipe(
165 Stream.runForEach((batch) =>
166 Effect.uninterruptibleMask((restore) =>
167 Effect.gen(function* () {
168 const jobs = batch.events.filter((job) => job.owner.active);
169 for (const job of batch.events) if (!job.owner.active) yield* job.cancel;
170 if (jobs.length === 0) return;
171 yield* Effect.annotateCurrentSpan({
172 "orchestration_v2.work_item_count": jobs.length,
173 "orchestration_v2.consumer_count": new Set(jobs.map((job) => job.owner)).size,
174 "orchestration_v2.raw_json_bytes": batch.bytes,
175 "orchestration_v2.batch_flush_reason": batch.reason,
176 "orchestration_v2.backlog_batching": true,
177 "orchestration_v2.batch_wait_ms":
178 (yield* Clock.currentTimeMillis) - Math.min(...jobs.map((job) => job.queuedAt)),
179 });
180 const outcomes = new Map<Job, Exit.Exit<void, CommitBatchError>>();
181 const work = Effect.forEach(
182 jobs,
183 (job) =>
184 Effect.gen(function* () {
185 if (!job.owner.active) return yield* job.cancel;
186 const outcome = yield* (
187 jobs.length > 1 && job.bytes > 0 ? isolate(job.execute) : job.execute
188 ).pipe(Effect.exit);
189 outcomes.set(job, outcome);
190 if (Exit.isFailure(outcome)) {
191 job.owner.active = false;
192 if (jobs.length === 1) return yield* Effect.failCause(outcome.cause);
193 }
194 }),
195 { discard: true },
196 );
197 const exit = yield* restore(
198 (jobs.every((job) => job.bytes === 0) ? work : commit(work)).pipe(
199 Effect.provideService(CurrentWorker, yield* Effect.fiberId),
200 ),
201 ).pipe(Effect.exit);
202 for (const job of jobs) {
203 const outcome = outcomes.get(job) ?? Exit.void;
204 yield* job.settle(
205 Exit.isSuccess(exit) ? outcome : exit,
206 Exit.isSuccess(exit) ||
207 (Exit.isFailure(exit) &&
208 Exit.isFailure(outcome) &&
209 Cause.squash(exit.cause) === Cause.squash(outcome.cause)),
210 );
211 }
212 }),
213 ).pipe(Effect.withSpan("orchestrationV2.ProviderCommitBatch.flush")),
214 ),
215 Effect.ensuring(shutdown),
216 Effect.forkScoped,
217 );
218 }
219 const barrier = Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
220 if (closed) return yield* Effect.interrupt;
221 if (!enabled || pending.size === 0 || (yield* CurrentWorker) === (yield* Effect.fiberId))
222 return yield* effect;
223 const token = { active: true };
224 return yield* enqueue(Effect.exit(effect), token, false, 0).pipe(
225 Effect.flatten,
226 Effect.orDie,
227 Effect.flatten,
228 Effect.ensuring(
229 Effect.sync(() => {
230 token.active = false;
231 }),
232 ),
233 );
234 });
235 const consume = Effect.fnUntraced(function* <E, R, E2, R2>(
236 source: Stream.Stream<Event, E, R>,
237 process: (event: Event) => Effect.Effect<void, E2, R2>,
238 after: Effect.Effect<boolean, E2, R2>,
239 canBatch: Effect.Effect<boolean, never, R2> = Effect.succeed(true),
240 ) {
241 if (!enabled)
242 return yield* source.pipe(
243 Stream.mapEffect((event) => process(event).pipe(Effect.andThen(after))),
244 Stream.takeUntil(Boolean),
245 Stream.runDrain,
246 );
247 const token = { active: true };
248 const signals = source.pipe(
249 Stream.map((event) => ({ _tag: "Event" as const, event })),
250 Stream.catchCause((cause) => Stream.succeed({ _tag: "Failure" as const, cause })),
251 Stream.concat(Stream.succeed({ _tag: "End" as const })),
252 );
253 let resume: Effect.Effect<void> = Effect.void;
254 yield* signals.pipe(
255 Stream.mapEffect((signal) =>
256 Effect.gen(function* () {
257 yield* resume;
258 const processed = yield* Deferred.make<void>();
259 const event = signal._tag === "Event" ? signal.event : undefined;
260 // EOF only acknowledges prior work; it can share a commit with other consumers.
261 const snapshot =
262 signal._tag === "End" ||
263 (event !== undefined && isSnapshot(event) && (yield* canBatch));
264 const bytes =
265 snapshot && event !== undefined ? Buffer.byteLength(yield* encodeQueue(event)) : 0;
266 const work: Effect.Effect<boolean, E | E2, R2> =
267 signal._tag === "Failure"
268 ? Effect.failCause(signal.cause)
269 : event === undefined
270 ? Effect.succeed(true)
271 : process(event).pipe(Effect.as(false));
272 const reply = snapshot
273 ? yield* enqueue(work, token, true, bytes)
274 : (yield* enqueue(Effect.void, token, false, 0)).pipe(Effect.andThen(work));
275 if (!snapshot) resume = Deferred.await(processed);
276 return { reply, processed, check: !snapshot };
277 }),
278 ),
279 Stream.buffer({ capacity: MAX_EVENTS }),
280 Stream.mapEffect(({ reply, processed, check }) =>
281 reply.pipe(
282 Effect.flatMap((end) =>
283 end ? Effect.succeed(true) : check ? after : Effect.succeed(false),
284 ),
285 Effect.tap((stop) =>
286 Effect.sync(() => {
287 if (stop) token.active = false;
288 }),
289 ),
290 Effect.ensuring(Deferred.succeed(processed, undefined)),
291 ),
292 ),
293 Stream.takeUntil(Boolean),
294 Stream.runDrain,
295 Effect.ensuring(
296 Effect.sync(() => {
297 token.active = false;
298 }),
299 ),
300 );
301 });
302 return { barrier, consume };
303});