Python: fix: prevent superlinear history growth by deduplicating messages in save_messages - #7242
Conversation
There was a problem hiding this comment.
Pull request overview
This PR fixes a Python history-persistence defect where per-service-call history providers re-persist the full accumulated conversation every round, causing superlinear growth and duplicated context. It introduces message-level deduplication in history providers (in-memory, file, Redis) and adds regression tests to ensure repeated inputs don’t bloat stored history.
Changes:
- Added a message-identity helper and used it to filter out already-persisted messages before appending/pushing.
- Updated
save_messagesbehavior across in-memory, file (JSONL), and Redis history providers to skip duplicates. - Added unit/regression tests covering identical-message deduplication and mixed old/new message lists.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| python/packages/core/agent_framework/_sessions.py | Adds message identity + deduplication to in-memory and file history providers. |
| python/packages/core/tests/core/test_sessions.py | Adds regression tests for deduplication behavior in core providers and looped runs. |
| python/packages/redis/agent_framework_redis/_history_provider.py | Adds message identity + deduplication to Redis history persistence. |
| python/packages/redis/tests/test_providers.py | Adds Redis-provider tests validating deduplication behavior. |
|
Please check the failing tests, and make sure the comments have a reply or are marked as resolved @PratikWayase |
bf1f04f to
ed50554
Compare
Python Test Coverage Report •
Python Unit Test Overview
|
||||||||||||||||||||||||||||||||||||||||
|
Still some checks failing @PratikWayase |
|
and a new merge conflict @PratikWayase |
|
@eavanvalkenburg, @moonbox3 @giles17 the merge conflict seems to be addressed now. Lmk if there's anything else |
…://github.com/PratikWayase/agent-framework into fix/per-service-history-duplicate-persistence
|
@moonbox3 addressed your suggestions. Lmk if there's anything else. |
| if msg_id is not None: | ||
| return ("id", str(msg_id)) | ||
|
|
||
| new_id = str(uuid.uuid4()) |
There was a problem hiding this comment.
Could this fallback remain stable across requests? A stateless caller that reconstructs the same ID-less transcript gets a new UUID here on every call, so FileHistoryProvider and RedisHistoryProvider treat the replayed messages as new even though role and content are unchanged; only reusing the same Python object preserves the ID. That reintroduces the superlinear history growth this PR is meant to prevent. Could the identity be derived from stable request data or the generated ID be carried through the transport while still distinguishing separate identical turns?
There was a problem hiding this comment.
I've reverted the uuid4 approach entirely based on your feedback. Instead, I implemented a sequence-aware filter_new_messages() helper that uses stable content hashes. It correctly preserves legitimate duplicate turns within the same batch while detecting full transcript replays from stateless callers, preventing superlinear growth without requiring unstable IDs
| await pipe.rpush(key, serialized) # type: ignore[misc] | ||
| for msg in new_messages: | ||
| identity = get_message_identity(msg) | ||
| await pipe.sadd(seen_key, json.dumps(list(identity))) # type: ignore[misc] |
There was a problem hiding this comment.
Could the :seen ledger be bounded along with max_messages? Every newly accepted message is added permanently, while only the list is trimmed at lines 194-197 and the set is removed only by clear(). A long-lived session configured with max_messages=N therefore retains an unbounded set and SMEMBERS scans it on every save, so Redis memory and save cost can grow without limit despite the documented retention bound. Could the seen state be pruned or otherwise kept proportional to retained history?
There was a problem hiding this comment.
I've removed the unbounded :seen SET entirely. Deduplication now uses the same sequence-aware filter_new_messages() logic against the bounded LRANGE result. This keeps Redis memory strictly proportional to max_messages and eliminates the SMEMBERS scan overhead
|
@moonbox3 addressed your recent suggestions. Lmk if there's anything else. |
Motivation & Context
The current history providers (
InMemoryHistoryProvider,FileHistoryProvider, andRedisHistoryProvider) blindly append messages on every service call without checking if they already exist in the store.In looped runs (e.g., AG-UI stateless clients or harness todo loops), the transport passes the full accumulated conversation as input on every request. This caused the entire conversation history to be re-persisted every round, leading to superlinear store growth, corrupted context, repeated tool calls, and massive token bloat (up to 3× the real conversation size).
Multi-iteration flows where each service call's message list carries the accumulated conversation rather than a delta, particularly when using stateless chat clients over the AG-UI endpoint.
Description & Review Guide
What are the major changes?
_get_message_identityhelper function that generates a stable identity for a message (usingmessage.idif available, otherwise falling back to a deterministic hash ofrole + serialized contents).save_messagesinInMemoryHistoryProvider,FileHistoryProvider, andRedisHistoryProviderto build a set of existing message identities and filter out duplicates before appending/pushing new messages.What is the impact of these changes?
This hardens the system at the lowest storage level. It completely prevents duplicate message persistence regardless of how the middleware or transport layer constructs the message list. This stops token bloat, prevents context corruption, and ensures graceful degradation in long-running loops without requiring changes to the middleware routing logic.
What do you want reviewers to focus on?
_get_message_identityfallback logic (ensuring it handles missing IDs and serialization edge cases gracefully).RedisHistoryProvider.save_messagesimplementation, specifically ensuring it correctly fetches existing messages vialrangeto build the identity set before pushing only thenew_messagesvia the pipeline.Related Issue
Fixes #7211
Contribution Checklist
breaking changelabel (or add "[BREAKING]" to the title prefix, before or after any language prefix) — a workflow keeps the label and title prefix in sync automatically.