Skip to content

fix(context): truncate history by complete user turns - #11316

Merged
mantoujun12 merged 3 commits into
AstrBotDevs:masterfrom
zzz27578:fix/logical-context-turns
Nov 24, 2026
Merged

mantoujun12 merged 3 commits into
AstrBotDevs:masterfrom
zzz27578:fix/logical-context-turns

Conversation

@zzz27578

@zzz27578 zzz27578 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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 / 改动点

  • Reuse split_into_rounds() in ContextTruncator.truncate_by_turns() and truncate_by_dropping_oldest_turns() for both counting and slicing.
  • Retain complete recent turns, leading system messages, and at least the latest turn, including an unfinished current request. An unanswered user input counts towards the turn limit.
  • Exclude any assistant/tool fragment preceding the first actual user input from turn counts and requested drop counts. Discard this fragment when turns are truncated so retained context starts at a user input. No-op and disabled truncation preserve the original history.
  • Mark generated tool-image messages and forced final-response instructions as _turn_continuation. The shared round splitter keeps them with their originating request for turn limiting, LLM summary splitting, and token-overflow fallback.
  • Preserve this private marker in saved/reloaded histories and delegated-session requests. Strip it from provider payloads for both message models and dictionary inputs without mutating saved history. Existing unmarked histories retain role-based boundaries; no text matching or history migration is introduced.
  • Preserve the existing overflow retention target (max_turns - drop_turns + 1, with a minimum of one), the -1 bypass, and nonpositive drop behavior.
  • Correct the leading-system split for system-only histories so these messages are never treated as a conversation turn.
  • Extend existing test files with regressions for 22/100 sequential tool calls, follow-up inputs, exact boundaries, multi-turn drops, empty/system-only histories, pre-user fragments, internal messages, and input immutability. Check the exact retained turns.
  • Cover marker serialization, provider-payload exclusion, token-overflow fallback, and delegated-session continuation after closing and restoring the session.
  • Exercise the real runner and SQLite conversation store in streaming and non-streaming modes: the synthetic 42-record history must survive the next successful reply and grow to 44 records. Tool-image and step-limit scenarios also retain the original request and tool chain under a one-turn limit, persist the marker, and survive the next input after reloading.

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.

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

Verification steps, using Python 3.12.13 and the repository's pinned Ruff 0.15.22:

uv sync --group dev --no-install-project --python 3.12

uv run --no-sync pytest tests/agent tests/test_agent_history.py tests/test_tool_loop_agent_runner.py tests/test_conversation_writer_projection.py tests/unit/test_cron_context_compression.py tests/unit/test_agent_runner_config.py tests/unit/subagent tests/test_anthropic_kimi_code_provider.py tests/test_provider_user_agent.py -q --tb=short
465 passed, 1 skipped, 5 warnings in 59.54s

uv run --no-sync ruff format .
599 files left unchanged

uv run --no-sync ruff format --check .
599 files already formatted

uv run --no-sync ruff check .
All checks passed!

git diff --check
(no output; exit status 0)

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_tts dependency, which is absent locally. Warnings are existing audioop and Google SDK/aiohttp deprecations.


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc. (Not applicable: this is a bug fix.)
  • 👀 My changes have been well-tested, and verification steps and test results have been provided above.
  • 📚 I checked the affected WebUI instructions and screenshots in docs/zh and docs/en against 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.)
  • 🤓 I have ensured that no new dependencies are introduced, or that new dependencies are declared in the appropriate files. (No new dependencies.)
  • 😮 My changes do not introduce malicious code.

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:

  • Fix context truncation so tool-heavy tasks are counted and retained as complete logical user turns instead of being split by individual messages.
  • Preserve generated continuation markers across stored histories and delegated sessions while excluding them from provider payloads.
  • Prevent pre-user fragments and system-only messages from affecting turn counts or causing unrelated history loss.

Enhancements:

  • Unify logical-round handling across turn truncation, summary splitting, and token-overflow fallback.
  • Retain the active unfinished request and its complete assistant/tool chain under turn limits, including tool-image and step-limit continuations.

Tests:

  • Add regression coverage for long tool chains, exact turn boundaries, continuation serialization, provider payload filtering, token fallback, delegated-session restoration, and streaming/non-streaming persistence.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread astrbot/core/agent/context/truncator.py Resolved
Comment thread astrbot/core/agent/context/truncator.py Resolved
Comment thread astrbot/core/agent/context/truncator.py Resolved
messages.append(self.create_message("assistant", f"{prefix} done"))
return messages

@pytest.mark.parametrize("tool_calls", [22, 100])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ 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-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@zzz27578

Copy link
Copy Markdown
Contributor Author

@Soulter 麻烦看一下,这是有提到得bug修复,有关于压缩轮数的,github.com/AstrBotDevs/AstrBot/pull/11072这个也可以麻烦看一下,插件载入和更新重复的小修改

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery assessment

Approved.

@mantoujun12
mantoujun12 merged commit 6f376c5 into AstrBotDevs:master Nov 24, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants