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

threadHistoryPaging.ts

500 lines16.8 KB

1import type {
2 OrchestrationV2ProjectedTurnItem,
3 OrchestrationV2ThreadProjection,
4 OrchestrationV2TurnItem,
5 ThreadId,
6 TurnItemId,
7} from "@t3tools/contracts";
8​
9/**
10 * Centralized page budgets for progressive client hydration. Sized for relay
11 * cold opens: dozens of rows and about 1 MiB of encoded JSON per page.
12 */
13export const THREAD_HISTORY_PAGE_POLICY = {
14 maxItems: 75,
15 maxEncodedBytes: 1_048_576,
16} as const;
17​
18/** Extra rows let the projection query retain an inclusive cursor and prove another page exists. */
19export const THREAD_HISTORY_SNAPSHOT_ROW_LIMIT = THREAD_HISTORY_PAGE_POLICY.maxItems + 2;
20​
21/** Reject absurd cursors before base64 work or JSON parse. */
22export const THREAD_HISTORY_CURSOR_MAX_LENGTH = 4_096;
23​
24export type ThreadHistoryPagePolicy = {
25 readonly maxItems: number;
26 readonly maxEncodedBytes: number;
27};
28​
29export type ThreadHistoryCursorPayload = {
30 readonly v: 1;
31 readonly seq: number;
32 readonly st: string;
33 readonly si: string;
34 readonly p: number;
35};
36​
37export type SelectTimelinePageResult = {
38 readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
39 readonly nextCursor: string | null;
40 readonly hasMoreHistory: boolean;
41};
42​
43export type BoundedProjectionResult = {
44 readonly projection: OrchestrationV2ThreadProjection;
45 readonly historyCursor: string | null;
46 readonly hasMoreHistory: boolean;
47 /** Max ordinal across the authoritative full projection's local turnItems. */
48 readonly latestLocalTurnOrdinal: number | null;
49 readonly payloadBudgetExceeded: boolean;
50};
51​
52export class InvalidThreadHistoryCursorError extends Error {
53 readonly _tag = "InvalidThreadHistoryCursorError";
54 constructor(message = "Invalid thread history cursor.") {
55 super(message);
56 this.name = "InvalidThreadHistoryCursorError";
57 }
59​
60function bytesOfJson(value: unknown): number {
61 return Buffer.byteLength(JSON.stringify(value), "utf8");
63​
64/** Ordinary history-page cost: one projected row (item is nested once). */
65export function projectedRowEncodedBytes(row: OrchestrationV2ProjectedTurnItem): number {
66 return bytesOfJson(row);
68​
69/**
70 * Bounded-snapshot cost: local rows also land in `projection.turnItems`, so
71 * charge the nested item a second time. Inherited rows only appear in the
72 * visible list.
73 */
74export function projectedRowBoundedSnapshotEncodedBytes(
75 row: OrchestrationV2ProjectedTurnItem,
76 threadId: ThreadId | string,
77): number {
78 const rowBytes = projectedRowEncodedBytes(row);
79 if (row.visibility === "local" || String(row.sourceThreadId) === String(threadId)) {
80 return rowBytes + bytesOfJson(row.item);
81 }
82 return rowBytes;
84​
85function renumberPositions(
86 items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
87): OrchestrationV2ProjectedTurnItem[] {
88 return items.map((row, position) => (row.position === position ? row : { ...row, position }));
90​
91function encodeCursorPayload(payload: ThreadHistoryCursorPayload): string {
92 return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
94​
95export function encodeThreadHistoryCursor(input: {
96 readonly snapshotSequence: number;
97 readonly sourceThreadId: ThreadId | string;
98 readonly sourceItemId: TurnItemId | string;
99 readonly position: number;
100}): string {
101 return encodeCursorPayload({
102 v: 1,
103 seq: input.snapshotSequence,
104 st: String(input.sourceThreadId),
105 si: String(input.sourceItemId),
106 p: input.position,
107 });
109​
110export function decodeThreadHistoryCursor(cursor: string): ThreadHistoryCursorPayload {
111 if (cursor.length === 0 || cursor.length > THREAD_HISTORY_CURSOR_MAX_LENGTH) {
112 throw new InvalidThreadHistoryCursorError();
113 }
114 let parsed: unknown;
115 try {
116 const json = Buffer.from(cursor, "base64url").toString("utf8");
117 parsed = JSON.parse(json) as unknown;
118 } catch {
119 throw new InvalidThreadHistoryCursorError();
120 }
121 if (
122 typeof parsed !== "object" ||
123 parsed === null ||
124 !("v" in parsed) ||
125 (parsed as { v: unknown }).v !== 1 ||
126 !("seq" in parsed) ||
127 typeof (parsed as { seq: unknown }).seq !== "number" ||
128 !Number.isInteger((parsed as { seq: number }).seq) ||
129 (parsed as { seq: number }).seq < 0 ||
130 !("st" in parsed) ||
131 typeof (parsed as { st: unknown }).st !== "string" ||
132 (parsed as { st: string }).st.length === 0 ||
133 !("si" in parsed) ||
134 typeof (parsed as { si: unknown }).si !== "string" ||
135 (parsed as { si: string }).si.length === 0 ||
136 !("p" in parsed) ||
137 typeof (parsed as { p: unknown }).p !== "number" ||
138 !Number.isInteger((parsed as { p: number }).p) ||
139 (parsed as { p: number }).p < 0
140 ) {
141 throw new InvalidThreadHistoryCursorError();
142 }
143 return parsed as ThreadHistoryCursorPayload;
145​
146/**
147 * Walk a chronological timeline from `startIndex` backward, collecting rows
148 * under count and byte budgets. Always includes at least one row when available
149 * so a single oversized item cannot deadlock pagination.
150 */
151function selectOlderTimelinePage(input: {
152 readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
153 readonly exclusiveEndIndex: number;
154 readonly snapshotSequence: number;
155 readonly policy?: ThreadHistoryPagePolicy | undefined;
156 readonly rowEncodedBytes?: ((row: OrchestrationV2ProjectedTurnItem) => number) | undefined;
157}): SelectTimelinePageResult {
158 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
159 const rowCost = input.rowEncodedBytes ?? projectedRowEncodedBytes;
160 const end = Math.min(Math.max(input.exclusiveEndIndex, 0), input.items.length);
161 if (end <= 0) {
162 return { items: [], nextCursor: null, hasMoreHistory: false };
163 }
164​
165 const selected: OrchestrationV2ProjectedTurnItem[] = [];
166 let encodedBytes = 0;
167 for (let index = end - 1; index >= 0; index -= 1) {
168 const row = input.items[index]!;
169 const rowBytes = rowCost(row);
170 if (
171 selected.length > 0 &&
172 (selected.length >= policy.maxItems || encodedBytes + rowBytes > policy.maxEncodedBytes)
173 ) {
174 break;
175 }
176 selected.push(row);
177 encodedBytes += rowBytes;
178 }
179 selected.reverse();
180​
181 const oldest = selected[0];
182 const oldestIndex = oldest
183 ? input.items.findIndex(
184 (row) =>
185 row.sourceThreadId === oldest.sourceThreadId && row.sourceItemId === oldest.sourceItemId,
186 )
187 : -1;
188 const hasMoreHistory = oldestIndex > 0;
189 const nextCursor =
190 hasMoreHistory && oldest
191 ? encodeThreadHistoryCursor({
192 snapshotSequence: input.snapshotSequence,
193 sourceThreadId: oldest.sourceThreadId,
194 sourceItemId: oldest.sourceItemId,
195 position: oldest.position,
196 })
197 : null;
198​
199 return {
200 items: renumberPositions(selected),
201 nextCursor,
202 hasMoreHistory,
203 };
205​
206export function selectRecentTimelineWindow(input: {
207 readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
208 readonly snapshotSequence: number;
209 readonly policy?: ThreadHistoryPagePolicy | undefined;
210 readonly rowEncodedBytes?: ((row: OrchestrationV2ProjectedTurnItem) => number) | undefined;
211}): SelectTimelinePageResult {
212 return selectOlderTimelinePage({
213 items: input.items,
214 exclusiveEndIndex: input.items.length,
215 snapshotSequence: input.snapshotSequence,
216 ...(input.policy === undefined ? {} : { policy: input.policy }),
217 ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }),
218 });
220​
221function findCursorIndex(
222 items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
223 cursor: ThreadHistoryCursorPayload,
224): number {
225 const byIdentity = items.findIndex(
226 (row) => String(row.sourceThreadId) === cursor.st && String(row.sourceItemId) === cursor.si,
227 );
228 if (byIdentity !== -1) {
229 return byIdentity;
230 }
231 // Identity miss can happen if the cursor item was deleted; fall back to the
232 // recorded position clamped into the current timeline so pagination can
233 // continue from a stable-ish anchor rather than failing hard. Clamp to
234 // items.length (exclusive end) so a shrunken timeline never 400s forever.
235 // decodeThreadHistoryCursor already guarantees p is a non-negative integer.
236 return Math.min(cursor.p, items.length);
238​
239export function selectHistoryPageFromCursor(input: {
240 readonly items: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
241 readonly cursor: string;
242 readonly snapshotSequence: number;
243 readonly policy?: ThreadHistoryPagePolicy | undefined;
244}): SelectTimelinePageResult {
245 const decoded = decodeThreadHistoryCursor(input.cursor);
246 const anchorIndex = findCursorIndex(input.items, decoded);
247 return selectOlderTimelinePage({
248 items: input.items,
249 exclusiveEndIndex: anchorIndex,
250 snapshotSequence: input.snapshotSequence,
251 ...(input.policy === undefined ? {} : { policy: input.policy }),
252 });
254​
255function isLocalProjectedRow(
256 projection: OrchestrationV2ThreadProjection,
257 row: OrchestrationV2ProjectedTurnItem,
258): boolean {
259 return row.visibility === "local" || String(row.sourceThreadId) === String(projection.thread.id);
261​
262/**
263 * Visibility for superseded `run_interrupt_result` rows depends on a matching
264 * `run_interrupt_request` in `turnItems`. Keep every small request item from the
265 * full projection even when it sits outside the recent visible window, so a
266 * later history page that introduces the matching result still has the request
267 * available for live attempt/run reducers.
268 */
269function retainedInterruptRequestTurnItems(
270 projection: OrchestrationV2ThreadProjection,
271 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
272): OrchestrationV2TurnItem[] {
273 const visibleLocalIds = new Set<string>();
274 for (const row of visible) {
275 if (isLocalProjectedRow(projection, row)) {
276 visibleLocalIds.add(String(row.sourceItemId));
277 }
278 }
279​
280 const retained: OrchestrationV2TurnItem[] = [];
281 for (const item of projection.turnItems) {
282 if (item.type !== "run_interrupt_request") {
283 continue;
284 }
285 // Already covered by local turnItems for the visible window.
286 if (visibleLocalIds.has(String(item.id))) {
287 continue;
288 }
289 retained.push(item);
290 }
291 return retained;
293​
294function localTurnItemsForVisibleWindow(
295 projection: OrchestrationV2ThreadProjection,
296 visible: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
297): OrchestrationV2TurnItem[] {
298 const localIds = new Set<string>();
299 for (const row of visible) {
300 if (isLocalProjectedRow(projection, row)) {
301 localIds.add(String(row.sourceItemId));
302 }
303 }
304 if (localIds.size === 0) {
305 return [];
306 }
307 return projection.turnItems.filter((item) => localIds.has(String(item.id)));
309​
310function messagesForBoundedProjection(
311 projection: OrchestrationV2ThreadProjection,
312 turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
313): OrchestrationV2ThreadProjection["messages"] {
314 const retainedMessageIds = new Set<string>();
315 for (const item of turnItems) {
316 if ("messageId" in item) {
317 retainedMessageIds.add(String(item.messageId));
318 }
319 }
320​
321 const latestRun = projection.runs.reduce<(typeof projection.runs)[number] | null>(
322 (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest),
323 null,
324 );
325 const retainedRunIds = new Set<string>();
326 for (const run of projection.runs) {
327 if (
328 run.id === latestRun?.id ||
329 run.status === "preparing" ||
330 run.status === "starting" ||
331 run.status === "running" ||
332 run.status === "waiting" ||
333 run.status === "queued"
334 ) {
335 retainedRunIds.add(String(run.id));
336 retainedMessageIds.add(String(run.userMessageId));
337 }
338 }
339​
340 return projection.messages.filter(
341 (message) =>
342 retainedMessageIds.has(String(message.id)) ||
343 (message.runId !== null && retainedRunIds.has(String(message.runId))) ||
344 message.delegatedCompletion !== undefined,
345 );
347​
348/**
349 * Max local turn ordinal over the authoritative full projection turnItems.
350 * Used as a cheap partial-timeline watermark so old missing turn-item updates
351 * cannot append newest when the bounded window has no local rows.
352 */
353export function computeLatestLocalTurnOrdinal(
354 turnItems: ReadonlyArray<{ readonly ordinal: number }>,
355): number | null {
356 let latest: number | null = null;
357 for (const item of turnItems) {
358 if (latest === null || item.ordinal > latest) {
359 latest = item.ordinal;
360 }
361 }
362 return latest;
364​
365/**
366 * Encoded timeline contribution for a bounded snapshot: visible rows plus the
367 * duplicated local turnItems and any retained interrupt-request dependencies.
368 */
369export function boundedTimelineEncodedBytes(input: {
370 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
371 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
372}): number {
373 let total = 0;
374 for (const row of input.visibleTurnItems) {
375 total += projectedRowEncodedBytes(row);
376 }
377 for (const item of input.turnItems) {
378 total += bytesOfJson(item);
379 }
380 return total;
382​
383/**
384 * Builds a partial thread projection with full control-plane arrays and a
385 * bounded recent timeline window plus matching local turnItems.
386 */
387export function buildBoundedThreadProjection(input: {
388 readonly projection: OrchestrationV2ThreadProjection;
389 readonly snapshotSequence: number;
390 readonly policy?: ThreadHistoryPagePolicy | undefined;
391}): BoundedProjectionResult {
392 const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY;
393 const threadId = input.projection.thread.id;
394 const controlProjection = {
395 ...input.projection,
396 plans: input.projection.plans.filter((plan) => plan.status === "active"),
397 contextHandoffs: input.projection.contextHandoffs.filter(
398 (handoff) => handoff.status === "pending" || handoff.status === "ready",
399 ),
400 };
401 const latestLocalTurnOrdinal = computeLatestLocalTurnOrdinal(input.projection.turnItems);
402​
403 // Reserve bytes for small interrupt-request dependencies that may sit outside
404 // the recent window but are required for visibility of results inside it.
405 const dependencyReserve = (() => {
406 // Upper bound: all request items in the full projection. Window selection
407 // uses this reserve so the final contribution stays under the cap.
408 let reserve = 0;
409 for (const item of controlProjection.turnItems) {
410 if (item.type === "run_interrupt_request") {
411 reserve += bytesOfJson(item);
412 }
413 }
414 return reserve;
415 })();
416 const controlBytes = bytesOfJson({
417 ...controlProjection,
418 messages: [],
419 turnItems: [],
420 visibleTurnItems: [],
421 });
422 const windowBudget = Math.max(
423 0,
424 policy.maxEncodedBytes - dependencyReserve - controlBytes - 1_024,
425 );
426 const windowPolicy: ThreadHistoryPagePolicy = {
427 maxItems: policy.maxItems,
428 // Zero still admits the first row via the at-least-one rule.
429 maxEncodedBytes: windowBudget,
430 };
431​
432 const window = selectRecentTimelineWindow({
433 items: controlProjection.visibleTurnItems,
434 snapshotSequence: input.snapshotSequence,
435 policy: windowPolicy,
436 rowEncodedBytes: (row) => projectedRowBoundedSnapshotEncodedBytes(row, threadId),
437 });
438 const visibleTurnItems = renumberPositions(window.items);
439 const windowTurnItems = localTurnItemsForVisibleWindow(controlProjection, visibleTurnItems);
440 const dependencyTurnItems = retainedInterruptRequestTurnItems(
441 controlProjection,
442 visibleTurnItems,
443 );
444 const turnItemById = new Map<string, OrchestrationV2TurnItem>();
445 for (const item of windowTurnItems) {
446 turnItemById.set(String(item.id), item);
447 }
448 for (const item of dependencyTurnItems) {
449 turnItemById.set(String(item.id), item);
450 }
451 const turnItems = [...turnItemById.values()];
452​
453 const visiblePlanIds = new Set(
454 turnItems.flatMap((item) =>
455 item.type === "proposed_plan" || item.type === "todo_list" ? [String(item.planId)] : [],
456 ),
457 );
458 const visibleHandoffIds = new Set(
459 turnItems.flatMap((item) => (item.type === "handoff" ? [String(item.contextHandoffId)] : [])),
460 );
461 const plans = input.projection.plans
462 .filter((plan) => plan.status === "active" || visiblePlanIds.has(String(plan.id)))
463 .map((plan) =>
464 plan.status === "active"
465 ? plan
466 : plan.kind === "proposed_plan"
467 ? { ...plan, markdown: "", detailInTurnItem: true as const }
468 : { ...plan, explanation: undefined, detailInTurnItem: true as const },
469 );
470 const contextHandoffs = input.projection.contextHandoffs
471 .filter(
472 (handoff) =>
473 handoff.status === "pending" ||
474 handoff.status === "ready" ||
475 visibleHandoffIds.has(String(handoff.id)),
476 )
477 .map((handoff) =>
478 handoff.status === "pending" || handoff.status === "ready"
479 ? handoff
480 : { ...handoff, summaryText: "", detailInTurnItem: true as const },
481 );
482​
483 const projection = {
484 ...controlProjection,
485 plans,
486 contextHandoffs,
487 messages: messagesForBoundedProjection(controlProjection, turnItems),
488 turnItems,
489 visibleTurnItems,
490 };
491 return {
492 projection,
493 historyCursor: window.nextCursor,
494 hasMoreHistory: window.hasMoreHistory,
495 // Always from the full projection so inherited-only windows still carry a
496 // watermark for partial live reducers.
497 latestLocalTurnOrdinal,
498 payloadBudgetExceeded: bytesOfJson(projection) > policy.maxEncodedBytes,
499 };