The bug is confirmed in both scenarios. Now I need to fix the retain_recent_legal_suffix method.
The root cause: In the else branch, when the tail has no user message, the code does:
retained = list(self.messages[latest_user: latest_user + max_messages])
This creates retained that starts at latest_user but only has max_messages items. So if latest_user = 85 and max_messages = 10, retained = self.messages[85:95].
Then dropped_count = len(self.messages) - len(retained) = 100 - 10 = 90, and the caller does dropped = before[:90] which is before[0:90] (indices 0-89).
So indices 85-89 are in BOTH dropped and retained!
The fix: In the else branch, retained should be self.messages[latest_user:] (all messages from latest_user to the end). This way:
retained = self.messages[85:] (15 messages)
dropped_count = 100 - 15 = 85
dropped = before[:85] = before[0:85] (indices 0-84)
- No overlap!
But then we need to handle the hard cap. Currently:
if len(retained) > max_messages:
retained = retained[-max_messages:]
If retained has 15 messages and max_messages = 10, this would trim to the last 10, losing the user message at the start.
The solution: The hard cap should NOT be applied blindly. Instead, when the else branch was taken, we should keep all messages from latest_user to the end, even if it exceeds max_messages. The hard cap should only trim from the beginning, keeping the suffix intact.
Actually wait - if we keep retained = self.messages[latest_user:] and don't apply the hard cap, then len(retained) could be more than max_messages. The test test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chain expects len(session.messages) <= 6.
Hmm, let me think about this differently. The purpose of the method is to trim the message list while keeping a "legal" suffix. The hard cap is a secondary concern - it's there to prevent unbounded growth, but the primary goal is to keep a legal suffix.
Looking at the issue description again:
期望:
cut = latest_user # 应该是 85,不是 90
archive = tail[:85] # [0-84],不包含用户消息
kept = tail[85:] # [85-99],包含用户消息及其后续内容
The expected behavior is kept = tail[85:] which is 15 messages (more than max_messages=10). So the hard cap should NOT be applied in this case.
But the existing test expects <= 6. If we change the behavior, the test would fail. However, the instructions say:
If existing tests break because they need to be updated to reflect the changes you made, just ignore it.
So I should fix the bug and not worry about the test if it needs updating.
Let me think about what the correct behavior should be:
- When the tail (last N messages) contains a user message, trim to start at the first user message
- When the tail doesn't contain a user message, extend backwards to include the last user message
- The hard cap should still be respected, but it should not cause overlap
Wait, but if we keep retained = self.messages[latest_user:] and apply the hard cap as retained[-max_messages:], we'd lose the user message. And if we don't apply the hard cap, we might keep way too many messages.
I think the correct approach is:
- In the else branch, set
retained = self.messages[latest_user:]
- Remove or modify the hard cap check so it doesn't break the user message
Actually, looking more carefully at the code flow, the hard cap check happens AFTER all the logic:
# Hard-cap guarantee: never keep more than max_messages.
if len(retained) > max_messages:
retained = retained[-max_messages:]
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
This unconditionally trims to the last max_messages messages. This is wrong when we've extended backwards to include a user message.
I think the fix should be:
- In the else branch, set
retained = self.messages[latest_user:]
- If
len(retained) > max_messages, DON'T apply the hard cap. Just keep all messages from latest_user to the end.
The rationale: if we had to extend backwards to find a user message, it means the recent messages are all assistant/tool. The purpose of the method is to keep a "legal" suffix (starting from a user message). If we respect the hard cap, we'd lose the user message and end up with an illegal suffix.
So the fix is:
- Change
retained = list(self.messages[latest_user: latest_user + max_messages]) to retained = list(self.messages[latest_user:])
- Remove or modify the hard cap check to not apply when the else branch was taken
But wait, what about the case where latest_user is very far back (like index 0 out of 14)? If we keep all 14 messages instead of trimming to 6, that's a lot. But the alternative is losing the user message, which is worse.
Actually, let me reconsider. In the test test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chain, the user is at index 0 and there are 14 messages. If we keep all 14, that's fine - the hard cap is just a soft limit to keep things reasonable, but it shouldn't cause overlap or lose the user message.
Actually, the purpose of retain_recent_legal_suffix is different from what I thought. Let me re-read the docstring:
"""Keep a legal recent suffix constrained by a hard message cap."""
"Keep a legal recent suffix" - this means the kept messages should be a suffix (end portion) of the original messages. If retained = self.messages[latest_user:], this IS a suffix. But if retained = self.messages[latest_user: latest_user + max_messages], this is NOT a suffix when latest_user + max_messages < len(self.messages).
In the bug scenario:
latest_user = 85, max_messages = 10, len(self.messages) = 100
- Current:
retained = self.messages[85:95] - NOT a suffix! (messages 95-99 are lost)
- Fix:
retained = self.messages[85:] - IS a suffix!
So the fix is clear: retained should always be a suffix of the original messages.
Now, about the hard cap. If len(retained) > max_messages, the current code does:
retained = retained[-max_messages:]
This trims from the beginning, keeping the last max_messages messages. But this could lose the user message!
I think the hard cap should only apply when it doesn't lose the user message. Or more precisely:
- After the else branch,
retained starts at the user message
- If we need to trim for the hard cap, we should trim from the end (most recent messages), not from the beginning
Wait, that doesn't make sense either. We want to keep recent messages, so trimming from the beginning makes more sense.
Let me think again. The hard cap's purpose is to prevent unbounded growth. But if len(self.messages[latest_user:]) is much larger than max_messages, it means there are many messages between the last user and the end. These are probably all assistant/tool messages. In this case, maybe we should just keep the user message and the most recent messages.
Actually, I think I'm overcomplicating this. Let me look at the issue from a different angle:
The bug is that retained is not a proper suffix, causing overlap. The fix is to make retained a proper suffix:
retained = self.messages[latest_user:]
And then the hard cap check should be adjusted to not break the user message boundary. One simple approach:
- After setting
retained = self.messages[latest_user:], skip the hard cap check
The rationale: if the tail has no user message and we've extended to include the last user, we should keep everything from that user to the end. The hard cap is just a soft limit to keep things reasonable.
But this could result in keeping many more than max_messages messages. Is that OK?
Looking at the usage:
enforce_file_cap calls retain_recent_legal_suffix(limit) with limit=FILE_MAX_MESSAGES=2000. This is already a large number.
- The
memory.py usage uses max_suffix which is probably also large.
So in practice, exceeding max_messages by a small amount (like 15 vs 10) shouldn't be a big deal.
Actually, let me look at the test more carefully:
def test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chain():
session = Session(key="test:hard-cap-chain")
session.messages.append({"role": "user", "content": "u0"})
session.messages.append(
{
"role": "assistant",
"content": None,
"tool_calls": [
{"id": "c1", "type": "function", "function": {"name": "x", "arguments": "{}"}}
],
}
)
for i in range(12):
session.messages.append({"role": "assistant", "content": f"a{i}"})
session.retain_recent_legal_suffix(6)
assert len(session.messages) <= 6
This test has 14 messages (1 user + 1 assistant + 12 assistant). With max_messages=6:
retained = self.messages[-6:] = indices 8-13 (6 assistant messages)
first_user = None
latest_user = 0
- Current:
retained = self.messages[0:6] = indices 0-5 (user + assistant + 4 assistant messages)
- Hard cap:
len(retained) = 6 <= 6, no trim
- Result: 6 messages, user is present ✅ (but with overlap bug)
With my fix (retained = self.messages[latest_user:]):
retained = self.messages[0:] = all 14 messages
- Hard cap:
14 > 6, so retained = retained[-6:] = indices 8-13
- But these are all assistant messages! User is lost! ❌
So if I change the else branch but keep the hard cap, I lose the user message. I need to also modify the hard cap.
Option 1: Skip hard cap entirely when else branch was taken
retained = self.messages[0:] = 14 messages
- Skip hard cap
- Result: 14 messages, user is present ✅
- Test would fail:
assert len(session.messages) <= 6 would fail
Option 2: Apply hard cap but from the end, keeping the beginning
retained = self.messages[0:6] = indices 0-5
- But wait, this is what the current code does (almost), and it causes overlap!
Hmm, the issue is that the current code does self.messages[latest_user: latest_user + max_messages] which is NOT a suffix. If we instead do self.messages[latest_user: latest_user + max_messages] but then ensure dropped is computed correctly...
Actually wait, let me think about this differently. The overlap happens in enforce_file_cap:
dropped_count = before_count - len(self.messages)
dropped = before[:dropped_count]
If retain_recent_legal_suffix guarantees that self.messages is always a suffix of before, then before[:dropped_count] would correctly be the messages before the suffix.
So the fix is: retain_recent_legal_suffix should set self.messages to a suffix of the original messages. In the else branch, that means:
self.messages = self.messages[latest_user:]
And then dropped_count = before_count - len(self.messages) = 100 - 15 = 85, and dropped = before[:85] which is the correct prefix.
But we also need to handle the hard cap. If len(self.messages[latest_user:]) > max_messages, we need to trim. But trimming from the beginning would lose the user, and trimming from the end would lose recent context.
I think the answer is: don't trim at all in the else branch. The hard cap is a soft limit. If keeping from the last user to the end exceeds max_messages, that's fine. The purpose of the method is to keep a "legal" suffix, and keeping from the last user is the legal suffix.
For the test test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chain, the test would fail because len(session.messages) would be 14 instead of 6. But the instructions say to ignore test failures if the test needs updating.
Wait, let me re-read the test:
assert len(session.messages) <= 6
With the fix:
retained = self.messages[0:] = 14 messages (all of them)
find_legal_message_start returns 0 (user message at start)
- Hard cap: 14 > 6, but we skip it because else branch was taken
- Result: 14 messages
The test would fail. But the purpose of the method is to keep a legal suffix, and keeping 14 messages when the user is at index 0 is correct.
Actually, I realize there might be a way to satisfy both the bug fix and the hard cap:
After setting retained = self.messages[latest_user:], if len(retained) > max_messages:
- Don't trim from the end (that would lose recent context)
- Don't trim from the beginning (that would lose the user message)
- Just keep all messages from
latest_user to the end
The hard cap can't be enforced without losing important context. So we skip it.
But this might result in len(retained) >> max_messages in some cases. Is that acceptable?
Looking at the usage again, enforce_file_cap is called with limit=FILE_MAX_MESSAGES=2000. This is already very large. The method is meant to prevent unbounded growth, not to strictly enforce a cap. So exceeding the cap by a small amount is fine.
But what if latest_user = 0 and there are 10000 messages? Then retained = self.messages[0:] = 10000 messages, which defeats the purpose of the cap.
Hmm, I think the answer is: the hard cap should still be enforced, but it should NOT cause overlap. The way to do this is:
- In the else branch, find
latest_user
retained = self.messages[latest_user:]
- If
len(retained) > max_messages:
- We need to trim, but we can't lose the user message
- The user message is at index 0 of
retained
- We can keep the user message and trim the rest
retained = [retained[0]] + retained[-(max_messages-1):]
- But this breaks the suffix property!
OK this is getting complicated. Let me step back and think about what the method is supposed to achieve:
- Keep at most
max_messages messages
- The kept messages should form a "legal" suffix (not start mid-conversation)
- A legal suffix starts with a user message or a complete assistant turn
When the tail has no user message, the method extends backwards to find the last user. The current bug is that the extension doesn't preserve the suffix property.
I think the simplest and most correct fix is:
- Change the else branch to:
retained = list(self.messages[latest_user:])
- Remove the hard cap check (or make it conditional)
This way:
self.messages is always a suffix of the original
- No overlap between
dropped and self.messages
- The user message is preserved
The downside is that len(self.messages) might exceed max_messages. But this is acceptable because:
- The purpose is to prevent unbounded growth, and
retain_recent_legal_suffix is called after growth has already occurred
- The hard cap is a soft limit, and exceeding it by a small amount to preserve the user message is better than losing the user message
Let me also check if there's any issue with find_legal_message_start after the else branch:
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
If retained = self.messages[latest_user:] and the first message is a user message, find_legal_message_start would return 0, so no trimming. Good.
But wait, there might be orphan tool results before latest_user. Let me think...
Actually, latest_user is the index of the last user message in the full message list. So self.messages[latest_user:] starts with the user message. find_legal_message_start checks for orphan tool results (tool results without matching assistant calls). Since the user message is first, there can't be orphan tool results before it. So find_legal_message_start would return 0. Good.
Wait, but what if latest_user is 0 (the first message)? Then self.messages[0:] is all messages. If there are orphan tool results before the user message... wait, there can't be anything before index 0.
OK let me also think about what happens if there's no user message at all. The code checks if latest_user is not None, so if there's no user message, the else branch doesn't change retained. Good.
Alright, let me implement the fix. Here's my plan:
-
In the else branch, change:
retained = list(self.messages[latest_user: latest_user + max_messages])
to:
retained = list(self.messages[latest_user:])
-
The hard cap check at the end should be modified to not break the user message boundary. One approach: track whether the else branch was taken, and skip the hard cap if so.
Actually, wait. Let me re-read the hard cap code:
# Hard-cap guarantee: never keep more than max_messages.
if len(retained) > max_messages:
retained = retained[-max_messages:]
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
The problem is that retained[-max_messages:] trims from the beginning, which could lose the user message. And then find_legal_message_start might trim orphan tool results from the front.
I think the safest fix is to simply NOT apply the hard cap when the else branch was taken. We can do this by not changing retained to a non-suffix in the else branch, and then the hard cap naturally won't cause issues.
Wait, actually, let me think again. If retained = self.messages[latest_user:] and this has 14 messages with max_messages = 6:
- Hard cap:
14 > 6, so retained = retained[-6:] = last 6 messages
- But these are all assistant messages! User is lost!
So the hard cap DOES cause issues. I need to skip it when the else branch was taken.
One clean way to do this: after the else branch, add a comment and skip the hard cap check.
But actually, there's an even simpler approach. The issue is that the current else branch creates a non-suffix. If we just fix it to create a suffix, the hard cap would still apply but correctly:
If retained = self.messages[latest_user:] is a suffix and has 14 messages:
- Hard cap:
retained = retained[-6:] = last 6 of the 14
- These would be indices 8-13, which are all assistant messages
Hmm, the hard cap would still lose the user message even if retained is a suffix.
OK I think the fix needs to be more comprehensive:
- In the else branch, set
retained = self.messages[latest_user:]
- Skip the hard cap check if the else branch was taken
Here's my proposed fix:
def retain_recent_legal_suffix(self, max_messages: int) -> None:
"""Keep a legal recent suffix constrained by a hard message cap."""
if max_messages <= 0:
self.clear()
return
if len(self.messages) <= max_messages:
return
retained = list(self.messages[-max_messages:])
# Prefer starting at a user turn when one exists within the tail.
first_user = next((i for i, m in enumerate(retained) if m.get("role") == "user"), None)
if first_user is not None:
retained = retained[first_user:]
else:
# If the tail is assistant/tool-only, anchor to the latest user in
# the full session and take a capped forward window from there.
latest_user = next(
(i for i in range(len(self.messages) - 1, -1, -1)
if self.messages[i].get("role") == "user"),
None,
)
if latest_user is not None:
retained = list(self.messages[latest_user:])
# Mirror get_history(): avoid persisting orphan tool results at the front.
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
# Hard-cap guarantee: never keep more than max_messages.
# Only apply if we haven't already extended past latest_user.
if len(retained) > max_messages:
retained = retained[-max_messages:]
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
dropped = len(self.messages) - len(retained)
self.messages = retained
self.last_consolidated = max(0, self.last_consolidated - dropped)
self.updated_at = datetime.now()
Wait, this still has the hard cap issue. If retained = self.messages[latest_user:] has 14 messages and max_messages = 6, the hard cap would trim to 6, losing the user.
Hmm, let me think about this differently. Maybe the hard cap should only apply when the first user IS found in the tail (i.e., when first_user is not None):
if len(retained) > max_messages:
if first_user is not None:
# Only apply hard cap when the tail naturally contains a user
retained = retained[-max_messages:]
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
But wait, first_user is checked BEFORE the else branch. If first_user is not None, we trim retained to start at the first user, and then the hard cap applies. If first_user is None, we enter the else branch, extend to latest_user, and the hard cap should NOT apply.
Actually, I think the cleanest fix is:
else:
...
if latest_user is not None:
retained = list(self.messages[latest_user:])
# When extending to include the last user, keep the full suffix
# to avoid overlap between archive and kept. The hard cap is
# skipped because trimming would lose the user message or
# create a non-suffix.
self.messages = retained
dropped = len(self.messages) - len(retained) # This is wrong
...
Hmm, this gets messy. Let me try a different approach.
Actually, I realize the simplest fix is:
- Change
retained = list(self.messages[latest_user: latest_user + max_messages]) to retained = list(self.messages[latest_user:])
- Remove the hard cap check entirely, OR
- Make the hard cap check aware of the else branch
Option 3 is the cleanest. We can use a flag:
extended_for_user = False # Track if we extended beyond the tail
...
else:
if latest_user is not None:
retained = list(self.messages[latest_user:])
extended_for_user = True
...
# Hard-cap guarantee
if not extended_for_user and len(retained) > max_messages:
retained = retained[-max_messages:]
...
But this feels hacky. Let me think of a cleaner approach.
Actually, I think the key insight is: the hard cap should never result in a non-suffix. If retained is a suffix of self.messages, then retained[-max_messages:] is also a suffix. So the hard cap preserves the suffix property.
The issue is that the hard cap might lose the user message. But that's a different issue from the overlap bug.
Hmm, actually wait. Let me re-read the code:
retained = list(self.messages[-max_messages:]) # Suffix
first_user = next((i for i, m in enumerate(retained) if m.get("role") == "user"), None)
if first_user is not None:
retained = retained[first_user:] # Still a suffix (of the original suffix)
else:
latest_user = ...
if latest_user is not None:
retained = list(self.messages[latest_user: latest_user + max_messages]) # NOT a suffix!
The bug is specifically in the else branch where latest_user + max_messages < len(self.messages), making retained NOT a suffix.
If I change it to list(self.messages[latest_user:]), then retained IS a suffix.
Then:
# Hard-cap guarantee: never keep more than max_messages.
if len(retained) > max_messages:
retained = retained[-max_messages:] # Still a suffix
This would trim to the last max_messages messages, which IS a suffix. So the suffix property is preserved.
But the user message would be lost if latest_user is far back. That's a trade-off, but it's better than having overlap.
Actually wait, let me reconsider. If retained = self.messages[latest_user:] and len(retained) > max_messages:
retained = retained[-max_messages:] trims from the beginning
- The first message of
retained (the user message) would be trimmed
- But
retained[-max_messages:] would be a suffix of the original suffix, which is still a suffix of the original messages
So the suffix property is preserved. But the user message is lost. That's a problem.
But then find_legal_message_start would trim orphan tool results from the front. If the first message is an assistant message (not a user), the result might start with orphan tool results that get trimmed. Eventually, the result might be all assistant/tool messages, which is... OK? It's at least not overlapping.
Actually, I think the real question is: is it OK to lose the user message if it means no overlap?
Looking at the issue description:
期望行为:当会话历史中最近 N 条消息全是助手/工具消息,而用户消息位于更早位置时:
1. 用户消息不应被重复归档 - 用户消息应该只保留在 kept 中,不应该同时出现在 archive 和 kept 中
2. 归档边界应该正确
3. 上下文连贯性应该保持
The issue says the user message should be kept, not lost. So I need to find a way to keep the user message without overlap.
OK so let me try yet another approach:
The fix should be:
retained = self.messages[latest_user:] (suffix, includes user)
- Skip the hard cap when the else branch was taken
The trade-off is that len(retained) might exceed max_messages. But this is acceptable because:
- The hard cap is a soft limit to prevent unbounded growth
- The actual growth happens between calls to
enforce_file_cap, not within a single call
- Exceeding the cap by a small amount (e.g., 15 vs 10) is much better than losing the user message or having overlap
Let me implement this fix:
def retain_recent_legal_suffix(self, max_messages: int) -> None:
"""Keep a legal recent suffix constrained by a hard message cap."""
if max_messages <= 0:
self.clear()
return
if len(self.messages) <= max_messages:
return
retained = list(self.messages[-max_messages:])
# Prefer starting at a user turn when one exists within the tail.
first_user = next((i for i, m in enumerate(retained) if m.get("role") == "user"), None)
if first_user is not None:
retained = retained[first_user:]
else:
# If the tail is assistant/tool-only, anchor to the latest user in
# the full session and take all messages from there to the end.
latest_user = next(
(i for i in range(len(self.messages) - 1, -1, -1)
if self.messages[i].get("role") == "user"),
None,
)
if latest_user is not None:
retained = list(self.messages[latest_user:])
# Mirror get_history(): avoid persisting orphan tool results at the front.
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
# Hard-cap guarantee: never keep more than max_messages.
if len(retained) > max_messages:
retained = retained[-max_messages:]
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
dropped = len(self.messages) - len(retained)
self.messages = retained
self.last_consolidated = max(0, self.last_consolidated - dropped)
self.updated_at = datetime.now()
The only change is in the else branch: self.messages[latest_user:] instead of self.messages[latest_user: latest_user + max_messages].
Let me trace through both scenarios:
Bug scenario (100 messages, user at 85, max=10):
retained = self.messages[-10:] = indices 90-99
first_user = None
- Else:
latest_user = 85
retained = self.messages[85:] = indices 85-99 (15 messages)
find_legal_message_start(retained) returns 0 (starts with user)
- Hard cap:
15 > 10, so retained = retained[-10:] = indices 90-99 (loses user!) ❌
Hmm, the hard cap still loses the user. I need to also modify the hard cap.
Option: Skip hard cap when else branch was taken:
extended_past_tail = first_user is None and latest_user is not None
...
if not extended_past_tail and len(retained) > max_messages:
retained = retained[-max_messages:]
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
Wait, I need to define latest_user outside the else branch. Let me restructure:
retained = list(self.messages[-max_messages:])
first_user = next((i for i, m in enumerate(retained) if m.get("role") == "user"), None)
if first_user is not None:
retained = retained[first_user:]
else:
latest_user = next(
(i for i in range(len(self.messages) - 1, -1, -1)
if self.messages[i].get("role") == "user"),
None,
)
if latest_user is not None:
retained = list(self.messages[latest_user:])
I can use a flag:
extended_past_tail = False
...
else:
latest_user = next(...)
if latest_user is not None:
retained = list(self.messages[latest_user:])
extended_past_tail = True
...
if not extended_past_tail and len(retained) > max_messages:
retained = retained[-max_messages:]
start = find_legal_message_start(retained)
if start:
retained = retained[start:]
Let me trace through both scenarios again:
Bug scenario (100 messages, user at 85, max=10):
retained = self.messages[-10:] = indices 90-99
first_user = None
- Else:
latest_user = 85, retained = self.messages[85:] = indices 85-99 (15 messages), extended_past_tail = True
find_legal_message_start returns 0
- Hard cap: skipped because
extended_past_tail = True
dropped = 100 - 15 = 85
self.messages = retained (15 messages)
- In
enforce_file_cap: dropped = before[:85] = indices 0-84 (no user) ✅
Test scenario (14 messages, user at 0, max=6):
retained = self.messages[-6:] = indices 8-13
first_user = None
- Else:
latest_user = 0, retained = self.messages[0:] = all 14 messages, extended_past_tail = True
find_legal_message_start returns 0
- Hard cap: skipped because
extended_past_tail = True
dropped = 14 - 14 = 0
self.messages = retained (14 messages)
- Test assertion:
len(session.messages) <= 6 → FAILS (14 > 6)
But the overlap bug is fixed. The test would fail, but the instructions say to ignore test failures if the test needs updating.
Actually, let me reconsider the test scenario. With extended_past_tail = True:
dropped = 14 - 14 = 0
dropped_count = 14 - 14 = 0
- No messages are dropped, so no overlap ✅
But len(self.messages) = 14 > 6. The test would fail.
Is there a way to fix the overlap bug without breaking the test?
Actually, the test test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chain is testing a specific edge case: "hard cap with long non-user chain". The purpose is to verify that when there are many assistant messages after a single user message, the hard cap is still enforced.
With the fix, the hard cap is not enforced when extending past the tail. The rationale is that extending past the tail means we need the user message for context, and dropping it would cause more harm than exceeding the cap.
But the test expects the hard cap to be enforced. This is a legitimate test case that the fix would break.
Hmm, let me think about this from a different angle. Is the hard cap really important in the test scenario?
In the test scenario:
- 14 messages, user at index 0
- max_messages = 6
- The user is at the very start
If we keep all 14 messages, the hard cap is violated. But is that a big deal? The method is called retain_recent_legal_suffix, and its purpose is to keep a "legal" suffix. If the user is at the start, the legal suffix is the entire message list. Trimming it would lose the user message.
On the other hand, if latest_user is very far back (like index 0 out of 10000), keeping all 10000 messages would defeat the purpose of the cap.
I think the answer is: we should keep all messages from latest_user to the end, regardless of the hard cap. The hard cap is a soft limit to prevent unbounded growth, but it shouldn't be enforced at the cost of losing the user message or creating overlap.
Actually, I just realized something. The test scenario has latest_user = 0 (the user is at the very start). This means the entire message list would be kept. But in the bug scenario, latest_user = 85 (not at the start), so only a portion would be kept.
For the test scenario, keeping all 14 messages is correct because the user is at the start. For the bug scenario, keeping 15 messages (slightly more than 10) is also correct.
I think the fix is correct, and the test should be updated to reflect the new behavior.
But wait, I should double-check: would there be any case where the fix causes a problem?
Case 1: latest_user = 0 and there are 10000 messages
retained = self.messages[0:] = all 10000 messages
- No hard cap, so all 10000 are kept
dropped = 0
- No archive
Is this OK? Well, enforce_file_cap is called with limit = FILE_MAX_MESSAGES = 2000. If the session has 10000 messages, that's already a problem. But the fix doesn't make it worse - it just keeps the user message.
Actually, wait. If the session has 10000 messages and latest_user = 0, the fix would keep all 10000. But that means no archiving happens. That's bad!
Hmm, but the original code also has this issue. Let me check:
retained = self.messages[-2000:] = last 2000 messages
first_user = None (assuming no user in the last 2000)
latest_user = 0
- Original:
retained = self.messages[0: 0 + 2000] = first 2000 messages
- Hard cap:
2000 <= 2000, no trim
dropped = 10000 - 2000 = 8000
dropped = before[:8000] = first 8000 messages
self.messages = first 2000 messages (NOT a suffix!)
Wait, the original code also doesn't produce a suffix in this case! self.messages = before[0:2000] is NOT the tail of the original 10000 messages. The messages at indices 2000-9999 are lost!
So the original code has TWO bugs:
- Overlap (user message in both archive and kept)
- Message loss (messages between
latest_user + max_messages and the end are lost)
With the fix:
retained = self.messages[0:] = all 10000 messages
dropped = 0
- No archive, no message loss
- But no trimming either, which defeats the purpose of the cap
Hmm, this is a problem. The fix prevents overlap and message loss but defeats the cap entirely.
I think the correct behavior should be:
- Keep from
latest_user to the end (suffix)
- If this exceeds
max_messages, trim the suffix to max_messages but DON'T lose the user message
But how to trim without losing the user? We could:
- Keep the user message
- Keep the last
max_messages - 1 messages
- Drop everything in between
if len(retained) > max_messages:
# Keep the first message (user) and the last max_messages-1 messages
if len(retained) > max_messages:
retained = [retained[0]] + retained[-(max_messages - 1):]
But this breaks the suffix property again! retained[0] is the user, and retained[-(max_messages-1):] is the tail. But we're dropping the middle.
Actually, I think this is OK. The suffix property is important for the dropped calculation in enforce_file_cap. But if we drop from the middle, we'd need to adjust the dropped calculation.
Hmm, this is getting complicated. Let me reconsider.
Actually, I think the simplest and most correct fix is:
- In the else branch, set
retained = list(self.messages[latest_user:]) to ensure a suffix
- Keep the hard cap check as-is
This fixes the overlap bug and message loss bug. The hard cap might lose the user message, but that's a trade-off.
Wait, but the issue specifically says the user should be kept. And the hard cap WOULD lose it in many cases.
OK let me look at this from a practical perspective. In real usage:
max_messages is typically 2000 (FILE_MAX_MESSAGES)
- The else branch is triggered when the last 2000 messages are all assistant/tool
- This is rare but possible
- If the last user is within the last few hundred messages, the suffix would be a few hundred messages, which is fine
- If the last user is very far back, the suffix could be large, but exceeding the cap by a bit is OK
I think the fix should be:
retained = list(self.messages[latest_user:])
- Skip the hard cap when the else branch was taken
And accept that the test test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chain would fail.
Actually, you know what, let me just look at what the test is really testing:
def test_retain_recent_legal_suffix_hard_cap_with_long_non_user_chain():
session = Session(key="test:hard-cap-chain")
session.messages.append({"role": "user", "content": "u0"})
session.messages.append(assistant with tool_calls)
for i in range(12):
session.messages.append({"role": "assistant", "content": f"a{i}"})
session.retain_recent_legal_suffix(6)
assert len(session.messages) <= 6
The test creates 14 messages (1 user + 1 assistant with tool_calls + 12 assistant). It then calls retain_recent_legal_suffix(6) and expects <= 6 messages.
With the current code:
retained = self.messages[-6:] = 6 assistant messages (indices 8-13)
first_user = None
latest_user = 0
retained = self.messages[0:6] = first 6 messages
find_legal_message_start might trim some
- Hard cap:
6 <= 6, no trim
- Result: 6 messages, which passes the test
With my fix:
retained = self.messages[0:] = all 14 messages
find_legal_message_start returns 0 (user at start)
- Hard cap skipped (extended past tail)
- Result: 14 messages, test fails
Hmm, 14 messages when the cap is 6 is a big difference. But the overlap is fixed.
OK wait, I just realized I might be overthinking this. Let me check if the hard cap even matters after the else branch.
The hard cap's purpose is to limit message count. But if the else branch is triggered, it means the recent messages are all assistant/tool. In this case, the user is looking at a long assistant response or tool execution. Keeping all messages from the user to the end makes sense for context.
If the session has 10000 messages and the last user is at index 0, keeping all 10000 would be bad. But in that case, latest_user = 0, and we'd keep all 10000. Is there a better approach?
Actually, I think the hard cap IS important. We need to trim, but we need to trim from the beginning (old messages) while keeping the user and the tail.
Here's another idea: after the else branch, if len(retained) > max_messages:
- Keep the first user message (at
retained[0])
- Keep the last
max_messages - 1 messages (the tail)
- Drop the middle
if len(retained) > max_messages:
head = [retained[0]] # User message
tail = retained[-(max_messages - 1):] # Recent messages
retained = head + tail
But this breaks the suffix property. self.messages would be [user] + [last 9 messages], which is NOT a suffix of the original. So dropped = before[:dropped_count] would be wrong.
Hmm, but what if we compute dropped differently? Instead of before[:dropped_count], we could explicitly compute which messages were dropped.
Actually, this brings me back to the idea that retain_recent_legal_suffix should return the dropped messages. Let me re-read the issue's Interface section:
Output: tuple[list[dict], int]
Description: 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.
So the interface should return (dropped_messages, already_consolidated_count). This way, the caller knows exactly which messages were dropped, regardless of how the trimming was done.
But this is a significant interface change that would affect all callers. Let me check the callers:
enforce_file_cap in manager.py
memory.py (line 810)
commands.py (line 1032)
Let me check how commands.py uses it:
<tool_call>
<function=bash_terminal>
<parameter=command>
grep -B10 -A10 "retain_recent_legal_suffix" /nanobot/nanobot/cli/commands.py
</tool_call>