Repository navigation
fix(context): truncate history by complete user turns - #11316
Conversation
There was a problem hiding this comment.
Hey - I've found 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="astrbot/core/agent/context/truncator.py" line_range="130" />
<code_context>
return messages
system_messages, non_system_messages = self._split_system_rest(messages)
+ rounds = cast(list[list[Message]], split_into_rounds(non_system_messages))
- if len(non_system_messages) // 2 <= keep_most_recent_turns:
</code_context>
<issue_to_address>
**Internal prompts split user turns**
When turn truncation is triggered and its retention boundary falls between an actual user request and an injected user-role image or max-step instruction, `split_into_rounds` treats the injected user-role message as a new turn, so truncation can discard the original request and its tool history while retaining only the injected prompt or image and later assistant reply. The model then continues without the task context.
Keep internal user-role messages within their originating logical turn, or otherwise mark and group them separately from new user inputs before splitting rounds.
</issue_to_address>
### Comment 2
<location path="astrbot/core/agent/context/truncator.py" line_range="136" />
<code_context>
- system_messages, truncated_contexts, messages
- )
+ num_to_keep = max(1, keep_most_recent_turns - drop_turns + 1)
+ result = system_messages + [msg for rnd in rounds[-num_to_keep:] for msg in rnd]
return self.fix_messages(result)
</code_context>
<issue_to_address>
**Truncation returns assistant-first context**
When non-system history has an assistant or tool prefix and truncation retains that prefix round, including the zero-drop overflow case, the truncator retains the prefix ahead of the first user, and `fix_messages` does not restore user-first order; providers that require a user message after system messages reject the context.
Keep the prefix from becoming a retained first round, or otherwise ensure the truncated context starts with a user message after any system messages.
</issue_to_address>
### Comment 3
<location path="astrbot/core/agent/context/truncator.py" line_range="130" />
<code_context>
return messages
system_messages, non_system_messages = self._split_system_rest(messages)
+ rounds = cast(list[list[Message]], split_into_rounds(non_system_messages))
- if len(non_system_messages) // 2 <= keep_most_recent_turns:
</code_context>
<issue_to_address>
**Assistant prelude counts as a turn**
When the non-system context starts with assistant or tool messages before its first user message, `split_into_rounds` groups any messages before the first user into a round, so these calls count an assistant/tool prelude as a user turn. Turn limiting can discard that prelude instead of applying the configured limit or drop to actual user turns, leaving callers with premature compaction or less history removed than requested.
Keep any pre-user prefix separate from the user-turn rounds so it is not counted or dropped as a turn.
Also at `astrbot/core/agent/context/truncator.py:159`.
</issue_to_address>
### Comment 4
<location path="tests/agent/test_truncator.py" line_range="69" />
<code_context>
+ messages.append(self.create_message("assistant", f"{prefix} done"))
+ return messages
+
+ @pytest.mark.parametrize("tool_calls", [22, 100])
+ @pytest.mark.parametrize("with_follow_up", [False, True])
+ @pytest.mark.parametrize("limit", [-1, 2, 20])
</code_context>
<issue_to_address>
**Regression tests are added**
When the added regression tests are included in the changed test files, the changes add regression tests to both existing test files, contrary to the repository's testing instruction. The PR therefore adds test-file content the instruction says not to generate.
Remove the newly added test cases from these files.
Also at `tests/test_tool_loop_agent_runner.py:2251`.
</issue_to_address>Sourcery assessment
Approval pending. 3 findings to address first.
Blocking findings: astrbot/core/agent/context/truncator.py:130, astrbot/core/agent/context/truncator.py:136, astrbot/core/agent/context/truncator.py:130
| messages.append(self.create_message("assistant", f"{prefix} done")) | ||
| return messages | ||
|
|
||
| @pytest.mark.parametrize("tool_calls", [22, 100]) |
There was a problem hiding this comment.
⚪ Low · Regression tests are added
When the added regression tests are included in the changed test files, the changes add regression tests to both existing test files, contrary to the repository's testing instruction. The PR therefore adds test-file content the instruction says not to generate.
Remove the newly added test cases from these files.
Also at tests/test_tool_loop_agent_runner.py:2251.
Prompt for AI agents
In `tests/agent/test_truncator.py` at line 69:
**Regression tests are added**
When the added regression tests are included in the changed test files, the changes add regression tests to both existing test files, contrary to the repository's testing instruction. The PR therefore adds test-file content the instruction says not to generate.
Remove the newly added test cases from these files.
Also at `tests/test_tool_loop_agent_runner.py:2251`.From .github/copilot-instructions.md L27:
Do not generate test files for now.|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
@Soulter 麻烦看一下,这是有提到得bug修复,有关于压缩轮数的,github.com/AstrBotDevs/AstrBot/pull/11072这个也可以麻烦看一下,插件载入和更新重复的小修改 |
Turn-based context limits currently count non-system messages in pairs, so assistant tool calls and tool results consume the same quota as user conversations. A single task with 17 tool-call batches and 22 results produces 41 non-system messages. With a 20-turn limit, the next user input triggers truncation that can remove the entire previous task. Persisting the next reply then replaces the saved history with the shortened context.
Count and truncate logical user turns instead: one user input and all subsequent assistant messages, tool calls, results, and generated user-role continuations until the next actual user input. Related: #9864 and #7916.
Modifications / 改动点
split_into_rounds()inContextTruncator.truncate_by_turns()andtruncate_by_dropping_oldest_turns()for both counting and slicing._turn_continuation. The shared round splitter keeps them with their originating request for turn limiting, LLM summary splitting, and token-overflow fallback.max_turns - drop_turns + 1, with a minimum of one), the-1bypass, and nonpositive drop behavior.No WebUI navigation, labels, configuration schema, or API changes are involved, so no WebUI instruction/screenshot updates or entry-point mapping is needed. The existing order of turn limiting and token-based compression is unchanged.
Screenshots or Test Results / 运行截图或测试结果
Verification steps, using Python 3.12.13 and the repository's pinned Ruff 0.15.22:
The original regressions reproduced the history loss against the old truncator. The review regressions also failed before the follow-up fixes: both tool-image and step-limit continuations lost the original request/tool history, pre-user fragments affected counting/dropping, and delegated-session serialization lost the new marker. The passing runner tests use mocked providers and a temporary database. The skipped existing test requires the optional
edge_ttsdependency, which is absent locally. Warnings are existingaudioopand Google SDK/aiohttp deprecations.Checklist / 检查清单
docs/zhanddocs/enagainst the changed navigation, page structure, and labels, and updated them in this PR or explained why no documentation update is needed. (No WebUI or entry-point changes; explanation above.)Summary by Sourcery
Count context limits by complete logical user turns so tool-heavy conversations and generated continuations remain intact across truncation, persistence, and follow-up requests.
Bug Fixes:
Enhancements:
Tests: