Open History to see the last commit
1import type {
2 OrchestrationV2ThreadProjection,
3 OrchestrationV2ThreadStreamItem,
4} from "@t3tools/contracts";
5
6import {
7 omitCheckpointItemFiles,
8 omitLocalVisibleTurnItems,
9} from "@t3tools/shared/orchestrationV2BoundedSnapshot";
10
11import {
12 buildBoundedThreadProjection,
13 type BoundedProjectionResult,
14} from "./threadHistoryPaging.ts";
15import { projectThreadProjectionForWire } from "./WireProjection.ts";
16
17export const THREAD_RESUME_MAX_REPLAY_EVENTS = 128;
18
19export const THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES = 1_048_576;
20
21/**
22 * Keep the original preflight budget: decoded objects and temporary strings
23 * cost more than their stored JSON, even if wire projection shrinks them later.
24 */
25export const THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES = 1_048_576;
26
27export function isThreadReplayRawPayloadSafe(rawPayloadBytes: number): boolean {
28 return rawPayloadBytes <= THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES;
29}
30
31export function threadReplayEncodedBytes(items: ReadonlyArray<unknown>): number {
32 let total = 0;
33 for (const item of items) {
34 const encoded = JSON.stringify(item);
35 total += Buffer.byteLength(encoded ?? "", "utf8");
36 }
37 return total;
38}
39
40type ThreadSnapshotStreamItem = Extract<
41 OrchestrationV2ThreadStreamItem,
42 { readonly kind: "snapshot" }
43>;
44
45export function boundedSnapshotResponseFields(input: {
46 readonly bounded: BoundedProjectionResult;
47 readonly compactTurnItems: boolean;
48 readonly compactCheckpointItems?: boolean;
49}) {
50 const { bounded } = input;
51 const compactProjection = input.compactTurnItems
52 ? omitLocalVisibleTurnItems(bounded.projection)
53 : null;
54 // After the turn-item compaction, which matches rows to items by identity.
55 const compactCheckpoints =
56 input.compactCheckpointItems === true
57 ? omitCheckpointItemFiles(compactProjection ?? bounded.projection)
58 : null;
59 return {
60 projection: compactCheckpoints?.projection ?? compactProjection ?? bounded.projection,
61 historyCursor: bounded.historyCursor,
62 hasMoreHistory: bounded.hasMoreHistory,
63 latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal,
64 payloadBudgetExceeded: bounded.payloadBudgetExceeded,
65 ...(compactProjection === null ? {} : { turnItemsOmitLocalVisible: true as const }),
66 ...(compactCheckpoints === null
67 ? {}
68 : { checkpointFilesOmittedItemIds: compactCheckpoints.itemIds }),
69 };
70}
71
72export function buildBoundedThreadStreamSnapshot(input: {
73 readonly snapshotSequence: number;
74 readonly projection: OrchestrationV2ThreadProjection;
75 readonly compactTurnItems?: boolean;
76 readonly compactCheckpointItems?: boolean;
77}): ThreadSnapshotStreamItem {
78 const bounded = buildBoundedThreadProjection({
79 snapshotSequence: input.snapshotSequence,
80 projection: projectThreadProjectionForWire(input.projection),
81 });
82 return {
83 kind: "snapshot",
84 snapshotSequence: input.snapshotSequence,
85 ...boundedSnapshotResponseFields({
86 bounded,
87 compactTurnItems: input.compactTurnItems === true,
88 compactCheckpointItems: input.compactCheckpointItems === true,
89 }),
90 };
91}
92
93export type ThreadResumePlan =
94 | {
95 readonly mode: "replay";
96 readonly afterSequence: number;
97 readonly throughSequence: number;
98 }
99 | { readonly mode: "snapshot" };
100
101/**
102 * Event count limits reducer churn while encoded bytes limit a small number of
103 * large updates. Either excess is cheaper to replace with one current snapshot.
104 */
105export function decideThreadResume(input: {
106 readonly afterSequence: number;
107 readonly highWater: number;
108 readonly replayEventCount: number;
109 readonly replayEncodedBytes: number;
110}): ThreadResumePlan {
111 if (
112 input.afterSequence > input.highWater ||
113 input.replayEventCount > THREAD_RESUME_MAX_REPLAY_EVENTS ||
114 input.replayEncodedBytes > THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES
115 ) {
116 return { mode: "snapshot" };
117 }
118 return {
119 mode: "replay",
120 afterSequence: input.afterSequence,
121 throughSequence: input.highWater,
122 };
123}