Skip to content

Commit 8243cc8

Browse files
authored
perf(gateway): reuse prepared display projections (#133203)
1 parent 3483c89 commit 8243cc8

11 files changed

Lines changed: 148 additions & 173 deletions

‎src/gateway/server-chat-progress-snapshot.ts‎

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -97,20 +97,23 @@ export function updateChatRunProgressSnapshot(
9797
next.byteLength = next.events.reduce((total, candidate) => total + jsonUtf8Bytes(candidate), 0);
9898
};
9999

100-
if (isStartupStatus) {
101-
if (
102-
next.events.some((candidate) => candidate.stream === "tool" || candidate.stream === "item")
103-
) {
104-
return next;
105-
}
106-
removeWhere((candidate) => candidate.stream === "run_status");
107-
} else if (isTool || isPreamble) {
108-
removeWhere((candidate) => candidate.stream === "run_status");
100+
if (
101+
isStartupStatus &&
102+
next.events.some((candidate) => candidate.stream === "tool" || candidate.stream === "item")
103+
) {
104+
return next;
109105
}
110106

111-
if (isTool) {
107+
if (isStartupStatus || isTool || isPreamble) {
108+
// Remove superseded startup and item state together; recount retained mutable payloads once.
112109
removeWhere((candidate) => {
113-
if (candidate.stream !== "tool" || candidate.data?.toolCallId !== toolCallId) {
110+
if (candidate.stream === "run_status") {
111+
return true;
112+
}
113+
if (isPreamble) {
114+
return matchesPreamble(candidate);
115+
}
116+
if (!isTool || candidate.stream !== "tool" || candidate.data?.toolCallId !== toolCallId) {
114117
return false;
115118
}
116119
if (phase === "start") {
@@ -126,10 +129,7 @@ export function updateChatRunProgressSnapshot(
126129
// review ID so reconnect restores every still-relevant decision.
127130
return asNullableRecord(candidate.data.review)?.id === reviewId;
128131
});
129-
} else if (isPreamble) {
130-
const progressText = typeof data.progressText === "string" ? data.progressText.trim() : "";
131-
removeWhere(matchesPreamble);
132-
if (!progressText) {
132+
if (isPreamble && !(typeof data.progressText === "string" && data.progressText.trim())) {
133133
return next;
134134
}
135135
} else if ((isStandaloneGuardian || resolvesStrictReview) && typeof data.reviewId === "string") {

‎src/gateway/server-methods/chat-history-handler.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,9 @@ async function handleChatHistoryRequest({
382382
? (capChatHistoryAroundMessage({
383383
messages: replaced.messages,
384384
messageId,
385-
fits: (messages) => byteCounter.messagesBytes(messages) <= maxHistoryBytes,
385+
// A nonempty JSON array costs one framing byte plus each message and its separator.
386+
maxCost: maxHistoryBytes - 1,
387+
messageCost: (message) => byteCounter.messageBytes(message) + 1,
386388
}) ?? capArrayByJsonBytes(replaced.messages, maxHistoryBytes, byteCounter.messageBytes).items)
387389
: capArrayByJsonBytes(replaced.messages, maxHistoryBytes, byteCounter.messageBytes).items;
388390
const historyBudgetPreserved =

‎src/gateway/server-methods/chat-history-pages.ts‎

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -148,56 +148,64 @@ export function enrichChatHistoryCompactionMarkers(
148148
function resolveChatHistoryMessageGroup(
149149
messages: unknown[],
150150
index: number,
151-
): { start: number; end: number } {
151+
messageCost: (message: unknown) => number,
152+
): { start: number; end: number; cost: number } {
152153
const seq = readChatHistoryMessageSeq(messages[index]);
153-
if (seq === undefined) {
154-
return { start: index, end: index + 1 };
155-
}
156154
let start = index;
157155
let end = index + 1;
156+
let cost = messageCost(messages[index]);
157+
if (seq === undefined) {
158+
return { start, end, cost };
159+
}
158160
while (start > 0 && readChatHistoryMessageSeq(messages[start - 1]) === seq) {
159161
start -= 1;
162+
cost += messageCost(messages[start]);
160163
}
161164
while (end < messages.length && readChatHistoryMessageSeq(messages[end]) === seq) {
165+
cost += messageCost(messages[end]);
162166
end += 1;
163167
}
164-
return { start, end };
168+
return { start, end, cost };
165169
}
166170

167171
export function capChatHistoryAroundMessage(params: {
168172
messages: unknown[];
169173
messageId: string;
170-
fits: (messages: unknown[]) => boolean;
174+
maxCost: number;
175+
messageCost?: (message: unknown) => number;
171176
}): unknown[] | undefined {
172177
const anchorIndex = params.messages.findIndex(
173178
(message) => readChatHistoryMessageId(message) === params.messageId,
174179
);
175180
if (anchorIndex === -1) {
176181
return undefined;
177182
}
178-
const anchorGroup = resolveChatHistoryMessageGroup(params.messages, anchorIndex);
179-
if (!params.fits(params.messages.slice(anchorGroup.start, anchorGroup.end))) {
183+
const messageCost = params.messageCost ?? (() => 1);
184+
const anchorGroup = resolveChatHistoryMessageGroup(params.messages, anchorIndex, messageCost);
185+
if (!(anchorGroup.cost <= params.maxCost)) {
180186
return [params.messages[anchorIndex]];
181187
}
182188

183-
let { start, end } = anchorGroup;
189+
let { start, end, cost } = anchorGroup;
184190
let canGrowOlder = start > 0;
185191
let canGrowNewer = end < params.messages.length;
186192
while (canGrowOlder || canGrowNewer) {
187193
if (canGrowOlder) {
188-
const olderGroup = resolveChatHistoryMessageGroup(params.messages, start - 1);
189-
if (params.fits(params.messages.slice(olderGroup.start, end))) {
194+
const olderGroup = resolveChatHistoryMessageGroup(params.messages, start - 1, messageCost);
195+
if (cost + olderGroup.cost <= params.maxCost) {
190196
start = olderGroup.start;
197+
cost += olderGroup.cost;
191198
} else {
192199
canGrowOlder = false;
193200
}
194201
}
195202
canGrowOlder &&= start > 0;
196203

197204
if (canGrowNewer) {
198-
const newerGroup = resolveChatHistoryMessageGroup(params.messages, end);
199-
if (params.fits(params.messages.slice(start, newerGroup.end))) {
205+
const newerGroup = resolveChatHistoryMessageGroup(params.messages, end, messageCost);
206+
if (cost + newerGroup.cost <= params.maxCost) {
200207
end = newerGroup.end;
208+
cost += newerGroup.cost;
201209
} else {
202210
canGrowNewer = false;
203211
}
@@ -321,7 +329,7 @@ export async function readChatHistoryPage(params: {
321329
? (capChatHistoryAroundMessage({
322330
messages: projected,
323331
messageId,
324-
fits: (messages) => messages.length <= max,
332+
maxCost: max,
325333
}) ?? capOffsetChatHistoryProjectedMessages(projected, max))
326334
: projected;
327335
if (messageId) {

‎src/gateway/session-list-order.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,17 @@ function selectNewestLimitedEntries(
3636
): SessionEntryPair[] {
3737
const selected: SessionEntryPair[] = [];
3838
for (const entry of entries) {
39-
const insertAt = selected.findIndex(
40-
(candidate) => compareSessionEntryPairs(entry, candidate, sortBy) < 0,
41-
);
39+
const first = selected[0];
40+
const beforeFirst = first && compareSessionEntryPairs(entry, first, sortBy) < 0;
41+
const worst = selected[limit - 1];
42+
if (!beforeFirst && worst && compareSessionEntryPairs(entry, worst, sortBy) >= 0) {
43+
continue;
44+
}
45+
const insertAt = beforeFirst
46+
? 0
47+
: selected.findIndex(
48+
(candidate, index) => index > 0 && compareSessionEntryPairs(entry, candidate, sortBy) < 0,
49+
);
4250
if (insertAt >= 0) {
4351
selected.splice(insertAt, 0, entry);
4452
if (selected.length > limit) {

‎src/gateway/session-utils-contracts.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ export type SessionActorProfileIdentity = Extract<CurrentUserProfileDisplay, { k
2020

2121
export type SessionListRowContext = {
2222
subagentRuns: SubagentRunReadIndex<SubagentRunReadRecord>;
23-
storeChildSessionsByKey: Map<string, string[]>;
2423
selectedModelByOverrideRef: Map<string, ReturnType<typeof resolveSessionModelRef>>;
2524
thinkingMetadataByModelRef: Map<string, GatewayModelThinkingProfile>;
2625
displayModelIdentityByKey: Map<string, { provider?: string; model?: string }>;

‎src/gateway/session-utils-core.ts‎

Lines changed: 46 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,7 @@ function rememberSingleRowChildSessionCandidateCacheEntry(
289289

290290
function buildStoreChildSessionCandidateIndex(
291291
store: Record<string, SessionEntry> | null | undefined,
292+
selectedParents?: ReadonlySet<string>,
292293
): Map<string, string[]> {
293294
const childSessionsByKey = new Map<string, string[]>();
294295
if (!store) {
@@ -303,7 +304,9 @@ function buildStoreChildSessionCandidateIndex(
303304
normalizeOptionalString(entry.parentSessionKey),
304305
].filter((value): value is string => Boolean(value) && value !== key);
305306
for (const parentKey of parentKeys) {
306-
addChildSessionKey(childSessionsByKey, parentKey, key);
307+
if (!selectedParents || selectedParents.has(parentKey)) {
308+
addChildSessionKey(childSessionsByKey, parentKey, key);
309+
}
307310
}
308311
}
309312
return childSessionsByKey;
@@ -412,92 +415,72 @@ export function isCurrentSessionChildOwner(params: {
412415
);
413416
}
414417

415-
export function buildStoreChildSessionIndex(
416-
store: Record<string, SessionEntry>,
417-
now = Date.now(),
418-
subagentRuns?: SessionListRowContext["subagentRuns"],
419-
): Map<string, string[]> {
420-
const childSessionsByKey = new Map<string, string[]>();
421-
for (const [key, entry] of Object.entries(store)) {
422-
if (!entry) {
423-
continue;
424-
}
425-
const parentKeys = [
426-
normalizeOptionalString(entry.spawnedBy),
427-
normalizeOptionalString(entry.parentSessionKey),
428-
].filter((value): value is string => Boolean(value) && value !== key);
429-
if (parentKeys.length === 0) {
430-
continue;
431-
}
432-
const latest = subagentRuns
433-
? subagentRuns.getDisplaySubagentRun(key)
434-
: getSessionDisplaySubagentRunByChildSessionKey(key);
435-
let latestControllerSessionKey: string | undefined;
436-
if (latest) {
437-
latestControllerSessionKey =
438-
normalizeOptionalString(latest.controllerSessionKey) ||
439-
normalizeOptionalString(latest.requesterSessionKey);
440-
if (
441-
!shouldKeepSubagentRunChildLink(latest, {
442-
activeDescendants: subagentRuns
443-
? subagentRuns.countActiveDescendantRuns(key)
444-
: countActiveDescendantRuns(key),
445-
now,
446-
})
447-
) {
448-
continue;
449-
}
450-
} else if (!shouldKeepStoreOnlyChildLink(entry, now)) {
451-
continue;
452-
}
453-
for (const parentKey of parentKeys) {
454-
if (
455-
latestControllerSessionKey &&
456-
!isCurrentSessionChildOwner({
457-
entry,
458-
ownerSessionKey: parentKey,
459-
controllerSessionKey: latestControllerSessionKey,
460-
})
461-
) {
462-
continue;
463-
}
464-
addChildSessionKey(childSessionsByKey, parentKey, key);
418+
/** Prepare only selected parents; a supplied candidate map retains exact-row cache ownership. */
419+
export function buildStoreChildSessionIndex(params: {
420+
store: Record<string, SessionEntry>;
421+
keys: readonly string[];
422+
now: number;
423+
subagentRuns?: SessionListRowContext["subagentRuns"];
424+
candidates?: ReadonlyMap<string, readonly string[]>;
425+
excludedChildKeys?: ReadonlySet<string>;
426+
requireCurrentController?: boolean;
427+
}): Map<string, string[]> {
428+
const children = new Map<string, string[]>();
429+
if (params.keys.length === 0) {
430+
return children;
431+
}
432+
const candidates =
433+
params.candidates ?? buildStoreChildSessionCandidateIndex(params.store, new Set(params.keys));
434+
for (const key of params.keys) {
435+
const childKeys = resolveStoreChildSessionKeysFromCandidates({ ...params, key, candidates });
436+
if (childKeys) {
437+
children.set(key, childKeys);
465438
}
466439
}
467-
return childSessionsByKey;
440+
return children;
468441
}
469442

470-
export function resolveStoreChildSessionKeysFromCandidates(params: {
443+
function resolveStoreChildSessionKeysFromCandidates(params: {
471444
store: Record<string, SessionEntry>;
472445
key: string;
473446
now: number;
474447
candidates: ReadonlyMap<string, readonly string[]>;
448+
subagentRuns?: SessionListRowContext["subagentRuns"];
449+
excludedChildKeys?: ReadonlySet<string>;
450+
requireCurrentController?: boolean;
475451
}): string[] | undefined {
476452
const childSessionKeys: string[] = [];
477453
for (const childKey of params.candidates.get(params.key) ?? []) {
454+
if (params.excludedChildKeys?.has(childKey)) {
455+
continue;
456+
}
478457
const entry = params.store[childKey];
479458
if (!entry) {
480459
continue;
481460
}
482-
const latest = getSessionDisplaySubagentRunByChildSessionKey(childKey);
461+
const latest = params.subagentRuns
462+
? params.subagentRuns.getDisplaySubagentRun(childKey)
463+
: getSessionDisplaySubagentRunByChildSessionKey(childKey);
483464
if (latest) {
484465
const latestControllerSessionKey =
485466
normalizeOptionalString(latest.controllerSessionKey) ||
486467
normalizeOptionalString(latest.requesterSessionKey);
487-
if (
488-
!isCurrentSessionChildOwner({
489-
entry,
490-
ownerSessionKey: params.key,
491-
controllerSessionKey: latestControllerSessionKey,
492-
})
493-
) {
468+
const matchesOwner = isCurrentSessionChildOwner({
469+
entry,
470+
ownerSessionKey: params.key,
471+
controllerSessionKey: latestControllerSessionKey,
472+
});
473+
if (params.requireCurrentController && !matchesOwner) {
494474
continue;
495475
}
496476
if (
497477
!shouldKeepSubagentRunChildLink(latest, {
498-
activeDescendants: countActiveDescendantRuns(childKey),
478+
activeDescendants: params.subagentRuns
479+
? params.subagentRuns.countActiveDescendantRuns(childKey)
480+
: countActiveDescendantRuns(childKey),
499481
now: params.now,
500-
})
482+
}) ||
483+
(latestControllerSessionKey && !matchesOwner)
501484
) {
502485
continue;
503486
}

0 commit comments

Comments
 (0)