Skip to content

Commit b5e509b

Browse files
committed
perf(agents): amortize history-limit eviction with hysteresis (#115273)
1 parent b403cb5 commit b5e509b

2 files changed

Lines changed: 85 additions & 13 deletions

File tree

‎src/agents/embedded-agent-runner.limithistoryturns.test.ts‎

Lines changed: 66 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,12 @@ describe("limitHistoryTurns", () => {
7171
role === "user" ? userMessage(`message ${i}`) : assistantTextMessage(`message ${i}`),
7272
);
7373

74+
const makeTurns = (count: number): AgentMessage[] =>
75+
Array.from({ length: count }, (_, i) => [
76+
userMessage(`user ${i}`),
77+
assistantTextMessage(`assistant ${i}`),
78+
]).flat();
79+
7480
it("returns all messages when limit is undefined", () => {
7581
const messages = makeMessages(["user", "assistant", "user", "assistant"]);
7682
expect(limitHistoryTurns(messages, undefined)).toBe(messages);
@@ -95,11 +101,42 @@ describe("limitHistoryTurns", () => {
95101
expect(limitHistoryTurns(messages, 10)).toBe(messages);
96102
});
97103

98-
it("limits to last N user turns", () => {
99-
const messages = makeMessages(["user", "assistant", "user", "assistant", "user", "assistant"]);
104+
it("cuts back to the limit after crossing the hysteresis cushion", () => {
105+
const messages = makeTurns(4);
100106
const limited = limitHistoryTurns(messages, 2);
101107
expect(limited.length).toBe(4);
102-
expect(firstText(expectDefined(limited[0], "limited[0] test invariant"))).toBe("message 2");
108+
expect(firstText(expectDefined(limited[0], "limited[0] test invariant"))).toBe("user 2");
109+
});
110+
111+
it("keeps the window start fixed while turns append within the cushion", () => {
112+
const messages = makeTurns(9);
113+
114+
for (const turnCount of [7, 8, 9]) {
115+
const limited = limitHistoryTurns(messages.slice(0, turnCount * 2), 4);
116+
expect(limited[0]).toBe(messages[6]);
117+
}
118+
});
119+
120+
it("makes a single cut to exactly the limit when crossing 1.5x", () => {
121+
const messages = makeTurns(7);
122+
const atThreshold = messages.slice(0, 12);
123+
124+
expect(limitHistoryTurns(atThreshold, 4)).toBe(atThreshold);
125+
const limited = limitHistoryTurns(messages, 4);
126+
expect(limited).toHaveLength(8);
127+
expect(limited[0]).toBe(messages[6]);
128+
});
129+
130+
it("repeats batched cuts with stable starts between them", () => {
131+
const messages = makeTurns(13);
132+
const expectedStartTurns = [3, 3, 3, 6, 6, 6, 9];
133+
134+
for (const [offset, expectedStartTurn] of expectedStartTurns.entries()) {
135+
const turnCount = offset + 7;
136+
const limited = limitHistoryTurns(messages.slice(0, turnCount * 2), 4);
137+
expect(limited[0]).toBe(messages[expectedStartTurn * 2]);
138+
expect(limited).toHaveLength((turnCount - expectedStartTurn) * 2);
139+
}
103140
});
104141

105142
it("handles single user turn limit", () => {
@@ -113,7 +150,15 @@ describe("limitHistoryTurns", () => {
113150
it("handles messages with multiple assistant responses per user turn", () => {
114151
// The limit is counted by user turns, so only the assistant tail attached to
115152
// the kept user turn should remain.
116-
const messages = makeMessages(["user", "assistant", "assistant", "user", "assistant"]);
153+
const messages = makeMessages([
154+
"user",
155+
"assistant",
156+
"assistant",
157+
"user",
158+
"assistant",
159+
"user",
160+
"assistant",
161+
]);
117162
const limited = limitHistoryTurns(messages, 1);
118163
expect(limited.length).toBe(2);
119164
expect(expectDefined(limited[0], "limited[0] test invariant").role).toBe("user");
@@ -130,13 +175,13 @@ describe("limitHistoryTurns", () => {
130175
} as AgentMessage;
131176
const messages = [
132177
compactionSummary,
133-
...makeMessages(["user", "assistant", "user", "assistant"]),
178+
...makeMessages(["user", "assistant", "user", "assistant", "user", "assistant"]),
134179
];
135180
const limited = limitHistoryTurns(messages, 1);
136181
// compactionSummary is preserved, last 1 user turn + assistant kept
137182
expect(limited.length).toBe(3);
138183
expect(expectDefined(limited[0], "limited[0] test invariant").role).toBe("compactionSummary");
139-
expect(firstText(expectDefined(limited[1], "limited[1] test invariant"))).toBe("message 2");
184+
expect(firstText(expectDefined(limited[1], "limited[1] test invariant"))).toBe("message 4");
140185
});
141186

142187
it("preserves leading branchSummary when limiting", () => {
@@ -146,7 +191,10 @@ describe("limitHistoryTurns", () => {
146191
fromId: "abc",
147192
timestamp: Date.now(),
148193
} as AgentMessage;
149-
const messages = [branchSummary, ...makeMessages(["user", "assistant", "user", "assistant"])];
194+
const messages = [
195+
branchSummary,
196+
...makeMessages(["user", "assistant", "user", "assistant", "user", "assistant"]),
197+
];
150198
const limited = limitHistoryTurns(messages, 1);
151199
expect(limited.length).toBe(3);
152200
expect(expectDefined(limited[0], "limited[0] test invariant").role).toBe("branchSummary");
@@ -160,13 +208,16 @@ describe("limitHistoryTurns", () => {
160208
value: true,
161209
});
162210
}
163-
const messages = [...prelude, ...makeMessages(["user", "assistant", "user", "assistant"])];
211+
const messages = [
212+
...prelude,
213+
...makeMessages(["user", "assistant", "user", "assistant", "user", "assistant"]),
214+
];
164215

165216
const limited = limitHistoryTurns(messages, 1);
166217

167218
expect(limited).toHaveLength(4);
168219
expect(firstText(expectDefined(limited[0], "limited[0] test invariant"))).toBe("message 0");
169-
expect(firstText(expectDefined(limited[2], "limited[2] test invariant"))).toBe("message 2");
220+
expect(firstText(expectDefined(limited[2], "limited[2] test invariant"))).toBe("message 4");
170221
});
171222

172223
it("returns all when only non-conversation messages exist", () => {
@@ -188,9 +239,13 @@ describe("limitHistoryTurns", () => {
188239
assistantToolCallMessage("1"),
189240
userMessage("second"),
190241
assistantTextMessage("response"),
242+
userMessage("third"),
243+
assistantTextMessage("final response"),
191244
];
192245
const limited = limitHistoryTurns(messages, 1);
193-
expect(firstText(expectDefined(limited[0], "limited[0] test invariant"))).toBe("second");
194-
expect(firstText(expectDefined(limited[1], "limited[1] test invariant"))).toBe("response");
246+
expect(firstText(expectDefined(limited[0], "limited[0] test invariant"))).toBe("third");
247+
expect(firstText(expectDefined(limited[1], "limited[1] test invariant"))).toBe(
248+
"final response",
249+
);
195250
});
196251
});

‎src/agents/embedded-agent-runner/history.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ function stripThreadSuffix(value: string): string {
2222
}
2323

2424
/**
25-
* Limits conversation history to the last N user turns (and their associated
25+
* Limits conversation history to recent user turns (and their associated
2626
* assistant responses). This reduces token usage for long-running DM sessions.
2727
*
2828
* Leading non-conversation messages (e.g. compactionSummary, branchSummary)
@@ -58,12 +58,29 @@ export function limitHistoryTurns(
5858
}
5959

6060
let userCount = 0;
61+
for (const message of tail) {
62+
if (message.role === "user") {
63+
userCount++;
64+
}
65+
}
66+
67+
// Allow a 50% cushion, then evict a full batch so the prompt-cache prefix stays
68+
// stable between cuts; up to 1.5x turns trades strictness for amortized cache reuse.
69+
const targetUserTurns = Math.floor(limit);
70+
const maxUserTurns = Math.ceil(targetUserTurns * 1.5);
71+
if (userCount <= maxUserTurns) {
72+
return messages;
73+
}
74+
const evictionBatchSize = maxUserTurns - targetUserTurns + 1;
75+
const userTurnsToKeep = targetUserTurns + ((userCount - targetUserTurns) % evictionBatchSize);
76+
77+
userCount = 0;
6178
let lastUserIndex = tail.length;
6279

6380
for (const [i, message] of Array.from(tail.entries()).toReversed()) {
6481
if (message.role === "user") {
6582
userCount++;
66-
if (userCount > limit) {
83+
if (userCount > userTurnsToKeep) {
6784
return [...messages.slice(0, conversationStart), ...tail.slice(lastUserIndex)];
6885
}
6986
lastUserIndex = i;

0 commit comments

Comments
 (0)