Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(context-engine): keep stale tool-result trims across warm turns (#22981)

YuTengjing4f1c63272489
diff --git a/packages/context-engine/src/processors/StaleToolResultTrim.ts b/packages/context-engine/src/processors/StaleToolResultTrim.ts
index d539663eb25..ff1bd008bad 100644
--- a/packages/context-engine/src/processors/StaleToolResultTrim.ts
+++ b/packages/context-engine/src/processors/StaleToolResultTrim.ts
@@ -9,6 +9,8 @@ declare module '../types' {
byRule: Record<string, number>;
/** Whether the turn boundary fell inside the provider cache TTL. */
cacheWarm?: boolean;
+ /** Trims an earlier turn accepted, kept so the cached prefix stays byte-stable. */
+ carriedMessages?: number;
/** Estimated gain used by the warm break-even check (skip path only). */
gainEstimate?: number;
/** Measured gap between the previous turn's last activity and the trigger. */
@@ -113,10 +115,69 @@ export interface StaleToolResultTrimConfig {
warmSafetyMargin?: number;
}
+interface TrimCandidate {
+ content: string;
+ index: number;
+ rule: string;
+}
+
+/** One turn's trim decision, made at its trigger and replayed by every later turn. */
+interface TurnPlan {
+ /** New trims this turn accepted. */
+ accepted: TrimCandidate[];
+ cacheWarm?: boolean;
+ gapMs?: number;
+ /** Set when the warm break-even check rejected this turn's new candidates. */
+ skipped?: NonNullable<PipelineContext['metadata']['staleToolResultTrim']>;
+}
+
+/**
+ * What the turn replay has learned about the closed history so far. Turn
+ * boundaries only move forward, so every field grows incrementally and each
+ * message is indexed once per request however many turns are replayed.
+ */
+interface ReplayIndex {
+ /** Tool chars (images weighted) in messages [0, scanned), for the size gate. */
+ closedToolChars: number;
+ lastWriteIndexByPath: Map<string, number>;
+ /** Current trim candidates in [0, scanned) that no turn has accepted yet. */
+ pending: Map<number, TrimCandidate>;
+ /** `rawCharsPrefix[i]` = untrimmed chars (images weighted) of messages [0, i). */
+ rawCharsPrefix: number[];
+ readWindowsByPath: Map<string, { end: number; index: number; start: number }[]>;
+ /** Messages [0, scanned) are indexed. */
+ scanned: number;
+ /** Chars removed by each trim accepted so far, keyed by message index. */
+ trimmedSavedByIndex: Map<number, number>;
+ /** Untrimmed readFile windows in [0, scanned) per path, re-derived when a later write or covering re-read arrives. */
+ untrimmedReadsByPath: Map<string, { end: number; index: number; start: number }[]>;
+}
+
const LOCAL_SYSTEM = 'lobe-local-system';
const imageCountOf = (message: Message) =>
(message.pluginState as { images?: unknown[] } | undefined)?.images?.length ?? 0;
+
+const charsOf = (value: unknown): number =>
+ typeof value === 'string' ? value.length : value == null ? 0 : JSON.stringify(value).length;
+
+/**
+ * Model-visible chars of a message for cache pricing: its content (text or
+ * parts) plus the arguments of the tool calls it issued, which reach the
+ * provider as `tool_calls[].function.arguments`. A large `writeFile` call is
+ * mostly arguments, and leaving them out underprices the rewrite behind it.
+ */
+const payloadCharsOf = (message: Message): number => {
+ let chars = charsOf(message.content);
+ for (const tool of (message.tools as { arguments?: unknown }[] | undefined) ?? []) {
+ chars += charsOf(tool?.arguments);
+ }
+ for (const call of (message.tool_calls as { function?: { arguments?: unknown } }[] | undefined) ??
+ []) {
+ chars += charsOf(call?.function?.arguments);
+ }
+ return chars;
+};
const BROWSER = 'lobe-browser';
const WEB_BROWSING = 'lobe-web-browsing';
const MESSAGE = 'lobe-message';
@@ -271,7 +332,9 @@ const toEpochMs = (value: unknown): number | undefined => {
* warm cache (user followed up within the provider's cache TTL), the trim is
* a paid rewrite, so it only fires when the savings clear the warm
* thresholds. Trimming is truly free at cold boundaries β€” the first turn,
- * or any gap longer than the cache TTL.
+ * or any gap longer than the cache TTL. A trim an earlier turn accepted is
+ * kept by every later turn, warm or cold: the warm gate only decides whether
+ * to add new trims, never whether to undo old ones.
*
* Must run AFTER the flatten processors (assistantGroup / compressedGroup
* hoist nested tool results into top-level `role: 'tool'` rows with
@@ -310,6 +373,159 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
const messages = context.messages;
+ // Trims are sticky across turns. The processor is stateless β€” nothing about
+ // a trim is persisted β€” so the decision every earlier turn made is replayed
+ // here from its own boundary, oldest first. Once a turn accepted a trim, the
+ // provider cache holds the trimmed bytes, and every later turn must send the
+ // same bytes. Before this replay, a warm follow-up whose break-even check
+ // failed fell back to the untrimmed history: it meant to keep the warm
+ // prefix, but restored the full text of results the previous turn had
+ // trimmed and invalidated the cache from the first of them.
+ // A turn's decision only reads persisted history up to its own trigger, so
+ // the replay reproduces it exactly from the current history.
+ //
+ // Virtual tail user messages (`meta.virtualLastUser`, e.g. TodoInjector) are
+ // re-created at the end of the payload on every step and never persist, so
+ // they are not turn triggers: counting one would move the boundary on every
+ // step of a running operation.
+ const userIndexes = messages.flatMap((m, i) =>
+ m.role === 'user' && m.meta?.virtualLastUser !== true ? [i] : [],
+ );
+ const turnTriggers = userIndexes.length > 0 ? userIndexes : [-1];
+
+ const rawCharsPrefix = [0];
+ for (const m of messages) {
+ rawCharsPrefix.push(
+ rawCharsPrefix.at(-1)! +
+ payloadCharsOf(m) +
+ imageCountOf(m) * this.config.imageCharEquivalent,
+ );
+ }
+ const replay: ReplayIndex = {
+ closedToolChars: 0,
+ lastWriteIndexByPath: new Map(),
+ rawCharsPrefix,
+ readWindowsByPath: new Map(),
+ scanned: 0,
+ trimmedSavedByIndex: new Map(),
+ pending: new Map(),
+ untrimmedReadsByPath: new Map(),
+ };
+
+ const trimmed = new Map<number, TrimCandidate>();
+ let current: TurnPlan | undefined;
+ for (const lastUserIndex of turnTriggers) {
+ current = this.planTurn(messages, lastUserIndex, replay);
+ if (current.accepted.length === 0) continue;
+ for (const candidate of current.accepted) {
+ trimmed.set(candidate.index, candidate);
+ replay.pending.delete(candidate.index);
+ replay.trimmedSavedByIndex.set(
+ candidate.index,
+ this.savedCharsOf(messages[candidate.index], candidate),
+ );
+ }
+ // Only the accepted rows' own paths can hold them; scanning every path
+ // per turn would grow quadratically over a long history of distinct files.
+ const touchedPaths = new Set<string>();
+ for (const candidate of current.accepted) {
+ const m = messages[candidate.index];
+ const path = pathOf(m, getPlugin(m));
+ if (path) touchedPaths.add(path);
+ }
+ for (const path of touchedPaths) {
+ const reads = replay.untrimmedReadsByPath.get(path);
+ if (!reads) continue;
+ const remaining = reads.filter((read) => !trimmed.has(read.index));
+ if (remaining.length > 0) replay.untrimmedReadsByPath.set(path, remaining);
+ else replay.untrimmedReadsByPath.delete(path);
+ }
+ }
+
+ const carriedMessages = trimmed.size - (current?.accepted.length ?? 0);
+ if (trimmed.size === 0) {
+ if (!current?.skipped) return this.markAsExecuted(context);
+ const skipped = this.cloneContext(context);
+ skipped.metadata.staleToolResultTrim = current.skipped;
+ return this.markAsExecuted(skipped);
+ }
+
+ const clonedContext = this.cloneContext(context);
+ let savedChars = 0;
+ const byRule: Record<string, number> = {};
+
+ clonedContext.messages = clonedContext.messages.map((message, index) => {
+ const candidate = trimmed.get(index);
+ if (!candidate) return message;
+
+ savedChars += this.savedCharsOf(message, candidate);
+ byRule[candidate.rule] = (byRule[candidate.rule] ?? 0) + 1;
+ // A trimmed image read must not keep its attachments: MessageContentProcessor
+ // (later in the pipeline) would still turn pluginState.images into
+ // model-visible image_url parts, billing the stale image while the text
+ // claims the result was trimmed.
+ const pluginState = (message.pluginState as { images?: unknown } | undefined)?.images
+ ? { ...(message.pluginState as Record<string, unknown>), images: undefined }
+ : message.pluginState;
+ return { ...message, content: candidate.content, pluginState };
+ });
+
+ log(
+ 'Trimmed %d stale tool result(s) (%d carried from earlier turns), saved %d chars',
+ trimmed.size,
+ carriedMessages,
+ savedChars,
+ );
+
+ clonedContext.metadata.staleToolResultTrim = {
+ ...current?.skipped,
+ byRule,
+ cacheWarm: current?.skipped?.cacheWarm ?? current?.cacheWarm,
+ carriedMessages,
+ gapMs: current?.skipped?.gapMs ?? current?.gapMs,
+ savedChars,
+ trimmedMessages: trimmed.size,
+ };
+ return this.markAsExecuted(clonedContext);
+ }
+
+ private savedCharsOf(message: Message, candidate: TrimCandidate): number {
+ return (
+ (message.content as string).length -
+ candidate.content.length +
+ imageCountOf(message) * this.config.imageCharEquivalent
+ );
+ }
+
+ /** Re-derive whether the closed-history tool row at `index` is a trim candidate now. */
+ private refreshCandidate(messages: Message[], index: number, replay: ReplayIndex): void {
+ replay.pending.delete(index);
+ const message = messages[index];
+ if (typeof message.content !== 'string' || message.content.length === 0) return;
+ // Error results are the most valuable debugging context β€” never trim.
+ if (message.pluginError) return;
+
+ const replacement = this.trimMessage(
+ message,
+ index,
+ replay.lastWriteIndexByPath,
+ replay.readWindowsByPath,
+ );
+ if (replacement === undefined || replacement.content === message.content) return;
+ // Never admit a replacement that grows the payload β€” a result barely over
+ // the keep threshold would come back longer once the notice is appended.
+ // Image reads are exempt: the dropped attachment dwarfs any notice.
+ const hasImages =
+ ((message.pluginState as { images?: unknown[] } | undefined)?.images?.length ?? 0) > 0;
+ if (!hasImages && replacement.content.length >= message.content.length) return;
+ replay.pending.set(index, { content: replacement.content, index, rule: replacement.rule });
+ }
+
+ /**
+ * Decide which NEW trims the turn triggered by `messages[lastUserIndex]`
+ * accepts, given the trims earlier turns already applied (tracked in `replay`).
+ */
+ private planTurn(messages: Message[], lastUserIndex: number, replay: ReplayIndex): TurnPlan {
// Turn boundary: the last user message starts the in-flight turn. Every
// LLM step of a running operation re-assembles the payload and re-runs
// this pipeline, so the trim set must be FROZEN for the whole turn β€”
@@ -333,35 +549,29 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
//
// When no user message exists (tests, exotic flows), the recency window
// alone applies.
- const lastUserIndex = messages.reduce((acc, m, i) => (m.role === 'user' ? i : acc), -1);
+ const none: TurnPlan = { accepted: [] };
const boundary =
lastUserIndex >= 0
? Math.max(0, lastUserIndex + 1 - this.config.keepRecentMessages)
: Math.max(0, messages.length - this.config.keepRecentMessages);
- let closedToolChars = 0;
- for (let i = 0; i < boundary; i++) {
- const m = messages[i];
- if (m.role !== 'tool') continue;
- if (typeof m.content === 'string') closedToolChars += m.content.length;
- closedToolChars += imageCountOf(m) * this.config.imageCharEquivalent;
- }
- if (closedToolChars < this.config.minTotalToolChars) {
- return this.markAsExecuted(context);
- }
-
- // Pass 1 β€” index events inside the closed history that invalidate earlier
- // results:
+ // Pass 1 β€” extend the index of the closed history up to this boundary.
+ // Boundaries only move forward across turns, so each message is indexed
+ // once per request no matter how many turns are replayed:
+ // - tool chars for the minimum-size gate
// - writes per file path (any writeFile/editFile result row marks a write)
// - read windows per path, to find reads fully covered by a later re-read
// Failed results index nothing: a failed write did not supersede anything,
// a failed read covers nothing.
- const lastWriteIndexByPath = new Map<string, number>();
- const readWindowsByPath = new Map<string, { end: number; index: number; start: number }[]>();
-
- for (let index = 0; index < boundary; index++) {
+ const firstNew = replay.scanned;
+ // Earlier untrimmed reads whose candidacy the newly indexed events change.
+ const affected = new Set<number>();
+ for (let index = firstNew; index < boundary; index++) {
const m = messages[index];
if (m.role !== 'tool') continue;
+ if (typeof m.content === 'string') replay.closedToolChars += m.content.length;
+ replay.closedToolChars += imageCountOf(m) * this.config.imageCharEquivalent;
+
if (m.pluginError) continue;
const plugin = getPlugin(m);
if (plugin?.identifier !== LOCAL_SYSTEM) continue;
@@ -369,50 +579,74 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
const path = pathOf(m, plugin);
if (!path) continue;
+ const earlierReads = replay.untrimmedReadsByPath.get(path) ?? [];
if (WRITE_APIS.has(plugin.apiName ?? '')) {
- lastWriteIndexByPath.set(path, index);
+ replay.lastWriteIndexByPath.set(path, index);
+ // A write supersedes every earlier read of the path, even one already
+ // pending as covered by a re-read (the write rule takes precedence).
+ for (const read of earlierReads) {
+ if (replay.pending.get(read.index)?.rule !== 'readSupersededByWrite') {
+ affected.add(read.index);
+ }
+ }
} else if (READ_APIS.has(plugin.apiName ?? '')) {
const loc = effectiveReadWindow(m, plugin);
- const windows = readWindowsByPath.get(path) ?? [];
- windows.push({ end: loc[1], index, start: loc[0] });
- readWindowsByPath.set(path, windows);
+ const window = { end: loc[1], index, start: loc[0] };
+ const windows = replay.readWindowsByPath.get(path) ?? [];
+ windows.push(window);
+ replay.readWindowsByPath.set(path, windows);
+ // A re-read only changes the earlier reads it fully covers; one that is
+ // already pending stays superseded either way.
+ for (const read of earlierReads) {
+ if (
+ !replay.pending.has(read.index) &&
+ window.start <= read.start &&
+ window.end >= read.end
+ ) {
+ affected.add(read.index);
+ }
+ }
+ earlierReads.push(window);
+ replay.untrimmedReadsByPath.set(path, earlierReads);
}
}
-
- // Pass 2 β€” collect trim candidates (dry run first; the cache-warmth gate
- // below needs the total savings before deciding).
- const candidates: { content: string; index: number; rule: string }[] = [];
- for (let index = 0; index < boundary; index++) {
- const message = messages[index];
- if (message.role !== 'tool') continue;
- if (typeof message.content !== 'string' || message.content.length === 0) continue;
- // Error results are the most valuable debugging context β€” never trim.
- if (message.pluginError) continue;
-
- const trimmed = this.trimMessage(message, index, lastWriteIndexByPath, readWindowsByPath);
- if (trimmed === undefined || trimmed.content === message.content) continue;
- // Never admit a replacement that grows the payload β€” a result barely over
- // the keep threshold would come back longer once the notice is appended.
- // Image reads are exempt: the dropped attachment dwarfs any notice.
- const hasImages =
- ((message.pluginState as { images?: unknown[] } | undefined)?.images?.length ?? 0) > 0;
- if (!hasImages && trimmed.content.length >= message.content.length) continue;
- candidates.push({ content: trimmed.content, index, rule: trimmed.rule });
+ replay.scanned = Math.max(replay.scanned, boundary);
+
+ // Pass 2 β€” keep the pending candidate set current (dry run; the
+ // cache-warmth gate below needs the total savings before deciding).
+ // A row's candidacy only changes when it enters the closed history, or β€”
+ // for a readFile β€” when a later write or covering re-read of the same path
+ // does, so only those rows are re-derived. Rows an earlier turn trimmed
+ // are gone from the pending set and keep that turn's replacement, so the
+ // placeholder stays byte-identical even when a later event would now pick
+ // a different rule for it.
+ for (const index of affected) {
+ if (index < firstNew) this.refreshCandidate(messages, index, replay);
}
-
- if (candidates.length === 0) {
- return this.markAsExecuted(context);
+ for (let index = firstNew; index < boundary; index++) {
+ if (messages[index].role === 'tool') this.refreshCandidate(messages, index, replay);
}
+ if (replay.closedToolChars < this.config.minTotalToolChars) return none;
+
+ const candidates = [...replay.pending.values()];
+
+ if (candidates.length === 0) return none;
+
// Cache-warmth gate. Trimming is free only when the prompt cache is cold β€”
// i.e. the gap between the previous turn's last activity and this turn's
// trigger exceeds the provider's cache TTL (Anthropic: 5 min, refreshed
- // per hit). When the user follows up within the TTL, the untrimmed prefix
- // would still hit, so the trim must clear a break-even check against the
- // rewrite it causes:
+ // per hit). When the user follows up within the TTL, the cached prefix
+ // (with earlier turns' trims applied) would still hit, so the new trims
+ // must clear a break-even check against the rewrite they cause:
//
// gain = R_est Γ— S Γ— readPrice (each remaining step reads S less)
- // cost = ((P βˆ’ S) Γ— writePrice βˆ’ P Γ— readPrice) Γ— margin
+ // cost = ((Q βˆ’ S) Γ— writePrice βˆ’ Q Γ— readPrice) Γ— margin
+ //
+ // Q is the span the trims rewrite: from the first new candidate up to the
+ // trigger, with earlier turns' trims applied (that is what the cache
+ // holds). The prefix before it stays cached, and the trigger and everything
+ // after it are written in either case.
//
// Thanks to determinism the rewrite is paid at most once per trim-set
// change, not per follow-up β€” but a warm quick-question turn (1-5 steps)
@@ -423,11 +657,7 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
// A trimmed result also loses its images (pass 3), which is most of the saving for an
// image read.
const potentialSavedChars = candidates.reduce(
- (s, c) =>
- s +
- (messages[c.index].content as string).length -
- c.content.length +
- imageCountOf(messages[c.index]) * this.config.imageCharEquivalent,
+ (s, c) => s + this.savedCharsOf(messages[c.index], c),
0,
);
const triggeredAt = toEpochMs(messages[lastUserIndex]?.createdAt);
@@ -439,19 +669,25 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
const cacheWarm = gapMs !== undefined && gapMs <= this.config.cacheTtlMs;
if (cacheWarm) {
- // The cost side of the break-even must be priced from the payload frozen
- // at the turn boundary (closed history + the trigger), not the live
- // message list: candidates and savings are already frozen there, and
- // counting in-flight output would grow the estimated rewrite cost
- // step by step, flipping a trim that passed the gate back to a skip
- // mid-operation and restoring the original prefix.
- const payloadEnd = lastUserIndex >= 0 ? lastUserIndex + 1 : messages.length;
- let totalChars = 0;
- for (let i = 0; i < payloadEnd; i++) {
- const m = messages[i];
- if (typeof m.content === 'string') totalChars += m.content.length;
- totalChars += imageCountOf(m) * this.config.imageCharEquivalent;
+ // Q only covers persisted history strictly between the first candidate
+ // and the trigger, so later turns replaying this decision price exactly
+ // the same bytes. Send-time context never lands there: injectors write
+ // into the head (system prompt, document index), the trigger itself
+ // (e.g. an active-document snapshot appended to the last user message),
+ // or after it. Pricing the whole payload let a large one-turn injection
+ // skip a trim that the next turn's replay, no longer seeing it, accepted β€”
+ // trimming bytes the cache still held in full. The span is also frozen at
+ // the turn boundary, so in-flight output cannot flip the decision
+ // mid-operation.
+ const firstCandidate = Math.min(...candidates.map((c) => c.index));
+ let trimmedInSpan = 0;
+ for (const [index, saved] of replay.trimmedSavedByIndex) {
+ if (index >= firstCandidate && index < lastUserIndex) trimmedInSpan += saved;
}
+ const totalChars =
+ replay.rawCharsPrefix[lastUserIndex] -
+ replay.rawCharsPrefix[firstCandidate] -
+ trimmedInSpan;
const gainEstimate =
this.config.warmRemainingStepsEstimate * potentialSavedChars * this.config.cacheReadPrice;
const rewriteCostEstimate =
@@ -460,67 +696,30 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
const worthwhile = gainEstimate > rewriteCostEstimate * this.config.warmSafetyMargin;
if (!worthwhile) {
log(
- 'Skipping trim: cache warm (gap <= %dms), gain %d <= cost %d Γ— %d',
+ 'Skipping new trims: cache warm (gap <= %dms), gain %d <= cost %d Γ— %d',
this.config.cacheTtlMs,
gainEstimate,
rewriteCostEstimate,
this.config.warmSafetyMargin,
);
- const skipped = this.cloneContext(context);
- skipped.metadata.staleToolResultTrim = {
- byRule: {},
- cacheWarm,
- gapMs,
- gainEstimate,
- potentialSavedChars,
- rewriteCostEstimate,
- savedChars: 0,
- skippedReason: 'warm-cache',
- trimmedMessages: 0,
+ return {
+ accepted: [],
+ skipped: {
+ byRule: {},
+ cacheWarm,
+ gapMs,
+ gainEstimate,
+ potentialSavedChars,
+ rewriteCostEstimate,
+ savedChars: 0,
+ skippedReason: 'warm-cache',
+ trimmedMessages: 0,
+ },
};
- return this.markAsExecuted(skipped);
}
}
- // Pass 3 β€” apply
- const clonedContext = this.cloneContext(context);
- let savedChars = 0;
- const byRule: Record<string, number> = {};
- const candidateByIndex = new Map(candidates.map((c) => [c.index, c]));
-
- clonedContext.messages = clonedContext.messages.map((message, index) => {
- const candidate = candidateByIndex.get(index);
- if (!candidate) return message;
-
- savedChars +=
- (message.content as string).length -
- candidate.content.length +
- imageCountOf(message) * this.config.imageCharEquivalent;
- byRule[candidate.rule] = (byRule[candidate.rule] ?? 0) + 1;
- // A trimmed image read must not keep its attachments: MessageContentProcessor
- // (later in the pipeline) would still turn pluginState.images into
- // model-visible image_url parts, billing the stale image while the text
- // claims the result was trimmed.
- const pluginState = (message.pluginState as { images?: unknown } | undefined)?.images
- ? { ...(message.pluginState as Record<string, unknown>), images: undefined }
- : message.pluginState;
- return { ...message, content: candidate.content, pluginState };
- });
-
- const trimmedMessages = candidates.length;
-
- if (trimmedMessages > 0) {
- log('Trimmed %d stale tool result(s), saved %d chars', trimmedMessages, savedChars);
- }
-
- clonedContext.metadata.staleToolResultTrim = {
- byRule,
- cacheWarm,
- gapMs,
- savedChars,
- trimmedMessages,
- };
- return this.markAsExecuted(clonedContext);
+ return { accepted: candidates, cacheWarm, gapMs };
}
/** Returns the replacement, or undefined when the message must stay untouched. */
diff --git a/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts b/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts
index 32770594fa1..88d0009b798 100644
--- a/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts
+++ b/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import type { PipelineContext } from '../../types';
import { cacheEconomicsForProvider, StaleToolResultTrimProcessor } from '../StaleToolResultTrim';
@@ -409,9 +409,12 @@ describe('StaleToolResultTrimProcessor', () => {
// the recency tail (keepRecentMessages=3 in createProcessor), so the stale
// read is a trim candidate; the last two entries fix the turn-boundary
// timestamps the warmth gate reads.
- const turnMessages = (staleChars: number, gapMs: number) => [
+ const turnMessages = (staleChars: number, gapMs: number, liveChars = 0) => [
readFileResult('/a.ts', 'x'.repeat(staleChars), [0, 200]),
writeFileResult('/a.ts'),
+ ...(liveChars > 0
+ ? [{ content: 'z'.repeat(liveChars), id: 'big-live-doc', role: 'assistant' }]
+ : []),
{ content: 'filler 1', id: 'f1', role: 'assistant' },
{ content: 'filler 2', id: 'f2', role: 'assistant' },
{ content: 'filler 3', id: 'f3', role: 'assistant' },
@@ -439,16 +442,13 @@ describe('StaleToolResultTrimProcessor', () => {
});
it('skips the trim on a warm follow-up when savings are small relative to the payload', async () => {
- // Large live payload (untrimmed) + small stale read: the rewrite of ~500k
- // chars at write price dwarfs 20 estimated steps of 5k-char savings.
+ // Large live payload after the stale read + small saving: rewriting the
+ // ~500k chars behind it at write price dwarfs 20 steps of 5k-char savings.
const result = await createProcessor().process(
- createContext([
- { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },
- ...turnMessages(5000, 1 * MIN),
- ]),
+ createContext(turnMessages(5000, 1 * MIN, 500_000)),
);
- expect(result.messages[1].content).toBe('x'.repeat(5000));
+ expect(result.messages[0].content).toBe('x'.repeat(5000));
expect(result.metadata.staleToolResultTrim).toMatchObject({
cacheWarm: true,
gapMs: 60_000,
@@ -476,9 +476,9 @@ describe('StaleToolResultTrimProcessor', () => {
// disable the warmth gate (always "cold").
it('reads numeric epoch-ms timestamps for the warmth check', async () => {
const messages = [
- { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },
readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
writeFileResult('/a.ts'),
+ { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },
{ content: 'filler', id: 'f1', role: 'assistant' },
{ content: 'filler', id: 'f2', role: 'assistant' },
{ content: 'filler', id: 'f3', role: 'assistant' },
@@ -555,6 +555,169 @@ describe('StaleToolResultTrimProcessor', () => {
});
});
+ // Regression: a cold turn trimmed old results and the cache stored
+ // the trimmed bytes; the next warm follow-up failed the break-even for its
+ // new candidates and fell back to the untrimmed history, restoring the full
+ // text and invalidating the cache from the first restored result.
+ describe('sticky trims across turns', () => {
+ const T0 = Date.parse('2026-09-20T08:00:00Z');
+ const MIN = 60_000;
+ const at = (ms: number) => new Date(ms).toISOString();
+ const fillers = (prefix: string) =>
+ Array.from({ length: 3 }, (_, i) => ({
+ content: `${prefix} filler ${i}`,
+ id: `${prefix}-f${i}`,
+ role: 'assistant',
+ }));
+
+ it('keeps an earlier turn’s trims on a warm follow-up that skips new trims', async () => {
+ const messages = [
+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
+ writeFileResult('/a.ts'),
+ ...fillers('t1'),
+ previousTurnMessage(at(T0)),
+ // Turn 1 starts after a cold gap, so its trim of /a.ts is free.
+ { content: 'turn 1', createdAt: at(T0 + 10 * MIN), id: 'u1', role: 'user' },
+ ...fillers('t1-run'),
+ readFileResult('/b.ts', 'y'.repeat(5000), [0, 200]),
+ writeFileResult('/b.ts'),
+ { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },
+ ...fillers('t2'),
+ { content: 'turn 1 done', createdAt: at(T0 + 20 * MIN), id: 'done1', role: 'assistant' },
+ // Turn 2 follows within the TTL; trimming /b.ts would not pay for the rewrite.
+ { content: 'turn 2', createdAt: at(T0 + 21 * MIN), id: 'u2', role: 'user' },
+ ...recencyPadding(3),
+ ];
+
+ const result = await createProcessor().process(createContext(messages));
+
+ expect(result.messages[0].content).toContain('superseded by a later write');
+ expect(result.messages.find((m) => m.content === 'y'.repeat(5000))).toBeDefined();
+ expect(result.metadata.staleToolResultTrim).toMatchObject({
+ cacheWarm: true,
+ carriedMessages: 1,
+ skippedReason: 'warm-cache',
+ trimmedMessages: 1,
+ });
+ });
+
+ it('keeps the placeholder an earlier turn chose when a later event matches another rule', async () => {
+ const messages = [
+ readFileResult('/c.ts', 'x'.repeat(5000), [0, 200]),
+ readFileResult('/c.ts', 'x'.repeat(5000), [0, 200]),
+ ...fillers('t1'),
+ previousTurnMessage(at(T0)),
+ { content: 'turn 1', createdAt: at(T0 + 10 * MIN), id: 'u1', role: 'user' },
+ // Turn 1 writes the file: by turn 2 the first read also counts as superseded by a write.
+ writeFileResult('/c.ts'),
+ ...fillers('t2'),
+ { content: 'turn 1 done', createdAt: at(T0 + 20 * MIN), id: 'done1', role: 'assistant' },
+ { content: 'turn 2', createdAt: at(T0 + 30 * MIN), id: 'u2', role: 'user' },
+ ...recencyPadding(3),
+ ];
+
+ const result = await createProcessor().process(createContext(messages));
+
+ expect(result.messages[0].content).toBe(
+ '[readFile result trimmed: /c.ts (lines 0-200) β€” the same range was read again later. Refer to the newer read, or call readFile again if needed.]',
+ );
+ });
+
+ // Regression: the warm gate priced the whole payload, including context
+ // injected into the trigger only for that request (an active-document
+ // snapshot). The next turn's replay no longer saw the injection, so it
+ // reached a different verdict than the turn itself had.
+ it('reaches the same warm-gate verdict when the turn is replayed without its send-time injection', async () => {
+ const history = [
+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
+ writeFileResult('/a.ts'),
+ ...fillers('t1'),
+ previousTurnMessage(at(T0)),
+ ];
+ const turn1 = (content: string) => ({
+ content,
+ createdAt: at(T0 + MIN),
+ id: 'u1',
+ role: 'user',
+ });
+
+ const sentInTurn1 = await createProcessor().process(
+ createContext([
+ ...history,
+ turn1(`turn 1\n\n<active_topic_document>${'d'.repeat(500_000)}</active_topic_document>`),
+ ...recencyPadding(3),
+ ]),
+ );
+ const replayedInTurn2 = await createProcessor().process(
+ createContext([
+ ...history,
+ turn1('turn 1'),
+ ...fillers('t1-run'),
+ { content: 'turn 1 done', createdAt: at(T0 + 2 * MIN), id: 'done1', role: 'assistant' },
+ { content: 'turn 2', createdAt: at(T0 + 3 * MIN), id: 'u2', role: 'user' },
+ ...recencyPadding(3),
+ ]),
+ );
+
+ expect(sentInTurn1.messages[0].content).toContain('superseded by a later write');
+ expect(replayedInTurn2.messages[0].content).toBe(sentInTurn1.messages[0].content);
+ });
+
+ // Regression: the rewrite was priced on string content only, so a large
+ // tool-call argument behind the candidate (a 500k-char writeFile) did not
+ // count, and the gate accepted a rewrite that could never pay back.
+ it('prices tool-call arguments behind the candidate in the warm gate', async () => {
+ const messages = [
+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
+ {
+ content: '',
+ id: 'big-write-call',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'writeFile',
+ arguments: JSON.stringify({ content: 'w'.repeat(500_000), path: '/a.ts' }),
+ id: 'call-w',
+ identifier: 'lobe-local-system',
+ },
+ ],
+ },
+ writeFileResult('/a.ts'),
+ ...fillers('t1'),
+ previousTurnMessage(at(T0)),
+ { content: 'turn 1', createdAt: at(T0 + MIN), id: 'u1', role: 'user' },
+ ...recencyPadding(3),
+ ];
+
+ const result = await createProcessor().process(createContext(messages));
+
+ expect(result.messages[0].content).toBe('x'.repeat(5000));
+ expect(result.metadata.staleToolResultTrim?.skippedReason).toBe('warm-cache');
+ });
+
+ // Regression: a virtual tail user message (TodoInjector and friends) is
+ // re-created at the end of every step; treating it as the turn trigger
+ // moved the boundary mid-operation and trimmed the in-flight turn.
+ it('ignores virtual tail user messages when locating the turn boundary', async () => {
+ const messages = [
+ { content: 'turn 1', id: 'u1', role: 'user' },
+ readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
+ writeFileResult('/a.ts'),
+ ...fillers('t1-run'),
+ {
+ content: '<todos>…</todos>',
+ id: 'virtual-last-user-TodoInjector',
+ meta: { injectType: 'TodoInjector', virtualLastUser: true },
+ role: 'user',
+ },
+ ];
+
+ const result = await createProcessor().process(createContext(messages));
+
+ expect(result.messages[1].content).toBe('x'.repeat(5000));
+ });
+ });
+
describe('invalidation index hygiene', () => {
// Regression (Codex P2): a FAILED write must not supersede a good read.
it('ignores failed writes when superseding reads', async () => {
@@ -645,6 +808,33 @@ describe('StaleToolResultTrimProcessor', () => {
expect(result.messages[0].content).toBe('p'.repeat(101));
expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);
});
+
+ // Regression: after each accepting turn the replay pruned trimmed reads
+ // from every path it had ever seen, so a long history of distinct files
+ // cost O(turnsΒ²) per request.
+ it('prunes trimmed reads only from the accepted rows’ paths', async () => {
+ const turns = 60;
+ const messages = Array.from({ length: turns }, (_, i) => [
+ { content: `turn ${i}`, id: `user-${i}`, role: 'user' },
+ readFileResult(`/f${i}.ts`, 'x'.repeat(5000)),
+ writeFileResult(`/f${i}.ts`),
+ ]).flat();
+ messages.push(...recencyPadding(3), { content: 'last', id: 'user-last', role: 'user' });
+
+ const filter = vi.spyOn(Array.prototype, 'filter');
+ let result;
+ let filterCalls: number;
+ try {
+ result = await createProcessor().process(createContext(messages));
+ } finally {
+ // mockRestore clears the recorded calls, so read the count first.
+ filterCalls = filter.mock.calls.length;
+ filter.mockRestore();
+ }
+
+ expect(result.metadata.staleToolResultTrim?.trimmedMessages).toBe(turns);
+ expect(filterCalls).toBeLessThanOrEqual(turns * 2);
+ });
});
describe('cacheEconomicsForProvider', () => {
@@ -659,9 +849,9 @@ describe('StaleToolResultTrimProcessor', () => {
// DeepSeek's hour-long disk cache.
const T0 = Date.parse('2026-09-20T08:00:00Z');
const messages = [
- { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },
readFileResult('/a.ts', 'x'.repeat(5000), [0, 200]),
writeFileResult('/a.ts'),
+ { content: 'z'.repeat(500_000), id: 'big-live-doc', role: 'assistant' },
{ content: 'filler', id: 'f1', role: 'assistant' },
{ content: 'filler', id: 'f2', role: 'assistant' },
{ content: 'filler', id: 'f3', role: 'assistant' },