Conversation
WalkthroughAdds a SessionQAEntry model and extends the cache layer with full session QA CRUD (create/read/update/delete), feedback fields, validation, and prune support. Redis and filesystem adapters implement the new API; cache interface updated with backward-compatible wrappers; tests and prune integration updated. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Please make sure all the checkboxes are checked:
|
|
|
||
| logs_after_prune = await cache_engine.get_usage_logs("unknown", limit=50) | ||
| mcp_logs_after_prune = [log for log in logs_after_prune if log.get("type") == "mcp_tool"] | ||
| assert len(mcp_logs_after_prune) == 1, ( |
There was a problem hiding this comment.
This test needed to be changed due to the introduction of prune in Redis and FS adapters. Prune now deletes the corresponding cache as well therefore the mcp tool usage logs didn't match
This reverts commit 210a1f3.
…mplement-sessionmanager
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Fix all issues with AI agents
In `@cognee/infrastructure/databases/cache/fscache/FsCacheAdapter.py`:
- Around line 101-145: The update_qa_entry (and similarly delete_feedback and
delete_qa_entry) currently calls cache.set(..., expire=86400) which overwrites
the original TTL; change each to read the existing TTL for session_key (e.g.,
ttl = self.cache.ttl(session_key) or equivalent), and when calling
cache.set(...) pass the existing ttl if >0, omit/use None for no-expiry (ttl ==
-1 or None depending on client), and treat ttl <=0 as expired (return False) —
ensure you use session_key, cache.get, cache.ttl and cache.set to preserve the
original expiration semantics instead of hard-coding 86400.
In `@cognee/infrastructure/databases/cache/redis/RedisAdapter.py`:
- Around line 273-301: The delete_qa_entry implementation currently deletes and
rebuilds the Redis list which drops any TTL; before calling delete(session_key)
capture the key's TTL via await self.async_redis.ttl(session_key), then after
rebuilding the list call await self.async_redis.expire(session_key, ttl) if ttl
and ttl > 0 to restore expiry. Update the logic in delete_qa_entry (where
session_key is built and entries are popped/re-pushed) to store ttl, perform the
delete and rpush loop as-is, and then restore expiry using expire when ttl is
positive; preserve existing exception handling.
- Around line 396-401: The close method in RedisAdapter currently only closes
self.async_redis and can leak the synchronous client; after awaiting
self.async_redis.aclose() inside the try block (and even if that raises),
call/ensure self.sync_redis.close() is invoked to close the sync client—use the
existing logger to debug any exceptions from both closures (e.g., wrap sync
close in its own try/except or add a finally that calls
self.sync_redis.close()), referencing the RedisAdapter.close method and the
async_redis and sync_redis attributes.
In `@cognee/tests/unit/infrastructure/databases/cache/test_redis_adapter_crud.py`:
- Around line 70-79: The test assumes non-string feedback_text will raise, but
Pydantic v2 coerces ints to strings; either make SessionQAEntry.feedback_text
strict by adding a field_validator(..., mode='strict') on
SessionQAEntry.feedback_text to reject non-str inputs, or update
test_update_invalid_raises to stop expecting an exception for feedback_text:
call adapter.update_qa_entry("u1","s1","id1", feedback_text=5), then retrieve
the entry (e.g., via adapter.get_qa_entry or the adapter's read method) and
assert the stored feedback_text equals the coerced string "5" instead of using
pytest.raises.
🧹 Nitpick comments (4)
cognee/infrastructure/databases/cache/models.py (1)
11-11: Minor docstring inconsistency.The docstring states
qa_idis "required for update/delete", but the field is declared asOptional[str] = None(line 23). Consider updating the docstring to clarify thatqa_idis optional during creation but required for update/delete operations.cognee/tests/test_usage_logger_e2e.py (1)
224-224: Consider reducing or documenting long sleep durations.The 30-second
asyncio.sleepcalls (lines 224 and 236) make this test slow. If these are necessary for the cognify operation to complete, consider adding a brief comment explaining why, or exploring whether a shorter timeout with polling could achieve the same result.cognee/tests/unit/infrastructure/databases/cache/test_redis_adapter_crud.py (1)
9-16: Add short docstrings to the in-memory Redis mock methods.
These helper methods are currently undocumented; a brief one-liner per method would satisfy the project’s docstring convention.As per coding guidelines: "As a general rule, undocumented function definitions and class definitions in the project's Python code are assumed incomplete. Please consider suggesting a short summary of the code for any of these incomplete definitions as docstrings when reviewing."
cognee/infrastructure/databases/cache/fscache/FsCacheAdapter.py (1)
22-33: Add a short__init__docstring.
It would help document the cache directory layout and diskcache initialization.As per coding guidelines: "As a general rule, undocumented function definitions and class definitions in the project's Python code are assumed incomplete. Please consider suggesting a short summary of the code for any of these incomplete definitions as docstrings when reviewing."
cognee/tests/unit/infrastructure/databases/cache/test_redis_adapter_crud.py
Show resolved
Hide resolved
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
cognee/infrastructure/databases/cache/fscache/FsCacheAdapter.py (1)
47-84:⚠️ Potential issue | 🟠 MajorAdd explicit
ValidationErrorhandling tocreate_qa_entryfor correct error semantics.The method wraps a Pydantic
ValidationErrorasCacheConnectionError, misclassifying input validation failures as infrastructure errors. The sibling methodsupdate_qa_entryanddelete_feedbackcorrectly map this toSessionQAEntryValidationError. Apply the same pattern here.Proposed fix
except Exception as e: + except ValidationError as e: + raise SessionQAEntryValidationError( + message=f"Session QA entry validation failed during create_qa_entry operation: {e!s}" + ) from e + except Exception as e: error_msg = f"Unexpected error while adding Q&A to diskcache: {str(e)}" logger.error(error_msg) raise CacheConnectionError(error_msg) from eAlso consider adding a docstring to
create_qa_entry(seeupdate_qa_entryat line 111 for the pattern).cognee/infrastructure/databases/cache/redis/RedisAdapter.py (1)
119-156:⚠️ Potential issue | 🟠 MajorAdd explicit
ValidationErrorhandling increate_qa_entryto distinguish validation failures from connection errors.The method constructs
SessionQAEntrywithout explicitly catchingValidationError. Invalid data (e.g.,feedback_scoreoutside 1–5 range) gets caught by the generic exception handler and mislabeled asCacheConnectionError. Add aValidationErrorcatch block before the generic handler, matching the pattern inupdate_qa_entry.Suggested fix
except (redis.ConnectionError, redis.TimeoutError) as e: error_msg = f"Redis connection error while adding Q&A: {str(e)}" logger.error(error_msg) raise CacheConnectionError(error_msg) from e + except ValidationError as e: + raise SessionQAEntryValidationError( + message=f"Session QA entry validation failed during create_qa_entry operation: {e!s}" + ) from e except Exception as e: error_msg = f"Unexpected error while adding Q&A to Redis: {str(e)}" logger.error(error_msg) raise CacheConnectionError(error_msg) from e
…mplement-sessionmanager
lxobr
left a comment
There was a problem hiding this comment.
Nice work, looks good to me.
…mplement-sessionmanager
…mplement-sessionmanager
…mplement-sessionmanager
…ssionManager (part 2: Session Manager) (#2082) <!-- .github/pull_request_template.md --> Taks: This PR adds CRUD operations and a centralized SessionManager to manage session QAs. Each QA now has a stable ID and can store optional feedback. The goal is to make session data easier to work with and prepare the ground for future feedback-related features, without changing existing behavior. PR: This PR is the second and final part of the session manager implemenation. Due to the size of the PR the rest of the implementation can be found in #2077 Acceptance Criteria SessionManager provides full CRUD for session QAs. Stored QAs include qa_id and feedback_text / feedback_score fields. Create: New QAs are stored with a generated qa_id; existing “save after search” behavior is unchanged. Read: Session QAs can be fetched by user_id and session_id, with optional last_n; responses include qa_id and feedback fields when present. Update: A QA can be updated by user_id, session_id, and qa_id without losing any existing QA data. Delete: A single QA or an entire session can be deleted; cache keys and layout remain consistent. Cache interfaces and adapters are extended only where necessary; existing contracts are preserved or explicitly migrated. Tests cover SessionManager CRUD and Adapter changes, and existing session-related flows continue to pass. ## Type of Change <!-- Please check the relevant option --> - [ ] Bug fix (non-breaking change that fixes an issue) - [x] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Code refactoring - [ ] Performance improvement - [ ] Other (please specify): ## Screenshots/Videos (if applicable) <!-- Add screenshots or videos to help explain your changes --> ## Pre-submission Checklist <!-- Please check all boxes that apply before submitting your PR --> - [x] **I have tested my changes thoroughly before submitting this PR** - [x] **This PR contains minimal changes necessary to address the issue/feature** - [x] My code follows the project's coding standards and style guidelines - [x] I have added tests that prove my fix is effective or that my feature works - [x] I have added necessary documentation (if applicable) - [x] All new and existing tests pass - [x] I have searched existing PRs to ensure this change hasn't been submitted already - [x] I have linked any relevant issues in the description - [x] My commits have clear and descriptive messages ## DCO Affirmation I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Introduced SessionManager to manage user sessions with question-answer entries and feedback tracking. * Added operations to add, retrieve, update, and delete QA entries and sessions with flexible caching support. * Enabled formatted session output for seamless prompt integration. * **Tests** * Added comprehensive integration tests with filesystem and Redis caching backends. * Added unit tests validating session operations and parameter validation. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: lxobr <122801072+lxobr@users.noreply.github.com>
Description
Taks:
This PR adds CRUD operations and a centralized SessionManager to manage session QAs. Each QA now has a stable ID and can store optional feedback. The goal is to make session data easier to work with and prepare the ground for future feedback-related features, without changing existing behavior.
PR:
This PR is the first part of the implementation containing the FS and Redis adapter level logic. Due to the size of the PR the rest of the implementation can be found in #2082
Acceptance Criteria
Type of Change
Screenshots/Videos (if applicable)
None
Pre-submission Checklist
DCO Affirmation
I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin.
Summary by CodeRabbit
New Features
Improvements
Tests