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
我先检查仓库结构、目标方法及相关测试,确认当前边界计算逻辑,并据此设计最小复现。
完整命令:sed -n '1,260p' nanobot/session/manager.py && printf '\n--- tests referencing method ---\n' && grep -R "retain_recent_legal_suffix" -n . --exclude-dir=.git - Assistant
方法位于后续代码中,当前仓库签名与问题描述中的接口返回值似乎不一致,因此我继续读取实现、调用方和全部相关测试,避免只修公式却破坏
last_consolidated语义。
完整命令:sed -n '240,350p' nanobot/session/manager.py; sed -n '110,190p' tests/agent/test_session_manager_history.py; sed -n '500,555p' tests/agent/test_session_manager_history.py; sed -n '780,830p' nanobot/agent/memory.py; git status --short - Assistant
已确认根因:该方法在 assistant-only 尾部时会保留一个“从最后用户开始的前向窗口”,它不一定是原列表的真正后缀;调用方却用长度反推
cut,造成tail[:cut]与kept重叠。问题给出的期望还明确要求完整保留用户消息之后的 15 条,即此特殊分支允许超过软目标 10。接下来检查归档后如何拼回会话,以及测试对 hard cap 和归档边界的既有约束。
完整命令:sed -n '830,900p' nanobot/agent/memory.py; sed -n '1,120p' tests/agent/test_auto_compact.py; sed -n '120,230p' tests/agent/test_auto_compact.py; grep -R "hard_truncate\\|archive_msgs\\|raw_archive" -n tests/agent/test_auto_compact.py tests | head -80 - Assistant
复现预期与现有 “hard cap” 测试存在语义冲突:问题明确要求用户位于 85、总长 100 时保留 15 条,而旧测试要求长链不超过 cap。这里应以新问题定义为准,将 cap 视为选择尾窗的目标,但为保持从最近用户开始的完整上下文可适度超出。先用临时 Python 脚本精确复现当前重叠(不修改测试文件),同时检查提交历史以判断接口是否正在演进。
完整命令:python - <<'PY'\nfrom nanobot.session.manager import Session\nmessages = [{\"role\": \"assistant\", \"content\": f\"a{i}\"} for i in range(100)]\nmessages[85] = {\"role\": \"user\", \"content\": \"u85\"}\ntail = list(messages)\nprobe = Session(key=\"repro\", messages=tail.copy())\nprobe.retain_recent_legal_suffix(10)\nkept = probe.messages\ncut = len(tail) - len(kept)\narchive = tail[:cut]\nprint(\"cut\", cut, \"kept indices\", [messages.index(m) for m in kept])\nprint(\"user in archive\", messages[85] in archive, \"user in kept\", messages[85] in kept)\nprint(\"overlap count\", len([m for m in kept if m in archive]))\nPY\nprintf '\\n--- recent history ---\\n'; git log -8 --oneline -- nanobot/session/manager.py nanobot/agent/memory.py - Assistant
复现成功:当前
cut=90,用户消息同时出现在 archive/kept,且有 5 条实际重叠。为实现稳健接口,我检查引入该方法的提交;尤其确认是否可以让方法直接返回被删除前缀,从而调用方不再靠长度猜测边界(问题的 Interface 正是这样描述)。
完整命令:git show 48d35bd2:nanobot/session/manager.py | grep -n -A55 -B5 "retain_recent_legal_suffix"; git show 48d35bd2:nanobot/agent/memory.py | grep -n -A45 -B10 "probe.retain_recent" - Assistant
- Assistant
代码现已使用显式归档前缀。接下来执行三类验证:问题给定的 100/85/10 复现、
last_consolidated返回计数和无用户尾部边界;然后运行目标测试文件。预期旧的“hard cap”单测会因新需求的软上限语义失败,其余应通过。
完整命令:python - <<'PY'\nfrom nanobot.session.manager import Session\n\nmessages = [{\"role\": \"assistant\", \"content\": f\"a{i}\"} for i in range(100)]\nmessages[85] = {\"role\": \"user\", \"content\": \"u85\"}\ns = Session(key=\"repro\", messages=messages.copy())\narchive, consolidated = s.retain_recent_legal_suffix(10)\nassert archive == messages[:85]\nassert s.messages == messages[85:]\nassert not any(m is messages[85] for m in archive)\nassert s.messages[0] is messages[85]\nprint(\"reported case: cut=\", len(archive), \"kept=\", len(s.messages), \"overlap=0\")\n\ns = Session(key=\"consolidated\", messages=messages.copy(), last_consolidated=90)\narchive, consolidated = s.retain_recent_legal_suffix(10)\nassert len(archive) == 85 and consolidated == 85 and s.last_consolidated == 5\nprint(\"consolidated accounting:\", consolidated, s.last_consolidated)\n\nno_user = [{\"role\": \"assistant\", \"content\": str(i)} for i in range(20)]\ns = Session(key=\"no-user\", messages=no_user.copy())\narchive, _ = s.retain_recent_legal_suffix(10)\nassert archive == no_user[:10] and s.messages == no_user[10:]\nprint(\"no-user fallback: cut=\", len(archive), \"kept=\", len(s.messages))\nPY\npytest -q tests/agent/test_session_manager_history.py tests/agent/test_auto_compact.py, omitted` - Assistant
定向测试共 79 个,78 个通过;唯一失败是旧语义的 hard-cap 测试,而问题的新明确示例要求
max=10时保留 15 条,因此两者不可同时满足。这里不通过任意阈值硬编码来迎合冲突测试;保留上下文连贯性优先,并记录该已知语义更新。我还需要检查所有调用点是否适配新返回值、执行格式/静态检查,并验证生产
compact_idle_session(而非测试里的旧 fake helper)确实只归档[0:85]。先查看项目工具配置和调用点。
完整命令:grep -R "retain_recent_legal_suffix(" -n nanobot --exclude='*.pyc'; grep -n "\\[tool\\..*\\]\\|ruff\\|mypy\\|pyright" pyproject.toml | head -60; sed -n '1,180p' pyproject.toml - Assistant
调用点已全部核对:CLI 可安全忽略返回值,两个归档路径均已改用返回的真实前缀。现在运行 Ruff 与真实 Consolidator 测试;该测试组覆盖
compact_idle_session的归档和会话替换流程。
完整命令:ruff check nanobot/session/manager.py nanobot/agent/memory.py && pytest -q tests/agent/test_consolidator.py - Assistant
静态检查和真实 Consolidator 的 28 个测试全部通过。为排查跨模块回归,我将运行完整测试套件;预期只有已经确认与新需求直接冲突的旧 hard-cap 断言失败,如有其他失败则继续修复。
完整命令:pytest -q - Assistant
完整套件结果:3774 通过、3 跳过、2 失败。第一项是已说明的新旧需求冲突;第二项 MCP 测试与改动文件无关,可能是全套运行时的环境/状态污染,我会单独重跑确认。之后检查 diff 和空白,并决定是否需补充生产级异步复现。
完整命令:pytest -q tests/webui/test_mcp_presets_api.py::test_test_mcp_preset_connects_and_reports_tools; git diff --check; git status --short - Assistant
MCP 测试单独仍失败,确认是仓库当前环境中的独立既有问题(改动仅涉及 session manager 与 memory)。提交前再做随机化不变量验证:对不同长度、cap、用户位置和
last_consolidated,返回的 archive 与 kept 必须无重叠且拼接后严格等于原消息序列;同时运行除旧 hard-cap 语义断言外的全部相关测试。
完整命令:python - <<'PY'\nfrom nanobot.session.manager import Session\n\nfor n in range(1, 60):\n for cap in range(0, 20):\n for user_at in [None, 0, n // 2, n - 1]:\n original = [{\"role\": \"assistant\", \"id\": i} for i in range(n)]\n if user_at is not None:\n original[user_at] = {\"role\": \"user\", \"id\": user_at}\n for last in [0, n // 2, n]:\n session = Session(key=\"property\", messages=original.copy(), last_consolidated=last)\n dropped, already = session.retain_recent_legal_suffix(cap)\n assert dropped + session.messages == original, (n, cap, user_at, last)\n assert {m[\"id\"] for m in dropped}.isdisjoint(m[\"id\"] for m in session.messages)\n assert already == min(last, len(dropped))\n assert session.last_consolidated == max(0, last - len(dropped))\nprint(\"suffix/accounting invariants passed\")\nPY\npytest -q tests/agent/test_session_manager_history.py tests/agent/test_auto_compact.py tests/agent/test_consolidator.py -k 'not hard_cap_with_long_non_user_chain' - Assistant
最终检查结论与用户要求的 checklist:
- 已成功复现报告错误:原实现得到
cut=90,索引 85 的用户消息同时进入 archive 和 kept,且两者重叠 5 条。 - 已确认修复解决错误:修复后得到
archive == messages[:85]、kept == messages[85:],用户消息只在 kept 中,重叠为 0。 - 已考虑边界情况:验证了无用户消息、
max_messages <= 0、不同用户位置、不同last_consolidated;随机化验证确认 dropped + kept 始终严格还原原序列且 consolidated 计数正确。 - 已运行相关现有测试:Ruff 通过;Consolidator 28 项通过;相关测试按新语义 106 项通过。完整套件 3774 项通过、3 项跳过;失败项中一个是与问题明确期望冲突的旧 hard-cap 断言(新需求明确允许 10 的目标保留 15 条),另一个是与本改动无关且单独可复现的 MCP preset 既有失败。未修改或新增任何测试。
最后确认提交差异仅包含两个源文件,然后提交。
完整命令:git diff --stat && git diff --check && git status --short && submit - 已成功复现报告错误:原实现得到
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.