Fix get_last_k_turns ordering issues and add robust event sorting #97
+147
−34
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Root Cause
The original implementation had a fundamental misunderstanding of the boto3
list_eventsAPI behavior. The code mistakenly assumed thatlist_eventsreturns events in chronological order, when it actually returns them in reverse chronological order (newest first). This incorrect assumption caused cascading issues throughoutMemoryClient.list_events()andMemoryClient.get_last_k_turns(). The problems were never caught because all tests mocked the boto3list_eventsbehavior based on mistaken assumptions.Problems Caused by Root Cause
list_events, so the real API behavior was never validatedSolution
1. Fixed MemoryClient's list_events Method
list_eventsmethod to ensure events are always returned in the correct chronological order regardless of what boto3 returnseventTimestampafter retrieval2. Refactored get_last_k_turns Method
REVERSE_CHRONOLOGICALtoCHRONOLOGICAL(now that we guarantee correct order)Key Changes
MemoryClient.list_events:
orderwith an EnumEventOrdering.CHRONOLOGICAL|REVERSE_CHRONOLOGICAL, withCHRONOLOGICALas defaultMemoryClient.get_last_k_turns:
Test Coverage
Impact
This fix ensures that
list_eventsandget_last_k_turnsworks correctly with the actual boto3 API behavior, handles pagination properly, and provides consistent results regardless of how events are distributed across API responses. The robust sorting approach also makes the code more resilient to potential future changes in the boto3 API.