Repository navigation
refactor(storage): validate row-graph consistency with content hash (#841) - #917
Conversation
Add _compute_hash_from_row_graph() that re-derives the conversation content hash from storage records, then cross-validate it against ConversationRecord.content_hash in save_via_backend(). When the row graph diverges from the recorded hash, log a warning and force a full write instead of trusting the stale hash for the idempotency skip. Document the full hash boundary (inside/outside) in the module docstring and mark action_events as derived from messages + content_blocks, outside the hash. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Warning Rate limit exceeded
To continue reviewing without waiting, purchase usage credits in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
✨ 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a8be8d99d9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
Pull request overview
This PR strengthens the archive conversation write path by documenting the intended content-hash boundary and adding a row-graph → content-hash re-derivation step inside save_via_backend() to prevent incorrect idempotency skips when the provided storage records don’t match ConversationRecord.content_hash.
Changes:
- Documented what is included/excluded from
ConversationRecord.content_hashin the conversation write helpers module docstring. - Added
_compute_hash_from_row_graph()(and aContentBlockRecordhashing helper) and used it insave_via_backend()to detect hash/row-graph divergence and force a full write instead of skipping. - Updated/added storage repository lifecycle tests to cover hash mismatch forcing writes and action-event derivation behavior.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| tests/unit/storage/test_repository_lifecycle_laws.py | Updates idempotency/provider-event tests to account for row-graph validation; adds new tests for hash consistency, stale-hash forcing, skip behavior, and action-event derivation. |
| polylogue/storage/repository/archive/writes/conversations.py | Adds hash-boundary documentation, implements row-graph hash re-derivation helpers, and enforces row-graph/content-hash validation in save_via_backend(). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| msg_entry: dict[str, JSONValue] = { | ||
| "id": str(msg.message_id), | ||
| "role": _normalize_for_hash(str(msg.role) if msg.role else None), | ||
| "text": _normalize_for_hash(msg.text), | ||
| "timestamp": _normalize_for_hash(timestamp_str), |
| att_name: str | None = None | ||
| if att.provider_meta and isinstance(att.provider_meta, dict): | ||
| raw_name = att.provider_meta.get("name") | ||
| if isinstance(raw_name, str): | ||
| att_name = raw_name | ||
| if att_name is None: | ||
| att_name = att.attachment_id | ||
|
|
||
| attachments_payload.append( | ||
| { | ||
| "id": _normalize_for_hash(att.attachment_id), | ||
| "message_id": _normalize_for_hash(att.message_id), | ||
| "name": _normalize_for_hash(att_name), | ||
| "mime_type": _normalize_for_hash(att.mime_type), | ||
| "size_bytes": _normalize_for_hash(att.size_bytes), |
| { | ||
| "event_index": event.event_index, | ||
| "event_type": _normalize_for_hash(event.event_type), | ||
| "timestamp": _normalize_for_hash(event.timestamp), | ||
| "source_message_id": _normalize_for_hash(event.source_message_id), | ||
| "payload": hash_payload(event.payload), | ||
| } |
| # hash hashes the dict representation. Parse and re-hash for consistency. | ||
| try: | ||
| parsed = loads(block.tool_input) | ||
| if isinstance(parsed, dict): | ||
| payload["tool_input"] = hash_payload(parsed) | ||
| else: | ||
| payload["tool_input"] = hash_payload(block.tool_input) |
`save_via_backend()` accepted five independent parameters (conversation, messages, attachments, content_blocks, provider_events) but trusted `ConversationRecord.content_hash` to represent all of them. A caller could pass changed rows with an unchanged hash and the idempotent skip would silently lose data; action events were also undocumented as derived from messages + content_blocks at write time. - `_compute_hash_from_row_graph()` re-derives the content hash from the storage record graph using the same canonical `_conversation_hash_payload` helper that `pipeline/ids.py:conversation_content_hash()` uses; mirrors `attachment_from_record` and `message_from_record` hydration patterns for timestamp and attachment-name reconstruction. - `_content_block_record_to_hash_payload()` is the analogue of `_content_block_payload()` for the storage record shape. - `save_via_backend()` cross-validates after the `content_unchanged` check: on mismatch it logs a structlog warning and forces a full write so silent data loss cannot follow a stale hash. - The hash boundary is now documented in the module docstring: what is inside (conversation/message/attachment/content_block), what is outside (action events, derived insights, user metadata), and why. Closes #841
`save_via_backend()` accepted five independent parameters (conversation, messages, attachments, content_blocks, provider_events) but trusted `ConversationRecord.content_hash` to represent all of them. A caller could pass changed rows with an unchanged hash and the idempotent skip would silently lose data; action events were also undocumented as derived from messages + content_blocks at write time. - `_compute_hash_from_row_graph()` re-derives the content hash from the storage record graph using the same canonical `_conversation_hash_payload` helper that `pipeline/ids.py:conversation_content_hash()` uses; mirrors `attachment_from_record` and `message_from_record` hydration patterns for timestamp and attachment-name reconstruction. - `_content_block_record_to_hash_payload()` is the analogue of `_content_block_payload()` for the storage record shape. - `save_via_backend()` cross-validates after the `content_unchanged` check: on mismatch it logs a structlog warning and forces a full write so silent data loss cannot follow a stale hash. - The hash boundary is now documented in the module docstring: what is inside (conversation/message/attachment/content_block), what is outside (action events, derived insights, user metadata), and why. Closes #841
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Makes the conversation write path honest about its hash boundary. Adds
_compute_hash_from_row_graph()that re-derives the content hash from storage records, then cross-validates it againstConversationRecord.content_hashinsave_via_backend(). When the row graph diverges from the recorded hash, logs a structlog warning and forces a full write instead of trusting the stale hash for the idempotency skip.Problem
save_via_backend()accepted 5 independent params (conversation, messages, attachments, content_blocks, provider_events) with no cross-validation that the row graph matched the hash. If a caller passed changed rows with an unchanged hash, writes were silently skipped. Action events were not documented as derived/outside the hash boundary.Solution
_compute_hash_from_row_graph(): New function that re-derives the content hash from the storage record graph using the same canonical_conversation_hash_payloadhelper frompipeline/ids.py. Mirrorsattachment_from_record/message_from_recordhydration patterns for timestamp and attachment name reconstruction._content_block_record_to_hash_payload(): New helper forContentBlockRecord→ hash payload conversion, mirrors_content_block_payload()frompipeline/ids.py.save_via_backend(): After thecontent_unchangedcheck, computes the row-graph hash and compares againstConversationRecord.content_hash. On mismatch: logs a structured warning, and ifcontent_unchangedwas True, forcescontent_unchanged = Falseto prevent silent data loss.What was done
_compute_hash_from_row_graph()addedsave_via_backend()with warning + forced-write escalationWhat's the gap
ConversationBuildergenerates UUID-based hashes that don't match SHA-256 row-graph hashes. Tests that exercise the skip path now compute real hashes before saving. This is a test-layer concern only — production path always uses canonical hash viaconversation_to_record()._compute_hash_from_row_graphusessort_key→datetime.fromtimestamp()→.isoformat()for message timestamps, consistent withmessage_from_record()hydration. Edge cases with sub-microsecond precision may not perfectly match the domain hash, but all key mismatch cases (changed messages, changed provider events) are correctly detected.Verification
Closes #841.