Repository navigation
fix(storage): persist provider protocol events (#843) - #843
Conversation
Problem: Provider protocol artifacts such as Claude/Codex compactions were parser-level semantics but not durable archive rows. Some paths still treated conversation provider_meta as the semantic source, and the loose repository save path could not persist hydrated provider events. What changed: Add provider-event domain/record/schema/query surfaces, bump the archive schema to v7 with backfill from provider_meta.context_compactions, and persist provider events through batch ingest, prepare/save, repository hydration, and session insight rebuilds. Claude/Codex parsers now leave compactions out of provider_meta, Claude index enrichment preserves semantic fields, and per-message tool/thinking flags are computed from content blocks for action-event parity. Also fix schema validation empty-array normalization to follow the selected JSON schema, so structural arrays such as ChatGPT mapping children are not rewritten to null during strict validation. Verification: direnv exec /realm/project/polylogue uv run pytest -n 0 tests/unit/storage tests/unit/pipeline tests/unit/core/test_schema_validation.py tests/unit/sources/test_compaction.py tests/unit/sources/test_source_laws.py tests/unit/sources/test_parsers_codex.py tests/unit/sources/test_parsers_base.py tests/unit/cli/test_insights.py -q # 1288 passed Verification: direnv exec /realm/project/polylogue uv run ruff check polylogue tests/unit/storage/test_provider_events_schema.py tests/unit/storage/test_repository_lifecycle_laws.py tests/unit/pipeline/test_prepare_records.py tests/unit/pipeline/test_prepare_runtime.py tests/unit/pipeline/test_ingest_batch.py tests/unit/pipeline/test_run_sources.py tests/unit/core/test_schema_validation.py tests/unit/sources/test_compaction.py tests/unit/sources/test_source_laws.py tests/unit/cli/test_insights.py tests/unit/storage/test_session_insight_refresh.py tests/unit/sources/test_parsers_base.py tests/unit/storage/test_backend.py # All checks passed Closes #837. Refs #840 #841 #842
|
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 (16)
📝 WalkthroughWalkthroughThis PR introduces provider-events as first-class archive rows, replacing reliance on ChangesProvider Events End-to-End Implementation
Sequence DiagramsequenceDiagram
actor Parser
participant Materialization Pipeline
participant Prepare & Enrichment
participant Ingest Worker
participant Ingest Batch
participant Storage Layer
participant Session Insights
Parser->>Materialization Pipeline: ParsedConversation with provider_events
Materialization Pipeline->>Materialization Pipeline: Materialize provider_events into<br/>MaterializedProviderEvent list
Materialization Pipeline->>Prepare & Enrichment: MaterializedConversation with<br/>provider_events field
Prepare & Enrichment->>Prepare & Enrichment: Map provider_events to<br/>ProviderEventRecord with ID,<br/>timestamp mapping, raw_id
Prepare & Enrichment->>Ingest Worker: RecordBundle with<br/>provider_events list
Ingest Worker->>Ingest Worker: Transform to ProviderEventTuple<br/>(serialize payload, normalize<br/>timestamp, attach version)
Ingest Worker->>Ingest Batch: ConversationData with<br/>provider_event_tuples
Ingest Batch->>Ingest Batch: Detect content change,<br/>skip or insert provider_events
Ingest Batch->>Storage Layer: Execute<br/>SQL_PROVIDER_EVENT_INSERT
Storage Layer->>Storage Layer: Persist provider_events rows<br/>with event_id, conversation_id,<br/>event_type, payload_json
Storage Layer->>Session Insights: Fetch provider_events for<br/>batch of conversations
Session Insights->>Session Insights: Count provider_events with<br/>event_type=="compaction"<br/>(replaces context_compactions)
Session Insights->>Session Insights: Build session profile with<br/>compaction_count from<br/>provider_events, not provider_meta
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly Related Issues
Possibly Related PRs
Suggested Labels
Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2150e96980
ℹ️ 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
Promotes provider protocol artifacts into first-class archive rows so provider events survive ingest, storage, hydration, and session-insight rebuilds instead of being hidden in provider_meta.
Changes:
- Adds a new archive/domain/storage path for
provider_events, including schema v7 DDL, queries, hydration, IDs, and write/read plumbing. - Updates Claude/Codex parsing, materialization, prepare/ingest, and session enrichment to emit/preserve provider events and stop duplicating compactions into
provider_meta. - Expands regression coverage for schema migration/backfill, repository round-trips, session insight compaction counting, and related runtime helpers.
Reviewed changes
Copilot reviewed 53 out of 53 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/unit/storage/test_session_insight_refresh.py | Adds async session-insight coverage for provider-event compaction counting. |
| tests/unit/storage/test_repository_lifecycle_laws.py | Verifies repository round-trip behavior for hydrated provider events. |
| tests/unit/storage/test_provider_events_schema.py | Covers v6→v7 schema migration/backfill from legacy compaction metadata. |
| tests/unit/storage/test_backend.py | Updates schema-extension expectations for the new table. |
| tests/unit/sources/test_parsers_base.py | Adjusts parser contract tests from metadata compactions to provider events. |
| tests/unit/sources/test_compaction.py | Reworks compaction tests around first-class provider events and session profiles. |
| tests/unit/sources/test_assembly.py | Verifies Claude index enrichment preserves provider events and branch semantics. |
| tests/unit/pipeline/test_prepare_runtime.py | Checks prepare save-bundle plumbing now passes provider-event records. |
| tests/unit/pipeline/test_prepare_records.py | Adds prepare-records persistence coverage for provider events. |
| tests/unit/pipeline/test_ingest_batch.py | Updates ingest-batch monkeypatching to the package split/import path. |
| tests/unit/core/test_schema_validation.py | Adds validator coverage for schema-aware empty-array normalization. |
| tests/unit/cli/test_insights.py | Rebuild insight test now seeds provider events instead of provider_meta compactions. |
| polylogue/types.py | Introduces ProviderEventId. |
| polylogue/storage/sqlite/schema.py | Wires schema runtime to recognize v7 upgrades. |
| polylogue/storage/sqlite/schema_ddl.py | Bumps schema version to 7 and includes provider-event DDL. |
| polylogue/storage/sqlite/schema_ddl_provider_events.py | Defines the new provider_events table and indexes. |
| polylogue/storage/sqlite/schema_bootstrap.py | Adds v6→v7 migration/backfill and related bootstrap logic. |
| polylogue/storage/sqlite/query_store_archive.py | Exposes provider-event batch/single read helpers. |
| polylogue/storage/sqlite/queries/provider_events.py | Implements provider-event read/replace query helpers. |
| polylogue/storage/sqlite/queries/mappers.py | Re-exports provider-event row mapper. |
| polylogue/storage/sqlite/queries/mappers_archive.py | Maps provider-event rows into runtime records. |
| polylogue/storage/sqlite/queries/init.py | Registers provider-event query module exports. |
| polylogue/storage/sqlite/async_sqlite_archive.py | Adds backend archive methods for provider-event retrieval. |
| polylogue/storage/runtime/store_constants.py | Adds provider-event materializer version constant. |
| polylogue/storage/runtime/archive/records.py | Adds ProviderEventRecord. |
| polylogue/storage/runtime/init.py | Re-exports provider-event runtime types/constants. |
| polylogue/storage/repository/archive/writes/conversations.py | Persists provider events during repository writes and includes them in hash calculation. |
| polylogue/storage/repository/archive/repository_writes.py | Extends repository save API to accept/derive provider-event records. |
| polylogue/storage/repository/archive/conversations.py | Hydrates provider events on repository reads. |
| polylogue/storage/insights/session/rebuild.py | Rebuild path now loads provider events and hydrates them into conversations. |
| polylogue/storage/hydrators.py | Hydrates provider-event domain models and attaches them to conversations. |
| polylogue/sources/parsers/codex.py | Stops duplicating compactions into provider metadata; emits provider events only. |
| polylogue/sources/parsers/claude/index.py | Uses model_copy() so enrichment preserves semantic fields like provider events. |
| polylogue/sources/parsers/claude/code_parser.py | Removes compaction duplication from Claude provider metadata. |
| polylogue/schemas/validator.py | Makes empty-array normalization schema-aware instead of global. |
| polylogue/pipeline/services/ingest_worker.py | Materializes provider-event tuples for sync ingest writes. |
| polylogue/pipeline/services/ingest_batch/_models.py | Tracks provider-event write counters in ingest summaries. |
| polylogue/pipeline/services/ingest_batch/_core.py | Writes provider-event rows in sync batch ingest and counts them. |
| polylogue/pipeline/services/ingest_batch/init.py | Re-exports write pragma constants for test/runtime parity. |
| polylogue/pipeline/prepare.py | Passes provider-event records through prepare save flow. |
| polylogue/pipeline/prepare_transform.py | Builds provider-event records from materialized conversations. |
| polylogue/pipeline/prepare_models.py | Extends prepare bundle/save result models with provider events. |
| polylogue/pipeline/prepare_enrichment.py | Rewrites provider-event IDs/message links/raw IDs during DB-aware enrichment. |
| polylogue/pipeline/materialization_runtime.py | Materializes provider events and excludes legacy compaction metadata duplication. |
| polylogue/pipeline/ids.py | Adds provider-event ID generation and hashes provider events into conversation content hashes. |
| polylogue/core/common.py | Adds canonical SQL insert template for provider events. |
| polylogue/archive/session/runtime.py | Counts compactions from hydrated provider events instead of provider_meta. |
| polylogue/archive/provider/events.py | Introduces provider-event domain model. |
| polylogue/archive/provider/init.py | Exports provider-event archive semantics. |
| polylogue/archive/models.py | Re-exports ProviderEvent from top-level archive models. |
| polylogue/archive/conversation/models.py | Adds provider events to the conversation domain model. |
| docs/topology-status.md | Updates generated topology counts/status for new files. |
| docs/plans/topology-target.yaml | Registers new/changed files in topology ownership metadata. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| self, | ||
| conversation: Conversation | ConversationRecord, | ||
| messages: builtins.list[MessageRecord], | ||
| attachments: builtins.list[AttachmentRecord], | ||
| content_blocks: builtins.list[ContentBlockRecord] | None = None, | ||
| provider_events: builtins.list[ProviderEventRecord] | None = None, |
| attachments = await get_attachments_batch(conn, list(conversation_ids)) | ||
| provider_events = await get_provider_events_batch(conn, list(conversation_ids)) | ||
| return SessionInsightArchiveBatch( | ||
| conversations=conversations, | ||
| messages=messages, | ||
| attachments_by_conversation=attachments, | ||
| provider_events_by_conversation=provider_events, |
| conversations=conversations, | ||
| messages=messages, | ||
| attachments_by_conversation=sync_attachment_batch(conn, conversation_ids), | ||
| provider_events_by_conversation=sync_provider_events_batch(conn, conversation_ids), |
There was a problem hiding this comment.
Actionable comments posted: 12
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
polylogue/storage/repository/archive/repository_writes.py (1)
58-64:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPreserve
Nonefor omitted provider-event rows.Line 63 collapses “not provided” into “authoritatively empty”. For
ConversationRecordcallers that have not been updated to materialize provider events, that can turn a normal resave into a provider-event wipe if the backend treats this list as the full replacement set.Suggested fix
return await self._save_via_backend( conv_record, messages, attachments, content_blocks or [], - provider_events or [], + provider_events, )Please verify the downstream contract before merging: the safe outcome is either
save_via_backend(..., provider_events=None)preserves existing rows, or every caller already passes provider_events explicitly.#!/bin/bash set -euo pipefail echo "=== Downstream provider_events handling ===" rg -n -C3 --type=py '\bdef\s+save_via_backend\b|provider_events\b|DELETE FROM provider_events|replace_provider_events|save_provider_events' \ polylogue/storage/repository/archive/writes \ polylogue/storage/sqlite echo echo "=== save_conversation call sites to inspect for omitted provider_events ===" rg -n -C2 --type=py '\.save_conversation\s*\(' polylogue tests🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@polylogue/storage/repository/archive/repository_writes.py` around lines 58 - 64, The call currently collapses omitted provider_events into an empty list by using "provider_events or []", which can cause unintended deletion of provider-event rows; change the invocation in repository_writes.py so it forwards provider_events as-is (i.e., pass provider_events directly or pass None when omitted) to self._save_via_backend (the _save_via_backend(...) call and its provider_events parameter) so that a None input is preserved and backends that interpret None as "leave unchanged" will not wipe rows.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@polylogue/core/common.py`:
- Around line 125-131: Add a one-line docstring immediately above the
_PROVIDER_EVENT_INSERT_SQL constant stating that this is a plain INSERT with no
ON CONFLICT handling and that callers must delete or otherwise ensure no
existing rows for the same (conversation_id, event_index) (the UNIQUE
constraint) before using this template to avoid IntegrityError; reference
_PROVIDER_EVENT_INSERT_SQL and the UNIQUE (conversation_id, event_index)
constraint in the docstring so future maintainers know the required
precondition.
In `@polylogue/pipeline/ids.py`:
- Around line 160-161: The provider_event_id function currently uses
f"{event_index:06d}" which will expand past 999,999 and break lexical ordering;
update provider_event_id (and the ProviderEventId generation) to use a fixed,
sufficiently large zero-pad width (e.g., increase to 9 or 12 digits via a
constant like EVENT_INDEX_WIDTH and format with that width) so string ordering
matches numeric ordering for all realistic event_index values, or alternatively
stop relying on string padding and return/emit a separate numeric sort_key for
ordering; apply the chosen approach consistently where ProviderEventId is
produced/consumed.
In `@polylogue/pipeline/materialization_runtime.py`:
- Around line 164-175: The MaterializedProviderEvent rows are not preserving the
source message linkage: while iterating convo.provider_events in the
materialization loop (the block that creates MaterializedProviderEvent with
provider_event_id(...)), set the MaterializedProviderEvent.source_message_id by
looking up the parsed event's source message id through the message_id_map
(e.g., message_id_map.get(event.source_message_id) or equivalent) so the
archived rows carry the correct message linkage; update the construction of
MaterializedProviderEvent to include source_message_id populated from
message_id_map rather than leaving it at the default.
In `@polylogue/schemas/validator.py`:
- Around line 122-132: _schema_for_property incorrectly re-resolves the parent
schema against the child value by calling _schema_branch_for_value(schema,
value); remove that call so the function uses the provided parent schema as-is
(the parent is resolved by the caller in _normalize_empty_arrays), and instead
if you need branch resolution apply _schema_branch_for_value to the found
property schema (properties[key]) with the child value after the lookup; apply
the same simplification to _schema_for_items which has the same shape.
In `@polylogue/storage/repository/archive/writes/conversations.py`:
- Around line 94-101: The provider-event content hash used in
save_via_backend()/replace_provider_events() omits the event.source_message_id,
so relinked events appear unchanged; update the provider_events hashing logic
(the list comprehension that builds provider_events using _normalize_for_hash
and hash_payload) to incorporate event.source_message_id (normalized like other
fields, e.g., _normalize_for_hash(event.source_message_id or None)) into the
hash input so that changes to source_message_id cause the hash to differ and
trigger replace_provider_events().
In `@polylogue/storage/runtime/archive/records.py`:
- Around line 187-210: ProviderEventRecord hydration fails for legacy rows with
provider_name == "" because non_empty_string validator rejects empty strings;
update the read path in mappers_archive.py where provider_name is set (the
expression provider_name=_row_text(row, "provider_name") or "") to sanitize
empty values into a safe non-empty sentinel (e.g., replace "" with "unknown" or
None-then-map-to-"unknown") before calling ProviderEventRecord, or alternatively
backfill the DB; ensure the sanitized value satisfies
ProviderEventRecord.non_empty_string so model instantiation no longer raises.
In `@polylogue/storage/sqlite/schema_bootstrap.py`:
- Around line 814-829: Collapse the repeated SCHEMA_VERSION checks by adding a
helper _chain_extra_statements_since(snapshot, since_version: int) -> tuple[str,
...] that returns the cumulative DDL statements for versions (since_version+1)
.. SCHEMA_VERSION (e.g. importing and _split_ddl_into_statements for
SOURCE_FILE_CURSOR_DDL, TAGS_M2M_DDL, BLOB_LEASE_DDL, IDENTITY_DDL, and
including build_v6_to_v7_upgrade_plan(snapshot).statements when appropriate),
then replace the repeated ladders in build_v2_to_current_upgrade_plan and each
branch of decide_schema_bootstrap (the v3/v4/v5 call sites) with a single call
to _chain_extra_statements_since(snapshot, <starting_version>) and append its
result to the existing statements tuple.
In `@tests/unit/cli/test_insights.py`:
- Around line 667-692: Replace the hardcoded materializer version literal in the
provider_events INSERT with the runtime constant to avoid drift: import the
project-wide MATERIALIZER_VERSION (or the specific constant used at runtime,
e.g. MATERIALIZER_VERSION from the materializer/module that defines it) at the
top of the test file and change the final tuple element in the INSERT (currently
`1`) to MATERIALIZER_VERSION so the fixture always uses the single
source-of-truth; leave the rest of the INSERT and the payload_json json.dumps
call unchanged.
In `@tests/unit/core/test_schema_validation.py`:
- Around line 186-202: The test currently only asserts result.is_valid; enhance
it to assert the normalized payload so behavior is pinned down: after calling
SchemaValidator.validate (use the existing variable result from validate),
inspect the normalized output (e.g., result.value or the structure returned by
validate) and assert that "children" remains an empty list ([]) while
"legacy_null" has been normalized to None (null); reference SchemaValidator and
its _normalize_empty_arrays behavior by name so the test verifies the concrete
normalization outcome rather than only validity.
In `@tests/unit/storage/test_provider_events_schema.py`:
- Around line 12-113: Add test coverage for multiple compactions and the
empty-after-cleanup branch by extending
test_ensure_schema_upgrades_v6_provider_meta_compactions_to_provider_events:
insert a second conversation row for the same conversation_id with a later
compaction entry (so the migration uses printf('%06d', CAST(je.key AS INTEGER))
and creates event_index 0 and 1) and insert another conversation where
provider_meta only contains context_compactions (so the SQL in
_V6_TO_V7_PROVIDER_META_CLEANUP_SQL that does WHEN json_remove(...) IN
('{}','null') THEN NULL is exercised); run _ensure_schema and assert both events
are created in provider_events with sequential event_index values and that
provider_meta becomes NULL for the single-key case while other keys remain for
the multi-key case.
In `@tests/unit/storage/test_repository_lifecycle_laws.py`:
- Around line 240-256: Replace the hardcoded materializer version literal used
when inserting into provider_events with the canonical constant to keep test
seed aligned with production; specifically, import and use
PROVIDER_EVENT_MATERIALIZER_VERSION instead of the literal 1 in the VALUES tuple
for the INSERT that uses conv_record (the statement inserting event_id,
conversation_id, provider_name, ..., materializer_version) so the test uses the
same symbol as production.
In `@tests/unit/storage/test_session_insight_refresh.py`:
- Around line 119-127: The test currently asserts on a substring of the JSON
text from session_profiles.evidence_payload_json which is fragile; replace that
with parsing the JSON and asserting the typed value. After retrieving row via
open_connection(db_path) and fetchone, keep the assert row is not None, then
json.loads(row["evidence_payload_json"]) and assert parsed["compaction_count"]
== 1; add an import for the json module if missing so the test fails with a
clear typed assertion instead of a brittle substring check.
---
Outside diff comments:
In `@polylogue/storage/repository/archive/repository_writes.py`:
- Around line 58-64: The call currently collapses omitted provider_events into
an empty list by using "provider_events or []", which can cause unintended
deletion of provider-event rows; change the invocation in repository_writes.py
so it forwards provider_events as-is (i.e., pass provider_events directly or
pass None when omitted) to self._save_via_backend (the _save_via_backend(...)
call and its provider_events parameter) so that a None input is preserved and
backends that interpret None as "leave unchanged" will not wipe rows.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 97b84a1f-4390-4e18-a8aa-4d867e9e0b3a
📒 Files selected for processing (53)
docs/plans/topology-target.yamldocs/topology-status.mdpolylogue/archive/conversation/models.pypolylogue/archive/models.pypolylogue/archive/provider/__init__.pypolylogue/archive/provider/events.pypolylogue/archive/session/runtime.pypolylogue/core/common.pypolylogue/pipeline/ids.pypolylogue/pipeline/materialization_runtime.pypolylogue/pipeline/prepare.pypolylogue/pipeline/prepare_enrichment.pypolylogue/pipeline/prepare_models.pypolylogue/pipeline/prepare_transform.pypolylogue/pipeline/services/ingest_batch/__init__.pypolylogue/pipeline/services/ingest_batch/_core.pypolylogue/pipeline/services/ingest_batch/_models.pypolylogue/pipeline/services/ingest_worker.pypolylogue/schemas/validator.pypolylogue/sources/parsers/claude/code_parser.pypolylogue/sources/parsers/claude/index.pypolylogue/sources/parsers/codex.pypolylogue/storage/hydrators.pypolylogue/storage/insights/session/rebuild.pypolylogue/storage/repository/archive/conversations.pypolylogue/storage/repository/archive/repository_writes.pypolylogue/storage/repository/archive/writes/conversations.pypolylogue/storage/runtime/__init__.pypolylogue/storage/runtime/archive/records.pypolylogue/storage/runtime/store_constants.pypolylogue/storage/sqlite/async_sqlite_archive.pypolylogue/storage/sqlite/queries/__init__.pypolylogue/storage/sqlite/queries/mappers.pypolylogue/storage/sqlite/queries/mappers_archive.pypolylogue/storage/sqlite/queries/provider_events.pypolylogue/storage/sqlite/query_store_archive.pypolylogue/storage/sqlite/schema.pypolylogue/storage/sqlite/schema_bootstrap.pypolylogue/storage/sqlite/schema_ddl.pypolylogue/storage/sqlite/schema_ddl_provider_events.pypolylogue/types.pytests/unit/cli/test_insights.pytests/unit/core/test_schema_validation.pytests/unit/pipeline/test_ingest_batch.pytests/unit/pipeline/test_prepare_records.pytests/unit/pipeline/test_prepare_runtime.pytests/unit/sources/test_assembly.pytests/unit/sources/test_compaction.pytests/unit/sources/test_parsers_base.pytests/unit/storage/test_backend.pytests/unit/storage/test_provider_events_schema.pytests/unit/storage/test_repository_lifecycle_laws.pytests/unit/storage/test_session_insight_refresh.py
💤 Files with no reviewable changes (1)
- polylogue/sources/parsers/claude/code_parser.py
| _PROVIDER_EVENT_INSERT_SQL = """ | ||
| INSERT INTO provider_events ( | ||
| event_id, conversation_id, provider_name, event_index, event_type, | ||
| timestamp, sort_key, payload_json, source_message_id, raw_id, | ||
| materializer_version | ||
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | ||
| """ |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | 💤 Low value
LGTM — column order matches DDL; note the lack of conflict handling.
11 placeholders match the 11-column DDL exactly. Unlike the other upserts in this file, this is a plain INSERT with no ON CONFLICT clause, so callers must DELETE FROM provider_events WHERE conversation_id = ? (or otherwise guarantee absence) before re-materializing — otherwise the UNIQUE (conversation_id, event_index) constraint will raise IntegrityError. Worth a one-line docstring above this template documenting that contract so downstream maintainers don't introduce a partial-replace path that breaks.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@polylogue/core/common.py` around lines 125 - 131, Add a one-line docstring
immediately above the _PROVIDER_EVENT_INSERT_SQL constant stating that this is a
plain INSERT with no ON CONFLICT handling and that callers must delete or
otherwise ensure no existing rows for the same (conversation_id, event_index)
(the UNIQUE constraint) before using this template to avoid IntegrityError;
reference _PROVIDER_EVENT_INSERT_SQL and the UNIQUE (conversation_id,
event_index) constraint in the docstring so future maintainers know the required
precondition.
| def provider_event_id(conversation_id: ConversationId, event_index: int) -> ProviderEventId: | ||
| return ProviderEventId(f"{conversation_id}:provider-event:{event_index:06d}") |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | 💤 Low value
provider_event_id zero-padding only stable up to 999,999 events.
f"{event_index:06d}" does not truncate — values ≥ 1,000,000 simply widen the field, breaking lexical ordering of IDs within a conversation (e.g. …provider-event:000999 < …provider-event:001000 but …provider-event:999999 > …provider-event:1000000). Not a uniqueness risk, but if any caller relies on string-ordered IDs as a proxy for event order, it will silently misorder once a conversation crosses the threshold. Bumping to a wider pad (e.g. :09d) or relying solely on event_index/sort_key for ordering would be safer.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@polylogue/pipeline/ids.py` around lines 160 - 161, The provider_event_id
function currently uses f"{event_index:06d}" which will expand past 999,999 and
break lexical ordering; update provider_event_id (and the ProviderEventId
generation) to use a fixed, sufficiently large zero-pad width (e.g., increase to
9 or 12 digits via a constant like EVENT_INDEX_WIDTH and format with that width)
so string ordering matches numeric ordering for all realistic event_index
values, or alternatively stop relying on string padding and return/emit a
separate numeric sort_key for ordering; apply the chosen approach consistently
where ProviderEventId is produced/consumed.
| conn.execute( | ||
| """ | ||
| INSERT INTO provider_events ( | ||
| event_id, | ||
| conversation_id, | ||
| provider_name, | ||
| event_index, | ||
| event_type, | ||
| timestamp, | ||
| sort_key, | ||
| payload_json, | ||
| materializer_version | ||
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) | ||
| """, | ||
| ( | ||
| "conv-heavy:provider-event:000000", | ||
| "conv-heavy", | ||
| "codex", | ||
| 0, | ||
| "compaction", | ||
| "2026-03-01T10:04:00+00:00", | ||
| None, | ||
| json.dumps({"summary": "Earlier context collapsed."}), | ||
| 1, | ||
| ), | ||
| ) |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
Avoid hardcoding provider-event materializer version in fixture SQL.
At Line 690, using literal 1 can drift from runtime constants and create avoidable test churn when versions bump.
Proposed patch
@@
from polylogue.storage.runtime.store_constants import SESSION_INSIGHT_MATERIALIZER_VERSION
+from polylogue.storage.runtime.store_constants import PROVIDER_EVENT_MATERIALIZER_VERSION
@@
- 1,
+ PROVIDER_EVENT_MATERIALIZER_VERSION,
),
)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| conn.execute( | |
| """ | |
| INSERT INTO provider_events ( | |
| event_id, | |
| conversation_id, | |
| provider_name, | |
| event_index, | |
| event_type, | |
| timestamp, | |
| sort_key, | |
| payload_json, | |
| materializer_version | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| """, | |
| ( | |
| "conv-heavy:provider-event:000000", | |
| "conv-heavy", | |
| "codex", | |
| 0, | |
| "compaction", | |
| "2026-03-01T10:04:00+00:00", | |
| None, | |
| json.dumps({"summary": "Earlier context collapsed."}), | |
| 1, | |
| ), | |
| ) | |
| conn.execute( | |
| """ | |
| INSERT INTO provider_events ( | |
| event_id, | |
| conversation_id, | |
| provider_name, | |
| event_index, | |
| event_type, | |
| timestamp, | |
| sort_key, | |
| payload_json, | |
| materializer_version | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) | |
| """, | |
| ( | |
| "conv-heavy:provider-event:000000", | |
| "conv-heavy", | |
| "codex", | |
| 0, | |
| "compaction", | |
| "2026-03-01T10:04:00+00:00", | |
| None, | |
| json.dumps({"summary": "Earlier context collapsed."}), | |
| PROVIDER_EVENT_MATERIALIZER_VERSION, | |
| ), | |
| ) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/cli/test_insights.py` around lines 667 - 692, Replace the
hardcoded materializer version literal in the provider_events INSERT with the
runtime constant to avoid drift: import the project-wide MATERIALIZER_VERSION
(or the specific constant used at runtime, e.g. MATERIALIZER_VERSION from the
materializer/module that defines it) at the top of the test file and change the
final tuple element in the INSERT (currently `1`) to MATERIALIZER_VERSION so the
fixture always uses the single source-of-truth; leave the rest of the INSERT and
the payload_json json.dumps call unchanged.
| def test_ensure_schema_upgrades_v6_provider_meta_compactions_to_provider_events(tmp_path: Path) -> None: | ||
| db_path = tmp_path / "v6-provider-events.db" | ||
| conn = sqlite3.connect(db_path) | ||
| conn.row_factory = sqlite3.Row | ||
| conn.executescript( | ||
| """ | ||
| CREATE TABLE raw_conversations ( | ||
| raw_id TEXT PRIMARY KEY, | ||
| provider_name TEXT NOT NULL, | ||
| payload_provider TEXT, | ||
| source_name TEXT, | ||
| source_path TEXT NOT NULL, | ||
| source_index INTEGER, | ||
| blob_size INTEGER NOT NULL, | ||
| acquired_at TEXT NOT NULL | ||
| ); | ||
| CREATE TABLE conversations ( | ||
| conversation_id TEXT PRIMARY KEY, | ||
| provider_name TEXT NOT NULL, | ||
| provider_conversation_id TEXT NOT NULL, | ||
| title TEXT, | ||
| created_at TEXT, | ||
| updated_at TEXT, | ||
| sort_key REAL, | ||
| content_hash TEXT NOT NULL DEFAULT '', | ||
| provider_meta TEXT, | ||
| metadata TEXT DEFAULT '{}', | ||
| source_name TEXT GENERATED ALWAYS AS (json_extract(provider_meta, '$.source')) STORED, | ||
| version INTEGER NOT NULL, | ||
| raw_id TEXT REFERENCES raw_conversations(raw_id) ON DELETE SET NULL | ||
| ); | ||
| INSERT INTO raw_conversations ( | ||
| raw_id, | ||
| provider_name, | ||
| source_name, | ||
| source_path, | ||
| blob_size, | ||
| acquired_at | ||
| ) VALUES ( | ||
| 'raw-1', | ||
| 'codex', | ||
| 'codex', | ||
| '/tmp/session.jsonl', | ||
| 10, | ||
| '2026-04-01T10:00:00+00:00' | ||
| ); | ||
| INSERT INTO conversations ( | ||
| conversation_id, | ||
| provider_name, | ||
| provider_conversation_id, | ||
| title, | ||
| content_hash, | ||
| provider_meta, | ||
| metadata, | ||
| version, | ||
| raw_id | ||
| ) VALUES ( | ||
| 'codex:session-1', | ||
| 'codex', | ||
| 'session-1', | ||
| 'Session', | ||
| 'hash-1', | ||
| '{"source":"codex","context_compactions":[{"summary":"Earlier context","timestamp":"2026-04-01T10:05:00+00:00"}],"git":{"branch":"master"}}', | ||
| '{}', | ||
| 1, | ||
| 'raw-1' | ||
| ); | ||
| PRAGMA user_version = 6; | ||
| """ | ||
| ) | ||
| conn.commit() | ||
|
|
||
| _ensure_schema(conn) | ||
|
|
||
| assert conn.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION | ||
| row = conn.execute( | ||
| """ | ||
| SELECT event_id, conversation_id, provider_name, event_index, event_type, | ||
| timestamp, payload_json, raw_id, materializer_version | ||
| FROM provider_events | ||
| WHERE conversation_id = ? | ||
| """, | ||
| ("codex:session-1",), | ||
| ).fetchone() | ||
| assert row is not None | ||
| assert row["event_id"] == "codex:session-1:provider-event:000000" | ||
| assert row["provider_name"] == "codex" | ||
| assert row["event_index"] == 0 | ||
| assert row["event_type"] == "compaction" | ||
| assert row["timestamp"] == "2026-04-01T10:05:00+00:00" | ||
| assert row["raw_id"] == "raw-1" | ||
| assert row["materializer_version"] == 1 | ||
| assert json.loads(row["payload_json"])["summary"] == "Earlier context" | ||
|
|
||
| provider_meta = conn.execute( | ||
| "SELECT provider_meta FROM conversations WHERE conversation_id = ?", | ||
| ("codex:session-1",), | ||
| ).fetchone()[0] | ||
| assert "context_compactions" not in provider_meta | ||
| assert '"source":"codex"' in provider_meta.replace(" ", "") | ||
| assert '"git":{"branch":"master"}' in provider_meta.replace(" ", "") | ||
| conn.close() |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
Consider extending coverage to multi-event and empty-after-cleanup cases.
The current test exercises only a single compaction entry and a provider_meta payload that retains other keys after cleanup. Two valuable branches are not exercised:
- Multiple compactions → validates the
printf('%06d', CAST(je.key AS INTEGER))ordering andevent_indexsequence (e.g.,000000,000001). - A
provider_metawhose only key iscontext_compactions→ validates theWHEN json_remove(...) IN ('{}', 'null') THEN NULLbranch in_V6_TO_V7_PROVIDER_META_CLEANUP_SQL.
Adding a second conversation row (or a parametrized variant) would close both gaps cheaply.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/storage/test_provider_events_schema.py` around lines 12 - 113, Add
test coverage for multiple compactions and the empty-after-cleanup branch by
extending
test_ensure_schema_upgrades_v6_provider_meta_compactions_to_provider_events:
insert a second conversation row for the same conversation_id with a later
compaction entry (so the migration uses printf('%06d', CAST(je.key AS INTEGER))
and creates event_index 0 and 1) and insert another conversation where
provider_meta only contains context_compactions (so the SQL in
_V6_TO_V7_PROVIDER_META_CLEANUP_SQL that does WHEN json_remove(...) IN
('{}','null') THEN NULL is exercised); run _ensure_schema and assert both events
are created in provider_events with sequential event_index values and that
provider_meta becomes NULL for the single-key case while other keys remain for
the multi-key case.
Summary Persist provider protocol events as first-class archive rows instead of keeping runtime/provider protocol artifacts in provider_meta. The change adds provider event domain/storage models, schema v7 migration/backfill, ingestion/write/read support, and regression coverage for Claude/Codex protocol events and session enrichment. Problem Claude Code compactions and related provider protocol events were parsed but mostly folded into provider_meta, which made semantically primary archive events hard to query, easy to drop during enrichment, and invisible to storage round-trips. Runtime projection fallbacks were also masking a schema deficiency instead of making the schema model the data directly. Solution - Add `provider_events` as a durable schema v7 table with storage mappers, hydrators, repository reads/writes, and migration/backfill from legacy compaction metadata. - Materialize Claude/Codex provider events through ingest, prepare, repository write, and hydrated domain conversation paths. - Preserve provider events, branch type, parent linkage, source-message linkage, and typed empty arrays during enrichment and validation. - Keep provider_meta focused on provider-specific metadata by removing `context_compactions` from new parser output. - Update topology manifests/status for the new archive/provider and storage files. Verification - `direnv exec /realm/project/polylogue uv run mypy polylogue` -> `Success: no issues found in 721 source files` - `direnv exec /realm/project/polylogue uv run pytest -n 0 tests/unit/pipeline/test_ingest_batch.py tests/unit/sources/test_assembly.py tests/unit/sources/test_source_laws.py -q` -> `188 passed in 14.70s` - `nix develop --command bash -lc 'pytest tests/unit/core/test_schema_validation.py::test_schema_validator_preserves_empty_arrays_when_schema_expects_array tests/unit/pipeline/test_prepare_records.py::test_prepare_records_persists_provider_events tests/unit/storage/test_repository_lifecycle_laws.py::test_repository_resaves_hydrated_domain_provider_events tests/unit/storage/test_repository_lifecycle_laws.py::test_repository_record_resave_preserves_provider_events_when_omitted tests/unit/storage/test_repository_lifecycle_laws.py::test_repository_record_resave_replaces_explicit_provider_events_on_hash_match tests/unit/storage/test_session_insight_refresh.py::test_apply_session_insight_conversation_updates_async_counts_provider_event_compactions -q -n 0'` -> `6 passed in 0.85s` - `direnv exec /realm/project/polylogue devtools verify-topology` -> `realized=721 declared=721 blocking=False` - `direnv exec /realm/project/polylogue devtools verify-file-budgets` -> `file-size budgets: clean` - `direnv exec /realm/project/polylogue devtools render-topology-status --check` -> exit 0 - Pre-push quick verification baseline -> `verify: all checks passed` - GitHub checks: CodeRabbit pass; GitGuardian pass. Closes #837. Refs #838, #839, #840, #841, #842, #844, #845.
|
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
Persist provider protocol events as first-class archive rows instead of keeping runtime/provider protocol artifacts in provider_meta. The change adds provider event domain/storage models, schema v7 migration/backfill, ingestion/write/read support, and regression coverage for Claude/Codex protocol events and session enrichment.
Problem
Claude Code compactions and related provider protocol events were parsed but mostly folded into provider_meta, which made semantically primary archive events hard to query, easy to drop during enrichment, and invisible to storage round-trips. Runtime projection fallbacks were also masking a schema deficiency instead of making the schema model the data directly.
Solution
provider_eventsas a durable schema v7 table with storage mappers, hydrators, repository reads/writes, and migration/backfill from legacy compaction metadata.context_compactionsfrom new parser output.Verification
direnv exec /realm/project/polylogue uv run mypy polylogue->Success: no issues found in 721 source filesdirenv exec /realm/project/polylogue uv run pytest -n 0 tests/unit/pipeline/test_ingest_batch.py tests/unit/sources/test_assembly.py tests/unit/sources/test_source_laws.py -q->188 passed in 14.70sdirenv exec /realm/project/polylogue devtools verify-topology->realized=721 declared=721 blocking=Falsedirenv exec /realm/project/polylogue devtools verify-file-budgets->file-size budgets: cleandirenv exec /realm/project/polylogue devtools render-topology-status --check-> exit 0verify: all checks passedCloses #837.
Refs #840, #841, #842.
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Database
Tests