Repository navigation
Description
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.pyaccepts separate row lists insave_conversation().polylogue/storage/repository/archive/writes/conversations.pyskips row replacement whenconversation.content_hashmatches the stored hash.polylogue/pipeline/ids.pyincludes provider events in the canonical conversation hash payload.- Domain
Conversationconversion can compute a provider-event-aware hash, but rawConversationRecordcallers 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.pypolylogue/pipeline/services/ingest_batch/polylogue/storage/repository/archive/repository_writes.pypolylogue/storage/repository/archive/writes/polylogue/storage/repository/archive/models.pyor adjacent write-bundle model locationpolylogue/storage/sqlite/schema_bootstrap.pyonly if tests expose schema/write couplingtests/unit/pipeline/tests/unit/storage/
Non-goals
- Do not adopt a full ORM.
- Do not change schema semantics unless the write-boundary fix requires a narrowly-scoped correction.
- Do not re-open the public
polylogue runsurface. - Do not solve the full schema inventory in chore(schema): inventory universal archive semantics vs provider metadata #840.
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 --quickfor type/render/layer checks.- Full
devtools verifybefore PR because this touches the archive write contract.
Activity
fix(storage): persist provider protocol events (#843)
Sinity commentedon May 6, 2026
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.
Sinity commentedon May 6, 2026
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.
Sinity commentedon May 7, 2026
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:Idempotency gate --
save_via_backend()(writes/conversations.py:188) comparesexisting_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:content_blocksparam but messages unchanged → HASH DOES NOT change (because content_blocks hash is computed fromconversation.messages, not from the independentcontent_blocksparam)The
content_blocksparam (line 156) is appended frommessage.content_blocksat line 233, so in current callers they agree -- but the API shape invites divergence.Build this
Do NOT build this
Files to touch
polylogue/storage/repository/archive/writes/conversations.pysave_via_backendto accept a bundle object instead of 5 independent paramspolylogue/pipeline/ids.py_conversation_hash_payloadincludes all semantic fields (currently action_events excluded -- intentional?)polylogue/storage/runtime/archive/records.pytests/unit/storage/test_repository_lifecycle_laws.pyCoordination
title,created_at,updated_at, messages, attachments, and provider_events are hashed. If refactor(schema): graduate universal semantics out of provider_meta #864 promotes fields into the hash boundary, coordinate.Focused tests
Acceptance criteria
save_via_backend()validates row graph consistency with content_hash or bundles args into a validated structuredevtools verify --quickpasses; fulldevtools verifybefore PRStale / ambiguous findings
provider_metaon 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 inconversation_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.
Sinity commentedon May 7, 2026
Implementation scope for #841
What this will do
Add
_compute_hash_from_rows()validation function inconversations.pythat re-derives the content hash from the storage record graph (ConversationRecord + MessageRecord + AttachmentRecord + ProviderEventRecord) using the same canonical_conversation_hash_payloadhelper fromids.py. This validates that the hash on the record matches what the row graph actually contains.Add validation call in
save_via_backend(): Before making the skip/write decision, validate that the row graph hash matchesconversation.content_hash. On mismatch, log a structlog warning. This catches the scenario where a caller passes changed rows with an unchanged hash.Document the hash boundary: Add a clear docstring/comment block in
save_via_backend()documenting:build_action_event_records()Tests:
test_row_graph_hash_consistency— pass changed provider_events with unchanged content_hash, verify validation catches the mismatchtest_action_events_are_derived_from_content— document that action_events are outside the hash and are always rebuilt from content on writetest_hash_match_skip_is_consistent— verify that when the row graph hash matches the stored hash, writes are correctly skipped (content idempotency)Non-goals
Files
polylogue/storage/repository/archive/writes/conversations.py— validation function + doc + warning logtests/unit/storage/test_repository_lifecycle_laws.py— 3 new testsVerification
ruff check polylogue/ tests/mypy --stricton touched filespytest tests/unit/storage/test_repository_lifecycle_laws.py -xvsdevtools verifybefore PRSinity commentedon May 7, 2026
Completion report for #841
What was done
Hash boundary documented in module docstring of
polylogue/storage/repository/archive/writes/conversations.py— lists every field inside/outside the content hash with rationale._compute_hash_from_row_graph()added — 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. Also added_content_block_record_to_hash_payload()for ContentBlockRecord → hash payload conversion.Row-graph validation in
save_via_backend()— after checkingcontent_unchanged, computes the row-graph hash and compares it againstConversationRecord.content_hash. On mismatch:save_via_backend_hash_mismatch) with conversation ID, record hash, row-graph hash, and content_unchanged statuscontent_unchangedwas True (hash matched DB but not row graph), forcescontent_unchanged = Falseto prevent silent data lossAction 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 datatest_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 correctlytest_action_events_are_derived_and_replaced_on_content_change— action events are created on write, skipped on hash match, rebuilt on content changeTests updated (2 pre-existing)
test_repository_resave_existing_conversation_is_idempotent— now uses real computed hash instead of UUID for correct skip-path validationtest_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_graphfunction usessort_key→ ISO datetime round-trip for message timestamps, which is consistent withmessage_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
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)refactor(storage): cross-validate row graph against content hash (#841)
fix(storage): persist provider protocol events (#843)
docs(schema): inventory universal vs provider metadata (#874)
refactor(storage): cross-validate row graph against content hash (#917)
docs(schema): inventory universal vs provider metadata (#874)
refactor(storage): cross-validate row graph against content hash (#917)