Fix consolidation checkpoint-based trim to preserve history #17
Reference in New Issue
Block a user
Delete Branch "fix/consolidation-checkpoint-trim"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem
When
memory_consolidateis called mid-turn, deferred trim was using a relative count (_pending_trim) that gets applied after the turn completes. This caused the trim to recalculate the cut point based on the FINAL session size, and_trim_to_clean_boundarywould walk backward to find a user message, often landing at the START of the current turn and wiping all prior history.Example bug flow:
pending_trim=10cut = 440 - 10 = 430Solution
Replace relative count with absolute checkpoint position:
checkpoint = len(session) - keep_countsession._trim_checkpointsession.messages[checkpoint:]This preserves the intended trim point regardless of messages added during the remainder of the turn.
Testing
Hot-patched to production and verified:
Changes
_find_clean_boundary_before()to find clean user message boundary at checkpoint time_consolidate_memory()to set_trim_checkpointinstead of_pending_trimsession.messages[checkpoint:]Code Review: Checkpoint-Based Trim Fix
Summary
CONDITIONAL APPROVAL - Fix is sound but incomplete. One critical issue must be addressed before merge.
✅ What Works Well
_pending_trim) recalculates from final session size, causing history wipe_find_clean_boundary_before()properly handles empty lists, bounds, and missing user messages❌ CRITICAL: Missing Deferred Trim in System Handler
The
_process_system_message()method (lines 611-812) does NOT apply deferred trims.Impact:
memory_consolidatetool_trim_checkpointRequired fix (add after line 804):
📝 Verification of Fix Logic
Bug scenario reproduced:
_pending_trim=10cut = 440-10 = 430, walks back to msg 426 (turn start), wipes history ❌New behavior:
checkpoint = 426-10 = 416, finds user msg at 415messages[415:]keeps 25 messages from checkpoint ✅Fix verified!
📊 Test Coverage Gap
Missing tests:
_find_clean_boundary_before()edge casesRecommended (not blocking):
🔍 Code Quality Notes
_trim_to_clean_boundarystill needed: Used at line 991 for non-mem0 immediate trim. Not dead code.max(0, len-keep_count)prevents negative indicescheckpoint={checkpoint}, current_size={len}aids debugging���� Recommendation
DO NOT MERGE until deferred trim is added to system message handler.
Once fixed: LGTM ✅
This is a well-designed fix for a critical bug. The checkpoint approach is more maintainable than the old relative-count method.
✅ Fixed in commit
e782318Added deferred trim logic to
_process_system_message()(lines 806-815):Now both message handlers apply deferred trims. Ready for merge.