Skip to content

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

Closed

Description

@Sinity

Problem

ConversationRepository.save_conversation() accepts a loose tuple of independently supplied storage rows: a ConversationRecord | Conversation, message records, attachment records, content blocks, and provider-event records. The skip path then trusts ConversationRecord.content_hash to represent all of those row sets.

That is only honest when callers used the same materialization/hash pipeline that produced the rows. It is easy for a caller to pass changed rows with an unchanged hash, or a hash that includes provider events without the matching provider-event records. This is exactly the kind of workaround-shaped API boundary that #837 exposed.

The immediate provider-event persistence gap was fixed by #837/#843, but the write API is still too loose for a canonical archive boundary.

Evidence

  • polylogue/storage/repository/archive/repository_writes.py accepts separate row lists in save_conversation().
  • polylogue/storage/repository/archive/writes/conversations.py skips row replacement when conversation.content_hash matches the stored hash.
  • polylogue/pipeline/ids.py includes provider events in the canonical conversation hash payload.
  • Domain Conversation conversion can compute a provider-event-aware hash, but raw ConversationRecord callers can still provide arbitrary hashes and row lists.

Scope

Replace the loose write surface with a typed aggregate or equivalent validated boundary, likely reusing or graduating RecordBundle / prepared bundle concepts.

The fixed design should make it hard to persist a conversation whose hash and row graph disagree.

Likely files:

  • polylogue/pipeline/prepare_enrichment.py
  • polylogue/pipeline/services/ingest_batch/
  • polylogue/storage/repository/archive/repository_writes.py
  • polylogue/storage/repository/archive/writes/
  • polylogue/storage/repository/archive/models.py or adjacent write-bundle model location
  • polylogue/storage/sqlite/schema_bootstrap.py only if tests expose schema/write coupling
  • tests/unit/pipeline/
  • tests/unit/storage/

Non-goals

Acceptance criteria

  • Repository write APIs accept a typed conversation write bundle or validate the full row graph against the supplied content hash.
  • Provider events, messages, content blocks, attachments, and action-event derivation are represented as one coherent write unit.
  • Existing prepare/ingest paths use the same write contract or have an explicit reason not to.
  • Tests cover at least one mismatch case that would previously have skipped row replacement incorrectly.
  • Keep explicit SQL and high-throughput ingest paths; this issue is about write-boundary honesty, not adopting a full ORM.

Verification

  • Focused storage write tests for hash/row mismatch replacement.
  • Focused ingest/materialization tests proving prepared bundles and repository writes agree.
  • devtools verify --quick for type/render/layer checks.
  • Full devtools verify before PR because this touches the archive write contract.

Refs #837 #840 #843 #852.

Activity

  1. added
    type:refactor
    on May 5, 2026
  2. Sinity commented on May 6, 2026

    @Sinity
    OwnerAuthor

    Agent trap note

    Do not solve this by wrapping the existing loose arguments in a cosmetic dataclass while preserving the same independent hash/row-list trust problem.

    The acceptance point is semantic: the write boundary must make it hard or impossible for content hash, messages, content blocks, attachments, provider events, and derived action events to disagree silently.

    Speed-up for implementers: begin with a failing mismatch test that passes changed provider events or rows with an unchanged hash and proves the old skip path would miss replacement. Let that test drive the bundle/validation shape.

  3. Sinity commented on May 6, 2026

    @Sinity
    OwnerAuthor

    Boundary with user mutations

    #862 now tracks shared tag/metadata/delete mutation contracts.

    Keep this issue focused on canonical conversation write-bundle/hash honesty for imported/archive content. User tags and metadata remain user-owned state outside the content hash. If this issue changes repository write primitives that #862 uses, coordinate result/idempotency expectations there, but do not fold user-mutation UX or MCP/CLI delete semantics into the content write-bundle slice.

    Ref #862.

  4. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Reconnaissance Report: #841 write bundle/hash honesty

    Current state (from code audit)

    Hash boundary -- _content_hash_from_metadata_or_domain() (repository_writes.py:47-105) currently hashes:

    • Conversation: title, created_at, updated_at
    • Messages: id, role, text, timestamp, content_blocks (type, text, tool_name, tool_id, hashed tool_input, media_type)
    • Attachments: id, message_id, name, mime_type, size_bytes
    • Provider events: event_index, event_type, timestamp, source_message_id, hashed payload

    Idempotency gate -- save_via_backend() (writes/conversations.py:188) compares existing_hash == conversation.content_hash. If the hash matches, it SKIPS message/attachment/content_block/action_event writes entirely, only replacing provider events.

    The gap -- save_via_backend() accepts independent params: conversation, messages, attachments, content_blocks, provider_events. The hash is computed from the domain Conversation model via _content_hash_from_metadata_or_domain(), but the actual rows written come from independently built record lists. There is no validation that the row graph matches the hash boundary. If a caller passes:

    • Different messages but an unchanged hash → rows NOT replaced (silent drift)
    • Same messages but provider_events change → HASH DOES change (correct, because provider events are in the hash payload)
    • Changed content_blocks via content_blocks param but messages unchanged → HASH DOES NOT change (because content_blocks hash is computed from conversation.messages, not from the independent content_blocks param)

    The content_blocks param (line 156) is appended from message.content_blocks at line 233, so in current callers they agree -- but the API shape invites divergence.

    Build this

    1. Add a cross-validation assertion/check that the row graph (messages + their content_blocks + attachments + provider_events) is consistent with the hash payload. At minimum, a test that proves changed rows with unchanged hash would be caught.
    2. Make the write path refuse to write when hash and row graph diverge (or at minimum warn loudly).
    3. Ensure action_events (also written at line 241) are inside the hash boundary or explicitly documented as derived/outside it. Currently action_events are NOT in the content_hash but are unconditionally replaced on every write regardless of hash match.

    Do NOT build this

    • Do not wrap args in a cosmetic dataclass without enforcing semantic consistency between hash and rows.
    • Do not include user tags/metadata in the content hash (refactor(mutations): centralize tag metadata and delete contracts #862 owns those).
    • Do not change the hash algorithm itself unless needed for the gap fix.
    • Do not fold action_events into the hash unless you also make the idempotency skip conditional on action_event stability -- currently action_events are always replaced.

    Files to touch

    File Change
    polylogue/storage/repository/archive/writes/conversations.py Add hash-row consistency validation; potentially refactor save_via_backend to accept a bundle object instead of 5 independent params
    polylogue/pipeline/ids.py Verify _conversation_hash_payload includes all semantic fields (currently action_events excluded -- intentional?)
    polylogue/storage/runtime/archive/records.py Possibly add WriteBundle/BundleHash model
    tests/unit/storage/test_repository_lifecycle_laws.py Add hash-row consistency test (failing mismatch test as described in agent trap note)

    Coordination

    Focused tests

    # Existing hash boundary tests (check these first)
    pytest tests/unit/storage/test_repository_lifecycle_laws.py -xvs -k "hash" 2>&1
    pytest tests/unit/storage/test_store_ops.py -xvs -k "hash" 2>&1
    
    # Required new test: prove hash mismatch catches changed rows
    pytest tests/unit/storage/ -xvs -k "test_write_bundle_hash_consistency" 2>&1
    
    # Required new test: prove action_events replacement doesn't silently diverge
    pytest tests/unit/storage/ -xvs -k "test_action_event_idempotency" 2>&1

    Acceptance criteria

    • A test passes changed provider_events with unchanged hash and catches the mismatch
    • A test passes changed action_events vs unchanged hash and documents the expected behavior
    • save_via_backend() validates row graph consistency with content_hash or bundles args into a validated structure
    • The hash boundary is explicitly documented: what's inside, what's outside, and why
    • Action events are either included in hash or explicitly documented as derived/always-replaced
    • devtools verify --quick passes; full devtools verify before PR

    Stale / ambiguous findings

    • The issue body says "content hash currently hashes title/timestamps/messages/attachments" -- it also hashes provider_events now (since fix(storage): make provider protocol events first-class archive rows #837). The body text may be slightly stale.
    • provider_meta on conversations is NOT in the content_hash. This is intentional (it includes source which is derived). But the hash is computed from the domain Conversation, while provider_meta is populated separately in conversation_to_record(). If provider_meta ever becomes hash-relevant, the two paths must converge.

    Ambiguity

    The agent trap note says "create a failing mismatch test that passes changed provider events or rows with an unchanged hash." Provider events ARE already in the hash, so the failing test should target: (a) changed action_events vs unchanged hash, or (b) content_blocks passed separately from messages, or (c) a synthetic caller that builds an inconsistent row graph. Clarifying which exact gap to target first would speed implementation.

  5. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Implementation scope for #841

    What this will do

    1. Add _compute_hash_from_rows() validation function in conversations.py that re-derives the content hash from the storage record graph (ConversationRecord + MessageRecord + AttachmentRecord + ProviderEventRecord) using the same canonical _conversation_hash_payload helper from ids.py. This validates that the hash on the record matches what the row graph actually contains.

    2. Add validation call in save_via_backend(): Before making the skip/write decision, validate that the row graph hash matches conversation.content_hash. On mismatch, log a structlog warning. This catches the scenario where a caller passes changed rows with an unchanged hash.

    3. Document the hash boundary: Add a clear docstring/comment block in save_via_backend() documenting:

      • What's inside the content hash: title, timestamps, messages (with content_blocks), attachments, provider_events
      • What's outside: user metadata (tags, summaries), provider_meta, action_events (derived from messages + content_blocks)
      • Why action_events are derived: they are materialized from message content_blocks by build_action_event_records()
    4. Tests:

      • test_row_graph_hash_consistency — pass changed provider_events with unchanged content_hash, verify validation catches the mismatch
      • test_action_events_are_derived_from_content — document that action_events are outside the hash and are always rebuilt from content on write
      • test_hash_match_skip_is_consistent — verify that when the row graph hash matches the stored hash, writes are correctly skipped (content idempotency)

    Non-goals

    • Not changing what fields go into the hash
    • Not redesigning the write path — keeping the same API shape
    • Not including user tags/metadata in content hash (refactor(mutations): centralize tag metadata and delete contracts #862 owns those)
    • Not folding action_events into the hash (they are derived, not stored)
    • Not wrapping args in a cosmetic dataclass (the acceptance point is semantic validation, not type wrapping)

    Files

    • polylogue/storage/repository/archive/writes/conversations.py — validation function + doc + warning log
    • tests/unit/storage/test_repository_lifecycle_laws.py — 3 new tests

    Verification

    • ruff check polylogue/ tests/
    • mypy --strict on touched files
    • pytest tests/unit/storage/test_repository_lifecycle_laws.py -xvs
    • devtools verify before PR
  6. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Completion report for #841

    What was done

    1. Hash boundary documented in module docstring of polylogue/storage/repository/archive/writes/conversations.py — lists every field inside/outside the content hash with rationale.

    2. _compute_hash_from_row_graph() added — 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. Also added _content_block_record_to_hash_payload() for ContentBlockRecord → hash payload conversion.

    3. Row-graph validation in save_via_backend() — after checking content_unchanged, computes the row-graph hash and compares it against ConversationRecord.content_hash. On mismatch:

      • Logs a structured warning (save_via_backend_hash_mismatch) with conversation ID, record hash, row-graph hash, and content_unchanged status
      • If content_unchanged was True (hash matched DB but not row graph), forces content_unchanged = False to prevent silent data loss
    4. Action events documented as derived — explicitly documented as outside the content hash, rebuilt from messages + content_blocks at write time via build_action_event_records().

    Tests added (4 new)

    • test_compute_hash_from_row_graph_matches_domain_hash — proves the row-graph hash equals the canonical domain hash for the same data
    • test_hash_consistency_forces_write_on_stale_hash — changed messages with stale content_hash force a full write (the core gap case from the recon)
    • test_hash_match_skips_writes_when_row_graph_agrees — when both stored hash and row-graph hash agree, idempotency skip works correctly
    • test_action_events_are_derived_and_replaced_on_content_change — action events are created on write, skipped on hash match, rebuilt on content change

    Tests updated (2 pre-existing)

    • test_repository_resave_existing_conversation_is_idempotent — now uses real computed hash instead of UUID for correct skip-path validation
    • test_repository_record_resave_replaces_explicit_provider_events_on_hash_match — now uses real computed hash; accepts that changed provider events force a full write (consistent with the new validation)

    Gap assessment

    • Honest gap: The _compute_hash_from_row_graph function uses sort_key → ISO datetime round-trip for message timestamps, which is consistent with message_from_record() hydration but may not perfectly match the domain hash for edge cases (e.g., timestamps with sub-microsecond precision). This is acceptable for a validation check — the key mismatch cases (changed messages, changed provider events) are correctly detected.

    • ConversationBuilder UUID hashes: Test infrastructure uses 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, not a production concern — the production path always uses the canonical hash via conversation_to_record().

    • Pre-existing test failures in broader suite: 15 tests in tests/unit/storage/ fail independently of these changes (FTS5 index update, Gemini drive attachments, embedding stats). Not caused by this PR.

    Verification

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

    Files changed

    • polylogue/storage/repository/archive/writes/conversations.py — +~100 lines (docstring, 2 new functions, validation in save_via_backend)
    • tests/unit/storage/test_repository_lifecycle_laws.py — +~185 lines (4 new tests, 2 test updates)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:storagetype:refactor

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions