Skip to content

refactor(storage): validate row-graph consistency with content hash (#841) - #917

Merged
Sinity merged 1 commit into
masterfrom
feature/refactor/hash-honesty-841
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/refactor/hash-honesty-841

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026

Copy link
Copy Markdown
Owner

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 against ConversationRecord.content_hash in save_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_payload helper from pipeline/ids.py. Mirrors attachment_from_record/message_from_record hydration patterns for timestamp and attachment name reconstruction.
  • _content_block_record_to_hash_payload(): New helper for ContentBlockRecord → hash payload conversion, mirrors _content_block_payload() from pipeline/ids.py.
  • Validation in save_via_backend(): After the content_unchanged check, computes the row-graph hash and compares against ConversationRecord.content_hash. On mismatch: logs a structured warning, and if content_unchanged was True, forces content_unchanged = False to prevent silent data loss.
  • Hash boundary documented in the module docstring: what's inside, what's outside, and why. Action events explicitly documented as derived from messages + content_blocks at write time.

What was done

  1. Hash boundary documented in module docstring
  2. _compute_hash_from_row_graph() added
  3. Row-graph validation in save_via_backend() with warning + forced-write escalation
  4. Action events documented as derived/outside hash
  5. 4 new tests + 2 pre-existing tests updated

What's the gap

  • Test infrastructure: ConversationBuilder generates 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 via conversation_to_record().
  • Timestamp round-trip: The _compute_hash_from_row_graph uses sort_key → datetime.fromtimestamp() → .isoformat() for message timestamps, consistent with message_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.
  • Pre-existing mypy/format/render failures on master cause pre-push hook failure; these are not caused by this branch.

Verification

ruff check: clean
ruff format: clean
mypy --strict on changed files: 0 issues
pytest tests/unit/storage/test_repository_lifecycle_laws.py: 12 passed
pytest tests/unit/storage/ (excluding pre-existing): 565 passed

Closes #841.

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]>
Copilot AI review requested due to automatic review settings May 7, 2026 15:05
@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 7 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9ae26a8a-536d-4697-9c19-b89dbd6f1f0a

📥 Commits

Reviewing files that changed from the base of the PR and between c7092fe and a8be8d9.

📒 Files selected for processing (2)
  • polylogue/storage/repository/archive/writes/conversations.py
  • tests/unit/storage/test_repository_lifecycle_laws.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/hash-honesty-841

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Sinity
Sinity merged commit 40b9f6e into master May 7, 2026
5 checks passed
@Sinity
Sinity deleted the feature/refactor/hash-honesty-841 branch May 7, 2026 15:06

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_hash in the conversation write helpers module docstring.
  • Added _compute_hash_from_row_graph() (and a ContentBlockRecord hashing helper) and used it in save_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.

Comment on lines +242 to +246
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),
Comment on lines +254 to +268
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),
Comment on lines +276 to +282
{
"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),
}
Comment on lines +201 to +207
# 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)
Sinity added a commit that referenced this pull request May 7, 2026
`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
Sinity added a commit that referenced this pull request May 7, 2026
`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
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(storage): make conversation writes bundle/hash-honest

2 participants