ISSUE DESCRIPTION Bug: retainrecentlegalsuffix 在 else 分支下会导致用户消息被重复归档 Bug Description 在…
- User
ISSUE DESCRIPTION
Bug: retain_recent_legal_suffix 在 else 分支下会导致用户消息被重复归档
Bug Description
在
nanobot/session/manager.py的retain_recent_legal_suffix方法中,当 else 分支(最近 N 条消息全是助手/工具消息)被触发时,由于cut值的计算使用len(tail) - len(kept),而没有考虑用户消息的实际位置,导致用户消息被错误地同时归档到 archive 和 kept 中。具体影响:
- 用户消息同时出现在 archive(待压缩)和 kept(保留)中
- 可能导致 LLM 上下文不一致
Steps to Reproduce
- 会话中消息数量超过 _RECENT_SUFFIX_MESSAGES (默认10条)
- 最近 N 条消息中 不包含任何用户消息 (全是 assistant/tool 角色)
- 在完整会话历史中,最后一条用户消息位于倒数第 11-15 条之间
Expected Behavior
当会话历史中最近 N 条消息全是助手/工具消息,而用户消息位于更早位置时:
- 用户消息不应被重复归档 - 用户消息应该只保留在 kept 中,不应该同时出现在 archive 和 kept 中
- 归档边界应该正确 - cut 值应该基于用户消息的实际位置,而不是简单的 len(tail) - len(kept)
- 上下文连贯性应该保持 - 从用户消息开始的完整上下文应该被保留,不应该被错误切割
假设:
tail = messages[0:100](100条)
latest_user = 85(用户消息位置)
max_messages = 10
期望:
cut = latest_user # 应该是 85,不是 90 archive = tail[:85] # [0-84],不包含用户消息 kept = tail[85:] # [85-99],包含用户消息及其后续内容
结果:
archive 和 kept 没有重叠 ✅
用户消息只在 kept 中 ✅
上下文连贯 ✅
总结
期望行为 :无论用户消息位于何处,它都应该:
- 只出现在 kept 中(保留消息)
- 不出现在 archive 中(归档消息)
- 作为保留消息的起始点,确保上下文连贯
Relevant Logs
nanobot Version
0.2.0
Python Version
3.11
Operating System
Windows
Channel / Platform
Weixin (Personal WeChat)
LLM Provider
OpenAI
Configuration (Optional)
Additional Context
No response
Interface
Type: Function Name: retain_recent_legal_suffix Path: nanobot/session/manager.py Input: self, max_messages: int Output: tuple[list[dict], int] Description: Trims the session's message list to at most
max_messageswhile preserving a legal suffix (ending with a user message if possible). Returns the list of dropped messages and a count of how many of those were already in the consolidated prefix, so callers can archive only new, unconsolidated messages.ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use to restore the file to its original state. You can also reset all changes in the repository using command. Additionally, you can use and to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call ) using or commands. However you don't need to use or before submitting your changes. In fact, only submits currently unstaged changes because it uses to get the changes that need to be submitted.
Assistant
Let me start by exploring the repository structure and understanding the codebase, then look at the specific file mentioned in the issue.
Assistant
Let me find the
retain_recent_legal_suffixmethod specifically.Assistant
Let me look at the
retain_recent_legal_suffixmethod and the surrounding code, including_RECENT_SUFFIX_MESSAGES.Assistant
Let me look at how
retain_recent_legal_suffixis called in other places.Assistant
This is the exact code described in the issue! In
memory.py:probe.retain_recent_legal_suffix(max_suffix) kept = probe.messages cut = len(tail) - len(kept) archive_msgs = tail[:cut]This is the buggy code path.
cut = len(tail) - len(kept). In the else branch wherelatest_useris found earlier,kept = probe.messageswill bemessages[latest_user: latest_user + max_messages]. Solen(kept) = max_messages(say 10),len(tail) = 100,cut = 90. Butarchive_msgs = tail[:90]includes the user message at position 85, whilekept = tail[85:95]also includes the user message. Overlap!So the issue is in the calling code in
memory.pyandenforce_file_capinmanager.py. Both computecut = len(tail) - len(kept)ordropped = before[:dropped_count], which assumes the kept messages are a suffix.The fix according to the issue's interface section: change
retain_recent_legal_suffixto returntuple[list[dict], int]- the list of dropped messages and a count of how many were already in the consolidated prefix. Then callers can use this return value directly instead of computing .Assistant
Now let me check the
enforce_file_capcallers and the autocompact usage.The
cli/commands.py:1032usage just callssession.retain_recent_legal_suffix(hb_cfg.keep_recent_messages)and doesn't use a return value. So if I change the return type totuple[list[dict], int], I need to make sure these callers still work (they just ignore the return value, which is fine in Python).Now, let me check
enforce_file_capcallers:Assistant
This is the exact code path described in the issue. Let me look at the existing tests and the
find_legal_message_starthelper.Assistant
There's an existing test
test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chainthat assertslen(session.messages) <= 6. Let me check the git history to understand the context, and look at the fullenforce_file_capand memory.py code.Assistant
Let me look at the existing tests for
retain_recent_legal_suffixandenforce_file_capto understand the expected contract.Assistant
Let me look at the
_make_fake_compactfunction in test_auto_compact.py which mirrors the realcompact_idle_session.Assistant
Let me look at
test_consolidator.pyto see what it tests aboutcompact_idle_session.Assistant
Now I have a clear understanding. Let me analyze the bug:
Root cause: In
retain_recent_legal_suffix, theelsebranch computesretained = self.messages[latest_user: latest_user + max_messages], which is NOT a suffix of the messages (messages afterlatest_user + max_messagesare silently lost). Then callers (memory.py'scompact_idle_sessionandenforce_file_cap) compute the archive ascut = len(tail) - len(kept)/before[:dropped_count], assumingkeptis a suffix. Since it isn't, the archive overlaps withkept→ the user message ends up in both archive and kept.Let me first write a reproduction script to confirm the bug.
Assistant
Bug confirmed: user message at index 85 appears in BOTH archive and kept, and 5 messages (a95–a99) are silently lost.
Now let me implement the fix. Let me view the exact current code.
Assistant
Now let me implement the fix. First, rewrite
retain_recent_legal_suffixto returntuple[list[dict], int]and fix the else branch + hard cap to preserve the user anchor (no overlap, no message loss).Assistant
Now let me apply the edit to replace the
retain_recent_legal_suffixmethod.Assistant
Good. Now let me view the rest of the method and enforce_file_cap to update it.
Assistant
Let me fix the double blank line and update
enforce_file_capto use the new return value.Assistant
Now let me update
memory.py'scompact_idle_sessionto use the returned archive messages.Assistant
Now let me update my reproduction script to use the new return value and verify the fix.
Assistant
The issue scenario is now fixed exactly as expected (archive len=85, kept len=15, no overlap, no loss, kept is true suffix at idx 85). The "OVERLAP=True" in other cases is a false positive of my crude check (it flags any user in both lists, but they are different user messages). Let me refine the check to verify no same message is duplicated.
Assistant
No duplication or message loss in any scenario. Now let me run the existing tests to check for breakages.
Assistant
As expected, only
test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chainfails. This test assertslen(session.messages) <= 6for the case where the only user message is at index 0 followed by 13 assistant messages.This test encodes the old behavior (hard cap wins; the user message is kept within the cap but the most-recent 8 assistant messages are silently lost). The issue explicitly requires the opposite: the user message must always be the starting point of
kept, even if that means exceedingmax_messages(the issue's own example keeps 15 > 10). This is a direct consequence of the requested behavior change, so per the guidance I leave the test unmodified.Let me run the broader test suite to confirm nothing else breaks.
Assistant
Only the one expected test fails (the hard-cap test that encodes the old behavior). All other 1092 tests pass. Let me also run the CLI tests since
cli/commands.pycalls the function.Assistant
Let me verify the file's imports/annotations setup and do a final review of the diff.
Assistant
The diff is clean. Let me run one final end-to-end verification simulating the
enforce_file_cappath and thecompact_idle_sessionpath with the issue scenario to confirm no overlap.Assistant
Both paths are correct and match the issue's expected output exactly:
enforce_file_cap: dropped 85, raw-archived 65 (skipping the first 20 already-consolidated), kept 15, no duplication.compact_idle_session: archive =tail[:85](a0…a84), kept =tail[85:](USER@85…a99), clean boundary, no overlap — exactlycut = latest_user = 85.
Let me clean up the temp files.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.