Skip to content

fix: connection profiles, identity ledger, tags M2M wiring (#780, #775, #776) - #788

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/connection-tags-identity
May 4, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/connection-tags-identity

Conversation

@Sinity

@Sinity Sinity commented May 4, 2026

Copy link
Copy Markdown
Owner

Summary

Wave 1 Slice B: connection profile unification, identity ledger wiring, tags many-to-many migration.

Problem

  • 14 sites used bare sqlite3.connect() without WAL/busy_timeout/foreign_keys pragmas
  • identity_ledger DDL existed but was never composed into SCHEMA_DDL
  • tags DDL existed but was never wired — all tag operations used JSON extraction

Solution

Verification

  • devtools verify --quick: all checks passed
  • mypy: 0 errors
  • ruff format + check: clean

Route all bare sqlite3.connect() calls through lightweight factory
functions in connection_profile.py (open_connection, open_readonly_connection,
connection_context) that apply canonical pragma profiles.

Wire the identity ledger: include IDENTITY_DDL in SCHEMA_DDL composition
(SCHEMA_VERSION 5 → 6), write identity ledger rows during ingest batch,
and look up existing identities during conversation tombstone.

Wire tags M2M: read tag listings from normalized conversation_tags + tags
tables with JSON metadata fallback for pre-migration archives.  Tag writes
(add, remove, bulk) write to both JSON metadata (backwards compatibility)
and normalized tables.  Add idempotent migration backfills that copy
existing JSON tags into normalized tables.

Add devtools/verify_connection_sites.py linter to prevent bare connects.

Closes #780, closes #776, closes #775.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 4, 2026 00:58
@Sinity
Sinity merged commit 8e2788c into master May 4, 2026
@Sinity
Sinity deleted the feature/fix/connection-tags-identity branch May 4, 2026 00:58
@coderabbitai

coderabbitai Bot commented May 4, 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 57 minutes and 25 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ 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: 5a2af0a5-a908-47a9-adc2-5abfd890d4cb

📥 Commits

Reviewing files that changed from the base of the PR and between e1d8c0f and c86e6f6.

📒 Files selected for processing (21)
  • devtools/verify_connection_sites.py
  • docs/verification-catalog.md
  • polylogue/archive/write_gateway.py
  • polylogue/cli/commands/reset.py
  • polylogue/cli/shell_completion_values.py
  • polylogue/daemon/cli.py
  • polylogue/daemon/events.py
  • polylogue/insights/storage.py
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/pipeline/tail_overlay.py
  • polylogue/schemas/sampling_db.py
  • polylogue/schemas/validation/corpus.py
  • polylogue/sources/live/cursor.py
  • polylogue/storage/blob_gc.py
  • polylogue/storage/repository/archive/repository_writes.py
  • polylogue/storage/search_providers/sqlite_vec_runtime.py
  • polylogue/storage/sqlite/connection_profile.py
  • polylogue/storage/sqlite/queries/conversations_identity.py
  • polylogue/storage/sqlite/schema.py
  • polylogue/storage/sqlite/schema_bootstrap.py
  • polylogue/storage/sqlite/schema_ddl.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/connection-tags-identity

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
Review rate limit: 0/1 reviews remaining, refill in 57 minutes and 25 seconds.

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

@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: c86e6f62e3

ℹ️ 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 unifies SQLite connection handling via shared connection-profile factories, wires the previously-dead identity-ledger DDL into the canonical archive schema (v6) and ingest path, and migrates tags from JSON metadata extraction to normalized many-to-many tables with backfill support.

Changes:

  • Route multiple production sqlite3.connect() call sites through connection_profile.open_connection() / open_readonly_connection(), and add a devtools linter to prevent regressions.
  • Bump archive schema to v6 and compose IDENTITY_DDL into SCHEMA_DDL, with upgrade planning for v4→v6 and v5→v6.
  • Switch tag listing/completion and tag writes toward tags + conversation_tags, adding an idempotent JSON→M2M backfill.

Reviewed changes

Copilot reviewed 21 out of 21 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
polylogue/storage/sqlite/schema_ddl.py Bumps schema version to v6 and composes identity-ledger DDL into the canonical schema.
polylogue/storage/sqlite/schema_bootstrap.py Extends schema upgrade decisioning and adds tag JSON→M2M backfill steps.
polylogue/storage/sqlite/schema.py Recognizes new schema upgrade actions (v4→v6, v5→v6) during ensure-schema.
polylogue/storage/sqlite/queries/conversations_identity.py Updates list_tags() to prefer normalized tables with JSON fallback.
polylogue/storage/sqlite/connection_profile.py Adds lightweight sync connection factories for consistent PRAGMA application.
polylogue/storage/search_providers/sqlite_vec_runtime.py Uses connection-profile factory for sqlite-vec runtime connections.
polylogue/storage/repository/archive/repository_writes.py Writes tags to normalized tables in addition to JSON metadata.
polylogue/storage/blob_gc.py Uses connection-profile factory for GC DB access.
polylogue/sources/live/cursor.py Uses connection-profile factory for live cursor DB connections.
polylogue/schemas/validation/corpus.py Uses connection-profile factory for schema validation DB access.
polylogue/schemas/sampling_db.py Uses connection-profile factory for sampling DB reads.
polylogue/pipeline/tail_overlay.py Uses factories for snapshot backup source/target DB connections.
polylogue/pipeline/services/ingest_batch.py Adds identity-ledger upsert during ingest and routes sync connection setup through factory.
polylogue/insights/storage.py Uses connection-profile factory for insights DB connections.
polylogue/daemon/events.py Uses connection-profile factory for daemon events DB initialization.
polylogue/daemon/cli.py Uses connection-profile factory for daemon startup FTS readiness check.
polylogue/cli/shell_completion_values.py Prefers normalized tag tables for shell completion, with JSON fallback.
polylogue/cli/commands/reset.py Routes reset DB access through factory and adds identity-key-aware tombstoning.
polylogue/archive/write_gateway.py Routes write-gateway local fallback connection through factory.
docs/verification-catalog.md Updates generated reference line numbers for polylogue reset.
devtools/verify_connection_sites.py Adds a linter to reject bare sqlite3.connect() in production code.
Comments suppressed due to low confidence (1)

polylogue/cli/commands/reset.py:162

  • The --source tombstone path queries conversations using columns that do not exist in the archive schema (id and source_path). In schema_ddl_archive.py, the PK is conversation_id and source_path lives on raw_conversations; conversations only has a generated source_name. This will raise sqlite3.OperationalError at runtime; use conversation_id and join via raw_id to raw_conversations.source_path (or filter on conversations.source_name if that’s what you intended).
        conn = open_connection(_db)
        try:
            rows = conn.execute(
                "SELECT id FROM conversations WHERE source_path LIKE ?",
                (f"{source_path}%",),
            ).fetchall()

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +287 to +298
def _write_identity_ledger(conn: sqlite3.Connection, cdata: ConversationData) -> None:
"""Write identity ledger row so re-imported conversations are recognized."""
source_path = cdata.source_name
provider_conversation_id = cdata.conversation_tuple[2]
conn.execute(
_IDENTITY_LEDGER_UPSERT_SQL,
(
cdata.provider_name,
cdata.source_name,
source_path,
provider_conversation_id,
cdata.content_hash,
Comment on lines 162 to 165
await self._metadata_read_modify_write(conversation_id, _add)
# Also write to normalized tables for M2M query support
await self._upsert_normalized_tag(conversation_id, tag)

Comment on lines +72 to +81
try:
row = c.execute(
"SELECT provider || ':' || source || ':' || source_path || ':' || provider_conversation_id || ':' || raw_hash "
"FROM identity_ledger WHERE current_conversation_id = ? LIMIT 1",
(conv_id,),
).fetchone()
if row:
identity_key = row[0]
except Exception:
pass
Comment on lines +819 to 830
if snapshot.current_version == 5 and SCHEMA_VERSION >= 6:
from polylogue.storage.sqlite.schema_ddl_identity import IDENTITY_DDL

plan = SchemaExtensionPlan(
statements=_split_ddl_into_statements(SOURCE_FILE_CURSOR_DDL, TAGS_M2M_DDL, BLOB_LEASE_DDL),
statements=_split_ddl_into_statements(IDENTITY_DDL),
scripts=(),
)
return SchemaBootstrapDecision(
action="upgrade_v4_to_v5",
action="upgrade_v5_to_v6",
extension_plan=plan,
current_version=snapshot.current_version,
)
Comment on lines 225 to +227
await self._metadata_read_modify_write(conversation_id, _remove)
# Also remove from normalized tables
await self._delete_normalized_tag(conversation_id, tag)
Comment on lines +202 to +211
# Also write to normalized tables
for tag in tags:
await conn.execute("INSERT OR IGNORE INTO tags (name) VALUES (?)", (tag,))
cursor = await conn.execute("SELECT id FROM tags WHERE name = ?", (tag,))
row = await cursor.fetchone()
if row is not None:
await conn.execute(
"INSERT OR IGNORE INTO conversation_tags (conversation_id, tag_id) VALUES (?, ?)",
(conversation_id, row["id"]),
)
Comment on lines +574 to +583
SchemaBackfillDescriptor(
table_name="conversation_tags",
ddl="""
INSERT OR IGNORE INTO tags (name)
SELECT DISTINCT tag.value
FROM conversations,
json_each(json_extract(metadata, '$.tags')) AS tag
WHERE metadata IS NOT NULL
AND json_extract(metadata, '$.tags') IS NOT NULL
""",
Comment on lines +122 to +123
Returns ``None`` / raises ``sqlite3.OperationalError`` if the database file
does not exist.
Sinity added a commit that referenced this pull request May 7, 2026
#776) (#788)

## Summary
Wave 1 Slice B: connection profile unification, identity ledger wiring,
tags many-to-many migration.

## Problem
- 14 sites used bare sqlite3.connect() without
WAL/busy_timeout/foreign_keys pragmas
- identity_ledger DDL existed but was never composed into SCHEMA_DDL
- tags DDL existed but was never wired — all tag operations used JSON
extraction

## Solution
- **#780**: Route all connection sites through connection_profile.py
factories. Added verify_connection_sites.py linter.
- **#775**: Wired IDENTITY_DDL into SCHEMA_DDL composition, bumped
schema v5→v6 with upgrade path, added identity ledger writes on ingest,
identity-preserving reset.
- **#776**: Migrated list_tags/add_tag/remove_tag/bulk_add_tags to use
normalized conversation_tags + tags tables with JSON fallback. Added
idempotent backfill migration.

## Verification
- devtools verify --quick: all checks passed
- mypy: 0 errors
- ruff format + check: clean

Co-authored-by: Claude Opus 4.7 <[email protected]>
@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.

@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.

2 participants