fix(server): bound getThreadProjection history with explicit paging #11514
Closedsaphid(GitHub profile, opens in a new tab)wants to merge 250+ commits into
t3code/codex-turn-mapping fromrefs/pull/11514/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/orchestration-v2/threadHistoryPaging.ts lines 655 to 657OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -253,6 +253,10 @@253253 const byIdentity = items.findIndex(254254 (row) => String(row.sourceThreadId) === cursor.st && String(row.sourceItemId) === cursor.si,255255 );256- if (byIdentity !== -1) {257- return byIdentity;256+ // A resolvable anchor is always inside the fetched window, and positions are257+ // renumbered per window so `p` cannot order rows across windows. Guessing an258+ // index from it would silently skip history, so a miss is a typed error;259+ // the client refetches the bounded snapshot and repaginates.260+ if (byIdentity === -1) {261+ throw new InvalidThreadHistoryCursorError();258262 }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/orchestration-v2/ProjectionStore.ts line 5946OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4865,0 +5926,21 @@5926+ decodeTurnItemPayload,5927+ );5928+ const [5929+ thread,5930+ runs,5931+ attempts,5932+ nodes,5933+ subagents,5934+ providerSessions,5935+ providerThreads,5936+ providerTurns,5937+ runtimeRequests,5938+ messages,5939+ plans,5940+ checkpointScopes,5941+ checkpoints,5942+ contextHandoffs,5943+ contextTransfers,5944+ ] = yield* Effect.all([5945+ boundRow(snapshot.projection.thread, encodeThreadPayloadValue, decodeThreadPayload),5946+ boundRows(snapshot.projection.runs, encodeRunPayloadValue, decodeRunPayload),apps/server/src/orchestration-v2/ProjectionStore.ts line 2909OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2423,6 +2676,18 @@24232676 FROM user_anchors2677+ ), billed AS (2678+ -- Turn windows must not materialize unbounded rows or bytes: a2679+ -- single long turn can exceed every policy bound. Bill each row2680+ -- at most the per-row payload cap so oversized rows stay in the2681+ -- window (compacted below) while their budget cost stays sane.2682+ SELECT eligible.*,2683+ MIN(2684+ LENGTH(CAST(eligible.payload_json AS BLOB)),2685+ ${maxRowPayloadBytes}2686+ ) AS bill_bytes2687+ FROM eligible2688+ WHERE eligible.ordinal >= (SELECT ordinal FROM boundary)24242689 ), selected AS (24252690 SELECT payload_json, ordinal, turn_item_id, run_id, type2426- FROM eligible2427- WHERE ordinal >= (SELECT ordinal FROM boundary)2428- ORDER BY ordinal DESC, turn_item_id DESC2691+ FROM (2692+ SELECT billed.*,2693+ SUM(billed.bill_bytes) OVER (
- apps/server/src/orchestration-v2/ProjectionStore.ts line 2741OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2433,3 +2723,19 @@2723+ -- Row mode must also honor the hard cap so SQL and the2724+ -- in-memory fallback bound identically.2725+ ELSE MIN(${window.rowLimit}, ${maxWindowRows})24332726 END2434- ), retained AS (2435- SELECT payload_json, ordinal, turn_item_id FROM selected2727+ ), aligned AS (2728+ -- Initial turn-mode snapshots start on a turn boundary: when2729+ -- caps stop the window mid-turn and complete newer turns fit,2730+ -- drop the partial oldest turn. History-page reads must not2731+ -- align — a page that collapses to its anchor returns nothing2732+ -- and the rows the cap dropped become unreachable. A fork2733+ -- cutoff is not a page boundary: initial inherited snapshots2734+ -- still align. The drop also requires a turn start below the2735+ -- window: without one the leading rows are the indivisible2736+ -- pre-first-turn segment.2737+ SELECT payload_json, ordinal, turn_item_id, run_id, type2738+ FROM selected2739+ WHERE ${window.userTurnLimit ?? null} IS NULL2740+ OR ${window.anchorIsPageBoundary === true ? 1 : null} IS NOT NULL2741+ OR ordinal >= COALESCE(apps/server/src/orchestration-v2/ProjectionStore.ts lines 5766 to 5766OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4865,0 +5746,21 @@5746+ (index) => index >= rawStart && isThreadHistoryUserTurn(candidates[index]!.item),5747+ );5748+ const anchorLimit = (options.userTurnLimit ?? 0) + 2;5749+ const start =5750+ turnAnchors.length > 05751+ ? anchors.length < anchorLimit5752+ ? rawStart5753+ : anchors.at(-anchorLimit)!5754+ : Math.max(0, anchorIndex - options.rowLimit);5755+ // Mirror the SQL window hard caps: keep the newest rows within the5756+ // row and byte budgets and report anything dropped as older history.5757+ const maxWindowRows = options.maxWindowRows ?? THREAD_HISTORY_MAX_WINDOW_ROWS;5758+ const maxWindowBytes = options.maxWindowBytes ?? THREAD_HISTORY_MAX_WINDOW_BYTES;5759+ const maxRowPayloadBytes =5760+ options.maxRowPayloadBytes ?? THREAD_HISTORY_MAX_ROW_PAYLOAD_BYTES;5761+ const capped: typeof candidates = [];5762+ let billedBytes = 0;5763+ let headIndex = candidates.length;5764+ for (5765+ let index = candidates.length - 1;5766+ index >= start && capped.length < maxWindowRows;
- packages/client-runtime/src/operations/commands.ts line 270OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -259,5 +259,8 @@259259 const dispatch = (command: OrchestrationV2Command) =>260260 request(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command);261261262-const getProjection = (threadId: ThreadId) =>263- request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId });262+const getProjection = (threadId: ThreadId, options?: { readonly bounded?: boolean }) =>263+ request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, {264+ threadId,265+ // Older servers strip the unknown key and return the full projection.266+ ...(options?.bounded === false ? {} : { acceptBoundedSnapshot: true as const }),packages/client-runtime/src/state/threads.ts line 687OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -650,3 +651,12 @@650651 }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result);651652652653 if (Result.isFailure(pageResult)) {654+ const failure = pageResult.failure;655+ // A typed invalid_history_cursor means the anchor row no longer656+ // resolves (deleted or superseded). Reseed progressive meta from a657+ // fresh bounded snapshot instead of retrying the dead cursor forever.658+ if (659+ failure._tag === "EnvironmentRequestInvalidError" &&660+ failure.reason === "invalid_history_cursor"661+ ) {662+ const refreshed = yield* fetchEnvironmentBoundedThreadSnapshot({apps/server/src/persistence/Migrations/053_ProjectionV2BoundedPayloadPreviews.ts line 53OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +33,21 @@33+ "orchestration_v2_projection_checkpoints",34+ "orchestration_v2_projection_context_handoffs",35+ "orchestration_v2_projection_context_transfers",36+ "orchestration_v2_projection_subagents",37+] as const;38+39+const BACKFILL_PAGE_SIZE = 200;40+41+export default Effect.gen(function* () {42+ const sql = yield* SqlClient.SqlClient;43+44+ for (const table of PREVIEW_TABLES) {45+ yield* sql`ALTER TABLE ${sql.literal(table)} ADD COLUMN bounded_json TEXT`;46+47+ let lastRowId = 0;48+ while (true) {49+ const rows = yield* sql<{50+ readonly row_id: number;51+ readonly payload_json: string;52+ }>`53+ SELECT rowid AS row_id, payload_jsonapps/server/src/orchestration-v2/boundedPayloadPreview.ts lines 253 to 253OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +233,21 @@233+ // deeper must recurse so the stubs above can fire.234+ const sizeBytes = inputJsonBytes(policy.sizes, value);235+ if (236+ sizeBytes <= maxBytes &&237+ depth + Math.floor(sizeBytes / 2) <= THREAD_HISTORY_PREVIEW_SOFT_DEPTH238+ ) {239+ return value;240+ }241+ if (Array.isArray(value)) {242+ const members: unknown[] = [];243+ let cumulativeBytes = 0;244+ // Greedy first-come budgeting lets head members spend the whole budget and245+ // drops identical tail members a fair share would have kept — a pending246+ // user_input_request loses questions its compacted form could afford.247+ // When every member's floor fits the budget, all members survive and split248+ // the slack; tail members only drop when the floors genuinely overflow.249+ const floorSizes = value.map((element) =>250+ floorSerializedBytes(policy.untyped ? policy : { ...policy, droppableKeys: false }, element),251+ );252+ const floorTotal = floorSizes.reduce((total, size) => total + 8 + size, 0);253+ const keepAll = policy.preserveMembers || floorTotal <= maxBytes;
- apps/server/src/orchestration-v2/ProjectionStore.ts line 6018OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4848,18 +6015,4 @@6015+ decodeTurnItemPayload,48486016 );4849- const rawStart = turnAnchors.at(-(THREAD_HISTORY_MAX_RAW_TURNS + 2)) ?? 0;4850- const anchors = turnAnchors.filter(4851- (index) => index >= rawStart && isThreadHistoryUserTurn(candidates[index]!.item),4852- );4853- const anchorLimit = (options.userTurnLimit ?? 0) + 2;4854- const start =4855- turnAnchors.length > 04856- ? anchors.length < anchorLimit4857- ? rawStart4858- : anchors.at(-anchorLimit)!4859- : Math.max(0, anchorIndex - options.rowLimit);4860- const visibleTurnItems = candidates.slice(start);4861- return {4862- ...snapshot,4863- projection: { ...snapshot.projection, visibleTurnItems },4864- };4865- }),6017+ boundItems.set(row, boundItem);6018+ billedBytes += projectedRowEncodedBytes({ ...row, item: boundItem });
- @@ -4865,0 +6408,21 @@6408+ ...snapshot.projection,6409+ thread,6410+ runs,6411+ attempts,6412+ nodes,6413+ subagents,6414+ providerSessions,6415+ providerThreads,6416+ providerTurns,6417+ runtimeRequests,6418+ messages,6419+ plans,6420+ checkpointScopes,6421+ checkpoints,6422+ contextHandoffs,6423+ contextTransfers,6424+ turnItems,6425+ visibleTurnItems: bounded,6426+ },6427+ };6428+ }).pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause }))),
- @@ -2777,3 +2869,5 @@27772869 {27782870 threadId: ThreadId,27792871 message: Schema.String,2872+ /** Optional failure category so clients can branch without parsing `message`. */2873+ reason: Schema.optionalKey(Schema.Literals(["invalid_history_cursor"])),
- @@ -41,4 +40,4 @@4140 import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";4241 import { withWorkspaceLease } from "./workspace/workspaceLease.ts";434244-export class StorageCleanup extends Context.Service<43+class StorageCleanup extends Context.Service<
- @@ -116,4 +116,4 @@116116 );117117 }118118119-export const make = Effect.gen(function* () {119+const make = Effect.gen(function* () {
juliusmarminge closed this
Sign in to join this conversation.
Bugbot is paused — on-demand spend limit reached
Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.
A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.