Skip to content

Commit 7861fa1

Browse files
Keep large history merges and metrics processing bounded (#2728)
* Keep large history merges and metrics processing bounded Large equal-timestamp batches incur repeated scans, and large spreads can exceed the argument limit. Index collisions and avoid processing output bodies for metrics. Refs #2727 * Cover history metrics parity and timestamp matching
1 parent 672f0ee commit 7861fa1

6 files changed

Lines changed: 214 additions & 33 deletions

File tree

‎src/core/task-persistence/__tests__/mergeMessageSnapshots.spec.ts‎

Lines changed: 74 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/core/task-persistence/__tests__/taskMetadata.large.spec.ts‎

Lines changed: 63 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/core/task-persistence/mergeMessageSnapshots.ts‎

Lines changed: 54 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -39,59 +39,81 @@ function mergeTimestampedSnapshots(
3939
return incoming
4040
}
4141

42-
const existingGroups = new Map<number, MessageRecord[]>()
42+
type IndexQueue = { indices: number[]; cursor: number }
43+
type Group = {
44+
messages: MessageRecord[]
45+
byId?: Map<string, IndexQueue>
46+
legacy?: IndexQueue
47+
consumed: Set<number>
48+
}
49+
const existingGroups = new Map<number, Group>()
4350
const existingLegacy: unknown[] = []
4451

4552
for (const message of existing) {
4653
if (isRecord(message) && typeof message.ts === "number") {
47-
const group = existingGroups.get(message.ts) ?? []
48-
group.push(message)
49-
existingGroups.set(message.ts, group)
54+
let group = existingGroups.get(message.ts)
55+
if (!group) {
56+
group = { messages: [], consumed: new Set() }
57+
existingGroups.set(message.ts, group)
58+
}
59+
group.messages.push(message)
5060
} else {
5161
existingLegacy.push(message)
5262
}
5363
}
5464

55-
const consumedByTimestamp = new Map<number, Set<number>>()
65+
const takeIndex = (queue?: IndexQueue) =>
66+
queue && queue.cursor < queue.indices.length ? queue.indices[queue.cursor++] : undefined
5667
let incomingLegacyCount = 0
5768
const merged = incoming.map((message) => {
5869
if (!isRecord(message) || typeof message.ts !== "number") {
5970
incomingLegacyCount++
6071
return message
6172
}
6273

63-
const existingGroup = existingGroups.get(message.ts) ?? []
64-
const consumed = consumedByTimestamp.get(message.ts) ?? new Set<number>()
74+
const group = existingGroups.get(message.ts)
6575
const messageId = typeof message.messageId === "string" ? message.messageId : undefined
66-
let diskIndex =
67-
messageId === undefined
68-
? existingGroup.findIndex(
69-
(candidate, index) => !consumed.has(index) && candidate.messageId === undefined,
70-
)
71-
: existingGroup.findIndex(
72-
(candidate, index) => !consumed.has(index) && candidate.messageId === messageId,
73-
)
74-
if (diskIndex === -1 && messageId !== undefined) {
75-
// Match one legacy record while persisted histories are upgraded with identifiers.
76-
diskIndex = existingGroup.findIndex(
77-
(candidate, index) => !consumed.has(index) && candidate.messageId === undefined,
76+
let diskIndex: number | undefined
77+
if (group?.messages.length === 1) {
78+
const candidateId = group.messages[0].messageId
79+
if (
80+
!group.consumed.has(0) &&
81+
(candidateId === undefined || (messageId !== undefined && candidateId === messageId))
7882
)
83+
diskIndex = 0
84+
} else if (group) {
85+
// Only allocate ID queues for collisions. Most timestamps have one message.
86+
if (!group.byId) {
87+
const byId = new Map<string, IndexQueue>()
88+
const legacy: IndexQueue = { indices: [], cursor: 0 }
89+
for (const [index, candidate] of group.messages.entries()) {
90+
const id = candidate.messageId
91+
if (typeof id === "string") {
92+
const queue = byId.get(id) ?? { indices: [], cursor: 0 }
93+
queue.indices.push(index)
94+
byId.set(id, queue)
95+
} else if (id === undefined) legacy.indices.push(index)
96+
}
97+
group.byId = byId
98+
group.legacy = legacy
99+
}
100+
diskIndex = takeIndex(messageId === undefined ? group.legacy : group.byId.get(messageId))
101+
if (diskIndex === undefined && messageId !== undefined) diskIndex = takeIndex(group.legacy)
79102
}
80-
const diskMessage = diskIndex === -1 ? undefined : existingGroup[diskIndex]
81-
if (diskIndex !== -1) {
82-
consumed.add(diskIndex)
83-
consumedByTimestamp.set(message.ts, consumed)
84-
}
103+
const diskMessage = diskIndex === undefined ? undefined : group?.messages[diskIndex]
104+
if (diskIndex !== undefined) group?.consumed.add(diskIndex)
85105
if (mergeMatch !== undefined && diskMessage !== undefined) {
86106
return mergeMatch(diskMessage, message)
87107
}
88108
return message
89109
})
90110

91-
const diskOnlyTimestamped = [...existingGroups.entries()].flatMap(([timestamp, messages]) => {
92-
const consumed = consumedByTimestamp.get(timestamp)
93-
return messages.filter((_message, index) => !consumed?.has(index))
94-
})
111+
const diskOnlyTimestamped: MessageRecord[] = []
112+
for (const group of existingGroups.values()) {
113+
for (const [index, message] of group.messages.entries()) {
114+
if (!group.consumed.has(index)) diskOnlyTimestamped.push(message)
115+
}
116+
}
95117

96118
const timestampMerged: unknown[] = []
97119
let diskOnlyIndex = 0
@@ -107,9 +129,11 @@ function mergeTimestampedSnapshots(
107129
}
108130
timestampMerged.push(incomingMessage)
109131
}
110-
timestampMerged.push(...diskOnlyTimestamped.slice(diskOnlyIndex))
132+
for (; diskOnlyIndex < diskOnlyTimestamped.length; diskOnlyIndex++)
133+
timestampMerged.push(diskOnlyTimestamped[diskOnlyIndex])
111134

112-
timestampMerged.push(...existingLegacy.slice(incomingLegacyCount))
135+
for (let index = incomingLegacyCount; index < existingLegacy.length; index++)
136+
timestampMerged.push(existingLegacy[index])
113137
return timestampMerged
114138
}
115139

‎src/core/task-persistence/taskMetadata.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import getFolderSize from "get-folder-size"
44
import type { ClineMessage, HistoryItem } from "@roo-code/types"
55

66
import { combineApiRequests } from "../../shared/combineApiRequests"
7-
import { combineCommandSequences } from "../../shared/combineCommandSequences"
87
import { getApiMetrics } from "../../shared/getApiMetrics"
98
import { findLastIndex } from "../../shared/array"
109
import { getTaskDirectoryPath } from "../../utils/storage"
@@ -72,7 +71,17 @@ export async function taskMetadata({
7271

7372
timestamp = lastRelevantMessage.ts
7473

75-
tokenUsage = getApiMetrics(combineApiRequests(combineCommandSequences(messages.slice(1))))
74+
// Metrics never consume command/file bodies. Do not rebuild potentially
75+
// hundreds of MB of consolidated output on every history save.
76+
const metricMessages = messages.filter(
77+
(message, index) =>
78+
index > 0 &&
79+
message.type === "say" &&
80+
(message.say === "api_req_started" ||
81+
message.say === "api_req_finished" ||
82+
message.say === "condense_context"),
83+
)
84+
tokenUsage = getApiMetrics(combineApiRequests(metricMessages))
7685

7786
// Get task directory size
7887
const cachedSize = taskSizeCache.get<number>(taskDir)

‎webview-ui/src/utils/__tests__/batchNearby.spec.ts‎

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎webview-ui/src/utils/batchNearby.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ export function batchNearby<T>(items: T[], options: BatchNearbyOptions<T>): T[]
7878
result.push(batch[0])
7979
}
8080
if (pendingIgnorable.length > 0) {
81-
result.push(...pendingIgnorable)
81+
for (const item of pendingIgnorable) result.push(item)
8282
}
8383

8484
i = j // items[j] was not consumed — re-examine it on next iteration

0 commit comments

Comments
 (0)