Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(agent): size agent history by the window and calibrate token estimates (#3413)

lyingbug03d9d66a1ff9
diff --git a/config/builtin_agents.yaml b/config/builtin_agents.yaml
index 7f8cb94b3..fcea12421 100644
--- a/config/builtin_agents.yaml
+++ b/config/builtin_agents.yaml
@@ -83,7 +83,6 @@ builtin_agents:
web_search_max_results: 5
reflection_enabled: false
multi_turn_enabled: true
- history_turns: 5
faq_priority_enabled: true
faq_direct_answer_threshold: 0.9
faq_score_boost: 1.2
@@ -131,7 +130,6 @@ builtin_agents:
web_search_max_results: 0
reflection_enabled: true
multi_turn_enabled: true
- history_turns: 10
embedding_top_k: 5
keyword_threshold: 0.3
vector_threshold: 0.5
@@ -175,7 +173,6 @@ builtin_agents:
web_search_max_results: 0
reflection_enabled: false
multi_turn_enabled: true
- history_turns: 10
embedding_top_k: 10
keyword_threshold: 0.3
vector_threshold: 0.5
@@ -225,7 +222,6 @@ builtin_agents:
web_search_max_results: 0
reflection_enabled: false
multi_turn_enabled: true
- history_turns: 10
embedding_top_k: 10
keyword_threshold: 0.3
vector_threshold: 0.5
@@ -273,5 +269,4 @@ builtin_agents:
web_search_max_results: 0
reflection_enabled: false
multi_turn_enabled: true
- history_turns: 10
diff --git a/docs/docs.go b/docs/docs.go
index 3d44c3ad9..d065481a6 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -18994,7 +18994,7 @@ const docTemplate = `{
"type": "number"
},
"history_turns": {
- "description": "Number of history turns to keep in context",
+ "description": "Number of history turns to keep in context. Quick-answer only; smart-reasoning sizes history by context window",
"type": "integer"
},
"image_storage_provider": {
@@ -23016,6 +23016,10 @@ const docTemplate = `{
"completion_tokens": {
"type": "integer"
},
+ "context_token_scale": {
+ "description": "ContextTokenScale is provider prompt tokens per cl100k-estimated token,\nmeasured over the turn's rounds. Persisted with the turn so the next\nturn's history loading and first compaction check are calibrated before\nany provider count of their own. Zero when the turn measured none.",
+ "type": "number"
+ },
"prompt_tokens": {
"type": "integer"
},
diff --git a/docs/swagger.json b/docs/swagger.json
index be512fe83..c28e8c2f4 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -18987,7 +18987,7 @@
"type": "number"
},
"history_turns": {
- "description": "Number of history turns to keep in context",
+ "description": "Number of history turns to keep in context. Quick-answer only; smart-reasoning sizes history by context window",
"type": "integer"
},
"image_storage_provider": {
@@ -23009,6 +23009,10 @@
"completion_tokens": {
"type": "integer"
},
+ "context_token_scale": {
+ "description": "ContextTokenScale is provider prompt tokens per cl100k-estimated token,\nmeasured over the turn's rounds. Persisted with the turn so the next\nturn's history loading and first compaction check are calibrated before\nany provider count of their own. Zero when the turn measured none.",
+ "type": "number"
+ },
"prompt_tokens": {
"type": "integer"
},
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index 2debbc4fe..473275dfb 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -888,7 +888,7 @@ definitions:
this factor
type: number
history_turns:
- description: Number of history turns to keep in context
+ description: Number of history turns to keep in context. Quick-answer only; smart-reasoning sizes history by context window
type: integer
image_storage_provider:
description: |-
@@ -4086,6 +4086,13 @@ definitions:
type: integer
completion_tokens:
type: integer
+ context_token_scale:
+ description: |-
+ ContextTokenScale is provider prompt tokens per cl100k-estimated token,
+ measured over the turn's rounds. Persisted with the turn so the next
+ turn's history loading and first compaction check are calibrated before
+ any provider count of their own. Zero when the turn measured none.
+ type: number
prompt_tokens:
type: integer
total_tokens:
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 44fb0afc2..6a6e47cee 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -6150,7 +6150,7 @@ export default {
maxTokensAgent: 'Maximum tokens generated in each reasoning round, including tool-call JSON. Default is 4096 without a sandbox, or 24576 when a sandbox can write or edit files. A custom value is saved as entered and is not changed later.',
thinking: 'Enable extended thinking capability (requires model support)',
conversationSection: 'Configure multi-turn conversation and query rewriting parameters',
- conversationSectionAgent: 'How much earlier conversation each turn carries. Smart reasoning is always multi-turn',
+ conversationSectionAgent: 'Smart reasoning is always multi-turn. Earlier conversation is kept up to the model context window, and older turns are summarized automatically once it fills',
multiTurn: 'When enabled, historical conversation context will be preserved',
historyRounds: 'Number of recent conversation rounds to keep as context',
retainRetrievalHistory: 'Keep knowledge base results from earlier turns. When off, each turn searches again',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index 12d7aecf6..93b2532d8 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -6150,7 +6150,7 @@ export default {
maxTokensAgent: '推論の各ラウンドで生成される最大トークン数(ツール呼び出しのJSONを含む)。デフォルトは、サンドボックスなしの場合4096、サンドボックスがファイルの書き込みや編集を行える場合は24576です。カスタム値は入力したとおりに保存され、以降変更されません。',
thinking: '拡張思考機能を有効にします(モデルの対応が必要)',
conversationSection: 'マルチターン会話とクエリのリライトに関するパラメータを設定します',
- conversationSectionAgent: '各ターンで引き継ぐ過去の会話の量。スマート推論は常にマルチターンです',
+ conversationSectionAgent: 'スマート推論は常にマルチターンです。過去の会話はモデルのコンテキストウィンドウに収まる範囲で保持され、超えると古い部分が自動的に要約されます',
multiTurn: '有効にすると、過去の会話のコンテキストが保持されます',
historyRounds: 'コンテキストとして保持する直近の会話ラウンド数',
retainRetrievalHistory: '過去のターンのナレッジベース検索結果を保持します。無効にすると、ターンごとに再検索します',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 7ab5e03fe..8b839f09f 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -1378,7 +1378,7 @@ export default {
maxTokensAgent: '각 추론 라운드에서 생성할 최대 토큰 수(도구 호출 JSON 포함). 「기본값」은 샌드박스 없으면 4096, 파일 쓰기/편집이 가능하면 24576입니다. 「사용자 지정」은 입력한 값을 그대로 저장합니다.',
thinking: '모델의 확장 사고 기능 활성화 (모델 지원 필요)',
conversationSection: '다중 턴 대화 및 질문 재작성 관련 매개변수 설정',
- conversationSectionAgent: '매 턴에 실어 보낼 이전 대화 분량 설정 (스마트 추론은 항상 다중 턴)',
+ conversationSectionAgent: '스마트 추론은 항상 다중 턴입니다. 이전 대화는 모델의 컨텍스트 창 범위까지 유지되며, 초과하면 오래된 내용이 자동으로 요약됩니다',
multiTurn: '활성화하면 대화 기록 컨텍스트가 유지됩니다',
historyRounds: '컨텍스트로 유지할 최근 대화 라운드 수',
retainRetrievalHistory: '이전 턴의 지식베이스 검색 결과를 유지합니다. 끄면 매 턴 새로 검색합니다',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index b37e6a511..31be03720 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -1378,7 +1378,7 @@ export default {
maxTokensAgent: 'Максимум токенов за один раунд рассуждения, включая JSON вызовов инструментов. «По умолчанию»: 4096 без песочницы, 24576 с записью/правкой файлов. «Своё» сохраняет введённое число и больше не меняется.',
thinking: 'Включить расширенное мышление модели (требуется поддержка модели)',
conversationSection: 'Настройка параметров многооборотного диалога и перефразирования вопросов',
- conversationSectionAgent: 'Объём предыдущего диалога в каждом ходе. Умные рассуждения всегда многооборотные',
+ conversationSectionAgent: 'Умные рассуждения всегда многооборотные. Предыдущий диалог хранится в пределах контекстного окна модели, а при его заполнении ранние ходы автоматически сжимаются в сводку',
multiTurn: 'При включении сохраняется контекст истории диалога',
historyRounds: 'Количество последних раундов диалога для сохранения в контексте',
retainRetrievalHistory: 'Сохранять результаты поиска из прошлых ходов. При отключении каждый ход ищет заново',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index a7ec1bfce..51f2f1821 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -1380,7 +1380,7 @@ export default {
maxTokensAgent: '每一轮推理的最大生成 Token(含工具调用 JSON)。选「默认」时,未绑沙箱为 4096,绑了沙箱(可写/改文件)为 24576。选「自定义」后按你填的数保存,不再自动改。',
thinking: '启用模型的扩展思考能力(需要模型支持)',
conversationSection: '配置多轮对话开关与问题改写开关(改写提示词见「提示词」)',
- conversationSectionAgent: '配置每轮携带多少历史对话。智能推理始终为多轮模式。',
+ conversationSectionAgent: '智能推理始终为多轮模式:按模型上下文窗口保留历史对话,超出时自动把较早的内容压缩成摘要。',
multiTurn: '开启后将保留历史对话上下文',
historyRounds: '保留最近几轮对话作为上下文',
retainRetrievalHistory: '保留此前轮次的知识库检索结果。关闭时每轮重新检索',
diff --git a/frontend/src/views/agent/AgentEditorModal.test.mjs b/frontend/src/views/agent/AgentEditorModal.test.mjs
index 3f55589eb..e63fcf424 100644
--- a/frontend/src/views/agent/AgentEditorModal.test.mjs
+++ b/frontend/src/views/agent/AgentEditorModal.test.mjs
@@ -50,8 +50,8 @@ function settingRowGuard(labelKey) {
}
test('conversation settings stay reachable in smart-reasoning mode', () => {
- // The agent path reads history_turns (session_agent_qa.go -> LoadAgentHistory),
- // so the section must not be gated on the running mode.
+ // Agent mode keeps the section: it explains that history follows the context
+ // window and hosts retain_retrieval_history, so it must not be gated on mode.
assert.match(source, /v-show="currentSection === 'conversation'"/)
assert.doesNotMatch(source, /currentSection === 'conversation' && !isAgentMode/)
@@ -66,12 +66,12 @@ test('conversation settings stay reachable in smart-reasoning mode', () => {
assert.doesNotMatch(modeWatch, /conversation/)
})
-test('history turns is editable in smart-reasoning mode', () => {
- // A new agent defaults to smart-reasoning with multi_turn_enabled=false in the
- // form, while the server forces multi-turn on. Gating the input on the local
- // switch alone would hide it exactly where it is needed.
+test('history turns stays hidden in smart-reasoning mode', () => {
+ // The agent path sizes history by the context window and never reads
+ // history_turns (session_agent_qa.go -> LoadAgentHistory), so an input there
+ // would change nothing. KnowledgeQA still caps its history by it.
const guard = settingRowGuard('agent.editor.historyTurns')
- assert.match(guard, /formData\.config\.multi_turn_enabled \|\| isAgentMode/)
+ assert.match(guard, /v-if="!isAgentMode && formData\.config\.multi_turn_enabled"/)
})
test('multi-turn switch stays hidden in smart-reasoning mode', () => {
@@ -94,8 +94,8 @@ test('the section description matches what the mode actually shows', () => {
})
test('history turns can be raised beyond the old 20 cap', () => {
- // A 5-to-20 range sits two orders of magnitude below the 200k token budget
- // the agent engine already manages, so the turn cap always bites first.
+ // KnowledgeQA history is capped by turns alone; 20 was too tight for the
+ // windows current models have.
const input = source.match(/<t-input-number v-model="formData\.config\.history_turns"[^>]*>/)
assert.ok(input, 'expected to find the history turns input')
assert.match(input[0], /:max="100"/)
diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue
index d86e7a567..2361df2ca 100644
--- a/frontend/src/views/agent/AgentEditorModal.vue
+++ b/frontend/src/views/agent/AgentEditorModal.vue
@@ -846,9 +846,9 @@
</div>
</div>
- <!-- 多轮对话。Agent 模式下 history_turns 同样生效(session_agent_qa.go
- 经 LoadAgentHistory 读取),所以本组不再整体按模式隐藏;开关本身仍由
- EnsureDefaults 强制开启,故只在普通模式展示。 -->
+ <!-- 多轮对话。两种模式都保留本组:Agent 模式在这里说明历史按上下文窗口
+ 自动管理,并承载跨轮保留检索结果;开关由 EnsureDefaults 强制开启,
+ 故只在普通模式展示。 -->
<div v-show="currentSection === 'conversation'" class="section">
<div class="section-header">
<h2>{{ $t('agent.editor.conversationSettings') }}</h2>
@@ -868,8 +868,9 @@
</div>
</div>
- <!-- 保留轮数(Agent 模式恒为多轮,故不受开关状态影响) -->
- <div v-if="formData.config.multi_turn_enabled || isAgentMode" class="setting-row">
+ <!-- 保留轮数(仅普通模式:Agent 模式按上下文窗口加载历史、超出时压缩成
+ 摘要,见 session_agent_qa.go -> LoadAgentHistory,不读 history_turns) -->
+ <div v-if="!isAgentMode && formData.config.multi_turn_enabled" class="setting-row">
<div class="setting-info">
<label>{{ $t('agent.editor.historyTurns') }}</label>
<p class="desc">{{ $t('agentEditor.desc.historyRounds') }}</p>
@@ -2687,7 +2688,7 @@ const navItems = computed(() => {
{ key: 'model', icon: 'control-platform', label: t('agent.editor.modelConfig') },
{ key: 'suggestions', icon: 'help-circle', label: t('agentEditor.questionSuggestions.navLabel') },
];
- // 多轮对话(两种模式都需要:Agent 模式同样按 history_turns 截断历史)
+ // 多轮对话(两种模式都需要:Agent 模式在这里说明历史自动管理、保留检索结果)
items.push({ key: 'conversation', icon: 'chat', label: t('agent.editor.conversationSettings') });
// 知识库与检索
items.push({ key: 'knowledge', icon: 'folder', label: t('agent.editor.knowledgeConfig') });
diff --git a/internal/agent/calibration.go b/internal/agent/calibration.go
new file mode 100644
index 000000000..7b4f11b10
--- /dev/null
+++ b/internal/agent/calibration.go
@@ -0,0 +1,105 @@
+package agent
+
+import (
+ "context"
+
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/models/chat"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+const (
+ // A single sample outside these bounds is a usage report that does not
+ // mean what the delta assumes (a provider counting only uncached input,
+ // a prefix that changed underneath), not a tokenizer.
+ minPlausibleTokenRatio = 0.3
+ maxPlausibleTokenRatio = 3.0
+ // minCalibrationTokens is how much estimated conversation the samples must
+ // cover before their ratio replaces the prior. A tool result of a few
+ // dozen tokens is mostly per-message overhead and says little.
+ minCalibrationTokens = 256
+)
+
+// tokenCalibration learns how many provider tokens one estimated token of
+// conversation costs, from consecutive requests within a turn.
+//
+// Two requests in a row share their tool schemas, system prompt and earlier
+// messages, so the growth of the provider's prompt count between them is the
+// cost of exactly the messages appended in between: the previous reply, the
+// tool results, any steered message. Dividing it by their estimate prices
+// conversation alone. A ratio over the whole request would also measure how
+// the provider renders tool schemas, which OpenAI compacts; applied to
+// conversation that under-counts it, the direction that overflows the window.
+type tokenCalibration struct {
+ provider, estimated float64 // summed over this turn's samples
+
+ // The previous request, when the next one can be compared with it.
+ prevPrompt int
+ prevSent int
+ prevTools int // unscaled tool schema estimate
+ prevRewrites int
+}
+
+// calibrateEstimator compares this round's request with the previous one and,
+// once the turn has enough samples, rescales the estimator and records the
+// scale on the turn's usage so the next turn starts from it. messages is the
+// transcript whose first e.lastSentMsgCount entries were just sent.
+func (e *AgentEngine) calibrateEstimator(
+ ctx context.Context, round int, messages []chat.Message, tools []chat.Tool,
+ usage types.TokenUsage, state *types.AgentState,
+) {
+ if usage.PromptTokens <= 0 {
+ return
+ }
+ c := &e.calibration
+ sent := e.lastSentMsgCount
+ toolTokens := e.rawEstimator.EstimateTools(tools)
+
+ comparable := c.prevPrompt > 0 && usage.PromptTokens > c.prevPrompt &&
+ c.prevRewrites == e.contextRewrites && c.prevTools == toolTokens &&
+ c.prevSent > 0 && c.prevSent < sent && sent <= len(messages)
+ if comparable {
+ appended := messages[c.prevSent:sent]
+ estimated := 0
+ for i := range appended {
+ estimated += e.rawEstimator.EstimateMessage(&appended[i])
+ }
+ counted := usage.PromptTokens - c.prevPrompt
+ if estimated > 0 && !hasImageParts(appended) {
+ if ratio := float64(counted) / float64(estimated); ratio >= minPlausibleTokenRatio &&
+ ratio <= maxPlausibleTokenRatio {
+ c.provider += float64(counted)
+ c.estimated += float64(estimated)
+ } else {
+ logger.Debugf(ctx, "[Agent][Round-%d][ctx] calibration sample skipped: "+
+ "provider=%d estimated=%d", round, counted, estimated)
+ }
+ }
+ }
+ c.prevPrompt, c.prevSent, c.prevTools, c.prevRewrites = usage.PromptTokens, sent, toolTokens, e.contextRewrites
+
+ if c.estimated < minCalibrationTokens {
+ return
+ }
+ e.tokenEstimator.SetScale(c.provider / c.estimated)
+ state.TurnUsage.ContextTokenScale = e.tokenEstimator.Scale()
+ logger.Debugf(ctx, "[Agent][Round-%d][ctx] token scale %.2f (provider=%.0f estimated=%.0f)",
+ round, state.TurnUsage.ContextTokenScale, c.provider, c.estimated)
+}
+
+// hasImageParts reports whether any message carries an image. Images are
+// estimated at a fixed cost while providers bill them by tiles, so a sample
+// containing one measures image pricing, not text.
+func hasImageParts(messages []chat.Message) bool {
+ for i := range messages {
+ if len(messages[i].Images) > 0 {
+ return true
+ }
+ for _, part := range messages[i].MultiContent {
+ if part.ImageURL != nil || part.Type == "image_url" {
+ return true
+ }
+ }
+ }
+ return false
+}
diff --git a/internal/agent/calibration_test.go b/internal/agent/calibration_test.go
new file mode 100644
index 000000000..b90684ad9
--- /dev/null
+++ b/internal/agent/calibration_test.go
@@ -0,0 +1,218 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+
+ agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
+ "github.com/Tencent/WeKnora/internal/models/chat"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+// calibrationRun drives calibrateEstimator the way runReActIteration does:
+// each request is the transcript so far, and the provider reports a prompt
+// count for it.
+type calibrationRun struct {
+ engine *AgentEngine
+ state *types.AgentState
+ messages []chat.Message
+ tools []chat.Tool
+}
+
+func newCalibrationRun(t *testing.T, opts ...testEngineOption) *calibrationRun {
+ return &calibrationRun{
+ engine: newTestEngine(t, &mockChat{}, opts...),
+ state: &types.AgentState{},
+ messages: []chat.Message{
+ {Role: "system", Content: "you are an agent"},
+ {Role: "user", Content: "summarize the contract"},
+ },
+ }
+}
+
+// send reports prompt as the provider's count for the transcript as it stands.
+func (r *calibrationRun) send(prompt int) {
+ r.engine.lastSentMsgCount = len(r.messages)
+ r.engine.calibrateEstimator(context.Background(), 1, r.messages, r.tools,
+ types.TokenUsage{PromptTokens: prompt, TotalTokens: prompt}, r.state)
+}
+
+// appendRound adds a reply and a tool result and returns their raw estimate.
+func (r *calibrationRun) appendRound(result string) int {
+ appended := []chat.Message{
+ {Role: "assistant", ToolCalls: []chat.ToolCall{{
+ ID: "call", Type: "function",
+ Function: chat.FunctionCall{Name: "search_knowledge", Arguments: `{"query":"条款"}`},
+ }}},
+ {Role: "tool", Name: "search_knowledge", ToolCallID: "call", Content: result},
+ }
+ r.messages = append(r.messages, appended...)
+ estimated := 0
+ for i := range appended {
+ estimated += r.engine.rawEstimator.EstimateMessage(&appended[i])
+ }
+ return estimated
+}
+
+var chineseResult = strings.Repeat("合同第十二条约定,乙方应在验收合格后三十日内支付剩余款项。", 40)
+
+// The scale is the provider's growth between two requests over the estimate
+// of what was appended, and it is carried to the next turn on the usage.
+func TestCalibrationLearnsTheScaleOfAppendedConversation(t *testing.T) {
+ r := newCalibrationRun(t)
+ r.send(500)
+ appended := r.appendRound(chineseResult)
+ r.send(500 + appended*6/10)
+
+ require.InDelta(t, 0.6, r.engine.tokenEstimator.Scale(), 0.01)
+ require.InDelta(t, 0.6, r.state.TurnUsage.ContextTokenScale, 0.01)
+ require.Equal(t, 1.0, r.engine.rawEstimator.Scale(), "the measuring estimator stays raw")
+}
+
+// Tool schemas ride in every request, so they cancel out of the delta. A
+// provider that renders them at half their raw size must not pull the
+// conversation scale down with them: that would under-count conversation.
+func TestCalibrationIgnoresHowToolSchemasAreRendered(t *testing.T) {
+ r := newCalibrationRun(t)
+ for i := range 40 {
+ r.tools = append(r.tools, chat.Tool{Type: "function", Function: chat.FunctionDef{
+ Name: fmt.Sprintf("tool_%d", i),
+ Description: strings.Repeat("does something useful. ", 40),
+ Parameters: []byte(`{"type":"object"}`),
+ }})
+ }
+ schemas := r.engine.rawEstimator.EstimateTools(r.tools)
+ base := r.engine.rawEstimator.EstimateMessages(r.messages)
+
+ r.send(base + schemas/2)
+ appended := r.appendRound(strings.Repeat("the payment is due within thirty days. ", 80))
+ r.send(base + schemas/2 + appended)
+
+ require.InDelta(t, 1.0, r.engine.tokenEstimator.Scale(), 0.01)
+}
+
+// Compaction or trimming rewrites messages the previous request sent, so the
+// growth between the two requests no longer prices what was appended.
+func TestCalibrationSkipsARequestAfterTheContextWasRewritten(t *testing.T) {
+ r := newCalibrationRun(t)
+ r.send(500)
+ appended := r.appendRound(chineseResult)
+ r.engine.contextRewrites++
+ r.send(500 + appended*6/10)
+
+ require.Equal(t, 1.0, r.engine.tokenEstimator.Scale())
+ require.Zero(t, r.state.TurnUsage.ContextTokenScale, "nothing measured, nothing to carry forward")
+
+ // The rewritten request is the new baseline for the next comparison.
+ next := r.appendRound(chineseResult)
+ r.send(500 + appended*6/10 + next*6/10)
+ require.InDelta(t, 0.6, r.engine.tokenEstimator.Scale(), 0.01)
+}
+
+// A sample no tokenizer could produce is a usage report that does not mean
+// what the delta assumes, such as a provider counting only uncached input.
+func TestCalibrationSkipsImplausibleSamples(t *testing.T) {
+ r := newCalibrationRun(t)
+ r.send(5000)
+ appended := r.appendRound(chineseResult)
+ r.send(5000 + appended/10)
+
+ require.Equal(t, 1.0, r.engine.tokenEstimator.Scale())
+ require.Zero(t, r.state.TurnUsage.ContextTokenScale)
+}
+
+// Images are estimated at a fixed cost while providers bill them by tiles; a
+// sample containing one would measure image pricing, not text.
+func TestCalibrationSkipsSamplesWithImages(t *testing.T) {
+ r := newCalibrationRun(t)
+ r.send(500)
+ appended := r.appendRound(chineseResult)
+ r.messages = append(r.messages,
+ chat.Message{Role: "user", Content: "see image", Images: []string{"https://x/a.png"}})
+ r.send(500 + appended*6/10 + 800)
+
+ require.Equal(t, 1.0, r.engine.tokenEstimator.Scale())
+}
+
+// Too little appended text is mostly per-message overhead; it must not
+// replace the prior on its own.
+func TestCalibrationWaitsForEnoughText(t *testing.T) {
+ r := newCalibrationRun(t)
+ r.send(500)
+ appended := r.appendRound("ok")
+ r.send(500 + appended/2)
+
+ require.Equal(t, 1.0, r.engine.tokenEstimator.Scale())
+}
+
+// The previous turn's scale is where this turn starts, and compaction shares
+// the estimator, so its cut point and summarizer budget use the same scale.
+func TestEngineStartsFromThePreviousTurnsScale(t *testing.T) {
+ engine := newTestEngine(t, &mockChat{}, func(cfg *types.AgentConfig) {
+ cfg.ContextTokenScale = 0.6
+ })
+ require.InDelta(t, 0.6, engine.tokenEstimator.Scale(), 1e-9)
+
+ text := chat.Message{Role: "user", Content: chineseResult}
+ require.Less(t, engine.tokenEstimator.EstimateMessage(&text), engine.rawEstimator.EstimateMessage(&text))
+}
+
+// bigResultTool returns a long result, enough appended text to calibrate on.
+type bigResultTool struct{ countingTool }
+
+func (t *bigResultTool) Execute(context.Context, json.RawMessage) (*types.ToolResult, error) {
+ return &types.ToolResult{Success: true, Output: chineseResult}, nil
+}
+
+// Some providers report a prompt count and no total. Calibration needs only
+// the prompt count, and the scale it measures reaches the turn's usage even
+// though no total was ever reported.
+func TestExecuteCalibratesFromPromptCountsWithoutATotal(t *testing.T) {
+ tool := &bigResultTool{countingTool: *newCountingTool("read_contract")}
+ model := &mockChat{responses: []mockResponse{
+ {chunks: []types.StreamResponse{{
+ ResponseType: types.ResponseTypeAnswer,
+ ToolCalls: []types.LLMToolCall{{
+ ID: "c1", Type: "function",
+ Function: types.FunctionCall{Name: "read_contract", Arguments: `{}`},
+ }},
+ Done: true, FinishReason: "tool_calls",
+ Usage: &types.TokenUsage{PromptTokens: 1000},
+ }}},
+ {chunks: []types.StreamResponse{{
+ ResponseType: types.ResponseTypeAnswer, Content: "付款期限为验收后三十日。",
+ Done: true, FinishReason: "stop",
+ Usage: &types.TokenUsage{PromptTokens: 1000 + 700},
+ }}},
+ }}
+ engine := newTestEngine(t, model)
+ engine.toolRegistry = agenttools.NewToolRegistry()
+ engine.toolRegistry.RegisterTool(tool)
+
+ state, err := engine.Execute(context.Background(), "session", "message", "付款期限是多久", nil)
+ require.NoError(t, err)
+ require.InDelta(t, 0.6, state.TurnUsage.ContextTokenScale, 0.1)
+ usage := turnUsage(state)
+ require.NotNil(t, usage, "a scale is persisted even when no total was reported")
+ require.InDelta(t, 0.6, usage.ContextTokenScale, 0.1)
+}
+
+// A turn that measures nothing (one request, no tool call) passes on the scale
+// it started from, so the newest turn always carries the latest known scale.
+func TestExecuteCarriesTheStartingScaleForward(t *testing.T) {
+ model := &mockChat{responses: []mockResponse{{chunks: []types.StreamResponse{{
+ ResponseType: types.ResponseTypeAnswer, Content: "你好", Done: true, FinishReason: "stop",
+ }}}}}
+ engine := newTestEngine(t, model, func(cfg *types.AgentConfig) { cfg.ContextTokenScale = 0.7 })
+ engine.toolRegistry = agenttools.NewToolRegistry()
+
+ state, err := engine.Execute(context.Background(), "session", "message", "你好", nil)
+ require.NoError(t, err)
+ usage := turnUsage(state)
+ require.NotNil(t, usage)
+ require.InDelta(t, 0.7, usage.ContextTokenScale, 1e-9)
+}
diff --git a/internal/agent/checkpoint.go b/internal/agent/checkpoint.go
index 8b256a738..c7b4a0d23 100644
--- a/internal/agent/checkpoint.go
+++ b/internal/agent/checkpoint.go
@@ -25,12 +25,19 @@ func (e *AgentEngine) saveContextCheckpoint(ctx context.Context, cp *compaction.
err := e.checkpointSink.SaveContextCheckpoint(ctx, cp.TurnID, &types.ContextCheckpoint{
Summary: cp.Summary,
CreatedAt: time.Now(),
+ Degraded: cp.Degraded,
})
if err != nil {
logger.Warnf(ctx, "[Agent][Round-%d] Failed to save context checkpoint on turn %s: %v",
round, cp.TurnID, err)
return
}
+ if cp.Degraded {
+ logger.Warnf(ctx, "[Agent][Round-%d] Saved a degraded context checkpoint through turn %s "+
+ "(raw archive, %d chars): the summarizer failed; the next compaction refines it",
+ round, cp.TurnID, len(cp.Summary))
+ return
+ }
logger.Infof(ctx, "[Agent][Round-%d] Saved context checkpoint through turn %s (%d chars)",
round, cp.TurnID, len(cp.Summary))
}
diff --git a/internal/agent/compaction/checkpoint_test.go b/internal/agent/compaction/checkpoint_test.go
index 65096556d..f2a40da3c 100644
--- a/internal/agent/compaction/checkpoint_test.go
+++ b/internal/agent/compaction/checkpoint_test.go
@@ -2,6 +2,7 @@ package compaction
import (
"context"
+ "fmt"
"testing"
"github.com/Tencent/WeKnora/internal/models/chat"
@@ -127,17 +128,49 @@ func TestNoCheckpointForALiveTurnOnly(t *testing.T) {
assert.Nil(t, result.Checkpoint, "nothing stored was summarized")
}
-// A raw archive is a stopgap for the request that needed it. Persisting it
-// would make every later turn carry the archive instead of retrying the
-// summarizer.
-func TestNoCheckpointFromADegradedSummary(t *testing.T) {
+// A summarizer that keeps failing used to leave no checkpoint, so every later
+// turn loaded the same history, compacted it, and failed again. The raw
+// archive is kept as a degraded checkpoint instead; the next compaction folds
+// it in as the previous summary.
+func TestDegradedSummaryIsStillACheckpoint(t *testing.T) {
c := New(&stubChat{err: assert.AnError}, newEstimator(t), testSettings())
msgs := withStoredHistory(reactTurn(12), storedTurn("turn-a", 1, "/workspace/a.txt"))
result, err := c.Compact(context.Background(), msgs, ReasonThreshold)
require.NoError(t, err)
require.True(t, result.Degraded)
- assert.Nil(t, result.Checkpoint)
+
+ require.NotNil(t, result.Checkpoint)
+ assert.Equal(t, "turn-a", result.Checkpoint.TurnID)
+ assert.True(t, result.Checkpoint.Degraded)
+ assert.Contains(t, result.Checkpoint.Summary, "Raw conversation archive")
+ assert.Contains(t, result.Checkpoint.Summary, "/workspace/a.txt")
+}
+
+// The archive stands in for a summary, so it is held to the summary budget,
+// newest messages first. Unbounded, an archive of a history that filled the
+// window was nearly as large as the history, and the compaction freed nothing.
+func TestRawArchiveIsHeldToTheSummaryBudget(t *testing.T) {
+ est := newEstimator(t)
+ c := New(&stubChat{err: assert.AnError}, est, testSettings())
+
+ msgs := []chat.Message{{Role: "system", Content: "you are an agent"}}
+ for i := 0; i < 150; i++ {
+ msgs = append(msgs, storedTurn(fmt.Sprintf("turn-%03d", i), 1, "/workspace/f.txt")...)
+ }
+ msgs = append(msgs, chat.Message{Role: "user", Content: "next"})
+
+ result, err := c.Compact(context.Background(), msgs, ReasonThreshold)
+ require.NoError(t, err)
+ require.NotNil(t, result.Checkpoint)
+ archive := result.Checkpoint.Summary
+
+ assert.LessOrEqual(t, est.EstimateString(archive), c.Settings().summaryBudget()+300,
+ "the archive must fit where a summary would")
+ assert.Contains(t, archive, "earlier messages omitted]")
+ assert.Contains(t, archive, "question turn-14", "the newest messages are the ones kept")
+ assert.NotContains(t, archive, "question turn-000")
+ assert.Less(t, result.TokensAfter, result.TokensBefore/2, "a degraded compaction still frees room")
}
// History loaded from a checkpoint starts with that summary. The next
@@ -162,3 +195,50 @@ func TestCheckpointCarriesTheLoadedSummaryForward(t *testing.T) {
assert.Contains(t, result.Checkpoint.Summary, "/workspace/old.txt")
assert.Contains(t, result.Checkpoint.Summary, "/workspace/c.txt")
}
+
+// History can reach the whole window by design, so the part being summarized
+// can outgrow one summarization request. An overflowing request degrades to a
+// raw archive, which is never persisted, so every later turn would fail the
+// same way. The oldest messages are left out instead, the prompt says so, and
+// their file paths are still recorded.
+func TestSummarizerInputIsFittedToTheWindow(t *testing.T) {
+ est := newEstimator(t)
+ llm := &stubChat{response: "## Goal\nsummary"}
+ settings := Settings{Enabled: true, MaxContextTokens: 20000, ReserveTokens: 8000, KeepRecentTokens: 2000}
+ c := New(llm, est, settings)
+
+ msgs := []chat.Message{{Role: "system", Content: "you are an agent"}}
+ for i := 0; i < 150; i++ {
+ id := fmt.Sprintf("turn-%03d", i)
+ msgs = append(msgs, storedTurn(id, 1, "/workspace/"+id+".txt")...)
+ }
+ msgs = append(msgs, chat.Message{Role: "user", Content: "next"})
+
+ result, err := c.Compact(context.Background(), msgs, ReasonThreshold)
+ require.NoError(t, err)
+ require.False(t, result.Degraded)
+ require.Positive(t, result.Omitted)
+
+ prompt := llm.prompts[0]
+ request := est.EstimateString(summarizationSystemPrompt) + est.EstimateString(prompt) +
+ c.Settings().summaryBudget()
+ assert.LessOrEqual(t, request, settings.MaxContextTokens, "the request must fit the window")
+ assert.Contains(t, prompt, fmt.Sprintf("[%d earlier messages are not shown", result.Omitted))
+ assert.NotContains(t, prompt, "question turn-000", "the oldest messages are the ones left out")
+ assert.Contains(t, prompt, "question turn-140", "the newest summarized messages stay")
+
+ require.NotNil(t, result.Checkpoint)
+ assert.Contains(t, result.Checkpoint.Summary, "/workspace/turn-000.txt",
+ "paths come from every summarized message, not only the ones shown")
+}
+
+func TestSummarizerInputIsUntouchedWhenItFits(t *testing.T) {
+ llm := &stubChat{response: "## Goal\nsummary"}
+ c := New(llm, newEstimator(t), testSettings())
+
+ result, err := c.Compact(context.Background(),
+ withStoredHistory(reactTurn(12), storedTurn("turn-a", 1, "/workspace/a.txt")), ReasonThreshold)
+ require.NoError(t, err)
+ assert.Zero(t, result.Omitted)
+ assert.NotContains(t, llm.prompts[0], "earlier messages are not shown")
+}
diff --git a/internal/agent/compaction/compaction_test.go b/internal/agent/compaction/compaction_test.go
index fde395284..dae92ae47 100644
--- a/internal/agent/compaction/compaction_test.go
+++ b/internal/agent/compaction/compaction_test.go
@@ -36,10 +36,23 @@ func (s *stubChat) Chat(
return &types.ChatResponse{Content: s.response, FinishReason: s.finishReason}, nil
}
+// ChatStream answers like Chat, as a stream: compaction summarizes through it.
func (s *stubChat) ChatStream(
- context.Context, []chat.Message, *chat.ChatOptions,
+ ctx context.Context, messages []chat.Message, opts *chat.ChatOptions,
) (<-chan types.StreamResponse, error) {
- return nil, nil
+ resp, err := s.Chat(ctx, messages, opts)
+ if err != nil {
+ return nil, err
+ }
+ return streamOf(resp), nil
+}
+
+func streamOf(resp *types.ChatResponse) <-chan types.StreamResponse {
+ ch := make(chan types.StreamResponse, 2)
+ ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Content: resp.Content}
+ ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Done: true, FinishReason: resp.FinishReason}
+ close(ch)
+ return ch
}
func (s *stubChat) GetModelName() string { return "stub" }
diff --git a/internal/agent/compaction/compactor.go b/internal/agent/compaction/compactor.go
index 4be437dfa..8c7b9c937 100644
--- a/internal/agent/compaction/compactor.go
+++ b/internal/agent/compaction/compactor.go
@@ -18,9 +18,6 @@ const (
// better served by the raw archive than by stalling the turn.
maxSummarizationAttempts = 2
- // summarizationTimeout is the per-attempt budget for a summarization call.
- summarizationTimeout = 60 * time.Second
-
// llmCallLabel identifies compaction traffic in tracing and usage
// accounting, separating it from the agent's own reasoning rounds.
llmCallLabel = "agent_context_compaction"
@@ -62,6 +59,9 @@ type Result struct {
// Checkpoint is the part of this compaction a later turn can start from,
// or nil when there is none (see Preparation.checkpoint).
Checkpoint *Checkpoint
+ // Omitted counts the oldest messages left out of the summarization
+ // requests because they did not fit (see fitSummarizerInput).
+ Omitted int
}
// Checkpoint is a summary that ends exactly on a stored turn. Persisted onto
@@ -71,6 +71,10 @@ type Checkpoint struct {
// TurnID is the stored turn the summary covers through, inclusive.
TurnID string
Summary string
+ // Degraded reports that Summary holds a raw archive because the
+ // summarizer failed. It is still a checkpoint: the next compaction
+ // folds it in as the previous summary.
+ Degraded bool
}
// Freed is how much room the compaction actually recovered. A non-positive
@@ -132,6 +136,7 @@ func (c *Compactor) Compact(
Degraded: historyDegraded || prefixDegraded,
SplitTurn: prep.IsSplitTurn,
Checkpoint: prep.checkpoint(history, historyDegraded),
+ Omitted: prep.OmittedHistory + prep.OmittedTurnPrefix,
}, nil
}
@@ -146,13 +151,14 @@ func (c *Compactor) summarizeHistory(ctx context.Context, p *Preparation) (strin
instructions = updateSummarizationInstructions
}
text, err := c.summarize(
- ctx, p.MessagesToSummarize, p.PreviousSummary, instructions, c.settings.summaryBudget(),
+ ctx, p.MessagesToSummarize, p.OmittedHistory, p.PreviousSummary, instructions, c.settings.summaryBudget(),
)
if err != nil {
// The previous summary is still the best record of everything
// before this span, so the archive is appended to it rather than
// replacing it.
- return joinNonEmpty(p.PreviousSummary, rawArchive(p.MessagesToSummarize)), true
+ return joinNonEmpty(p.PreviousSummary,
+ rawArchive(p.MessagesToSummarize, c.settings.summaryBudget(), c.estimator)), true
}
return text, false
}
@@ -165,11 +171,11 @@ func (c *Compactor) appendTurnPrefix(ctx context.Context, p *Preparation, histor
}
degraded := false
prefix, err := c.summarize(
- ctx, p.TurnPrefixMessages, "", turnPrefixInstructions, c.settings.turnPrefixBudget(),
+ ctx, p.TurnPrefixMessages, p.OmittedTurnPrefix, "", turnPrefixInstructions, c.settings.turnPrefixBudget(),
)
if err != nil {
degraded = true
- prefix = rawArchive(p.TurnPrefixMessages)
+ prefix = rawArchive(p.TurnPrefixMessages, c.settings.turnPrefixBudget(), c.estimator)
}
if history == "" {
history = "No prior history."
@@ -178,54 +184,120 @@ func (c *Compactor) appendTurnPrefix(ctx context.Context, p *Preparation, histor
}
// summarize runs one summarization call with retries.
+//
+// The call streams and is cancelled only when it stops producing output for
+// the stall timeout, the rule the engine applies to its own rounds. A fixed
+// total budget was wrong for exactly the calls that matter: the history being
+// summarized can be most of the window, and a request that was prefilling and
+// writing normally was cut off at 60 seconds, degraded, and started over on
+// the next turn. The overall ceiling belongs to the provider transport.
func (c *Compactor) summarize(
ctx context.Context,
messages []chat.Message,
+ omitted int,
previousSummary, instructions string,
maxTokens int,
) (string, error) {
- prompt := buildSummarizationPrompt(messages, previousSummary, instructions)
+ request := []chat.Message{
+ {Role: "system", Content: summarizationSystemPrompt},
+ {Role: "user", Content: buildSummarizationPrompt(messages, omitted, previousSummary, instructions)},
+ }
+ opts := &chat.ChatOptions{
+ Temperature: 0.3, // low temperature for factual summarization
+ MaxTokens: maxTokens,
+ CacheRetention: chat.CacheRetentionNone,
+ }
var lastErr error
for attempt := 1; attempt <= maxSummarizationAttempts; attempt++ {
- callCtx, cancel := context.WithTimeout(ctx, summarizationTimeout)
- callCtx = types.WithLLMCallMetadata(callCtx, llmCallLabel, "")
- resp, err := c.chatModel.Chat(callCtx, []chat.Message{
- {Role: "system", Content: summarizationSystemPrompt},
- {Role: "user", Content: prompt},
- }, &chat.ChatOptions{
- Temperature: 0.3, // low temperature for factual summarization
- MaxTokens: maxTokens,
- CacheRetention: chat.CacheRetentionNone,
- })
- cancel()
-
- if err != nil {
- lastErr = err
- continue
+ content, finishReason, err := c.streamSummary(ctx, request, opts)
+ if err == nil {
+ err = validateSummary(content, finishReason)
+ }
+ if err == nil {
+ return strings.TrimSpace(content), nil
}
- if err := validateSummary(resp); err != nil {
- lastErr = err
- continue
+ lastErr = err
+ if ctx.Err() != nil {
+ break // the turn itself was stopped; another attempt cannot help
}
- return strings.TrimSpace(resp.Content), nil
}
return "", fmt.Errorf("summarization failed after %d attempts: %w",
maxSummarizationAttempts, lastErr)
}
+// streamSummary collects one summarization stream. Output of any kind, the
+// model's reasoning included, counts as progress and resets the stall timer.
+func (c *Compactor) streamSummary(
+ ctx context.Context, messages []chat.Message, opts *chat.ChatOptions,
+) (content, finishReason string, err error) {
+ callCtx, cancel := context.WithCancel(types.WithLLMCallMetadata(ctx, llmCallLabel, ""))
+ defer cancel()
+ stream, err := c.chatModel.ChatStream(callCtx, messages, opts)
+ if err != nil {
+ return "", "", err
+ }
+ if stream == nil {
+ return "", "", errors.New("summarization stream was not opened")
+ }
+ // Anything the provider still sends after this returns is discarded, so
+ // its goroutine can finish once the cancelled context closes the stream.
+ defer func() {
+ go func() {
+ for {
+ if _, ok := <-stream; !ok {
+ return
+ }
+ }
+ }()
+ }()
+
+ timeout := c.settings.stallTimeout()
+ stall := time.NewTimer(timeout)
+ defer stall.Stop()
+ var sb strings.Builder
+ streamErr := ""
+ for {
+ select {
+ case <-ctx.Done():
+ return "", "", ctx.Err()
+ case <-stall.C:
+ return "", "", fmt.Errorf("summarization stalled: no output for %s", timeout)
+ case chunk, ok := <-stream:
+ if !ok {
+ if streamErr != "" {
+ return "", finishReason, fmt.Errorf("summarization stream error: %s", streamErr)
+ }
+ return sb.String(), finishReason, nil
+ }
+ stall.Reset(timeout)
+ if chunk.FinishReason != "" {
+ finishReason = chunk.FinishReason
+ }
+ switch chunk.ResponseType {
+ case types.ResponseTypeError:
+ streamErr = chunk.Content
+ case types.ResponseTypeThinking:
+ // progress, but not part of the summary
+ default:
+ sb.WriteString(chunk.Content)
+ }
+ }
+ }
+}
+
// validateSummary rejects responses that cannot serve as a checkpoint.
//
// The length stop is the one worth spelling out: a summary cut off by the token
// cap reads like a valid summary but silently ends mid-section, and every later
// round inherits that truncation as its only memory of the dropped history.
// A partial summary is a failure: it cannot serve as a checkpoint.
-func validateSummary(resp *types.ChatResponse) error {
- if resp == nil || strings.TrimSpace(resp.Content) == "" {
+func validateSummary(content, finishReason string) error {
+ if strings.TrimSpace(content) == "" {
return errors.New("empty response from LLM")
}
- switch strings.ToLower(strings.TrimSpace(resp.FinishReason)) {
+ switch strings.ToLower(strings.TrimSpace(finishReason)) {
case "length", "max_tokens", "max_output_tokens":
return errors.New("generation hit the token cap and the summary is incomplete")
}
@@ -235,9 +307,13 @@ func validateSummary(resp *types.ChatResponse) error {
// buildSummarizationPrompt wraps the transcript in a tag and puts the
// instructions last, so the summarizer cannot mistake conversation text for
// its own instructions.
-func buildSummarizationPrompt(messages []chat.Message, previousSummary, instructions string) string {
+func buildSummarizationPrompt(messages []chat.Message, omitted int, previousSummary, instructions string) string {
var sb strings.Builder
sb.WriteString("<conversation>\n")
+ if omitted > 0 {
+ fmt.Fprintf(&sb, "[%d earlier messages are not shown: they did not fit in one summarization "+
+ "request, and no previous summary covers them. Do not guess at what they said.]\n\n", omitted)
+ }
sb.WriteString(serializeConversation(messages))
sb.WriteString("\n</conversation>\n\n")
if previousSummary != "" {
diff --git a/internal/agent/compaction/prepare.go b/internal/agent/compaction/prepare.go
index a3f16685a..18d529ad6 100644
--- a/internal/agent/compaction/prepare.go
+++ b/internal/agent/compaction/prepare.go
@@ -32,7 +32,14 @@ type Preparation struct {
// than summarized again.
PreviousSummary string
TokensBefore int
- fileOps fileOps
+ // OmittedHistory and OmittedTurnPrefix count the oldest messages of each
+ // range left out because one summarization request could not carry them
+ // (see fitSummarizerInput). Their file paths are still recorded.
+ OmittedHistory int
+ OmittedTurnPrefix int
+ fileOps fileOps
+ // historyFileOps is fileOps without the turn prefix, for the checkpoint.
+ historyFileOps fileOps
// storedTurnID is the stored turn MessagesToSummarize ends exactly on, or
// "" when it ends inside a turn or reaches into the live one.
storedTurnID string
@@ -84,29 +91,67 @@ func Prepare(messages []chat.Message, s Settings, estimator *agenttoken.Estimato
return nil
}
- return &Preparation{
- FirstKeptIdx: cut.FirstKeptIdx,
- MessagesToSummarize: toSummarize,
- TurnPrefixMessages: turnPrefix,
- IsSplitTurn: cut.IsSplitTurn,
- PreviousSummary: previousSummary,
- TokensBefore: estimator.EstimateMessages(messages),
- fileOps: extractFileOps(previousSummary, toSummarize, turnPrefix),
- storedTurnID: storedTurnEndingAt(messages, historyEnd),
+ p := &Preparation{
+ FirstKeptIdx: cut.FirstKeptIdx,
+ IsSplitTurn: cut.IsSplitTurn,
+ PreviousSummary: previousSummary,
+ TokensBefore: estimator.EstimateMessages(messages),
+ fileOps: extractFileOps(previousSummary, toSummarize, turnPrefix),
+ historyFileOps: extractFileOps(previousSummary, toSummarize),
+ storedTurnID: storedTurnEndingAt(messages, historyEnd),
+ }
+ p.MessagesToSummarize, p.OmittedHistory = fitSummarizerInput(
+ toSummarize, s.summarizerInputBudget(estimator, previousSummary, s.summaryBudget()), estimator)
+ p.TurnPrefixMessages, p.OmittedTurnPrefix = fitSummarizerInput(
+ turnPrefix, s.summarizerInputBudget(estimator, "", s.turnPrefixBudget()), estimator)
+ return p
+}
+
+// fitSummarizerInput keeps the newest messages whose transcript fits budget
+// and reports how many older ones it left out. The newest message is kept
+// regardless; transcripts truncate each message, so one alone never matters.
+//
+// History can reach the whole window by design (the loader leaves overflow to
+// compaction), so the part being summarized can be larger than one request
+// can carry. An overflowing request is rejected, the summary degrades to a raw
+// archive, and a degraded summary is never persisted, so the next turn would
+// load the same history and fail the same way. Leaving the oldest messages out
+// breaks that loop; the prompt says so rather than hiding it.
+func fitSummarizerInput(
+ messages []chat.Message, budget int, estimator *agenttoken.Estimator,
+) ([]chat.Message, int) {
+ if budget <= 0 {
+ return messages, 0
+ }
+ used := 0
+ for i := len(messages) - 1; i >= 0; i-- {
+ used += estimator.EstimateString(serializeConversation(messages[i : i+1]))
+ if used > budget && i < len(messages)-1 {
+ return messages[i+1:], i + 1
+ }
}
+ return messages, 0
}
// checkpoint returns the history summary as a Checkpoint when it ends exactly
// on a stored turn. The turn-prefix summary is left out: it describes part of a
// turn the next turn replays verbatim. Nothing newly summarized means the
-// previous checkpoint still stands, and a raw archive is not worth keeping
-// past the turn that needed it — the next turn retries the summarizer instead.
+// previous checkpoint still stands.
+//
+// A raw archive is kept too. Not keeping it made a failing summarizer a loop:
+// the next turn loaded the same history, compacted it, failed the same way,
+// and so on every turn. The archive is bounded like a summary, and the next
+// compaction folds it in as the previous summary, so it is refined rather
+// than kept as is.
func (p *Preparation) checkpoint(history string, degraded bool) *Checkpoint {
- if p.storedTurnID == "" || len(p.MessagesToSummarize) == 0 || degraded {
+ if p.storedTurnID == "" || len(p.MessagesToSummarize) == 0 {
return nil
}
- ops := extractFileOps(p.PreviousSummary, p.MessagesToSummarize)
- return &Checkpoint{TurnID: p.storedTurnID, Summary: history + ops.format()}
+ return &Checkpoint{
+ TurnID: p.storedTurnID,
+ Summary: history + p.historyFileOps.format(),
+ Degraded: degraded,
+ }
}
// storedTurnEndingAt returns the stored turn that ends immediately before end,
diff --git a/internal/agent/compaction/serialize.go b/internal/agent/compaction/serialize.go
index 6683c25de..f0a6bcab7 100644
--- a/internal/agent/compaction/serialize.go
+++ b/internal/agent/compaction/serialize.go
@@ -6,6 +6,7 @@ import (
"sort"
"strings"
+ agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
"github.com/Tencent/WeKnora/internal/models/chat"
)
@@ -106,23 +107,52 @@ func truncate(s string, maxChars int) string {
// rawArchive is the fallback when the summarizer is unavailable. It is lossy
// and unstructured, but it keeps the tool names and paths that the next round
// needs in order not to redo finished work.
-func rawArchive(messages []chat.Message) string {
- var sb strings.Builder
- sb.WriteString("Raw conversation archive (LLM summarization unavailable):\n\n")
+//
+// It stands in for a summary, so it is held to budget tokens like one, keeping
+// the newest messages. Unbounded, an archive of a history that filled the
+// window could be nearly as large as the history, and a compaction that frees
+// nothing leaves the request over the window.
+func rawArchive(messages []chat.Message, budget int, estimator *agenttoken.Estimator) string {
+ lines := make([]string, 0, len(messages))
for i := range messages {
- msg := &messages[i]
- switch msg.Role {
- case "user":
- fmt.Fprintf(&sb, "- User: %s\n", truncate(msg.Content, 500))
- case "assistant":
- if calls := serializeToolCalls(msg.ToolCalls); calls != "" {
- fmt.Fprintf(&sb, "- Assistant [%s]: %s\n", calls, truncate(msg.Content, 500))
- continue
+ if line := archiveLine(&messages[i]); line != "" {
+ lines = append(lines, line)
+ }
+ }
+ kept := len(lines)
+ if budget > 0 && estimator != nil {
+ used := 0
+ for i := len(lines) - 1; i >= 0; i-- {
+ used += estimator.EstimateString(lines[i])
+ if used > budget && i < len(lines)-1 {
+ kept = len(lines) - 1 - i
+ break
}
- fmt.Fprintf(&sb, "- Assistant: %s\n", truncate(msg.Content, 500))
- case "tool":
- fmt.Fprintf(&sb, "- Tool[%s]: %s\n", msg.Name, truncate(msg.Content, 500))
}
}
+
+ var sb strings.Builder
+ sb.WriteString("Raw conversation archive (LLM summarization unavailable):\n\n")
+ if omitted := len(lines) - kept; omitted > 0 {
+ fmt.Fprintf(&sb, "[%d earlier messages omitted]\n", omitted)
+ }
+ for _, line := range lines[len(lines)-kept:] {
+ sb.WriteString(line)
+ }
return sb.String()
}
+
+func archiveLine(msg *chat.Message) string {
+ switch msg.Role {
+ case "user":
+ return fmt.Sprintf("- User: %s\n", truncate(msg.Content, 500))
+ case "assistant":
+ if calls := serializeToolCalls(msg.ToolCalls); calls != "" {
+ return fmt.Sprintf("- Assistant [%s]: %s\n", calls, truncate(msg.Content, 500))
+ }
+ return fmt.Sprintf("- Assistant: %s\n", truncate(msg.Content, 500))
+ case "tool":
+ return fmt.Sprintf("- Tool[%s]: %s\n", msg.Name, truncate(msg.Content, 500))
+ }
+ return ""
+}
diff --git a/internal/agent/compaction/settings.go b/internal/agent/compaction/settings.go
index 3010e45e2..094fec08b 100644
--- a/internal/agent/compaction/settings.go
+++ b/internal/agent/compaction/settings.go
@@ -8,6 +8,12 @@
// per round achieving nothing.
package compaction
+import (
+ "time"
+
+ agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
+)
+
// DefaultReserveTokens is the floor on room kept free for the next response.
const DefaultReserveTokens = 16384
@@ -34,6 +40,20 @@ type Settings struct {
// MaxSummaryTokens caps the summarization completion. Zero falls back to
// the reserve-derived budget alone.
MaxSummaryTokens int
+ // StallTimeout is how long a summarization stream may produce no output
+ // before it is cancelled. Zero means DefaultSummarizationStallTimeout.
+ StallTimeout time.Duration
+}
+
+// DefaultSummarizationStallTimeout matches the engine's default stall budget
+// for its own rounds.
+const DefaultSummarizationStallTimeout = 120 * time.Second
+
+func (s Settings) stallTimeout() time.Duration {
+ if s.StallTimeout > 0 {
+ return s.StallTimeout
+ }
+ return DefaultSummarizationStallTimeout
}
// Normalize fills in defaults and reconciles budgets that cannot all be
@@ -105,6 +125,35 @@ func (s Settings) summaryBudget() int {
return max(budget, 1024)
}
+// summarizerInputBudget is how much transcript one summarization request can
+// carry: the window less the reply, the previous summary and the prompt's own
+// text, with a tenth held back because the provider counts tokens its own way.
+// Zero means unbounded (no window configured).
+func (s Settings) summarizerInputBudget(
+ estimator *agenttoken.Estimator, previousSummary string, maxTokens int,
+) int {
+ if s.MaxContextTokens <= 0 {
+ return 0
+ }
+ fixed := maxTokens + summarizerPromptTokens(estimator) + estimator.EstimateString(previousSummary)
+ return max((s.MaxContextTokens-fixed)*9/10, 1)
+}
+
+// summarizerPromptTokens is the prompt text that surrounds the transcript:
+// the system prompt and the longest instructions, plus the tags around them.
+func summarizerPromptTokens(estimator *agenttoken.Estimator) int {
+ instructions := max(
+ estimator.EstimateString(initialSummarizationInstructions),
+ estimator.EstimateString(updateSummarizationInstructions),
+ estimator.EstimateString(turnPrefixInstructions),
+ )
+ return estimator.EstimateString(summarizationSystemPrompt) + instructions + summarizerPromptSlack
+}
+
+// summarizerPromptSlack covers the tags and the omission note the prompt adds
+// around the transcript.
+const summarizerPromptSlack = 256
+
// turnPrefixBudget is the smaller cap for summarizing the discarded prefix of
// a split turn: it only has to explain the retained suffix, not the session.
func (s Settings) turnPrefixBudget() int {
diff --git a/internal/agent/compaction/stream_test.go b/internal/agent/compaction/stream_test.go
new file mode 100644
index 000000000..c7be02401
--- /dev/null
+++ b/internal/agent/compaction/stream_test.go
@@ -0,0 +1,127 @@
+package compaction
+
+import (
+ "context"
+ "errors"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/models/chat"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// pacedChat streams a summary as chunks spaced by gap, optionally stopping
+// after a number of chunks without closing the stream: a provider that stalls.
+type pacedChat struct {
+ stubChat
+ chunks []types.StreamResponse
+ gap time.Duration
+ stallFrom int // stop sending after this many chunks; 0 sends all
+ opened atomic.Int32
+}
+
+func (p *pacedChat) ChatStream(
+ ctx context.Context, _ []chat.Message, _ *chat.ChatOptions,
+) (<-chan types.StreamResponse, error) {
+ p.opened.Add(1)
+ ch := make(chan types.StreamResponse)
+ go func() {
+ defer close(ch)
+ for i, chunk := range p.chunks {
+ if p.stallFrom > 0 && i >= p.stallFrom {
+ <-ctx.Done() // stalled until cancelled
+ return
+ }
+ select {
+ case <-time.After(p.gap):
+ case <-ctx.Done():
+ return
+ }
+ select {
+ case ch <- chunk:
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ return ch, nil
+}
+
+func pacedSettings() Settings {
+ s := testSettings()
+ s.StallTimeout = 80 * time.Millisecond
+ return s
+}
+
+func answerChunks(n int) []types.StreamResponse {
+ chunks := []types.StreamResponse{{ResponseType: types.ResponseTypeThinking, Content: "considering"}}
+ for range n {
+ chunks = append(chunks, types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Content: "## Goal "})
+ }
+ return append(chunks,
+ types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Done: true, FinishReason: "stop"})
+}
+
+// A summarization that keeps producing output is left to finish, however long
+// it takes in total: the old 60-second total budget cut exactly the large
+// requests compaction exists for. Reasoning counts as progress but is not
+// part of the summary.
+func TestSummarizationRunsAsLongAsItProgresses(t *testing.T) {
+ chatModel := &pacedChat{chunks: answerChunks(10), gap: 30 * time.Millisecond}
+ c := New(chatModel, newEstimator(t), pacedSettings())
+
+ start := time.Now()
+ result, err := c.Compact(context.Background(), reactTurn(12), ReasonThreshold)
+ require.NoError(t, err)
+
+ require.Greater(t, time.Since(start), 4*80*time.Millisecond, "longer in total than the stall timeout")
+ require.False(t, result.Degraded)
+ assert.Contains(t, result.Summary, "## Goal")
+ assert.NotContains(t, result.Summary, "considering")
+}
+
+// A stream that stops producing output is cancelled after the stall timeout,
+// retried once, and then degrades to the archive rather than hanging the turn.
+func TestSummarizationIsCancelledWhenItStalls(t *testing.T) {
+ chatModel := &pacedChat{chunks: answerChunks(10), gap: 10 * time.Millisecond, stallFrom: 2}
+ c := New(chatModel, newEstimator(t), pacedSettings())
+
+ result, err := c.Compact(context.Background(), reactTurn(12), ReasonThreshold)
+ require.NoError(t, err)
+ require.True(t, result.Degraded)
+ assert.Contains(t, result.Summary, "Raw conversation archive")
+ assert.EqualValues(t, maxSummarizationAttempts, chatModel.opened.Load(),
+ "a single live turn has only its prefix to summarize, attempted twice")
+}
+
+// An error reported inside the stream is a failed attempt, not a summary.
+func TestSummarizationStreamErrorIsAFailure(t *testing.T) {
+ chatModel := &pacedChat{chunks: []types.StreamResponse{
+ {ResponseType: types.ResponseTypeAnswer, Content: "## Goal half"},
+ {ResponseType: types.ResponseTypeError, Content: "upstream reset", Done: true},
+ }}
+ c := New(chatModel, newEstimator(t), pacedSettings())
+
+ result, err := c.Compact(context.Background(), reactTurn(12), ReasonThreshold)
+ require.NoError(t, err)
+ require.True(t, result.Degraded)
+ assert.NotContains(t, result.Summary, "## Goal half")
+}
+
+// A stopped turn is not retried: another attempt cannot outlive the turn.
+func TestSummarizationIsNotRetriedOnceTheTurnIsCancelled(t *testing.T) {
+ chatModel := &pacedChat{chunks: answerChunks(10), gap: 10 * time.Millisecond, stallFrom: 1}
+ c := New(chatModel, newEstimator(t), pacedSettings())
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ _, _, err := c.streamSummary(ctx, nil, &chat.ChatOptions{})
+ require.True(t, errors.Is(err, context.Canceled))
+
+ _, err = c.summarize(ctx, reactTurn(2), 0, "", initialSummarizationInstructions, 1024)
+ require.Error(t, err)
+ assert.EqualValues(t, 2, chatModel.opened.Load(), "one open for streamSummary, one for summarize")
+}
diff --git a/internal/agent/const.go b/internal/agent/const.go
index ea9c4b37c..8cdeb618f 100644
--- a/internal/agent/const.go
+++ b/internal/agent/const.go
@@ -115,11 +115,15 @@ const contextSafetyTokens = 4096
// provider. Unset without a sandbox is 4096; unset with a sandbox
// (write_sandbox_file / edit_sandbox_file) is 24576.
func (e *AgentEngine) getCompletionTokenBudget() int {
+ return completionTokenBudgetFor(e.config)
+}
+
+func completionTokenBudgetFor(cfg *types.AgentConfig) int {
configured := 0
sandboxID := ""
- if e.config != nil {
- configured = e.config.MaxCompletionTokens
- sandboxID = e.config.SandboxConfigID
+ if cfg != nil {
+ configured = cfg.MaxCompletionTokens
+ sandboxID = cfg.SandboxConfigID
}
return types.AgentRoundMaxCompletionTokensFor(configured, sandboxID)
}
@@ -130,7 +134,30 @@ func (e *AgentEngine) getCompletionTokenBudget() int {
// emit 24576 tokens needs at least that much free, or the request is accepted
// and the reply is truncated.
func (e *AgentEngine) contextReserveTokens() int {
- return max(e.getCompletionTokenBudget()+contextSafetyTokens, compaction.DefaultReserveTokens)
+ return reserveTokensFor(e.config)
+}
+
+func reserveTokensFor(cfg *types.AgentConfig) int {
+ return max(completionTokenBudgetFor(cfg)+contextSafetyTokens, compaction.DefaultReserveTokens)
+}
+
+// HistoryTokenBudget is how much stored history one run of cfg may load: the
+// whole context window, deliberately more than the compaction threshold.
+//
+// The loader drops the oldest turns that do not fit, and what it drops is
+// lost: it is neither replayed nor summarized. With a budget equal to the
+// threshold the loader always trimmed first, so whenever one turn was larger
+// than the system prompt plus the new question the request never crossed the
+// threshold, nothing was summarized, and the session became a sliding window
+// that never got a checkpoint. Loading up to the window leaves the overflow
+// to the first round's compaction instead, which summarizes it and persists a
+// checkpoint. The compactor bounds its own summarizer input, so a history this
+// large cannot make the summarization request itself overflow.
+func HistoryTokenBudget(cfg *types.AgentConfig) int {
+ if cfg != nil && cfg.MaxContextTokens > 0 {
+ return cfg.MaxContextTokens
+ }
+ return types.DefaultMaxContextTokens
}
// clampCompletionBudgetToContext shrinks the round's completion budget to what
diff --git a/internal/agent/engine.go b/internal/agent/engine.go
index 4e30df2c8..319e0fb20 100644
--- a/internal/agent/engine.go
+++ b/internal/agent/engine.go
@@ -48,7 +48,8 @@ type AgentEngine struct {
skillsManager *skills.Manager // Skills manager for Progressive Disclosure (optional)
appConfig *appconfig.Config // Application config for prompt template resolution (optional)
imageDescriber ImageDescriberFunc // VLM function for describing images in tool results (optional)
- tokenEstimator *agenttoken.Estimator // Token estimator for context window management
+ tokenEstimator *agenttoken.Estimator // Token estimator for context window management, calibrated
+ rawEstimator *agenttoken.Estimator // Same tokenizer at scale 1, for measuring the calibration
compactor *compaction.Compactor // Summarizes older history to fit the context window (nil = disabled)
lastUsage types.TokenUsage // Token usage from the most recent LLM call
lastSentMsgCount int // Number of messages sent in the most recent LLM call
@@ -64,7 +65,14 @@ type AgentEngine struct {
// checkpointSink, when set, persists compactions that end on a stored
// turn so later turns start from them. Nil keeps compaction turn-local.
checkpointSink types.ContextCheckpointSink
- modelContext *modelcontext.Registry // single request-local boundary for every model handle
+ // calibration learns the provider's tokens per estimated token from
+ // consecutive requests (see calibrateEstimator).
+ calibration tokenCalibration
+ // contextRewrites counts compactions and tool-result trims. Either one
+ // changes messages an earlier request already sent, so the next request
+ // cannot be compared with that one for calibration.
+ contextRewrites int
+ modelContext *modelcontext.Registry // single request-local boundary for every model handle
// steerSink, when set, lets users append messages into the running turn.
// Drained at every round boundary; nil disables mid-run injection.
steerSink types.SteerSink
@@ -99,6 +107,9 @@ func NewAgentEngine(
if err != nil {
return nil
}
+ // The previous turn's measured scale, so this turn's first compaction
+ // check is calibrated before it has a provider count of its own.
+ tokenEst.SetScale(config.ContextTokenScale)
engine := &AgentEngine{
config: config,
toolRegistry: toolRegistry,
@@ -109,6 +120,7 @@ func NewAgentEngine(
sessionID: sessionID,
systemPromptTemplate: systemPromptTemplate,
tokenEstimator: tokenEst,
+ rawEstimator: tokenEst.Unscaled(),
modelContext: modelcontext.NewRegistry(config.CitationsEnabled()),
}
@@ -118,6 +130,7 @@ func NewAgentEngine(
ReserveTokens: engine.contextReserveTokens(),
KeepRecentTokens: config.CompactionKeepRecentTokens,
MaxSummaryTokens: engine.getCompletionTokenBudget(),
+ StallTimeout: engine.getLLMStallTimeout(),
})
return engine
@@ -337,6 +350,11 @@ func (e *AgentEngine) Execute(
KnowledgeRefs: []*types.SearchResult{},
IsComplete: false,
CurrentRound: 0,
+ // A turn that measures no scale of its own (no tool call, so no two
+ // requests to compare) passes on the one it started from, so the
+ // newest turn always carries the latest known scale and the loader
+ // never has to look past its first page for one.
+ TurnUsage: types.TokenUsage{ContextTokenScale: e.config.ContextTokenScale},
}
// Build system prompt using progressive RAG prompt
@@ -719,6 +737,8 @@ func (e *AgentEngine) runReActIteration(
}
response = resp
e.logContextDrift(ctx, round, currentTokens, response.Usage)
+ // Calibration needs only a prompt count; some providers report no total.
+ e.calibrateEstimator(ctx, round, *messagesPtr, tools, response.Usage, state)
if response.Usage.TotalTokens > 0 {
e.lastUsage = response.Usage
state.TurnUsage.Accumulate(response.Usage)
diff --git a/internal/agent/engine_test.go b/internal/agent/engine_test.go
index 405fe0b36..68f00049c 100644
--- a/internal/agent/engine_test.go
+++ b/internal/agent/engine_test.go
@@ -451,6 +451,19 @@ func (s *summarizerChat) Chat(
return &types.ChatResponse{Content: "## Goal\ndo the thing", FinishReason: "stop"}, nil
}
+// ChatStream is how compaction calls the summarizer.
+func (s *summarizerChat) ChatStream(
+ ctx context.Context, messages []chat.Message, opts *chat.ChatOptions,
+) (<-chan types.StreamResponse, error) {
+ resp, _ := s.Chat(ctx, messages, opts)
+ ch := make(chan types.StreamResponse, 1)
+ ch <- types.StreamResponse{
+ ResponseType: types.ResponseTypeAnswer, Content: resp.Content, Done: true, FinishReason: resp.FinishReason,
+ }
+ close(ch)
+ return ch, nil
+}
+
// The bug this replaces: inside one ReAct turn nothing was compactable, so
// every round crossed the threshold, spent a summarization call, and freed
// nothing. The loop is only broken if a second pass over the compacted context
@@ -575,6 +588,39 @@ func TestContextCheckpointFailureKeepsTheCompaction(t *testing.T) {
require.Less(t, engine.tokenEstimator.EstimateMessages(compacted), before/2)
}
+// A compaction can be discarded for freeing too little and still have
+// summarized the stored history in full: a short stored history next to a
+// live turn whose weight is one result the cut cannot reach. That summary is a
+// valid checkpoint, and dropping it would have the next turn pay for it again.
+func TestContextCheckpointIsKeptWhenTheCompactionFreesTooLittle(t *testing.T) {
+ engine := newTestEngine(t, &summarizerChat{},
+ withMaxContextTokens(40000), withMaxCompletionTokens(4000))
+ sink := &recordingCheckpointSink{}
+ engine.SetContextCheckpointSink(sink)
+
+ messages := []chat.Message{
+ {Role: "system", Content: "you are an agent"},
+ {Role: "user", Content: "first question", TurnID: "turn-a"},
+ {Role: "assistant", Content: "first answer", TurnID: "turn-a"},
+ {Role: "user", Content: "read the export"},
+ {Role: "assistant", ToolCalls: []chat.ToolCall{{
+ ID: "call-1", Type: "function",
+ Function: chat.FunctionCall{Name: "read_file", Arguments: `{"path":"/w/export.csv"}`},
+ }}},
+ {Role: "tool", Name: "read_file", ToolCallID: "call-1", Content: strings.Repeat("row,value ", 12000)},
+ }
+ before := engine.tokenEstimator.EstimateMessages(messages)
+ require.True(t, engine.compactor.Settings().ShouldCompact(before))
+
+ result, err := engine.compactor.Compact(context.Background(), messages, compaction.ReasonThreshold)
+ require.NoError(t, err)
+ require.Less(t, result.Freed(), result.TokensBefore/minFreedFraction,
+ "the fixture must be a compaction the engine discards")
+
+ engine.manageContextWindow(context.Background(), messages, 1, before)
+ require.Equal(t, []string{"turn-a"}, sink.turnIDs)
+}
+
// Redacting a stored KB result must not detach it from its turn, or a summary
// ending on that turn could no longer be recognized as ending there.
func TestRedactHistoryKBResultsKeepsTurnID(t *testing.T) {
@@ -587,6 +633,44 @@ func TestRedactHistoryKBResultsKeepsTurnID(t *testing.T) {
require.Equal(t, "turn-a", redacted[0].TurnID)
}
+// History loads up to the whole window, past the compaction threshold, so the
+// overflow reaches the first round's compaction instead of being dropped by
+// the loader before compaction can see it.
+func TestHistoryTokenBudgetExceedsTheCompactionThreshold(t *testing.T) {
+ for _, tc := range []struct{ window, completion int }{
+ {window: 40000, completion: 4000},
+ {window: 200000, completion: 24576},
+ {window: 32768, completion: 0},
+ } {
+ engine := newTestEngine(t, &mockChat{},
+ withMaxContextTokens(tc.window), withMaxCompletionTokens(tc.completion))
+ budget := HistoryTokenBudget(engine.config)
+ require.Equal(t, tc.window, budget)
+ require.Greater(t, budget, engine.compactor.Settings().Threshold(),
+ "window=%d completion=%d", tc.window, tc.completion)
+ }
+ require.Equal(t, types.DefaultMaxContextTokens, HistoryTokenBudget(&types.AgentConfig{}),
+ "an unresolved window falls back to the default")
+}
+
+// The history loader prices turns with HistoryAsSent, so it must match what
+// buildMessagesWithLLMContext sends under both settings.
+func TestHistoryAsSentFollowsTheRetainSetting(t *testing.T) {
+ history := []chat.Message{
+ {Role: "tool", Name: agenttools.ToolWikiReadPage, ToolCallID: "c1", Content: "full page"},
+ {Role: "tool", Name: agenttools.ToolWebFetch, ToolCallID: "c2", Content: "fetched"},
+ }
+
+ redacted := HistoryAsSent(history, false)
+ require.NotEqual(t, "full page", redacted[0].Content)
+ require.Equal(t, "fetched", redacted[1].Content, "only KB and Wiki results are redacted")
+ require.Equal(t, "full page", HistoryAsSent(history, true)[0].Content)
+
+ engine := newTestEngine(t, &mockChat{})
+ sent := engine.buildMessagesWithLLMContext("system", "next", "s1", history, nil)
+ require.Equal(t, redacted[0].Content, sent[1].Content)
+}
+
// Asking for more output than the window can still hold is rejected outright
// by the provider, which surfaces to the agent as an unexplained failure.
func TestClampCompletionBudgetToContext(t *testing.T) {
diff --git a/internal/agent/finalize.go b/internal/agent/finalize.go
index 06871bb69..02cf69f76 100644
--- a/internal/agent/finalize.go
+++ b/internal/agent/finalize.go
@@ -180,7 +180,9 @@ func (e *AgentEngine) emitCompletionEvent(
// reported usage so the field stays absent from the completion event and the
// persisted message alike.
func turnUsage(state *types.AgentState) *types.TokenUsage {
- if state == nil || state.TurnUsage.TotalTokens == 0 {
+ // A token scale is worth persisting on its own: the next turn's history
+ // loading is calibrated by it even when this provider reported no total.
+ if state == nil || (state.TurnUsage.TotalTokens == 0 && state.TurnUsage.ContextTokenScale <= 0) {
return nil
}
usage := state.TurnUsage
diff --git a/internal/agent/observe.go b/internal/agent/observe.go
index c945412ef..a16bff69e 100644
--- a/internal/agent/observe.go
+++ b/internal/agent/observe.go
@@ -101,13 +101,19 @@ func (e *AgentEngine) runCompaction(
logger.Warnf(ctx, "[Agent][Round-%d] Compaction freed too little (%d → %d tokens); "+
"not attempting again at this size", round, result.TokensBefore, result.TokensAfter)
e.compactionExhaustedAt = len(messages)
+ // This context keeps its messages, but the stored history was still
+ // summarized, and that summary is as good a checkpoint as any. The
+ // usual case is a large live turn next to a short stored history:
+ // discarding it would have the next turn summarize the same history
+ // again.
+ e.saveContextCheckpoint(ctx, result.Checkpoint, round)
return messages, false
}
logger.Infof(ctx, "[Agent][Round-%d] Compacted (%s): %d → %d tokens, %d → %d messages "+
- "(split_turn=%v, degraded=%v)",
+ "(split_turn=%v, degraded=%v, omitted=%d)",
round, result.Reason, result.TokensBefore, result.TokensAfter,
- result.MessagesBefore, result.MessagesAfter, result.SplitTurn, result.Degraded)
+ result.MessagesBefore, result.MessagesAfter, result.SplitTurn, result.Degraded, result.Omitted)
// Where the surviving tokens went. If the retained tail is far larger than
// keep_recent, the cut point could not reach past one oversized message.
logger.Debugf(ctx, "[Agent][Round-%d][ctx] post-compaction: summary=%d tail=%d "+
@@ -125,6 +131,7 @@ func (e *AgentEngine) runCompaction(
})
e.emitContextCompacted(ctx, result, round)
e.saveContextCheckpoint(ctx, result.Checkpoint, round)
+ e.contextRewrites++
// The usage baseline described the pre-compaction context; keeping it
// would have the next round estimate against history that no longer
@@ -193,6 +200,7 @@ func (e *AgentEngine) trimToolResults(
return messages, false
}
logger.Infof(ctx, "[Agent][Round-%d] Trimmed tool results to the token budget", round)
+ e.contextRewrites++
return trimmed, true
}
@@ -929,6 +937,19 @@ func redactHistoryKBResults(llmContext []chat.Message) []chat.Message {
return redacted
}
+// HistoryAsSent is stored history as the engine sends it. Unless the agent
+// retains retrieval history, KB and Wiki tool results from earlier turns are
+// redacted, so the model does not reuse retrieval data the knowledge base may
+// have outgrown. The history loader prices turns with it too, so its token
+// budget is spent on what reaches the model, not on a wiki page that goes out
+// as one line.
+func HistoryAsSent(history []chat.Message, retainRetrievalHistory bool) []chat.Message {
+ if retainRetrievalHistory {
+ return history
+ }
+ return redactHistoryKBResults(history)
+}
+
// buildMessagesWithLLMContext builds the message array with LLM context
func (e *AgentEngine) buildMessagesWithLLMContext(
systemPrompt, currentQuery, sessionID string,
@@ -940,14 +961,10 @@ func (e *AgentEngine) buildMessagesWithLLMContext(
}
if len(llmContext) > 0 {
- var sanitized []chat.Message
+ sanitized := HistoryAsSent(llmContext, e.config.RetainRetrievalHistory)
if e.config.RetainRetrievalHistory {
- sanitized = llmContext
logger.Infof(context.Background(), "Retaining full retrieval history in context (RetainRetrievalHistory=true)")
} else {
- // Redact KB tool results from previous turns to prevent the LLM
- // from reusing stale retrieval data when the KB has been modified.
- sanitized = redactHistoryKBResults(llmContext)
logger.Infof(context.Background(), "Added %d history messages to context (KB tool results redacted)", len(llmContext))
}
diff --git a/internal/agent/token/estimator.go b/internal/agent/token/estimator.go
index e51efd718..7eeeb6514 100644
--- a/internal/agent/token/estimator.go
+++ b/internal/agent/token/estimator.go
@@ -21,6 +21,8 @@ package token
import (
"fmt"
+ "math"
+ "sync/atomic"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/tiktoken-go/tokenizer"
@@ -39,20 +41,64 @@ const (
estimatedImageTokens = 1200
)
+// Scale bounds. cl100k counts Chinese at about one token a character, where
+// Qwen and DeepSeek spend about 0.6, so a scale near the floor is expected for
+// Chinese sessions on those models. Anything outside the bounds says more
+// about a provider's usage report than about its tokenizer.
+const (
+ MinScale = 0.5
+ MaxScale = 1.5
+)
+
// Estimator counts tokens for messages and strings using BPE tokenization.
// It is intended for incremental (delta) estimation between LLM calls; the
// authoritative token count comes from the API's Usage response.
+//
+// cl100k is not the provider's tokenizer, so text counts are multiplied by a
+// scale learned from the provider's own counts (see SetScale). Every budget an
+// estimate is compared with is in provider tokens, so one scaled estimator
+// keeps them all consistent: history loading, the compaction trigger, and
+// compaction's own cut point and summarizer budget.
type Estimator struct {
codec tokenizer.Codec
+ // scale holds float64 bits. The engine recalibrates between rounds, which
+ // must not race an estimate a tool is still taking.
+ scale atomic.Uint64
}
-// NewEstimator creates a token estimator using the cl100k_base encoding.
+// NewEstimator creates a token estimator using the cl100k_base encoding, at
+// scale 1.
func NewEstimator() (*Estimator, error) {
codec, err := tokenizer.Get(tokenizer.Cl100kBase)
if err != nil {
return nil, fmt.Errorf("token: failed to initialize tokenizer: %w", err)
}
- return &Estimator{codec: codec}, nil
+ e := &Estimator{codec: codec}
+ e.SetScale(1)
+ return e, nil
+}
+
+// Scale is the factor text counts are multiplied by.
+func (e *Estimator) Scale() float64 {
+ return math.Float64frombits(e.scale.Load())
+}
+
+// SetScale sets the factor text counts are multiplied by, clamped to
+// [MinScale, MaxScale]. A non-positive scale means uncalibrated, which is 1.
+func (e *Estimator) SetScale(scale float64) {
+ if scale <= 0 || math.IsNaN(scale) {
+ scale = 1
+ }
+ scale = min(max(scale, MinScale), MaxScale)
+ e.scale.Store(math.Float64bits(scale))
+}
+
+// Unscaled returns an estimator with the same tokenizer at scale 1, for
+// measuring the raw count a scale is derived from.
+func (e *Estimator) Unscaled() *Estimator {
+ u := &Estimator{codec: e.codec}
+ u.SetScale(1)
+ return u
}
// EstimateMessages returns the estimated token count for a slice of messages.
@@ -71,11 +117,14 @@ func (e *Estimator) EstimateString(s string) int {
if len(s) == 0 {
return 0
}
- ids, _, err := e.codec.Encode(s)
- if err != nil {
- return (len(s) + 3) / 4
+ count := (len(s) + 3) / 4
+ if ids, _, err := e.codec.Encode(s); err == nil {
+ count = len(ids)
+ }
+ if scale := e.Scale(); scale != 1 {
+ return int(math.Round(float64(count) * scale))
}
- return len(ids)
+ return count
}
// EstimateMessage returns the token count for a single message.
diff --git a/internal/agent/token/estimator_test.go b/internal/agent/token/estimator_test.go
index f8f73c0df..14a569e41 100644
--- a/internal/agent/token/estimator_test.go
+++ b/internal/agent/token/estimator_test.go
@@ -2,6 +2,7 @@ package token
import (
"fmt"
+ "math"
"strings"
"testing"
@@ -140,3 +141,38 @@ func TestEstimateTools(t *testing.T) {
}}
assert.Greater(t, e.EstimateTools(tools), 100)
}
+
+// Text counts carry the provider's scale; per-message overhead and the fixed
+// image cost do not, since they are not text the provider tokenizes.
+func TestEstimatorScalesTextOnly(t *testing.T) {
+ e, err := NewEstimator()
+ assert.NoError(t, err)
+ text := strings.Repeat("知识库文档检索结果,", 100)
+ raw := e.EstimateString(text)
+
+ e.SetScale(0.6)
+ assert.InDelta(t, float64(raw)*0.6, float64(e.EstimateString(text)), 1)
+ assert.Equal(t, raw, e.Unscaled().EstimateString(text), "Unscaled measures the raw count")
+
+ msg := chat.Message{Role: "user", Content: text}
+ withoutText := chat.Message{Role: "user"}
+ assert.InDelta(t, float64(raw)*0.6,
+ float64(e.EstimateMessage(&msg)-e.EstimateMessage(&withoutText)), 1)
+}
+
+// The scale is clamped: outside the bounds it says more about a provider's
+// usage report than about its tokenizer. Unset or invalid means uncalibrated.
+func TestEstimatorScaleIsClamped(t *testing.T) {
+ e, err := NewEstimator()
+ assert.NoError(t, err)
+ assert.Equal(t, 1.0, e.Scale())
+
+ e.SetScale(0.1)
+ assert.Equal(t, MinScale, e.Scale())
+ e.SetScale(9)
+ assert.Equal(t, MaxScale, e.Scale())
+ e.SetScale(0)
+ assert.Equal(t, 1.0, e.Scale())
+ e.SetScale(math.NaN())
+ assert.Equal(t, 1.0, e.Scale())
+}
diff --git a/internal/agent/turn_usage_test.go b/internal/agent/turn_usage_test.go
index 195956b12..da2a5ddf9 100644
--- a/internal/agent/turn_usage_test.go
+++ b/internal/agent/turn_usage_test.go
@@ -31,3 +31,12 @@ func TestTurnUsageCopiesTheAggregate(t *testing.T) {
t.Fatalf("emitted usage must be detached from state: %+v", usage)
}
}
+
+// A token scale is worth persisting on its own: it calibrates the next turn's
+// history loading even when the provider reported no token counts.
+func TestTurnUsageKeepsAScaleWithoutTokenCounts(t *testing.T) {
+ usage := turnUsage(&types.AgentState{TurnUsage: types.TokenUsage{ContextTokenScale: 0.7}})
+ if usage == nil || usage.ContextTokenScale != 0.7 {
+ t.Fatalf("scale-only usage must be kept: %+v", usage)
+ }
+}
diff --git a/internal/application/repository/message.go b/internal/application/repository/message.go
index c36c83f32..465552151 100644
--- a/internal/application/repository/message.go
+++ b/internal/application/repository/message.go
@@ -2,6 +2,7 @@ package repository
import (
"context"
+ "fmt"
"slices"
"time"
@@ -167,6 +168,27 @@ func (r *messageRepository) ListMessagesBySessionAfterCursor(ctx context.Context
return messages, nil
}
+// ListMessagesBySessionBeforeCursor pages a session backwards: up to limit
+// messages sorting strictly before the (before, beforeID) cursor, newest first.
+// A zero cursor starts from the newest message. The ID tie-breaker keeps a page
+// boundary from skipping messages that share a timestamp.
+func (r *messageRepository) ListMessagesBySessionBeforeCursor(
+ ctx context.Context, sessionID string, before time.Time, beforeID string, limit int,
+) ([]*types.Message, error) {
+ var messages []*types.Message
+ query := r.db.WithContext(ctx).Where("session_id = ?", sessionID)
+ if !before.IsZero() || beforeID != "" {
+ query = query.Where("created_at < ? OR (created_at = ? AND id < ?)", before, before, beforeID)
+ }
+ if err := query.Order("created_at DESC, id DESC").Limit(limit).Find(&messages).Error; err != nil {
+ return nil, err
+ }
+ if err := attachArtifacts(ctx, r.db, messages...); err != nil {
+ return nil, err
+ }
+ return messages, nil
+}
+
// ListMessagesBySessionUpTo returns every message of a session that sorts
// strictly before the (boundary, boundaryID) cursor, oldest first.
//
@@ -407,26 +429,37 @@ func (r *messageRepository) UpdateMessageRenderedContent(ctx context.Context, se
}
// UpdateMessageContextCheckpoint updates only the context_checkpoint column, so
-// it cannot race a full-row write of the same message.
+// it cannot race a full-row write of the same message. A write that matches no
+// row (the turn was deleted, or the ID is not this session's assistant
+// message) is an error rather than a silent success.
func (r *messageRepository) UpdateMessageContextCheckpoint(
ctx context.Context, sessionID, messageID string, checkpoint *types.ContextCheckpoint,
) error {
- return r.db.WithContext(ctx).
+ result := r.db.WithContext(ctx).
Model(&types.Message{}).
- Where("id = ? AND session_id = ? AND role = ?", messageID, sessionID, "assistant").
- Update("context_checkpoint", checkpoint).Error
+ Where("id = ? AND session_id = ? AND role = 'assistant'", messageID, sessionID).
+ Update("context_checkpoint", checkpoint)
+ if result.Error != nil {
+ return result.Error
+ }
+ if result.RowsAffected == 0 {
+ return fmt.Errorf("no assistant message %s in session %s", messageID, sessionID)
+ }
+ return nil
}
// GetLatestContextCheckpoint returns the newest checkpointed assistant message.
// Only the identity and ordering columns come back with the checkpoint: the
-// caller matches it against turns it has already loaded.
+// caller matches it against turns it has already loaded. It walks
+// idx_messages_session_created_id backwards and stops at the first
+// checkpointed row, which in a compacting session is a recent one.
func (r *messageRepository) GetLatestContextCheckpoint(
ctx context.Context, sessionID string,
) (*types.Message, error) {
var messages []*types.Message
if err := r.db.WithContext(ctx).
Select("id", "session_id", "request_id", "role", "created_at", "context_checkpoint").
- Where("session_id = ? AND role = ? AND context_checkpoint IS NOT NULL", sessionID, "assistant").
+ Where("session_id = ? AND role = 'assistant' AND context_checkpoint IS NOT NULL", sessionID).
Order("created_at DESC, id DESC").
Limit(1).
Find(&messages).Error; err != nil {
diff --git a/internal/application/repository/message_context_checkpoint_test.go b/internal/application/repository/message_context_checkpoint_test.go
index d0b80cced..699b405fd 100644
--- a/internal/application/repository/message_context_checkpoint_test.go
+++ b/internal/application/repository/message_context_checkpoint_test.go
@@ -45,7 +45,8 @@ func TestGetLatestContextCheckpointReturnsTheNewestInTheSession(t *testing.T) {
}
// The session guard keeps a stray turn ID from writing into another session,
-// and the role guard keeps it off user rows.
+// and the role guard keeps it off user rows. Either way nothing was saved, and
+// the caller hears so instead of logging a checkpoint that does not exist.
func TestUpdateMessageContextCheckpointIsScopedToTheSessionsAssistantRows(t *testing.T) {
repo, db := newMessageRepositoryForForkTest(t)
ctx := context.Background()
@@ -54,10 +55,12 @@ func TestUpdateMessageContextCheckpointIsScopedToTheSessionsAssistantRows(t *tes
seedMessage(t, db, "u1", "s1", "user", at)
seedMessage(t, db, "a1", "s1", "assistant", at)
- require.NoError(t, repo.UpdateMessageContextCheckpoint(ctx, "s2", "a1",
- &types.ContextCheckpoint{Summary: "wrong session"}))
- require.NoError(t, repo.UpdateMessageContextCheckpoint(ctx, "s1", "u1",
+ require.Error(t, repo.UpdateMessageContextCheckpoint(ctx, "s2", "a1",
+ &types.ContextCheckpoint{Summary: "wrong session"}), "a write that matches no row is not a save")
+ require.Error(t, repo.UpdateMessageContextCheckpoint(ctx, "s1", "u1",
&types.ContextCheckpoint{Summary: "user row"}))
+ require.Error(t, repo.UpdateMessageContextCheckpoint(ctx, "s1", "gone",
+ &types.ContextCheckpoint{Summary: "deleted turn"}))
got, err := repo.GetLatestContextCheckpoint(ctx, "s1")
require.NoError(t, err)
@@ -85,3 +88,34 @@ func TestUpdateMessageKeepsAnExistingContextCheckpoint(t *testing.T) {
require.NotNil(t, got)
require.Equal(t, "kept", got.ContextCheckpoint.Summary)
}
+
+// Agent history pages a session backwards. Messages sharing a timestamp are
+// ordered by ID, so a page boundary among them neither skips nor repeats one.
+func TestListMessagesBySessionBeforeCursorPagesBackwardsWithoutGaps(t *testing.T) {
+ repo, db := newMessageRepositoryForForkTest(t)
+ ctx := context.Background()
+ base := time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
+
+ seedMessage(t, db, "m1", "s1", "user", base)
+ seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))
+ seedMessage(t, db, "m3-a", "s1", "user", base.Add(2*time.Second))
+ seedMessage(t, db, "m3-b", "s1", "assistant", base.Add(2*time.Second))
+ seedMessage(t, db, "m4", "s1", "user", base.Add(3*time.Second))
+ seedMessage(t, db, "other", "s2", "user", base.Add(time.Hour))
+ // Sorts inside the cursor's tie range; only the session filter keeps it out.
+ seedMessage(t, db, "a-other", "s2", "user", base.Add(2*time.Second))
+
+ first, err := repo.ListMessagesBySessionBeforeCursor(ctx, "s1", time.Time{}, "", 2)
+ require.NoError(t, err)
+ require.Equal(t, []string{"m4", "m3-b"}, messageIDs(first))
+
+ oldest := first[len(first)-1]
+ second, err := repo.ListMessagesBySessionBeforeCursor(ctx, "s1", oldest.CreatedAt, oldest.ID, 2)
+ require.NoError(t, err)
+ require.Equal(t, []string{"m3-a", "m2"}, messageIDs(second))
+
+ oldest = second[len(second)-1]
+ last, err := repo.ListMessagesBySessionBeforeCursor(ctx, "s1", oldest.CreatedAt, oldest.ID, 2)
+ require.NoError(t, err)
+ require.Equal(t, []string{"m1"}, messageIDs(last))
+}
diff --git a/internal/application/service/agent_history.go b/internal/application/service/agent_history.go
index 28b4e5c5b..c04087563 100644
--- a/internal/application/service/agent_history.go
+++ b/internal/application/service/agent_history.go
@@ -9,7 +9,9 @@ import (
"strings"
"time"
+ "github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/compaction"
+ agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
@@ -17,15 +19,14 @@ import (
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
-// agentHistoryFetchMultiplier controls how many raw DB messages to fetch
-// when assembling history. Each turn contributes ~2 rows (user + assistant);
-// we ask for a generous multiple so we never under-fetch when some pairs are
-// incomplete (e.g. an in-flight turn).
-const agentHistoryFetchMultiplier = 4
+// agentHistoryPageSize is how many rows one backwards page reads. A turn is
+// two rows plus one per steered message.
+const agentHistoryPageSize = 200
-// agentHistoryFetchMin is the floor for the DB fetch limit, used when
-// maxRounds is small or unset.
-const agentHistoryFetchMin = 50
+// agentHistoryMaxRows bounds one load however the session is shaped. The token
+// budget normally stops the read long before this; a run of turns that never
+// completed contributes no tokens and would otherwise page the whole session.
+const agentHistoryMaxRows = 5000
var agentHistoryThinkTagRegex = regexp.MustCompile(`(?s)<think>.*?</think>`)
@@ -43,14 +44,27 @@ var agentHistoryThinkTagRegex = regexp.MustCompile(`(?s)<think>.*?</think>`)
// 3. A final assistant message with the canonical answer (msg.Content with
// <think> blocks stripped).
//
-// Turns lacking either user or assistant content are skipped. The newest
-// maxRounds turns are returned in chronological order.
+// Turns lacking either user or assistant content are skipped. Turns are
+// returned in chronological order.
//
-// When a turn carries a context checkpoint (a compaction summary persisted by
-// an earlier run), history starts from it: the summary replaces that turn and
-// everything before it, and only later turns are replayed. Every replayed
-// message is tagged with its turn's assistant message ID so this run's
-// compaction can persist a new checkpoint in turn.
+// History is sized in tokens, not turns. When a turn carries a context
+// checkpoint (a compaction summary persisted by an earlier run), history starts
+// from it: the summary replaces that turn and everything before it. The newest
+// turns after that are replayed while they fit tokenBudget. A turn left out
+// is gone (neither replayed nor summarized), so the budget is the whole window
+// (agent.HistoryTokenBudget), past the compaction threshold: overflow reaches
+// the first round's compaction, which summarizes it into a new checkpoint.
+// Compaction, not a turn count, keeps a long session in the window. Every
+// replayed message is tagged with its turn's assistant message ID so this
+// run's compaction can persist that checkpoint.
+//
+// Rows are read backwards a page at a time and stop at the checkpoint or once
+// the budget is full, so a long session is never read whole. Turns are priced
+// as the engine sends them, so retainRetrievalHistory must be the run's
+// setting, and in the provider's tokens: estimates are scaled by the newest
+// turn's measured ContextTokenScale, which is also returned so the engine's
+// first compaction check uses the same scale. Budget and trigger must agree,
+// or turns the loader drops can sit below a trigger that never fires.
//
// DB is treated as the single source of truth — there is no Redis/in-memory
// cache layer above this function. Callers are expected to invoke it once
@@ -59,27 +73,148 @@ func LoadAgentHistory(
ctx context.Context,
messageRepo interfaces.MessageRepository,
sessionID string,
- maxRounds int,
-) ([]chat.Message, error) {
- if maxRounds <= 0 {
- return []chat.Message{}, nil
+ tokenBudget int,
+ retainRetrievalHistory bool,
+) ([]chat.Message, float64, error) {
+ if tokenBudget <= 0 {
+ return []chat.Message{}, 0, nil
+ }
+ estimator, err := agenttoken.NewEstimator()
+ if err != nil {
+ return nil, 0, fmt.Errorf("load agent history: %w", err)
}
- fetchLimit := maxRounds * agentHistoryFetchMultiplier
- if fetchLimit < agentHistoryFetchMin {
- fetchLimit = agentHistoryFetchMin
+ checkpoint := loadContextCheckpoint(ctx, messageRepo, sessionID)
+ out := []chat.Message{}
+ if checkpoint != nil {
+ out = append(out, compaction.SummaryMessage(checkpoint.ContextCheckpoint.Summary))
}
- rows, err := messageRepo.GetRecentMessagesBySession(ctx, sessionID, fetchLimit)
- if err != nil {
- return nil, fmt.Errorf("load agent history: %w", err)
+ var (
+ // rows keeps only what grouping and ordering need; the full rows wait
+ // in replay until their turn is replayed, then are released. A page of
+ // stored rows can hold whole wiki pages that go out as one line each.
+ rows []*types.Message
+ turns []*agentHistoryTurn
+ dropped bool
+ before time.Time
+ beforeID string
+ reachedStart bool
+ scale float64
+ used int
+ replay = newHistoryReplay(estimator, 0, retainRetrievalHistory)
+ )
+ for len(rows) < agentHistoryMaxRows {
+ page, err := messageRepo.ListMessagesBySessionBeforeCursor(
+ ctx, sessionID, before, beforeID, agentHistoryPageSize,
+ )
+ if err != nil {
+ return nil, 0, fmt.Errorf("load agent history: %w", err)
+ }
+ if len(rows) == 0 {
+ // Price everything in the provider's tokens, with the scale the
+ // engine will start from, or loading and the first compaction
+ // check disagree on where the window ends.
+ scale = latestContextTokenScale(page)
+ estimator.SetScale(scale)
+ used = estimator.EstimateMessages(out)
+ replay.budget = tokenBudget - used
+ }
+ for _, msg := range page {
+ rows = append(rows, replay.track(msg))
+ }
+ reachedStart = len(page) < agentHistoryPageSize
+ turns, dropped = replay.newestWithin(turnsAfterCheckpoint(completeHistoryTurns(rows, reachedStart), checkpoint))
+ if reachedStart || dropped {
+ break
+ }
+ oldest := page[len(page)-1]
+ if checkpoint != nil && sortsAtOrBefore(oldest, checkpoint) {
+ break
+ }
+ before, beforeID = oldest.CreatedAt, oldest.ID
}
+
+ for _, t := range turns {
+ out = append(out, replay.messages(t)...)
+ used += replay.tokens[t.assistant.ID]
+ }
+ checkpointID := ""
+ if checkpoint != nil {
+ checkpointID = checkpoint.ID
+ }
+ logger.Infof(ctx, "Agent history: %d turn(s), ~%d of %d tokens (scale %.2f), %d row(s) read, "+
+ "checkpoint=%q, older turns dropped for the budget=%v",
+ len(turns), used, tokenBudget, estimator.Scale(), len(rows), checkpointID, dropped)
+ if checkpoint != nil && dropped {
+ // Turns between the summary and the kept ones are missing. Normal
+ // compaction keeps this from happening; it takes several turns in a
+ // row whose compactions could not be persisted.
+ logger.Warnf(ctx, "Agent history after checkpoint %s exceeds the budget; "+
+ "older turns after it were dropped", checkpointID)
+ }
+ return out, scale, nil
+}
+
+// latestContextTokenScale is the scale the newest calibrated turn among rows
+// measured (TokenUsage.ContextTokenScale), or 0 when none did. The first page
+// holds the newest turns, so a session that calibrates at all has one there.
+func latestContextTokenScale(rows []*types.Message) float64 {
+ var newest *types.Message
+ for _, msg := range rows {
+ if msg.Role != "assistant" || msg.Usage == nil || msg.Usage.ContextTokenScale <= 0 {
+ continue
+ }
+ if newest == nil || sortsAtOrBefore(newest, msg) {
+ newest = msg
+ }
+ }
+ if newest == nil {
+ return 0
+ }
+ return newest.Usage.ContextTokenScale
+}
+
+// agentHistoryTurn is one stored turn. A turn is not always one user message.
+// Mid-run steering persists every injected message under the running turn's
+// request ID, so a turn can be user → tools → user → tools → answer. Keeping
+// only the last user row would drop the original question from the next
+// turn's context.
+type agentHistoryTurn struct {
+ users []*types.Message
+ assistant *types.Message
+ createdAt time.Time
+}
+
+// completeHistoryTurns groups rows into completed turns, oldest first. Unless
+// the read reached the session's first row, the turn owning the oldest row
+// read may be missing its earlier rows — its original question above all — so
+// it is left out. When that oldest row is itself a user message the turn is
+// whole: steered messages are written after the turn's assistant row, so a
+// user row older than it can only be the question, and a steered row with no
+// assistant read after it leaves the turn incomplete anyway.
+func completeHistoryTurns(rows []*types.Message, reachedStart bool) []*agentHistoryTurn {
if len(rows) == 0 {
- return []chat.Message{}, nil
+ return nil
+ }
+ partialRequest, dropPartial := "", false
+ if !reachedStart {
+ oldest := rows[0]
+ for _, msg := range rows[1:] {
+ if sortsAtOrBefore(msg, oldest) {
+ oldest = msg
+ }
+ }
+ if oldest.Role != "user" {
+ partialRequest, dropPartial = oldest.RequestID, true
+ }
}
turns := make(map[string]*agentHistoryTurn)
for _, msg := range rows {
+ if dropPartial && msg.RequestID == partialRequest {
+ continue
+ }
t, ok := turns[msg.RequestID]
if !ok {
t = &agentHistoryTurn{}
@@ -96,56 +231,124 @@ func LoadAgentHistory(
}
}
- completeTurns := make([]*agentHistoryTurn, 0, len(turns))
+ complete := make([]*agentHistoryTurn, 0, len(turns))
for _, t := range turns {
if len(t.users) > 0 && t.assistant != nil && t.assistant.IsCompleted {
sort.SliceStable(t.users, func(i, j int) bool {
return t.users[i].CreatedAt.Before(t.users[j].CreatedAt)
})
- completeTurns = append(completeTurns, t)
+ complete = append(complete, t)
}
}
-
- sort.Slice(completeTurns, func(i, j int) bool {
- return completeTurns[i].createdAt.Before(completeTurns[j].createdAt)
+ sort.Slice(complete, func(i, j int) bool {
+ return complete[i].createdAt.Before(complete[j].createdAt)
})
+ return complete
+}
- summary := ""
- if checkpoint := loadContextCheckpoint(ctx, messageRepo, sessionID); checkpoint != nil {
- completeTurns = turnsAfterCheckpoint(completeTurns, checkpoint)
- summary = checkpoint.ContextCheckpoint.Summary
- logger.Infof(ctx, "Agent history resumes from the context checkpoint on %s, %d turn(s) after it",
- checkpoint.ID, len(completeTurns))
- }
+// sortsAtOrBefore reports whether msg sorts at or before boundary in the
+// (created_at, id) order the backwards read pages in.
+func sortsAtOrBefore(msg, boundary *types.Message) bool {
+ return msg.CreatedAt.Before(boundary.CreatedAt) ||
+ (msg.CreatedAt.Equal(boundary.CreatedAt) && msg.ID <= boundary.ID)
+}
+
+// historyReplay builds and prices each turn's replayed messages once, however
+// many pages the read takes.
+type historyReplay struct {
+ estimator *agenttoken.Estimator
+ budget int
+ retainRetrievalHistory bool
+ built map[string][]chat.Message
+ tokens map[string]int
+ // full holds stored rows by ID until their turn is replayed.
+ full map[string]*types.Message
+}
- if len(completeTurns) > maxRounds {
- completeTurns = completeTurns[len(completeTurns)-maxRounds:]
+func newHistoryReplay(
+ estimator *agenttoken.Estimator, budget int, retainRetrievalHistory bool,
+) *historyReplay {
+ return &historyReplay{
+ estimator: estimator,
+ budget: budget,
+ retainRetrievalHistory: retainRetrievalHistory,
+ built: make(map[string][]chat.Message),
+ tokens: make(map[string]int),
+ full: make(map[string]*types.Message),
}
+}
- out := make([]chat.Message, 0, len(completeTurns)*4+1)
- if summary != "" {
- out = append(out, compaction.SummaryMessage(summary))
+// track holds a stored row until its turn is replayed and returns the slim
+// copy grouping works on.
+func (r *historyReplay) track(msg *types.Message) *types.Message {
+ r.full[msg.ID] = msg
+ return &types.Message{
+ ID: msg.ID,
+ RequestID: msg.RequestID,
+ Role: msg.Role,
+ CreatedAt: msg.CreatedAt,
+ IsCompleted: msg.IsCompleted,
}
- for _, t := range completeTurns {
- start := len(out)
- out = append(out, buildUserHistoryMessage(t.users[0]))
- out = append(out, buildTurnBodyMessages(t.assistant, t.users[1:])...)
- for i := start; i < len(out); i++ {
- out[i].TurnID = t.assistant.ID
- }
+}
+
+// messages replays one turn as the engine will send it (agent.HistoryAsSent),
+// tagged with its assistant message ID, and releases the stored rows it was
+// built from. Replaying what is sent, not what is stored, keeps pricing and
+// loading on the same footing: a wiki page stored in full but sent as one line
+// costs one line and is held in memory as one line.
+func (r *historyReplay) messages(t *agentHistoryTurn) []chat.Message {
+ id := t.assistant.ID
+ if msgs, ok := r.built[id]; ok {
+ return msgs
+ }
+ users := make([]*types.Message, len(t.users))
+ for i, u := range t.users {
+ users[i] = r.stored(u)
+ }
+ msgs := append([]chat.Message{buildUserHistoryMessage(users[0])},
+ buildTurnBodyMessages(r.stored(t.assistant), users[1:])...)
+ for i := range msgs {
+ msgs[i].TurnID = id
+ }
+ sent := agent.HistoryAsSent(msgs, r.retainRetrievalHistory)
+ tokens := 0
+ for i := range sent {
+ tokens += r.estimator.EstimateMessage(&sent[i])
+ }
+ r.built[id] = sent
+ r.tokens[id] = tokens
+ for _, u := range t.users {
+ delete(r.full, u.ID)
+ }
+ delete(r.full, t.assistant.ID)
+ return sent
+}
+
+// stored returns the full row behind msg, or msg itself when it is not a
+// tracked slim copy (callers that group full rows directly).
+func (r *historyReplay) stored(msg *types.Message) *types.Message {
+ if full, ok := r.full[msg.ID]; ok {
+ return full
}
- return out, nil
+ return msg
}
-// agentHistoryTurn is one stored turn. A turn is not always one user message.
-// Mid-run steering persists every injected message under the running turn's
-// request ID, so a turn can be user → tools → user → tools → answer. Keeping
-// only the last user row would drop the original question from the next
-// turn's context.
-type agentHistoryTurn struct {
- users []*types.Message
- assistant *types.Message
- createdAt time.Time
+// newestWithin keeps the newest turns that fit the budget and reports whether
+// an older one had to be left out. It stops at the first turn that does not
+// fit, so what is kept stays contiguous. The newest turn is kept regardless:
+// it is what the next message most likely refers to, and compaction can split
+// a turn too large to fit on its own.
+func (r *historyReplay) newestWithin(turns []*agentHistoryTurn) ([]*agentHistoryTurn, bool) {
+ used := 0
+ for i := len(turns) - 1; i >= 0; i-- {
+ r.messages(turns[i])
+ cost := r.tokens[turns[i].assistant.ID]
+ if used+cost > r.budget && i < len(turns)-1 {
+ return turns[i+1:], true
+ }
+ used += cost
+ }
+ return turns, false
}
// loadContextCheckpoint returns the session's newest usable checkpoint, or nil.
@@ -167,9 +370,18 @@ func loadContextCheckpoint(
}
// turnsAfterCheckpoint drops the turns a checkpoint already covers: its own
-// turn and every turn before it. A checkpoint older than the loaded window is
-// matched by time instead, which keeps every loaded turn.
+// turn and every turn before it. A nil checkpoint covers nothing.
+//
+// When the checkpoint's own turn was not read whole (the budget filled first,
+// or the read ended on it), a turn is kept when its assistant row sorts after
+// the checkpoint's in the (created_at, id) order the read pages in. Comparing
+// assistant row with assistant row keeps a turn whose question shares the
+// checkpoint's timestamp; a turn's first user time against the checkpoint's
+// assistant time dropped it.
func turnsAfterCheckpoint(turns []*agentHistoryTurn, checkpoint *types.Message) []*agentHistoryTurn {
+ if checkpoint == nil {
+ return turns
+ }
for i, t := range turns {
if t.assistant.ID == checkpoint.ID {
return turns[i+1:]
@@ -177,7 +389,7 @@ func turnsAfterCheckpoint(turns []*agentHistoryTurn, checkpoint *types.Message)
}
after := make([]*agentHistoryTurn, 0, len(turns))
for _, t := range turns {
- if t.createdAt.After(checkpoint.CreatedAt) {
+ if !sortsAtOrBefore(t.assistant, checkpoint) {
after = append(after, t)
}
}
diff --git a/internal/application/service/agent_history_cadence_test.go b/internal/application/service/agent_history_cadence_test.go
new file mode 100644
index 000000000..ed27cd362
--- /dev/null
+++ b/internal/application/service/agent_history_cadence_test.go
@@ -0,0 +1,221 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/agent"
+ "github.com/Tencent/WeKnora/internal/agent/compaction"
+ agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
+ "github.com/Tencent/WeKnora/internal/models/chat"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+// cadenceChat answers every summarization with a fixed, modest summary, or,
+// when failing, errors the way a summarizer that times out on large inputs
+// does every time.
+type cadenceChat struct{ failing bool }
+
+func (c cadenceChat) Chat(context.Context, []chat.Message, *chat.ChatOptions) (*types.ChatResponse, error) {
+ if c.failing {
+ return nil, errors.New("summarization stalled")
+ }
+ return &types.ChatResponse{Content: "## Goal\n" + strings.Repeat("summary ", 200), FinishReason: "stop"}, nil
+}
+
+func (c cadenceChat) ChatStream(
+ ctx context.Context, messages []chat.Message, opts *chat.ChatOptions,
+) (<-chan types.StreamResponse, error) {
+ resp, err := c.Chat(ctx, messages, opts)
+ if err != nil {
+ return nil, err
+ }
+ ch := make(chan types.StreamResponse, 1)
+ ch <- types.StreamResponse{
+ ResponseType: types.ResponseTypeAnswer, Content: resp.Content, Done: true, FinishReason: resp.FinishReason,
+ }
+ close(ch)
+ return ch, nil
+}
+func (cadenceChat) GetModelName() string { return "cadence" }
+func (cadenceChat) GetModelID() string { return "cadence" }
+
+// cadenceRepo keeps checkpoints on its rows, the way the messages table does.
+type cadenceRepo struct{ historyRepo }
+
+func (r *cadenceRepo) GetLatestContextCheckpoint(context.Context, string) (*types.Message, error) {
+ var latest *types.Message
+ for _, m := range r.rows {
+ if m.ContextCheckpoint != nil && (latest == nil || sortsAtOrBefore(latest, m)) {
+ latest = m
+ }
+ }
+ return latest, nil
+}
+
+func (r *cadenceRepo) UpdateMessageContextCheckpoint(
+ _ context.Context, _, messageID string, checkpoint *types.ContextCheckpoint,
+) error {
+ for _, m := range r.rows {
+ if m.ID == messageID && m.Role == "assistant" {
+ m.ContextCheckpoint = checkpoint
+ return nil
+ }
+ }
+ return fmt.Errorf("no assistant message %s", messageID)
+}
+
+// runSessionCadence plays turns through the real loader, budget and compactor
+// the way AgentQA and the engine do: load history, compact at round one when
+// the request crosses the threshold, persist the checkpoint compaction offers.
+// It fails the test the moment a stored turn after the checkpoint is missing
+// from the loaded history, and returns the turns that compacted.
+// A positive scale stands for the provider's tokens per estimated token that
+// the engine measured and stored on each turn; the loader returns it and the
+// engine's estimator, shared with its compactor, runs at it.
+func runSessionCadence(t *testing.T, turns, systemTokens, turnTokens int, scale float64) []int {
+ t.Helper()
+ return runSessionCadenceWith(t, cadenceChat{}, turns, systemTokens, turnTokens, scale)
+}
+
+func runSessionCadenceWith(
+ t *testing.T, summarizer cadenceChat, turns, systemTokens, turnTokens int, scale float64,
+) []int {
+ t.Helper()
+ const window = 40000
+ cfg := &types.AgentConfig{MaxContextTokens: window}
+ est, err := agenttoken.NewEstimator()
+ require.NoError(t, err)
+ settings := compaction.Settings{Enabled: true, MaxContextTokens: window, ReserveTokens: 16384}
+ compactor := compaction.New(summarizer, est, settings)
+ repo := &cadenceRepo{}
+ system := chat.Message{Role: "system", Content: strings.Repeat("rule ", systemTokens)}
+
+ var compacted []int
+ for i := 1; i <= turns; i++ {
+ ctx := context.Background()
+ history, loadedScale, err := LoadAgentHistory(ctx, repo, "s1", agent.HistoryTokenBudget(cfg), false)
+ require.NoError(t, err)
+ est.SetScale(loadedScale)
+ requireNoGapAfterCheckpoint(t, repo, history, i)
+
+ request := append(append([]chat.Message{system}, history...),
+ chat.Message{Role: "user", Content: fmt.Sprintf("question %d", i)})
+ if settings.ShouldCompact(est.EstimateMessages(request)) {
+ result, err := compactor.Compact(ctx, request, compaction.ReasonThreshold)
+ require.NoError(t, err)
+ compacted = append(compacted, i)
+ if cp := result.Checkpoint; cp != nil {
+ require.NoError(t, repo.UpdateMessageContextCheckpoint(ctx, "s1", cp.TurnID,
+ &types.ContextCheckpoint{Summary: cp.Summary}))
+ }
+ }
+
+ at := historyBase.Add(time.Duration(i) * time.Minute)
+ req := fmt.Sprintf("req-%d", i)
+ repo.rows = append(repo.rows,
+ &types.Message{
+ ID: fmt.Sprintf("u%03d", i), RequestID: req, Role: "user",
+ Content: fmt.Sprintf("question %d", i), CreatedAt: at,
+ },
+ &types.Message{
+ ID: fmt.Sprintf("a%03d", i), RequestID: req, Role: "assistant", IsCompleted: true,
+ Content: strings.Repeat("word ", turnTokens), CreatedAt: at.Add(time.Second),
+ Usage: &types.TokenUsage{ContextTokenScale: scale},
+ },
+ )
+ }
+ return compacted
+}
+
+// requireNoGapAfterCheckpoint checks the loaded history replays every stored
+// turn after the newest checkpoint, in order: a turn neither summarized nor
+// replayed is gone for good.
+func requireNoGapAfterCheckpoint(t *testing.T, repo *cadenceRepo, history []chat.Message, turn int) {
+ t.Helper()
+ first := 1
+ if cp, _ := repo.GetLatestContextCheckpoint(context.Background(), "s1"); cp != nil {
+ _, err := fmt.Sscanf(cp.ID, "a%03d", &first)
+ require.NoError(t, err)
+ first++
+ }
+ var want, got []string
+ for n := first; n < turn; n++ {
+ want = append(want, fmt.Sprintf("a%03d", n))
+ }
+ for _, m := range history {
+ if m.TurnID != "" && (len(got) == 0 || got[len(got)-1] != m.TurnID) {
+ got = append(got, m.TurnID)
+ }
+ }
+ require.Equal(t, want, got, "turn %d: stored turns after the checkpoint must all be replayed", turn)
+}
+
+// The regression this guards: with a loading budget equal to the compaction
+// threshold, the loader trimmed the oldest turns first, so whenever one turn
+// was larger than the system prompt plus the new question the request never
+// crossed the threshold. Nothing was summarized, no checkpoint was written,
+// and the dropped turns were simply gone. Loading up to the window leaves the
+// overflow to compaction: turns are either replayed or summarized, compaction
+// recurs as the session refills, and the turn after one does not compact again.
+func TestAgentHistoryCompactsInsteadOfDroppingTurns(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ turns, systemTokens, turnTokens int
+ scale float64
+ }{
+ {"turns larger than the system prompt", 60, 300, 1000, 0},
+ {"turns larger than the keep-recent budget", 60, 300, 9000, 0},
+ {"system prompt larger than a turn", 60, 2000, 1000, 0},
+ // Calibrated sessions: loading and the compaction trigger must scale
+ // together, or the loader drops turns under a trigger that never fires.
+ // Cheaper turns take longer to refill the window.
+ {"provider counts fewer tokens than the estimate", 90, 300, 1000, 0.6},
+ {"provider counts more tokens than the estimate", 60, 300, 1000, 1.4},
+ {"large turns, provider counts fewer tokens", 60, 300, 9000, 0.6},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ compacted := runSessionCadence(t, tc.turns, tc.systemTokens, tc.turnTokens, tc.scale)
+ t.Logf("compacted at turns %v", compacted)
+
+ require.GreaterOrEqual(t, len(compacted), 2, "a session that keeps growing must keep compacting")
+ for i := 1; i < len(compacted); i++ {
+ require.Greater(t, compacted[i]-compacted[i-1], 1,
+ "turn %d compacted right after turn %d: the checkpoint did not take", compacted[i], compacted[i-1])
+ }
+ })
+ }
+}
+
+// Calibration is what makes the window fill: with the provider spending 0.6
+// tokens per estimated one, the first compaction comes well after the one an
+// uncalibrated session reaches, because the estimate no longer overstates it.
+func TestCalibratedSessionFillsMoreOfTheWindow(t *testing.T) {
+ uncalibrated := runSessionCadence(t, 60, 300, 1000, 0)
+ calibrated := runSessionCadence(t, 60, 300, 1000, 0.6)
+ require.NotEmpty(t, uncalibrated)
+ require.NotEmpty(t, calibrated)
+ require.Greater(t, calibrated[0], uncalibrated[0]*3/2)
+}
+
+// A summarizer that fails every time (the large request that always times out)
+// used to leave no checkpoint, so every later turn reloaded the same history
+// and compacted it again. The raw archive is now kept as a degraded
+// checkpoint: compaction still recurs only as the session refills, and no
+// stored turn goes missing.
+func TestAgentHistoryDoesNotRecompactAfterTheSummarizerFails(t *testing.T) {
+ compacted := runSessionCadenceWith(t, cadenceChat{failing: true}, 60, 300, 1000, 0)
+ t.Logf("compacted at turns %v", compacted)
+
+ require.GreaterOrEqual(t, len(compacted), 2)
+ for i := 1; i < len(compacted); i++ {
+ require.Greater(t, compacted[i]-compacted[i-1], 1,
+ "turn %d compacted right after turn %d: the failed compaction left no checkpoint",
+ compacted[i], compacted[i-1])
+ }
+}
diff --git a/internal/application/service/agent_history_checkpoint_test.go b/internal/application/service/agent_history_checkpoint_test.go
index 339cdc8dd..afc994e96 100644
--- a/internal/application/service/agent_history_checkpoint_test.go
+++ b/internal/application/service/agent_history_checkpoint_test.go
@@ -4,9 +4,13 @@ import (
"context"
"errors"
"fmt"
+ "sort"
+ "strings"
"testing"
"time"
+ agenttoken "github.com/Tencent/WeKnora/internal/agent/token"
+ agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -14,28 +18,44 @@ import (
"github.com/stretchr/testify/require"
)
-// checkpointHistoryRepo serves a fixed message list and one checkpoint lookup.
-type checkpointHistoryRepo struct {
+// historyRepo pages a fixed message list backwards the way the database does
+// and serves one checkpoint lookup.
+type historyRepo struct {
interfaces.MessageRepository
rows []*types.Message
checkpoint *types.Message
checkpointErr error
updates []string
+ pages int
}
-func (r *checkpointHistoryRepo) GetRecentMessagesBySession(
- context.Context, string, int,
+func (r *historyRepo) ListMessagesBySessionBeforeCursor(
+ _ context.Context, _ string, before time.Time, beforeID string, limit int,
) ([]*types.Message, error) {
- return r.rows, nil
+ r.pages++
+ sorted := append([]*types.Message(nil), r.rows...)
+ sort.Slice(sorted, func(i, j int) bool { return !sortsAtOrBefore(sorted[i], sorted[j]) })
+ var out []*types.Message
+ for _, m := range sorted {
+ cursor := &types.Message{ID: beforeID, CreatedAt: before}
+ if (!before.IsZero() || beforeID != "") && sortsAtOrBefore(cursor, m) {
+ continue
+ }
+ out = append(out, m)
+ if len(out) == limit {
+ break
+ }
+ }
+ return out, nil
}
-func (r *checkpointHistoryRepo) GetLatestContextCheckpoint(
+func (r *historyRepo) GetLatestContextCheckpoint(
context.Context, string,
) (*types.Message, error) {
return r.checkpoint, r.checkpointErr
}
-func (r *checkpointHistoryRepo) UpdateMessageContextCheckpoint(
+func (r *historyRepo) UpdateMessageContextCheckpoint(
_ context.Context, sessionID, messageID string, checkpoint *types.ContextCheckpoint,
) error {
r.updates = append(r.updates, sessionID+"/"+messageID+"/"+checkpoint.Summary)
@@ -44,12 +64,17 @@ func (r *checkpointHistoryRepo) UpdateMessageContextCheckpoint(
var historyBase = time.Date(2026, 9, 18, 9, 0, 0, 0, time.UTC)
-// storedTurns builds n completed turns; turn i has user u<i> and assistant a<i>.
-func storedTurns(n int) []*types.Message {
+// storedTurnsOfSize builds n completed turns; turn i has user u<i> and
+// assistant a<i>, and its answer is padded to roughly answerTokens tokens.
+func storedTurnsOfSize(n, answerTokens int) []*types.Message {
var rows []*types.Message
for i := 1; i <= n; i++ {
at := historyBase.Add(time.Duration(i) * time.Minute)
req := fmt.Sprintf("req-%d", i)
+ answer := fmt.Sprintf("answer %d", i)
+ if answerTokens > 0 {
+ answer += " " + strings.Repeat("word ", answerTokens)
+ }
rows = append(rows,
&types.Message{
ID: fmt.Sprintf("u%d", i), RequestID: req, Role: "user",
@@ -57,13 +82,15 @@ func storedTurns(n int) []*types.Message {
},
&types.Message{
ID: fmt.Sprintf("a%d", i), RequestID: req, Role: "assistant",
- Content: fmt.Sprintf("answer %d", i), IsCompleted: true, CreatedAt: at.Add(time.Second),
+ Content: answer, IsCompleted: true, CreatedAt: at.Add(time.Second),
},
)
}
return rows
}
+func storedTurns(n int) []*types.Message { return storedTurnsOfSize(n, 0) }
+
func checkpointOn(msg *types.Message, summary string) *types.Message {
return &types.Message{
ID: msg.ID, SessionID: msg.SessionID, RequestID: msg.RequestID, Role: "assistant",
@@ -79,12 +106,24 @@ func contents(msgs []chat.Message) []string {
return out
}
+func questions(msgs []chat.Message) []string {
+ var out []string
+ for _, m := range msgs {
+ if m.Role == "user" && m.Kind == "" {
+ out = append(out, m.Content)
+ }
+ }
+ return out
+}
+
+const unlimitedBudget = 1 << 30
+
// Without a checkpoint history is what it always was, plus the turn tags the
// engine needs to recognize a summary that ends on a stored turn.
func TestLoadAgentHistoryTagsEveryMessageWithItsTurn(t *testing.T) {
- repo := &checkpointHistoryRepo{rows: storedTurns(2)}
+ repo := &historyRepo{rows: storedTurns(2)}
- got, err := LoadAgentHistory(context.Background(), repo, "s1", 5)
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", unlimitedBudget, false)
require.NoError(t, err)
require.Equal(t, []string{"question 1", "answer 1", "question 2", "answer 2"}, contents(got))
@@ -93,13 +132,23 @@ func TestLoadAgentHistoryTagsEveryMessageWithItsTurn(t *testing.T) {
}
}
+// The turn count no longer bounds history: every turn that fits the budget is
+// replayed, however many there are.
+func TestLoadAgentHistoryIsNotCappedByTurnCount(t *testing.T) {
+ repo := &historyRepo{rows: storedTurns(40)}
+
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", unlimitedBudget, false)
+ require.NoError(t, err)
+ assert.Len(t, questions(got), 40)
+}
+
// The summary replaces its own turn and every turn before it; later turns are
// replayed verbatim after it.
func TestLoadAgentHistoryResumesFromTheCheckpoint(t *testing.T) {
rows := storedTurns(4)
- repo := &checkpointHistoryRepo{rows: rows, checkpoint: checkpointOn(rows[3], "## Goal\nturns one and two")}
+ repo := &historyRepo{rows: rows, checkpoint: checkpointOn(rows[3], "## Goal\nturns one and two")}
- got, err := LoadAgentHistory(context.Background(), repo, "s1", 5)
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", unlimitedBudget, false)
require.NoError(t, err)
require.Len(t, got, 5)
@@ -112,54 +161,177 @@ func TestLoadAgentHistoryResumesFromTheCheckpoint(t *testing.T) {
assert.Equal(t, "a4", got[4].TurnID)
}
-// A checkpoint can predate the rows fetched for the window. It still covers
-// everything before it, and every fetched turn is newer.
-func TestLoadAgentHistoryUsesACheckpointOlderThanTheWindow(t *testing.T) {
- rows := storedTurns(4)
- repo := &checkpointHistoryRepo{rows: rows[4:], checkpoint: checkpointOn(rows[1], "## Goal\nturn one")}
+// Rows the checkpoint already covers are never needed, so the read stops at
+// the page that reaches it instead of walking the whole session.
+func TestLoadAgentHistoryStopsReadingAtTheCheckpoint(t *testing.T) {
+ rows := storedTurns(300) // 600 rows, three pages
+ repo := &historyRepo{rows: rows, checkpoint: checkpointOn(rows[2*250-1], "## Goal\nthe first 250 turns")}
- got, err := LoadAgentHistory(context.Background(), repo, "s1", 5)
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", unlimitedBudget, false)
require.NoError(t, err)
- require.Len(t, got, 5)
- assert.Contains(t, got[0].Content, "turn one")
- assert.Equal(t, []string{"question 3", "answer 3", "question 4", "answer 4"}, contents(got[1:]))
+ assert.Equal(t, 1, repo.pages)
+ qs := questions(got)
+ require.Len(t, qs, 50)
+ assert.Equal(t, "question 251", qs[0])
+ assert.Equal(t, "question 300", qs[49])
}
-// The turn cap bounds the verbatim turns after the checkpoint, not the
-// summary, which is already bounded by the summarizer's budget.
-func TestLoadAgentHistoryCapsTurnsAfterTheCheckpoint(t *testing.T) {
- rows := storedTurns(3)
- repo := &checkpointHistoryRepo{rows: rows, checkpoint: checkpointOn(rows[1], "## Goal\nturn one")}
+// A session with no checkpoint is read only until the budget is full.
+func TestLoadAgentHistoryStopsReadingOnceTheBudgetIsFull(t *testing.T) {
+ repo := &historyRepo{rows: storedTurnsOfSize(300, 1000)}
- got, err := LoadAgentHistory(context.Background(), repo, "s1", 1)
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", 5500, false)
+ require.NoError(t, err)
+
+ assert.Equal(t, 1, repo.pages)
+ assert.Equal(t, []string{"question 296", "question 297", "question 298", "question 299", "question 300"},
+ questions(got), "the newest turns that fit, contiguous")
+}
+
+// The newest turn is what the next message most likely refers to. It is kept
+// even when it alone exceeds the budget; compaction can split it.
+func TestLoadAgentHistoryKeepsAnOversizedNewestTurn(t *testing.T) {
+ repo := &historyRepo{rows: storedTurnsOfSize(3, 1000)}
+
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", 100, false)
+ require.NoError(t, err)
+ assert.Equal(t, []string{"question 3"}, questions(got))
+}
+
+// Turns after the checkpoint that no longer fit are dropped oldest first. The
+// summary stays: it is the only record of how the session began.
+func TestLoadAgentHistoryBudgetsTurnsAfterTheCheckpoint(t *testing.T) {
+ rows := storedTurnsOfSize(6, 1000)
+ repo := &historyRepo{rows: rows, checkpoint: checkpointOn(rows[1], "## Goal\nturn one")}
+
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", 2500, false)
require.NoError(t, err)
- require.Len(t, got, 3)
assert.Equal(t, chat.MessageKindCompactionSummary, got[0].Kind)
- assert.Equal(t, []string{"question 3", "answer 3"}, contents(got[1:]))
+ assert.Equal(t, []string{"question 5", "question 6"}, questions(got))
+}
+
+// storedWikiTurns builds n completed turns that each read a wiki page of
+// roughly pageTokens tokens. Stored history keeps the page in full.
+func storedWikiTurns(n, pageTokens int) []*types.Message {
+ rows := storedTurns(n)
+ for i := 1; i < len(rows); i += 2 {
+ rows[i].AgentSteps = types.AgentSteps{{
+ Thought: "reading the page",
+ ToolCalls: []types.ToolCall{{
+ ID: fmt.Sprintf("call-%d", i),
+ Name: agenttools.ToolWikiReadPage,
+ Args: map[string]interface{}{"slugs": []string{"overview"}},
+ Result: &types.ToolResult{Success: true, Output: strings.Repeat("page ", pageTokens)},
+ }},
+ }}
+ }
+ return rows
+}
+
+// The engine sends an earlier turn's wiki page as a one-line marker unless the
+// agent retains retrieval history. The loader prices and returns what is sent:
+// pricing the stored page spent the budget on text the model never sees, and
+// returning it held every loaded page in memory only to redact it later.
+func TestLoadAgentHistoryReturnsTurnsAsTheEngineSendsThem(t *testing.T) {
+ repo := &historyRepo{rows: storedWikiTurns(5, 2000)}
+ toolContent := func(msgs []chat.Message) string {
+ for _, m := range msgs {
+ if m.Role == "tool" {
+ return m.Content
+ }
+ }
+ return ""
+ }
+
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", 1500, false)
+ require.NoError(t, err)
+ assert.Len(t, questions(got), 5, "redacted pages cost a line each, so every turn fits")
+ assert.NotContains(t, toolContent(got), "page page", "the page is not held, only its marker")
+ assert.Equal(t, "a5", got[len(got)-1].TurnID, "redaction keeps the turn tag")
+
+ got, _, err = LoadAgentHistory(context.Background(), repo, "s1", 1500, true)
+ require.NoError(t, err)
+ assert.Equal(t, []string{"question 5"}, questions(got),
+ "retained pages are sent in full and priced in full")
+ assert.Contains(t, toolContent(got), "page page")
+}
+
+// Stored rows are released as soon as their turn is replayed, so a long read
+// holds about a page of stored rows at a time rather than all of them.
+func TestHistoryReplayReleasesStoredRows(t *testing.T) {
+ est, err := agenttoken.NewEstimator()
+ require.NoError(t, err)
+ replay := newHistoryReplay(est, 1<<30, false)
+
+ var slim []*types.Message
+ for _, row := range storedWikiTurns(3, 500) {
+ slim = append(slim, replay.track(row))
+ }
+ require.Len(t, replay.full, 6)
+ assert.Empty(t, slim[1].AgentSteps, "grouping works on slim copies")
+
+ turns := completeHistoryTurns(slim, true)
+ replay.messages(turns[2])
+ assert.Len(t, replay.full, 4, "the replayed turn's rows are released")
+ replay.newestWithin(turns)
+ assert.Empty(t, replay.full)
+}
+
+// A read that stops mid-session may hold only the tail of its oldest turn. That
+// turn is left out rather than replayed without its original question.
+func TestCompleteHistoryTurnsLeavesOutATurnCutByTheRead(t *testing.T) {
+ rows := storedTurns(2)
+ steer := &types.Message{
+ ID: "s1", RequestID: "req-1", Role: "user", Content: "steered",
+ CreatedAt: rows[1].CreatedAt.Add(time.Second),
+ }
+ // Turn 1's original question (rows[0]) was not read.
+ read := []*types.Message{rows[3], rows[2], steer, rows[1]}
+
+ turns := completeHistoryTurns(read, false)
+ require.Len(t, turns, 1)
+ assert.Equal(t, "a2", turns[0].assistant.ID)
+
+ turns = completeHistoryTurns(append(read, rows[0]), true)
+ require.Len(t, turns, 2)
+ assert.Equal(t, "question 1", turns[0].users[0].Content)
+
+ // Ending on the question itself leaves nothing of that turn unread.
+ turns = completeHistoryTurns(append(read, rows[0]), false)
+ require.Len(t, turns, 2, "a read that ends on a turn's question has the whole turn")
+}
+
+func TestLoadAgentHistoryWithoutABudgetLoadsNothing(t *testing.T) {
+ repo := &historyRepo{rows: storedTurns(2)}
+
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", 0, false)
+ require.NoError(t, err)
+ assert.Empty(t, got)
+ assert.Zero(t, repo.pages)
}
// A failed lookup costs the turn a re-summarization, not its history.
func TestLoadAgentHistoryWithoutACheckpointWhenTheLookupFails(t *testing.T) {
- repo := &checkpointHistoryRepo{rows: storedTurns(2), checkpointErr: errors.New("db down")}
+ repo := &historyRepo{rows: storedTurns(2), checkpointErr: errors.New("db down")}
- got, err := LoadAgentHistory(context.Background(), repo, "s1", 5)
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", unlimitedBudget, false)
require.NoError(t, err)
assert.Equal(t, []string{"question 1", "answer 1", "question 2", "answer 2"}, contents(got))
}
func TestLoadAgentHistoryIgnoresAnEmptyCheckpoint(t *testing.T) {
rows := storedTurns(2)
- repo := &checkpointHistoryRepo{rows: rows, checkpoint: checkpointOn(rows[1], " ")}
+ repo := &historyRepo{rows: rows, checkpoint: checkpointOn(rows[1], " ")}
- got, err := LoadAgentHistory(context.Background(), repo, "s1", 5)
+ got, _, err := LoadAgentHistory(context.Background(), repo, "s1", unlimitedBudget, false)
require.NoError(t, err)
assert.Equal(t, []string{"question 1", "answer 1", "question 2", "answer 2"}, contents(got))
}
func TestMessageCheckpointSinkWritesThroughTheSession(t *testing.T) {
- repo := &checkpointHistoryRepo{}
+ repo := &historyRepo{}
sink := messageCheckpointSink{repo: repo, sessionID: "s1"}
require.NoError(t, sink.SaveContextCheckpoint(context.Background(), "a2",
diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go
index af890c7a5..fc55be56b 100644
--- a/internal/application/service/session_agent_qa.go
+++ b/internal/application/service/session_agent_qa.go
@@ -8,6 +8,7 @@ import (
"slices"
"strings"
+ "github.com/Tencent/WeKnora/internal/agent"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
@@ -146,19 +147,20 @@ func (s *sessionService) AgentQA(
// AgentSteps on each historical assistant message are expanded into proper
// assistant_with_tool_calls + tool messages so the model can see what was
// tried last turn — except final_answer, which is replayed as the trailing
- // canonical assistant message.
+ // canonical assistant message. History is sized by the window, not by a
+ // turn count: compaction and its persisted checkpoints keep it in bounds.
var llmContext []chat.Message
if agentConfig.MultiTurnEnabled {
- historyTurns := agentConfig.HistoryTurns
- if historyTurns <= 0 {
- historyTurns = 5
- }
- llmContext, err = LoadAgentHistory(ctx, s.messageRepo, sessionID, historyTurns)
+ budget := agent.HistoryTokenBudget(agentConfig)
+ llmContext, agentConfig.ContextTokenScale, err = LoadAgentHistory(
+ ctx, s.messageRepo, sessionID, budget, agentConfig.RetainRetrievalHistory,
+ )
if err != nil {
logger.Warnf(ctx, "Failed to load agent history from DB: %v, continuing without history", err)
llmContext = []chat.Message{}
}
- logger.Infof(ctx, "Loaded %d history messages from DB (turns=%d)", len(llmContext), historyTurns)
+ logger.Infof(ctx, "Loaded %d history messages from DB (budget=%d tokens, token scale=%.2f)",
+ len(llmContext), budget, agentConfig.ContextTokenScale)
} else {
logger.Infof(ctx, "Multi-turn disabled for this agent, running without history")
llmContext = []chat.Message{}
@@ -313,7 +315,6 @@ func (s *sessionService) buildAgentConfig(
WebSearchMaxResults: customAgent.Config.WebSearchMaxResults,
WebSearchProviderID: customAgent.Config.WebSearchProviderID,
MultiTurnEnabled: customAgent.Config.MultiTurnEnabled,
- HistoryTurns: customAgent.Config.HistoryTurns,
MemoryEnabled: customAgent.Config.MemoryEnabled,
MCPSelectionMode: customAgent.Config.MCPSelectionMode,
MCPServices: customAgent.Config.MCPServices,
diff --git a/internal/database/migration_postgres_test.go b/internal/database/migration_postgres_test.go
new file mode 100644
index 000000000..575dae01e
--- /dev/null
+++ b/internal/database/migration_postgres_test.go
@@ -0,0 +1,114 @@
+package database
+
+import (
+ "context"
+ "database/sql"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/golang-migrate/migrate/v4"
+ "github.com/stretchr/testify/require"
+)
+
+// TestPostgresMigrationsServeAgentHistory runs the versioned migrations against
+// a real PostgreSQL. Skipped unless WEKNORA_MIGRATION_TEST_POSTGRES_DSN points
+// at a disposable database, for example:
+//
+// docker run -d --rm -e POSTGRES_PASSWORD=pg -e POSTGRES_DB=weknora -p 55432:5432 \
+// paradedb/paradedb:v0.22.6-pg17
+// WEKNORA_MIGRATION_TEST_POSTGRES_DSN=postgres://postgres:pg@localhost:55432/weknora?sslmode=disable
+//
+// It checks what SQLite cannot: that 000106 builds its index CONCURRENTLY
+// through golang-migrate (which fails inside a transaction block), in both
+// directions, and that the agent history queries walk it without sorting.
+func TestPostgresMigrationsServeAgentHistory(t *testing.T) {
+ dsn := os.Getenv("WEKNORA_MIGRATION_TEST_POSTGRES_DSN")
+ if dsn == "" {
+ t.Skip("set WEKNORA_MIGRATION_TEST_POSTGRES_DSN to run PostgreSQL migration tests")
+ }
+ root := sqliteRepoRoot(t)
+ chdirAndRestore(t, root)
+
+ require.NoError(t, RunMigrationsWithOptions(dsn, MigrationOptions{}))
+
+ db, err := sql.Open("postgres", dsn)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = db.Close() })
+
+ var version int
+ var dirty bool
+ require.NoError(t, db.QueryRow("SELECT version, dirty FROM schema_migrations").Scan(&version, &dirty))
+ require.Equal(t, latestVersionedMigration(t, root), version)
+ require.False(t, dirty)
+ requirePostgresIndexValid(t, db)
+
+ // Down and up again: DROP/CREATE INDEX CONCURRENTLY through golang-migrate.
+ m, err := migrate.New("file://migrations/versioned", dsn)
+ require.NoError(t, err)
+ t.Cleanup(func() { _, _ = m.Close() })
+ require.NoError(t, m.Steps(-1))
+ var indexes int
+ require.NoError(t, db.QueryRow(
+ "SELECT count(*) FROM pg_class WHERE relname = 'idx_messages_session_created_id'").Scan(&indexes))
+ require.Zero(t, indexes, "the down migration drops the index")
+ require.NoError(t, m.Steps(1))
+ requirePostgresIndexValid(t, db)
+
+ ctx := context.Background()
+ conn, err := db.Conn(ctx)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = conn.Close() })
+ // An empty table is always cheapest to scan; rule the scan out to see
+ // which index the planner can use and whether it still has to sort.
+ _, err = conn.ExecContext(ctx, "SET enable_seqscan = off")
+ require.NoError(t, err)
+ for name, query := range map[string]string{
+ "backwards page": `SELECT * FROM messages WHERE session_id = 's'
+ AND (created_at < now() OR (created_at = now() AND id < 'x'))
+ AND deleted_at IS NULL ORDER BY created_at DESC, id DESC LIMIT 200`,
+ "newest checkpoint": `SELECT id FROM messages WHERE session_id = 's' AND role = 'assistant'
+ AND context_checkpoint IS NOT NULL AND deleted_at IS NULL
+ ORDER BY created_at DESC, id DESC LIMIT 1`,
+ } {
+ rows, err := conn.QueryContext(ctx, "EXPLAIN "+query)
+ require.NoError(t, err, name)
+ var plan strings.Builder
+ for rows.Next() {
+ var line string
+ require.NoError(t, rows.Scan(&line), name)
+ plan.WriteString(line + "\n")
+ }
+ require.NoError(t, rows.Close(), name)
+ require.Contains(t, plan.String(), "idx_messages_session_created_id", "%s plan:\n%s", name, plan.String())
+ require.NotContains(t, plan.String(), "Sort", "%s must not sort:\n%s", name, plan.String())
+ }
+}
+
+func requirePostgresIndexValid(t *testing.T, db *sql.DB) {
+ t.Helper()
+ var valid bool
+ require.NoError(t, db.QueryRow(`SELECT i.indisvalid FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indexrelid
+ WHERE c.relname = 'idx_messages_session_created_id'`).Scan(&valid))
+ require.True(t, valid, "a CONCURRENTLY build that failed leaves an INVALID index")
+}
+
+func latestVersionedMigration(t *testing.T, root string) int {
+ t.Helper()
+ entries, err := os.ReadDir(filepath.Join(root, "migrations", "versioned"))
+ require.NoError(t, err)
+ latest := 0
+ for _, e := range entries {
+ prefix, _, ok := strings.Cut(e.Name(), "_")
+ if !ok {
+ continue
+ }
+ if n, err := strconv.Atoi(prefix); err == nil && n > latest {
+ latest = n
+ }
+ }
+ return latest
+}
diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go
index 43582ebf4..0e52ac2ea 100644
--- a/internal/database/migration_sqlite_versioned_schema_test.go
+++ b/internal/database/migration_sqlite_versioned_schema_test.go
@@ -48,7 +48,7 @@ var versionedSQLiteColumns = map[string][]string{
"mcp_tool_approvals": {"enabled"}, // 000091
}
-const expectedSQLiteMigrationVersion = 24
+const expectedSQLiteMigrationVersion = 25
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
@@ -77,6 +77,10 @@ func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
}
}
+ require.True(t, sqliteIndexExists(t, db, "idx_messages_session_created_id"),
+ "SQLite migrations must add the session/created_at index") // 000106
+ assertSQLiteAgentHistoryQueriesUseTheIndex(t, db)
+
assertSQLiteShareLinkInvitationsWork(t, db)
assertSQLiteMCPOAuthPrincipalUpsertWorks(t, db)
require.False(t, sqliteColumnExists(t, db, "knowledges", "tag_id"),
@@ -220,6 +224,45 @@ func sqliteTableExists(t *testing.T, db *sql.DB, table string) bool {
return n == 1
}
+// assertSQLiteAgentHistoryQueriesUseTheIndex checks the two per-turn agent
+// history queries walk idx_messages_session_created_id in order instead of
+// sorting every message of the session.
+func assertSQLiteAgentHistoryQueriesUseTheIndex(t *testing.T, db *sql.DB) {
+ t.Helper()
+ for name, query := range map[string]string{
+ "backwards page": `SELECT * FROM messages WHERE session_id = 's'
+ AND (created_at < '2026-01-01' OR (created_at = '2026-01-01' AND id < 'x'))
+ AND deleted_at IS NULL ORDER BY created_at DESC, id DESC LIMIT 200`,
+ "newest checkpoint": `SELECT id FROM messages WHERE session_id = 's' AND role = 'assistant'
+ AND context_checkpoint IS NOT NULL AND deleted_at IS NULL
+ ORDER BY created_at DESC, id DESC LIMIT 1`,
+ } {
+ rows, err := db.Query("EXPLAIN QUERY PLAN " + query)
+ require.NoError(t, err, name)
+ var plan strings.Builder
+ for rows.Next() {
+ var id, parent, unused int
+ var detail string
+ require.NoError(t, rows.Scan(&id, &parent, &unused, &detail), name)
+ plan.WriteString(detail + "\n")
+ }
+ require.NoError(t, rows.Err(), name)
+ require.NoError(t, rows.Close(), name)
+ require.Contains(t, plan.String(), "idx_messages_session_created_id", "%s plan:\n%s", name, plan.String())
+ require.NotContains(t, plan.String(), "TEMP B-TREE", "%s must not sort:\n%s", name, plan.String())
+ }
+}
+
+func sqliteIndexExists(t *testing.T, db *sql.DB, index string) bool {
+ t.Helper()
+ var n int
+ require.NoError(t, db.QueryRow(
+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?",
+ index,
+ ).Scan(&n))
+ return n == 1
+}
+
func sqliteColumnExists(t *testing.T, db *sql.DB, table, column string) bool {
t.Helper()
var n int
diff --git a/internal/types/agent.go b/internal/types/agent.go
index fd33d3d7f..8f8217028 100644
--- a/internal/types/agent.go
+++ b/internal/types/agent.go
@@ -120,7 +120,6 @@ type AgentConfig struct {
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
WebSearchProviderID string `json:"web_search_provider_id,omitempty"` // WebSearchProviderEntity ID (resolved from agent config)
MultiTurnEnabled bool `json:"multi_turn_enabled"` // Whether multi-turn conversation is enabled
- HistoryTurns int `json:"history_turns"` // Number of history turns to keep in context
MemoryEnabled *bool `json:"memory_enabled,omitempty"` // nil inherits workspace
SearchTargets SearchTargets `json:"-"` // Pre-computed unified search targets (runtime only)
// MCP service selection
@@ -186,6 +185,12 @@ type AgentConfig struct {
// model's context_window, or DefaultMaxContextTokens (200000)".
MaxContextTokens int `json:"max_context_tokens,omitempty"`
+ // ContextTokenScale is the provider's tokens per estimated token that the
+ // session's last calibrated turn measured (TokenUsage.ContextTokenScale).
+ // The engine starts its estimator at this scale. Zero means uncalibrated.
+ // Runtime only.
+ ContextTokenScale float64 `json:"-"`
+
// How much recent conversation a compaction keeps verbatim. Zero means
// compaction.DefaultKeepRecentTokens, scaled down on small windows. This
// is the knob that decides how often compaction runs: whatever the context
diff --git a/internal/types/chat.go b/internal/types/chat.go
index 69b9051ea..b1fccb964 100644
--- a/internal/types/chat.go
+++ b/internal/types/chat.go
@@ -30,6 +30,11 @@ type TokenUsage struct {
CacheMissTokens int `json:"cache_miss_tokens,omitempty"`
CacheReported bool `json:"cache_reported"`
CacheStatus PromptCacheStatus `json:"cache_status,omitempty"`
+ // ContextTokenScale is provider prompt tokens per cl100k-estimated token,
+ // measured over the turn's rounds. Persisted with the turn so the next
+ // turn's history loading and first compaction check are calibrated before
+ // any provider count of their own. Zero when the turn measured none.
+ ContextTokenScale float64 `json:"context_token_scale,omitempty"`
}
// SetPromptCacheUsage normalizes provider-specific cache counters into the
@@ -91,6 +96,10 @@ func (u *TokenUsage) Accumulate(other TokenUsage) {
u.CacheWriteTokens += other.CacheWriteTokens
u.CacheMissTokens += other.CacheMissTokens
u.CacheReported = u.CacheReported || other.CacheReported
+ // A scale is a ratio, not a count: the newest measurement stands.
+ if other.ContextTokenScale > 0 {
+ u.ContextTokenScale = other.ContextTokenScale
+ }
switch {
case !u.CacheReported:
u.CacheStatus = mergeUnreportedCacheStatus(u.CacheStatus, other.CacheStatus)
diff --git a/internal/types/context_checkpoint.go b/internal/types/context_checkpoint.go
index 0ed58d2aa..bd042c8d3 100644
--- a/internal/types/context_checkpoint.go
+++ b/internal/types/context_checkpoint.go
@@ -19,6 +19,9 @@ import (
type ContextCheckpoint struct {
Summary string `json:"summary"`
CreatedAt time.Time `json:"created_at"`
+ // Degraded marks a raw archive kept because the summarizer failed. The
+ // next compaction folds it in as the previous summary.
+ Degraded bool `json:"degraded,omitempty"`
}
// Value implements the driver.Valuer interface for database serialization.
diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go
index 3002ae1ce..007a8fd2c 100644
--- a/internal/types/custom_agent.go
+++ b/internal/types/custom_agent.go
@@ -274,7 +274,7 @@ type CustomAgentConfig struct {
// ===== Multi-turn Conversation Settings =====
// Whether multi-turn conversation is enabled
MultiTurnEnabled bool `yaml:"multi_turn_enabled" json:"multi_turn_enabled"`
- // Number of history turns to keep in context
+ // Number of history turns to keep in context. Quick-answer only; smart-reasoning sizes history by context window
HistoryTurns int `yaml:"history_turns" json:"history_turns"`
// Whether this agent may read the user's long-term memory. Nil inherits
// the workspace setting; false opts a single agent out of memory even when
diff --git a/internal/types/interfaces/message.go b/internal/types/interfaces/message.go
index 543ec3714..ad1f28800 100644
--- a/internal/types/interfaces/message.go
+++ b/internal/types/interfaces/message.go
@@ -94,6 +94,12 @@ type MessageRepository interface {
) ([]*types.Message, error)
// ListMessagesBySessionAfterCursor uses (created_at, id) for lossless paging.
ListMessagesBySessionAfterCursor(ctx context.Context, sessionID string, cursor types.MemoryMessageCursor, limit int) ([]*types.Message, error)
+ // ListMessagesBySessionBeforeCursor pages a session backwards: up to limit
+ // messages sorting strictly before (before, beforeID), newest first. A zero
+ // cursor starts from the newest message.
+ ListMessagesBySessionBeforeCursor(
+ ctx context.Context, sessionID string, before time.Time, beforeID string, limit int,
+ ) ([]*types.Message, error)
// ListMessagesBySessionUpTo returns every message sorting strictly before
// the (boundary, boundaryID) composite cursor, oldest first. Used by
// session fork to copy the history preceding a fork point.
diff --git a/migrations/sqlite/000025_messages_session_created_index.down.sql b/migrations/sqlite/000025_messages_session_created_index.down.sql
new file mode 100644
index 000000000..5f63d0501
--- /dev/null
+++ b/migrations/sqlite/000025_messages_session_created_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX IF EXISTS idx_messages_session_created_id;
diff --git a/migrations/sqlite/000025_messages_session_created_index.up.sql b/migrations/sqlite/000025_messages_session_created_index.up.sql
new file mode 100644
index 000000000..5c20acbee
--- /dev/null
+++ b/migrations/sqlite/000025_messages_session_created_index.up.sql
@@ -0,0 +1,4 @@
+-- Mirrors versioned migration 000106_messages_session_created_index: the index
+-- behind agent history's backwards read and the newest-checkpoint lookup.
+CREATE INDEX IF NOT EXISTS idx_messages_session_created_id
+ ON messages (session_id, created_at DESC, id DESC);
diff --git a/migrations/versioned/000106_messages_session_created_index.down.sql b/migrations/versioned/000106_messages_session_created_index.down.sql
new file mode 100644
index 000000000..6dfa8bd29
--- /dev/null
+++ b/migrations/versioned/000106_messages_session_created_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_messages_session_created_id;
diff --git a/migrations/versioned/000106_messages_session_created_index.up.sql b/migrations/versioned/000106_messages_session_created_index.up.sql
new file mode 100644
index 000000000..9f71b3350
--- /dev/null
+++ b/migrations/versioned/000106_messages_session_created_index.up.sql
@@ -0,0 +1,15 @@
+-- Migration: 000106_messages_session_created_index
+-- Agent history pages a session backwards by (created_at, id) and looks up its
+-- newest context checkpoint on every agent turn. messages was indexed by
+-- session_id alone, so each page sorted every message of the session. This
+-- index serves the backwards read, the newest-checkpoint lookup (a backward
+-- scan that stops at the first checkpoint), and the existing recent-messages
+-- reads.
+--
+-- CONCURRENTLY keeps writes to messages flowing while the index builds. It
+-- cannot run inside a transaction block, so this file must hold exactly this
+-- one statement: golang-migrate sends a file as one query, and a query with
+-- several statements runs as an implicit transaction. If the build is
+-- interrupted it leaves an INVALID index behind; drop it and rerun.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_messages_session_created_id
+ ON messages (session_id, created_at DESC, id DESC);
diff --git a/website-docs/03-features/07-agent.md b/website-docs/03-features/07-agent.md
index 9c4a4d301..6c7732d8c 100644
--- a/website-docs/03-features/07-agent.md
+++ b/website-docs/03-features/07-agent.md
@@ -101,7 +101,7 @@ smart-reasoning 下还可选**类型预设**(`Config.AgentType`,定义在 `c
| 文件 | `supported_file_types`、`chat_parser_engine_rules`、`attachment_image_understanding`、`attachment_ocr_max_pages`、`attachment_parse_wait_timeout_sec` | 数据分析型 Agent 常限定 csv/xlsx |
| FAQ | `faq_priority_enabled`、`faq_direct_answer_threshold`、`faq_score_boost` | — |
| Web | `web_search_enabled`、`web_search_max_results`、`web_search_provider_id`、`web_fetch_enabled`、`web_fetch_top_n` | max_results 默认 5 |
-| 多轮 | `multi_turn_enabled`、`history_turns` | history_turns 默认 5;smart-reasoning 强制 multi_turn |
+| 多轮 | `multi_turn_enabled`、`history_turns` | history_turns 默认 5,只约束普通模式(KnowledgeQA);smart-reasoning 强制 multi_turn,历史按上下文窗口加载,不读 history_turns |
| 检索 | `embedding_top_k`(10)、`keyword_threshold`(0.3)、`vector_threshold`(0.5)、`rerank_top_k`(5)、`rerank_threshold` | 括号内为默认值 |
| 高级 | `enable_query_expansion`、`enable_rewrite`、`rewrite_prompt_*`、`query_understand_model_id`、`fallback_strategy`(默认 model)、`fallback_response`、`fallback_prompt`、`intent_prompts`、`data_analysis_enabled` | 主要作用于 quick-answer 管道 |
| 建议 | `question_suggestions`(starters / follow_ups) | starters 默认 hybrid 模式 6 条;follow_ups 默认关闭、3 条 |
@@ -127,8 +127,8 @@ Handler 层(`internal/handler/custom_agent.go`)提供 `CreateAgent`、`GetAg
| ID | 名称(zh-CN) | agent_mode / agent_type | 关键配置 |
| --- | --- | --- | --- |
| `builtin-quick-answer` | 快速问答 | `quick-answer` | 模板 `default_kb` + `default_context`;temperature 0.7;FAQ 优先(直接回答阈值 0.9、加权 1.2);query expansion + rewrite;web 搜索开、5 条;不进 Agent 引擎 |
-| `builtin-smart-reasoning` | 智能推理 | `smart-reasoning` / `rag-qa` | `max_iterations: 50`;工具:search_knowledge、read_document、list_documents、query_knowledge_graph;web 搜索开;多轮 5 轮 |
-| `builtin-data-analyst` | 数据分析师 | `smart-reasoning` / `data-analysis` | 模板 `data_analyst`;temperature 0.3;`max_iterations: 30`;工具仅 data_schema + data_analysis;限定 csv/xlsx;关闭 web 搜索;历史 10 轮 |
+| `builtin-smart-reasoning` | 智能推理 | `smart-reasoning` / `rag-qa` | `max_iterations: 50`;工具:search_knowledge、read_document、list_documents、query_knowledge_graph;web 搜索开;多轮(历史按上下文窗口加载) |
+| `builtin-data-analyst` | 数据分析师 | `smart-reasoning` / `data-analysis` | 模板 `data_analyst`;temperature 0.3;`max_iterations: 30`;工具仅 data_schema + data_analysis;限定 csv/xlsx;关闭 web 搜索;多轮(历史按上下文窗口加载) |
| `builtin-wiki-researcher` | 维基问答 | `smart-reasoning` / `wiki-qa` | 模板 `wiki_researcher`;`max_iterations: 30`;工具:wiki_search、wiki_read_page、read_document、wiki_flag_issue(只读 + 报障);关闭 web 搜索 |
| `builtin-wiki-fixer` | 维基修订 | `smart-reasoning` / `custom` | 模板 `wiki_fixer`;`retain_retrieval_history: true`(修订需要跨轮记住页面内容);工具含全部 wiki 写操作(wiki_write_page、wiki_replace_text、wiki_rename_page、wiki_delete_page、wiki_read_issue、wiki_update_issue 等 9 个);`kb_selection_mode: selected` |
@@ -507,6 +507,7 @@ var ToolCapabilityRequirements = map[string]ToolRequirement{
- 上下文预算:`AgentConfig.MaxContextTokens`,`buildAgentConfig` 未设置时兜底 `types.DefaultMaxContextTokens = 200000`;
- `token.Estimator`(`internal/agent/token/estimator.go`)用 tiktoken 的 **cl100k_base** 编码估算,常量 `perMessageOverhead = 3`、`perConversationTail = 3`;编码失败时退化为 `len(s)/4` 近似;
- **权威值优先**:真正的 token 数以模型 API 返回的 `Usage` 为准。引擎的 `estimateCurrentTokens` 用上一轮 API 报告的 `lastUsage.TotalTokens` 作基线,只对新增消息(assistant 回复 + tool 结果)做 BPE 增量估算;首轮无 Usage 时才全量估算。
+- **估算校准**:cl100k 不是各家模型的分词器,中文在 cl100k 下约每字 1 token,而 Qwen、DeepSeek 约 0.6,英文与 JSON 则基本一致。估算器因此带一个校准系数(`Estimator.SetScale`,限制在 0.5–1.5),只作用于文本,每条消息的固定开销和图片的固定估值不乘。系数由引擎在同一轮对话的相邻两次请求之间测量:两次请求的工具定义、system prompt 和已有消息都相同,模型报告的 prompt token 增量只对应新追加的消息(上一次回复、工具结果、追加消息),用它除以这些消息的估算即得对话内容的系数,不受各家渲染工具定义方式的影响。中间发生过压缩或工具结果裁剪、样本含图片、比值不可信(< 0.3 或 > 3)、或累计样本不足 256 估算 token 时不计入。测得的系数随本轮 usage 存为 `context_token_scale`(即使模型没有报告 total token 也会保存);本轮没测到系数(例如一次请求就结束、不调工具)时,沿用本轮开始时的系数,使最新一轮总带着最新的系数;下一轮 `LoadAgentHistory` 取最近一条带系数的消息,按它给历史计价并把系数交给引擎作为起点。加载器、首轮压缩判断和压缩器(保留原文预算、摘要输入上限)共用同一个估算器,因此同一把尺子:只校准压缩判断而不校准加载会让加载器先丢轮次,这一点由 `agent_history_cadence_test.go` 覆盖。首轮压缩判断仍只计消息、不计工具定义。
#### 上下文压缩与溢出恢复 {#_4-2-上下文压缩与溢出恢复}
@@ -514,13 +515,15 @@ var ToolCapabilityRequirements = map[string]ToolRequirement{
压缩按 Token 预算选择保留的最近消息,默认 KeepRecentTokens=20000,小窗口会压低到可用窗口的四分之一。长 ReAct 会话可以在当前轮内部切分;切点不拆开 assistant 工具调用与其 tool 结果,切分轮的前半段单独总结,以解释保留的后半段。
-旧摘要参与更新,较老历史生成结构化摘要;结果以带标记的 user 消息放在 system 与保留尾部之间。摘要预算由 reserve、模型输出上限和保留预算计算,不再固定为 2000。每次摘要最多尝试 2 次,每次 60 秒;失败时回退原始文本归档,并标记 degraded。
+旧摘要参与更新,较老历史生成结构化摘要;结果以带标记的 user 消息放在 system 与保留尾部之间。摘要预算由 reserve、模型输出上限和保留预算计算,不再固定为 2000。摘要调用走流式接口,与引擎自身的对话轮次一样只设停顿超时:连续一段时间(默认 120 秒,随 `LLMCallTimeout`)没有任何输出才取消,总时长交给模型传输层兜底。此前的 60 秒总超时会掐断正在正常预填充和输出的大请求。模型的思考输出也算进展,但不计入摘要;流里报出的错误视为本次失败。每次摘要最多尝试 2 次,本轮已被取消时不再重试;失败时回退原始文本归档并标记 degraded。原始归档与摘要一样受摘要预算约束,从最新的消息往前保留并注明省略了多少条,保证退化时也能缩小上下文。
+
+**摘要输入上限**。历史可以装到整个窗口,待摘要部分可能超出单次摘要请求能容纳的量。请求超窗会被拒绝并退化成原始归档,而退化结果不写压缩点,下一轮会原样再失败一次。因此 `Prepare` 只保留能装进一次请求的最新消息(窗口减去回复预算、上一次摘要和提示词,再留 10% 余量),并在提示里注明省略了多少条较早的消息;文件路径仍从全部待摘要消息中提取。省略条数记在 `Result.Omitted`,引擎日志里可见。
`internal/agent/compaction/fileops.go` 机械提取被压缩消息中的文件读写路径,并继承旧摘要的文件清单,避免模型忘记已经落盘的产物。普通读取使用 read_file,历史旧读取名仍可兼容识别。
若压缩后仍超预算,最后才裁短工具结果,工具结果预算取窗口的 20%,限制在 8192–32768 Token。没有可压缩内容或释放空间不足 5% 时,记下当前消息数量,避免在同一上下文大小反复花费模型调用。成功压缩会清除旧 usage 基线,并发出 context_compacted 事件,包含前后 Token/消息数、原因、split_turn 与 degraded。
-**压缩点持久化**。当摘要的历史部分恰好结束在某个已落库轮次的末尾时,引擎把这段摘要作为压缩点(`messages.context_checkpoint`)写回该轮的 assistant 消息,下一轮直接从它开始,不再对同一段历史重复摘要。历史消息在重建时带上所属轮次的 assistant 消息 ID(`chat.Message.TurnID`,不上线),据此判断切点是否落在轮次边界。以下情况不写压缩点:切点落在某个已落库轮次内部(例如停在追加消息处);摘要只覆盖当前轮;历史摘要回退成了原始归档(degraded)。切分轮前半段的摘要不写入压缩点,因为该轮下次会被完整重放。写入只更新这一列,失败时仅记日志,不影响本轮。压缩点存在被覆盖的那一轮上,所以会话分叉复制该轮时会一起复制,删除该轮时压缩点也随之失效。
+**压缩点持久化**。当摘要的历史部分恰好结束在某个已落库轮次的末尾时,引擎把这段摘要作为压缩点(`messages.context_checkpoint`)写回该轮的 assistant 消息,下一轮直接从它开始,不再对同一段历史重复摘要。历史消息在重建时带上所属轮次的 assistant 消息 ID(`chat.Message.TurnID`,不上线),据此判断切点是否落在轮次边界。以下情况不写压缩点:切点落在某个已落库轮次内部(例如停在追加消息处);摘要只覆盖当前轮。历史摘要回退成原始归档时仍然写入,并标记 `degraded`:不写的话,摘要器持续失败时每一轮都会重新加载同一段历史、再压缩、再失败;写入后下一次压缩会把它当作上一次的摘要交给模型重新整理。切分轮前半段的摘要不写入压缩点,因为该轮下次会被完整重放。压缩因释放不足 5% 被放弃时,本轮上下文保持不变,但只要历史部分给出了压缩点,照样写入,避免下一轮重复摘要同一段历史。写入只更新这一列,未匹配到该会话的 assistant 行时视为失败;失败时仅记日志,不影响本轮。历史的反向分页和按会话取最新压缩点都走索引 `idx_messages_session_created_id (session_id, created_at DESC, id DESC)`:取压缩点时从最新一条往回扫,遇到第一个压缩点即停。该索引用 `CREATE INDEX CONCURRENTLY` 创建,不阻塞 messages 的写入;迁移文件因此只能包含这一条语句(多条语句会被当作一个隐式事务执行,`CONCURRENTLY` 不能在事务中运行)。压缩点存在被覆盖的那一轮上,所以会话分叉复制该轮时会一起复制,删除该轮时压缩点也随之失效。
提供商报告上下文超限(错误或响应截断判据)时,还可强制压缩并重试一次。仅因生成耗尽 completion 预算的截断不应误判成上下文超限。具体提供商错误识别见 `internal/agent/compaction/overflow.go`。
@@ -528,9 +531,10 @@ var ToolCapabilityRequirements = map[string]ToolRequirement{
跨轮历史由 `LoadAgentHistory`(`internal/application/service/agent_history.go`)每轮从 messages 表重建(DB 是唯一事实来源,无 Redis/内存缓存):
-- 取 `HistoryTurns × 4`(最低 50)条原始消息,按 `RequestID` 配对 user/assistant,只保留 assistant 已完成(`IsCompleted`)的完整轮,按时间排序;
-- 会话中存在压缩点(见[上下文压缩与溢出恢复](#_4-2-上下文压缩与溢出恢复))时,取最新的一个:它所在的轮及更早的轮由一条摘要消息代替,放在历史最前面,之后的轮原样重放。压缩点早于本次读取范围时按时间判断,读到的轮都在它之后。压缩点查询失败时退回无压缩点的历史;
-- 再取最近 `HistoryTurns` 轮。这个上限只约束压缩点之后原样重放的轮,不包括摘要;
+- 历史按 Token 预算加载,不按轮数,`history_turns` 在 Agent 模式下不生效。预算是整个上下文窗口(`agent.HistoryTokenBudget`),刻意大于压缩阈值:加载器放不下的轮既不重放也不进摘要,等于丢失;若预算只到阈值,加载器会先裁掉旧轮,请求可能再也越不过阈值,压缩与压缩点都不会发生,会话退化成滑动窗口。预算到窗口时,超出阈值的部分交给首轮压缩摘要并写入压缩点,下一轮从新压缩点开始,历史随之回落;会话再次填满时才再压缩(`agent_history_cadence_test.go` 逐轮模拟验证:压缩点之后的轮不会缺失,压缩不会连续两轮发生);
+- 会话中存在压缩点(见[上下文压缩与溢出恢复](#_4-2-上下文压缩与溢出恢复))时,取最新的一个:它所在的轮及更早的轮由一条摘要消息代替,放在历史最前面,之后的轮原样重放。压缩点所在轮未被读到时(预算先装满),按 assistant 行的 `(created_at, id)` 顺序判断哪些轮在它之后。压缩点查询失败时退回无压缩点的历史;
+- 按 `(created_at, id)` 从新到旧分页读取(每页 200 行,单次最多 5000 行),按 `RequestID` 配对 user/assistant,只保留 assistant 已完成(`IsCompleted`)的完整轮。读到压缩点或预算装满即停止,长会话不会整段读出。读取未到会话开头且最旧一行不是 user 消息时,该行所在的轮缺少原始问题,会被舍弃;
+- 从最新的轮往前放入预算,遇到第一个放不下的轮即停止,保证保留的轮连续。最新一轮即使单独超出预算也会保留,由压缩负责切分。每轮按引擎实际发送的内容计价并返回(`agent.HistoryAsSent`):未开启 `RetainRetrievalHistory` 时,历史中的 KB/Wiki 结果只以一行占位发送,也只按一行计入预算、只以一行留在内存里(`search_knowledge` 等结果入库时已压成一行,差异主要在按全文存储的 `wiki_read_page` / `wiki_search`)。每轮回放完就释放对应的数据库行,分页读取时同时驻留的约为一页数据库行加上要发送的历史;
- 每轮展开为:user 消息(含图片 caption 与附件 prompt;忽略 `RenderedContent` 快照,避免将旧渲染协议带入上下文)→ 每个含工具调用的 `AgentStep` 展开为 assistant(with tool_calls) + 若干 tool 消息 → 末尾一条规范化最终答案 assistant 消息(剥离 `<think>` 块);
- 历史中的 tool 消息内容用 `CompactToolOutputForHistory`(`internal/agent/tools/persist.go`)压缩:带 `display_type` 的大载荷(如 `knowledge_chunks_list` 的 chunks、`grep_results` 的 chunk_results)替换为一行摘要(如 `"Listed 20/87 chunks from X (content omitted from history)"`)。