ai-compaction: checkpoint is never reused when an earlier middleware sets `providerMessages` (every harness handoff agent) #2318 (GitHub #2317)
Versions: @tanstack/ai 1.10.1, @tanstack/ai-compaction 1.1.0, @tanstack/ai-harness 0.6.1
What happens#
For an agent the harness hands a conversation to, withCompaction (non-durable, countTokens: "usage") summarizes the whole conversation again before every model call once it passes maxTokens. Every compaction:ended reports reusedCheckpoint: false. In one production-like run that was 16 summaries in a row, ~30s each.
Why#
onConfigonly reads or writes its checkpoint whenconfig.providerMessages === config.messages(inputMessages === messages).- The harness runs
harness:routed-history(andharness:media, plus any plugin agent middleware that rewrites attachments) before the agent's own middleware. Routed history returns a newproviderMessagesarray whenever it folds another speaker's message, which after a handoff is always. - So the checkpoint is never saved, and the next call has nothing to reuse.
- Compounding it:
onUsagesaves usage markedcompacted: true, andcountFromUsagerejects compacted usage unless the checkpoint was reused. Sobeforefalls back to estimating the full stored transcript, which stays over the limit, and compaction triggers again. - Separately,
onUsagerecords coverage againstctx.messageswhileonConfigworks onproviderMessages. Once routed history changes the message count, the usage count never matches the view.
Minimal runnable reproduction#
Zero API keys required — uses a mock TextAdapter with a 3-iteration tool loop and a middleware before withCompaction that sets providerMessages (simulating harness:routed-history):
import { chat, toolDefinition } from "@tanstack/ai";
import { withCompaction } from "@tanstack/ai-compaction";
import { z } from "zod";
let modelCalls = 0;
let strategyCalls = 0;
const ping = toolDefinition({
name: "ping",
description: "ping",
inputSchema: z.object({ n: z.number() }),
}).server(({ n }) => ({ ok: n }));
const adapter = {
kind: "text",
name: "mock",
model: "mock-model",
async *chatStream() {
modelCalls += 1;
const id = `run-${modelCalls}`;
yield { type: "RUN_STARTED", runId: id, model: "mock-model", timestamp: Date.now() };
if (modelCalls <= 3) {
yield { type: "TOOL_CALL_START", toolCallId: `tc-${modelCalls}`, toolCallName: "ping", timestamp: Date.now() };
yield { type: "TOOL_CALL_ARGS", toolCallId: `tc-${modelCalls}`, delta: JSON.stringify({ n: modelCalls }), timestamp: Date.now() };
yield { type: "TOOL_CALL_END", toolCallId: `tc-${modelCalls}`, toolCallName: "ping", input: { n: modelCalls }, timestamp: Date.now() };
yield {
type: "RUN_FINISHED",
runId: id,
model: "mock-model",
finishReason: "tool_calls",
usage: { promptTokens: 500, completionTokens: 20, totalTokens: 520 },
timestamp: Date.now(),
};
} else {
yield { type: "TEXT_MESSAGE_START", messageId: "m-final", role: "assistant", timestamp: Date.now() };
yield { type: "TEXT_MESSAGE_CONTENT", messageId: "m-final", delta: "done", timestamp: Date.now() };
yield { type: "TEXT_MESSAGE_END", messageId: "m-final", timestamp: Date.now() };
yield {
type: "RUN_FINISHED",
runId: id,
model: "mock-model",
finishReason: "stop",
usage: { promptTokens: 500, completionTokens: 10, totalTokens: 510 },
timestamp: Date.now(),
};
}
},
};
// Simulates harness:routed-history (or any middleware that sets providerMessages before withCompaction)
const routedHistory = {
name: "routed-history",
onConfig(_ctx, config) {
return {
providerMessages: [
{ role: "user", content: "[Earlier speaker] " + "x".repeat(600) },
...config.messages,
],
};
},
};
const compaction = withCompaction({
maxTokens: 100,
countTokens: "usage",
strategy: async (messages) => {
strategyCalls += 1;
return [{ role: "user", content: `Summary #${strategyCalls}` }, ...messages.slice(-1)];
},
});
await chat({
adapter,
stream: false,
threadId: "repro-thread",
tools: [ping],
middleware: [routedHistory, compaction],
messages: [{ role: "user", content: "Start " + "y".repeat(600) }],
});
console.log({ modelCalls, strategyCalls });
// Actual: { modelCalls: 4, strategyCalls: 4 } (compacts on every model call)
// Expected: { modelCalls: 4, strategyCalls: 1 } (reuses checkpoint after first compaction)
Suggested fix#
Checkpoint (hash, save, reuse) the view compaction actually works on (providerMessages ?? messages), and have onUsage record coverage against that same view (for example, kept per ctx from onConfig). Durable mode needs its records keyed to stored messages, so this probably applies to the checkpoint path only.
Our workaround#
For non-durable compaction, we wrap the middleware so onConfig receives { ...config, messages: view, providerMessages: view }, where view = config.providerMessages ?? config.messages, and return only providerMessages.
tanstack-source added labelsbug
Sign in to join this conversation.