Repository navigation
Conversation
Tests were using `from polylogue.storage.backends.sqlite import default_db_path` at module load time, capturing a reference before fixtures could monkeypatch XDG paths. This caused tests to write to the production database instead of isolated temp directories. Changes: - test_check.py: Use db_path fixture instead of default_db_path() - test_golden_outputs.py: Same pattern fix - test_store.py: Fixed wrong env var (XDG_STATE_HOME → XDG_DATA_HOME) and added proper module reload 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Implement schema v7 with unified branching support across all providers: Storage layer: - Add parent_conversation_id, branch_type to conversations table - Add parent_message_id, branch_index to messages table - Migration from v6 to v7 with indexes Importers: - Claude Code: extract parentUuid, detect isSidechain → branch_type - ChatGPT: extract parent, calculate branch_index from children array - Codex: track multiple session_meta for continuation detection Domain model: - Message: parent_id, branch_index, is_branch property - Conversation: parent_id, branch_type, is_continuation/is_sidechain/is_root - mainline_messages() to filter branches Query API: - Filters: is_continuation(), is_sidechain(), is_root(), parent(), has_branches() - Repository: get_parent(), get_children(), get_session_tree(), get_root() Tests: 13 new branching tests, 2022 total passing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Critical fix: the branching fields (parent_conversation_id, branch_type, parent_message_id, branch_index) were being extracted by importers but NOT copied to storage records during prepare_ingest(). This meant all branching metadata was silently lost. Changes: - Resolve parent_conversation_provider_id → internal conversation ID - Merge provider_meta instead of overwriting with just source name - Two-pass message processing to resolve parent_message_id references - Copy branch_type and branch_index to records Also adds test_branching_pipeline.py with 8 full-pipeline integration tests that exercise the REAL importer→ingest→database flow (vs the existing test_branching.py which uses ConversationBuilder direct DB writes). Fixed pre-existing property test failure where hypothesis generated name='.' which gets sanitized to "file" (dots-only security measure). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Addresses testing gaps identified in Phase 6: - Add claude-code sample with sidechain branching (57KB) - Add codex envelope format sample (159KB) - Add test_fixtures_contract.py for parser validation on real data - Add seeded_db session fixture in conftest.py - Refactor extraction tests to use fixtures instead of prod DB paths - Add iter_branches() to Conversation model for branching support The seeded_db fixture creates a temp database populated with real fixture data through the full pipeline, enabling integration tests without production database contamination. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Replace raw dict access with model_validate() in codex and claude importers: - codex.py: Use CodexRecord for format detection and property access - claude.py: Use ClaudeCodeRecord for type-safe parsing - claude_code.py: Accept int/float timestamps (not just strings) - extractors.py: Make codex timestamp optional in glom spec Benefits: - Validation at parse time catches malformed data earlier - IDE autocomplete and type checking work correctly - Normalized properties (role, text_content) replace manual extraction 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Add comprehensive security-focused fuzzing tests (291 test cases): - fuzz_path_sanitizer.py: Path traversal attack prevention (44 tests) - fuzz_fts5_escape.py: FTS5 injection prevention (64 tests) - fuzz_json_importers.py: Malformed JSON crash resistance (80 tests) - fuzz_timestamp.py: Timestamp parsing DoS prevention (117 tests) Add mutation testing configuration: - mutmut.toml: Target security-critical modules - Target >80% mutation kill rate Documentation: - docs/testing/fuzzing.md: Complete usage guide Findings: - FTS5 escape has documented edge cases (xfail markers) - No SQL injection vulnerabilities (parameterized queries) - All importers handle malformed input without crashing 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- Move Role enum and normalize_role to polylogue/core/roles.py - Enforce non-empty input: None and whitespace now raise errors - Update extractors to use new role module - Fix tests to expect errors on invalid input Role validation is now strict - missing roles must be handled at parse time, not silently defaulted. This preserves data integrity. Co-Authored-By: Claude <[email protected]>
- Simplify importer base with typed ParsedConversation/ParsedMessage - Remove redundant conversions in claude_code provider - Consolidate unified schema definitions - Update tests for new model structure Note: Some drive importer tests currently fail due to parser changes that need further investigation (pre-existing from model migration). Co-Authored-By: Claude <[email protected]>
Add MessageCollection class that streams messages from DB instead of loading all into memory. This reduces memory from O(n) to O(1) for large conversations. Key changes: - MessageCollection with lazy/eager modes - Conversation.from_lazy() factory for streaming - Repository.get() now returns lazy by default - Repository.get_eager() for explicit full loading - Pydantic serialization support for API responses Performance on 33k message conversation: - Lazy iteration: 0.08 MB (constant) - Eager loading: 237 MB - Improvement: 2,931x memory reduction API unchanged: for/len/indexing all work. Indexing auto-materializes for backward compatibility but iteration stays lazy. Co-Authored-By: Claude <[email protected]>
- Add query output options for large conversations - Improve CLI help and option grouping - Support lazy conversation loading in query paths Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
- claude.ai: skip messages without sender/role (no silent defaults) - drive: skip chunks without role/author (no data invention) - Update tests to include explicit roles in fixtures - Add mutants/ to .gitignore Strict parsing preserves data integrity - missing roles indicate malformed input that should be skipped, not silently "fixed". All 2105 tests pass. Co-Authored-By: Claude <[email protected]>
…e 1) Add infrastructure to capture and store original JSON bytes before parsing: - Schema v8: Add raw_conversations table with FK to conversations - RawConversationRecord model for persistence - RawConversationData for transport through ingestion pipeline - Backend methods: save_raw_conversation, get_raw_conversation, iter_raw_conversations, link_raw_to_parsed, get_raw_conversation_count - iter_source_conversations_with_raw() captures raw bytes alongside parsing Note: Raw capture disabled by default (capture_raw=False) due to SQLite lock contention with concurrent ingestion. Infrastructure ready for future single-threaded acquire stage. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add AcquisitionService for ACQUIRE stage (files → raw_conversations) - Refactor IngestionService to orchestrate acquire → parse flow - Add ingest_from_raw() for parsing from raw_conversations table - Add source_name column to raw_conversations (schema v9) - Update tests to mock new stage-based architecture The pipeline now properly separates concerns: - ACQUIRE: store raw bytes with content-hash deduplication - PARSE: read from raw_conversations, parse, store to conversations 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Phase 2: CLI Renaming & Stage Architecture - Rename `sync` command to `run` - Add new stages: acquire, parse, generate-schemas - Keep `sync` as deprecated alias with deprecation warning - Update tests to use new command name Phase 3: Type Consolidation - Delete duplicate ThinkingTrace class (use ReasoningTrace from viewports) - Document ToolCall vs ToolInvocation distinction: - ToolCall (viewports.py): Cross-provider harmonized for rendering - ToolInvocation (models.py): Claude-specific with semantic properties 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
The CLI was renamed from `sync` to `run` in the previous commit. This removes the backwards-compat `sync_command` alias and updates all tests to use the new `run` command name. - Delete sync_command function and its alias registration - Convert tests/test_cli_commands.py: TestSyncCommand → TestRunCommand - Update tests/test_cli.py to use `run` instead of `sync` - Update --stage "ingest" references to "parse" 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Test consolidation (Phase 6): - Merge CLI utilities: test_cli_formatting.py + test_cli_helpers.py + test_cli_container.py → test_cli_utilities.py (75 tests) - Remove 9 duplicate test classes from test_db_store.py - Delete superseded files: test_editor.py (→test_cli_editor.py), test_drive_config.py (trivial), test_retries.py (→test_drive_resilience.py), test_qdrant.py (→test_qdrant_resilience.py + test_search_index.py) Result: 102 → 96 test files, 2149 → 2125 tests (no lost coverage) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
…ples Rework schema_inference.py to load raw samples from polylogue database instead of filesystem crawling. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- Add raw_db_samples fixture to conftest.py (reads from polylogue.db) - Update test_fixtures_contract.py for database-driven validation - Update test_schema_drift.py for schema evolution tracking - Update test_raw_conversations.py for raw conversation tests - Update test_workflows_comprehensive.py for end-to-end validation 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- Update source.py with improved acquisition handling - Minor runner.py adjustments for stage compatibility - SQLite backend improvements for raw_conversations 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- Add claude/ fixtures directory with real samples - Update gemini sample-with-tools.jsonl fixture - Adjust test_claude_semantic.py and test_importers_drive.py 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
New test coverage for MCP server implementation (previously untested). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Consolidate test files to reduce fragmentation while preserving all tests: CLI tests (13 → 9 files, -4): - Merged test_cli_completions.py, test_cli_mcp.py, test_cli_reset.py, test_cli_serve.py into test_cli_commands.py - Preserved both subprocess integration tests AND CliRunner unit tests - Clear section organization with === banners Importer tests (7 → 5 files, -2): - Created test_importers_unit.py consolidating ChatGPT, Claude, Codex provider-specific unit tests - Kept test_importers_parametrized.py (cross-provider integration) - Kept test_importers_properties.py (Hypothesis property-based) Results: - Total test files: 96 → 90 (-6) - Test count unchanged: 2125 tests passing - No coverage loss 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Merge fragmented test files into cohesive domain modules: - CLI: test_cli.py + auth/check/editor/search → test_cli_unit.py, test_cli_integration.py - Core: test_core_json.py + test_core_utilities.py + test_lib.py → test_core.py - Storage: test_db.py + test_db_store.py + test_store.py → test_storage.py - Search: test_search.py + health/providers → test_search_core.py - Rendering: test_renderers.py + test_rendering_core.py → test_rendering.py - Backend: test_backend_*.py → test_backend_core.py - Pipeline: consolidate acquisition/ingestion services Net reduction: ~6,700 lines via deduplication and shared fixtures. Co-Authored-By: Claude <[email protected]>
Was declared in pyproject.toml but missing from flake.nix dependencies, causing pythonRuntimeDepsCheck to fail. Co-Authored-By: Claude Opus 4.5 <[email protected]>
Phase 1 — Protocol and container cleanup: - Delete StorageBackend protocol (20 methods, 1 impl) and Renderer protocol (0 impls) - Keep SearchProvider, VectorProvider, OutputRenderer (2+ impls each) - Remove 5 isinstance(SQLiteBackend) checks from repository.py; type backend directly - Replace dependency-injector container (~145 LOC) with services.py (~45 LOC) - Remove dependency-injector, fastapi, uvicorn from dependencies Phase 2 — Dissolve core/ package: - Move facade.py, async_facade.py to polylogue/ top-level - Move hashing, timestamps, dates, json, log, env, roles to polylogue/lib/ - Move code_detection to polylogue/schemas/ - Move content_enrichment to polylogue/pipeline/enrichment.py - Rewrite all imports across 48 files - Delete polylogue/core/ entirely 2096 tests pass, 12 skipped. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Caution Review failedFailed to post review comments 📝 WalkthroughWalkthroughThis PR implements a substantial architectural refactoring removing dependency injection containers, introducing lazy message loading via Changes
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related issues
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Refactors application wiring away from dependency-injector into a small services singleton module, and upgrades storage/ingest to be branch-aware with raw payload preservation and a staged acquire→parse pipeline (with CLI moving to run).
Changes:
- Replace DI container with
polylogue/services.pysingletons and update call sites. - Add branch lineage + raw payload storage (
raw_conversations) and update ingest to acquire raw bytes first then parse from DB. - Introduce lazy
MessageCollectionand expand/reshape tests, including fuzz/mutation tooling.
Reviewed changes
Copilot reviewed 87 out of 148 changed files in this pull request and generated 13 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/test_cli_serve.py | Removed serve command tests (CLI surface changed). |
| tests/test_cli_search_expanded.py | Removed expanded query/search CLI tests (reworked CLI). |
| tests/test_cli_reset.py | Removed reset command tests (suite refactor). |
| tests/test_cli_mcp.py | Removed MCP CLI tests (suite refactor). |
| tests/test_cli_formatting.py | Removed formatting tests (API changed). |
| tests/test_cli_editor.py | Removed editor/browser security tests (suite refactor). |
| tests/test_cli_container.py | Removed DI container tests (container deleted). |
| tests/test_cli_completions.py | Removed completions tests (suite refactor). |
| tests/test_cli_auth.py | Removed auth tests (suite refactor). |
| tests/test_cli.py | Removed legacy sync/search CLI integration tests (CLI moved to run). |
| tests/test_claude_semantic.py | Tunes Hypothesis settings to reduce slowness. |
| tests/test_check.py | Switch tests to use db_path fixture instead of default path. |
| tests/test_backend_sqlite.py | Removed SQLite backend tests (likely replaced elsewhere). |
| tests/test_backend_comparison.py | Removed prod-DB comparison tests (replaced by seeded fixtures). |
| tests/test_async_repository.py | Merged async repository tests into test_async_backend.py. |
| tests/test_async_backend.py | Adds merged async repository tests. |
| tests/strategies/messages.py | Adds Hypothesis strategies returning typed Parsed* model instances. |
| tests/strategies/init.py | Re-exports the new typed strategies. |
| tests/helpers.py | Adds branching helpers and a builder method returning domain objects. |
| tests/fuzz/fuzz_timestamp.py | Adds fuzzing for timestamp parsing/formatting (ReDoS/crash resistance). |
| tests/fuzz/fuzz_path_sanitizer.py | Adds fuzzing for attachment path/name sanitization. |
| tests/fuzz/fuzz_fts5_escape.py | Adds fuzzing for FTS5 query escaping behavior. |
| tests/fuzz/corpus/README.md | Documents seed corpus layout and usage. |
| tests/fuzz/init.py | Adds fuzz test package documentation/entry points. |
| tests/conftest.py | Replaces container reset with service reset; adds seeded DB + raw DB fixtures. |
| pyproject.toml | Removes DI/uvicorn/fastapi deps; adds fuzz extra; adjusts coverage/mypy excludes. |
| polylogue/ui/tui/screens/search.py | Adds a TUI search screen using repository services. |
| polylogue/ui/tui/screens/browser.py | Adds a TUI browser screen for provider trees + preview. |
| polylogue/storage/store.py | Adds branching/raw fields to records and upsert logic. |
| polylogue/storage/search_providers/init.py | Moves env import to polylogue.lib.env. |
| polylogue/storage/backends/init.py | Simplifies backend factory to SQLite-only. |
| polylogue/services.py | Introduces module-level backend/repository singletons with reset(). |
| polylogue/schemas/unified.py | Consolidates role/timestamp handling and expands provider text extraction helpers. |
| polylogue/schemas/schema_inference.py | Generates schemas from raw_conversations; loosens nested required. |
| polylogue/schemas/extractors.py | Switches to unified timestamp parsing and stricter role handling. |
| polylogue/schemas/common.py | Re-exports canonical Role from polylogue.lib.roles. |
| polylogue/schemas/claude_code_records.py | Uses unified timestamp parsing; updates return type annotations. |
| polylogue/providers/claude_code.py | Expands timestamp types, reuses unified extractors for tool/reasoning blocks. |
| polylogue/pipeline/services/rendering.py | Moves logger import to polylogue.lib.log. |
| polylogue/pipeline/services/ingestion.py | Implements parse-from-raw flow; adds acquire→parse convenience path. |
| polylogue/pipeline/services/indexing.py | Moves logger import to polylogue.lib.log. |
| polylogue/pipeline/services/acquisition.py | Adds acquisition stage storing raw bytes into raw_conversations. |
| polylogue/pipeline/runner.py | Removes DI wiring; adds acquire/parse stages; updates render/index wiring. |
| polylogue/pipeline/ingest.py | Adds branching/raw_id persistence and parent resolution. |
| polylogue/pipeline/ids.py | Moves hashing imports to polylogue.lib.hashing. |
| polylogue/pipeline/enrichment.py | Switches code detection import path. |
| polylogue/lib/viewports.py | Clarifies ToolCall viewport vs semantic model usage. |
| polylogue/lib/roles.py | Adds canonical Role enum + strict normalize_role(). |
| polylogue/lib/messages.py | Introduces lazy MessageCollection w/ pydantic serialization. |
| polylogue/lib/filters.py | Adds branch-aware filters and summary-only query path. |
| polylogue/lib/init.py | Exposes MessageCollection. |
| polylogue/ingestion/init.py | Exports raw capture APIs/types. |
| polylogue/importers/drive.py | Enforces role presence for prompt chunks. |
| polylogue/importers/codex.py | Uses typed CodexRecord parsing; adds continuation lineage. |
| polylogue/importers/claude.py | Uses typed ClaudeCodeRecord parsing; adds sidechain detection + parent UUID. |
| polylogue/importers/chatgpt.py | Adds parent message + branch index extraction. |
| polylogue/importers/base.py | Adds branch metadata fields + RawConversationData; re-exports normalize_role. |
| polylogue/health.py | Moves logger import to polylogue.lib.log. |
| polylogue/facade.py | Removes container usage; creates backend/repository directly; vector provider creation change. |
| polylogue/core/init.py | Deleted (core package API reshaped). |
| polylogue/container.py | Deleted dependency-injector container. |
| polylogue/cli/formatting.py | Updates plain-mode logic (drops interactive parameter). |
| polylogue/cli/commands/run.py | Renames sync→run; adds acquire/parse/generate-schemas stages; uses services config. |
| polylogue/cli/click_app.py | Registers run subcommand; adds streaming options to query-first CLI. |
| polylogue/async_facade.py | Switches record conversion helper import to storage repository. |
| polylogue/init.py | Re-exports facade modules; provides lazy ConversationRepository attribute. |
| mutmut.toml | Adds mutation testing configuration for security-critical modules. |
| flake.nix | Adds glom to dev dependencies. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| cursor_state: dict[str, Any] | None = None, | ||
| ) -> Generator[ParsedConversation, None, None]: | ||
| """Iterate over conversations from a source with error handling. | ||
| def _parse_raw_record(self, raw_record: RawConversationRecord) -> list[ParsedConversation]: |
There was a problem hiding this comment.
This will fail for JSONL providers because raw_content can contain multiple JSON objects separated by newlines (not valid for json.loads). Fix by detecting JSONL (e.g., by provider or by scanning for newline-delimited objects) and parsing into a list[dict] before calling _parse_json_payload, or by moving JSON/JSONL decoding into a shared helper used by both acquisition and parsing.
| # Deserialize the raw JSON bytes | ||
| payload = json.loads(raw_record.raw_content) | ||
|
|
||
| yield from iter_drive_conversations( | ||
| source=source, | ||
| archive_root=self.archive_root, | ||
| ui=ui, | ||
| download_assets=download_assets, | ||
| cursor_state=cursor_state, | ||
| drive_config=self.config.drive_config, | ||
| client=client, | ||
| ) | ||
| except DriveAuthError as exc: | ||
| logger.warning("Skipping Drive source %s: %s", source.name, exc) | ||
| if cursor_state is not None: | ||
| cursor_state["error_count"] = cursor_state.get("error_count", 0) + 1 | ||
| cursor_state["latest_error"] = str(exc) | ||
| cursor_state["latest_error_source"] = source.name | ||
| return | ||
| else: | ||
| yield from iter_source_conversations(source, cursor_state=cursor_state) | ||
| # Use the existing parser dispatcher | ||
| return _parse_json_payload( | ||
| raw_record.provider_name, | ||
| payload, | ||
| raw_record.raw_id, # Use raw_id as fallback conversation ID | ||
| ) |
There was a problem hiding this comment.
This will fail for JSONL providers because raw_content can contain multiple JSON objects separated by newlines (not valid for json.loads). Fix by detecting JSONL (e.g., by provider or by scanning for newline-delimited objects) and parsing into a list[dict] before calling _parse_json_payload, or by moving JSON/JSONL decoding into a shared helper used by both acquisition and parsing.
| record = RawConversationRecord( | ||
| raw_id=raw_id, | ||
| provider_name=raw_data.provider_hint or source_name, | ||
| source_name=source_name, # Config source name, distinct from provider | ||
| source_path=raw_data.source_path, | ||
| source_index=raw_data.source_index, | ||
| raw_content=raw_data.raw_bytes, | ||
| acquired_at=acquired_at, | ||
| file_mtime=raw_data.file_mtime, | ||
| ) |
There was a problem hiding this comment.
provider_name must reliably be the provider identifier used by parsers (e.g., 'chatgpt', 'claude-code'). Falling back to source_name is unsafe when config source names are things like 'inbox'/'drive', which will break parsing and schema inference. Prefer: (1) require raw_data.provider_hint (or infer provider from source/path/content) and raise/record an error if missing, and (2) keep source_name strictly as the config source label.
| # Pre-compute the REAL database path at module load time, before any test | ||
| # fixtures can modify environment variables. This ensures database-driven | ||
| # tests always use the user's actual database, not a temp test database. | ||
| _REAL_DB_PATH = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "polylogue" / "polylogue.db" | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session") | ||
| def raw_db_samples(): | ||
| """Load samples from user's actual raw_conversations table. | ||
|
|
||
| This enables honest, database-driven testing by using REAL data | ||
| that was acquired via `polylogue run --stage acquire`. | ||
|
|
||
| Control sample count via POLYLOGUE_TEST_SAMPLES environment variable: | ||
| - POLYLOGUE_TEST_SAMPLES=100 (default) - Fast CI, limited samples | ||
| - POLYLOGUE_TEST_SAMPLES=0 - Exhaustive mode, ALL raw conversations | ||
|
|
||
| Returns: | ||
| List of RawConversationRecord objects from the user's database | ||
| """ |
There was a problem hiding this comment.
Tests should not read a developer's real local database by default. This creates nondeterministic failures in CI, potential privacy leaks (local data in test logs), and makes the suite dependent on workstation state. Gate this fixture behind an explicit opt-in env var (e.g., POLYLOGUE_USE_REAL_DB=1), default to pytest.skip(...) when not enabled, and prefer the seeded_db fixture for deterministic integration coverage.
| # Use pre-computed path that bypasses test env modifications | ||
| if not _REAL_DB_PATH.exists(): | ||
| return [] # No database = no samples (skip in tests) | ||
|
|
||
| backend = SQLiteBackend(db_path=_REAL_DB_PATH) | ||
|
|
||
| # Load samples from raw_conversations table | ||
| samples = list(backend.iter_raw_conversations(limit=limit)) |
There was a problem hiding this comment.
Tests should not read a developer's real local database by default. This creates nondeterministic failures in CI, potential privacy leaks (local data in test logs), and makes the suite dependent on workstation state. Gate this fixture behind an explicit opt-in env var (e.g., POLYLOGUE_USE_REAL_DB=1), default to pytest.skip(...) when not enabled, and prefer the seeded_db fixture for deterministic integration coverage.
| # Extract parent message reference and calculate branch index | ||
| parent_id = node.get("parent") | ||
| parent_message_provider_id = str(parent_id) if parent_id else None | ||
| branch_index = 0 | ||
|
|
||
| # Calculate branch_index from parent's children array position | ||
| if parent_message_provider_id: | ||
| parent_node = mapping.get(parent_id) | ||
| if isinstance(parent_node, dict): | ||
| children = parent_node.get("children") | ||
| if isinstance(children, list): | ||
| current_node_id = node.get("id") | ||
| if current_node_id in children: | ||
| branch_index = children.index(current_node_id) |
There was a problem hiding this comment.
This does a linear children.index(...) scan per message, which can become O(n²) on large conversations with many sibling lists. Consider precomputing an index map per parent (child_id → branch_index) once (or caching it) so branch_index lookup is O(1) during message extraction.
| _backend: SQLiteBackend | None = None | ||
| _repository: ConversationRepository | None = None | ||
|
|
||
|
|
||
| def get_backend() -> SQLiteBackend: | ||
| global _backend | ||
| if _backend is None: | ||
| _backend = create_default_backend() | ||
| return _backend | ||
|
|
||
|
|
||
| def get_repository() -> ConversationRepository: | ||
| global _repository | ||
| if _repository is None: | ||
| _repository = ConversationRepository(backend=get_backend()) | ||
| return _repository |
There was a problem hiding this comment.
The singleton initialization is not thread-safe: two threads can race and create multiple backends/repositories (and potentially multiple SQLite connections) before assignment. If this module is used from concurrent entry points (TUI workers, thread pools, etc.), add a module-level lock around initialization or use a thread-safe caching approach.
| # ============================================================================= | ||
| # ASYNC STORAGE REPOSITORY TESTS (merged from test_async_repository.py) | ||
| # ============================================================================= | ||
|
|
||
| from polylogue.lib.models import Conversation, Message | ||
| from polylogue.storage.async_repository import AsyncStorageRepository | ||
| from polylogue.storage.store import AttachmentRecord, MessageRecord | ||
| from polylogue.types import ContentHash |
There was a problem hiding this comment.
These imports are placed mid-file after earlier test definitions. This can confuse test discovery tooling and will typically fail linting/isort rules. Move imports to the top of the module (or keep the merged tests in a dedicated file) to match standard Python test structure.
| from polylogue.core.timestamps import parse_timestamp | ||
| from polylogue.core.roles import Role, normalize_role as _normalize_role_str | ||
| from polylogue.schemas.common import CommonMessage, CommonToolCall |
There was a problem hiding this comment.
This appears inconsistent with the new canonical role/timestamp modules introduced in this PR (e.g., polylogue.lib.roles and polylogue.lib.timestamps). If polylogue.core.roles is removed or diverges (and polylogue.schemas.common now re-exports Role from polylogue.lib.roles), this import path can cause runtime ImportError or semantic drift. Align this file to import Role/normalize_role/parse_timestamp from the canonical polylogue.lib.* modules.
| @@ -0,0 +1,80 @@ | |||
| from __future__ import annotations | |||
|
|
|||
| from rich.markdown import Markdown | |||
There was a problem hiding this comment.
Markdown is imported but not used in this module. Removing unused imports reduces noise and avoids misleading readers about how rendering is performed here.
| from rich.markdown import Markdown |
… branching (#62) Dissolve the dependency-injector container in favor of plain module-level factories, simplify the StorageBackend protocol from ~400 lines to ~54, and introduce session branching with raw conversation preservation. Service layer (polylogue/services.py, polylogue/container.py): - Delete container.py and its dependency-injector wiring entirely - New services.py exposes get_backend(), get_repository(), get_service_config(), and reset() as module-level singletons - Pipeline runner constructs services directly instead of resolving through the container Storage backend (polylogue/storage/backends/sqlite.py): - Schema migrations v6 → v7 → v8 → v9 add branching columns (parent_conversation_id, branch_type, parent_message_id, branch_index) and a raw_conversations table for original provider bytes - iter_messages() enables row-at-a-time streaming without loading full conversation into memory - get_conversation_stats() provides lightweight counts Repository consolidation (polylogue/storage/repository.py, lib/repository.py): - Merge former StorageRepository (write) and ConversationRepository (read) into a single ConversationRepository with lazy and eager loading modes - list_summaries() returns ConversationSummary objects (no messages loaded) - Tree traversal methods for branch navigation Lazy message loading (polylogue/lib/messages.py, lib/models.py): - New MessageCollection wraps a backend reference and conversation ID; iterates messages on demand with O(1) memory - Conversation.messages typed as MessageCollection; eager mode available via get_eager() for callers that need random access - Pydantic serialization hooks preserve the lazy/eager distinction Role normalization (polylogue/lib/roles.py): - Canonical Role enum and normalize_role() with strict validation extracted from scattered per-importer logic - Empty-string input raises ValueError instead of silently defaulting Provider importers (importers/chatgpt.py, claude.py, codex.py): - ChatGPT importer extracts parent_message_provider_id and branch_index from mapping children arrays - Claude importer uses typed ClaudeCodeRecord, detects sidechain branches via parentUuid - Codex importer uses typed CodexRecord, detects session continuations from multiple session_metas entries Pipeline (pipeline/services/acquisition.py, pipeline/services/ingestion.py): - New AcquisitionService handles the ACQUIRE stage, storing raw bytes before any parsing - Ingestion rewritten to read from raw_conversations table, enabling database-driven replay without re-downloading Package structure: - Dissolve polylogue/core/ entirely; contents relocated to lib/, schemas/, and pipeline/ based on domain ownership - protocols.py reduced to SearchProvider, VectorProvider, OutputRenderer
… branching (#62) Dissolve the dependency-injector container in favor of plain module-level factories, simplify the StorageBackend protocol from ~400 lines to ~54, and introduce session branching with raw conversation preservation. Service layer (polylogue/services.py, polylogue/container.py): - Delete container.py and its dependency-injector wiring entirely - New services.py exposes get_backend(), get_repository(), get_service_config(), and reset() as module-level singletons - Pipeline runner constructs services directly instead of resolving through the container Storage backend (polylogue/storage/backends/sqlite.py): - Schema migrations v6 → v7 → v8 → v9 add branching columns (parent_conversation_id, branch_type, parent_message_id, branch_index) and a raw_conversations table for original provider bytes - iter_messages() enables row-at-a-time streaming without loading full conversation into memory - get_conversation_stats() provides lightweight counts Repository consolidation (polylogue/storage/repository.py, lib/repository.py): - Merge former StorageRepository (write) and ConversationRepository (read) into a single ConversationRepository with lazy and eager loading modes - list_summaries() returns ConversationSummary objects (no messages loaded) - Tree traversal methods for branch navigation Lazy message loading (polylogue/lib/messages.py, lib/models.py): - New MessageCollection wraps a backend reference and conversation ID; iterates messages on demand with O(1) memory - Conversation.messages typed as MessageCollection; eager mode available via get_eager() for callers that need random access - Pydantic serialization hooks preserve the lazy/eager distinction Role normalization (polylogue/lib/roles.py): - Canonical Role enum and normalize_role() with strict validation extracted from scattered per-importer logic - Empty-string input raises ValueError instead of silently defaulting Provider importers (importers/chatgpt.py, claude.py, codex.py): - ChatGPT importer extracts parent_message_provider_id and branch_index from mapping children arrays - Claude importer uses typed ClaudeCodeRecord, detects sidechain branches via parentUuid - Codex importer uses typed CodexRecord, detects session continuations from multiple session_metas entries Pipeline (pipeline/services/acquisition.py, pipeline/services/ingestion.py): - New AcquisitionService handles the ACQUIRE stage, storing raw bytes before any parsing - Ingestion rewritten to read from raw_conversations table, enabling database-driven replay without re-downloading Package structure: - Dissolve polylogue/core/ entirely; contents relocated to lib/, schemas/, and pipeline/ based on domain ownership - protocols.py reduced to SearchProvider, VectorProvider, OutputRenderer
|
@codex review |
💡 Codex Reviewpolylogue/polylogue/lib/repository.py Line 22 in ad5c668
polylogue/polylogue/cli/container.py Line 16 in ad5c668
polylogue/polylogue/schemas/extractors.py Lines 38 to 39 in ad5c668
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Summary
I removed the dependency-injector container, replaced it with a tiny services module, and used the same branch to make conversation lineage a first-class storage concern. The storage layer can preserve raw provider payloads, session continuations, sidechains, and message branches; the repository can traverse that tree; and the domain model no longer has to load every message eagerly just to answer summary-level questions. This also changes the ingest flow: raw bytes are stored first via a new acquisition stage, and parsing/replay happens from
raw_conversationswithout requiring the original provider source to still be present. The CLI follows that shift by consolidating staged execution underrunand removing the oldsyncalias. Across all of that, I tightened role normalization and expanded test/fuzz coverage around the new storage and pipeline behavior.Motivation
Two architectural problems had started to reinforce each other.
The first was process wiring. The container solved the "where do dependencies come from?" question, but by this point it was more ceremony than clarity. Most commands wanted the same small set of objects, and the storage repository was already the effective center of gravity. Carrying dependency-injector everywhere was no longer buying enough structure to justify the extra layer.
The second was that the archive model still flattened away too much history. ChatGPT edit branches, Claude sidechains, and Codex session continuations were all observable in raw data, but the stored representation had only a weak place to keep that lineage. At the same time, large conversations were getting expensive to load eagerly when many callers only needed counts, summaries, or a stream.
The branch history reflects that progression. It starts with test-isolation fixes and explicit branching metadata, then pushes those fields through ingest, then adds raw conversation capture and staged acquisition, and finally removes the container once the storage/repository model had become simpler and more self-sufficient.
Changes by concern
Module-level services instead of the DI container
polylogue/services.pyowns the runtime singletons:The goal here is not "global state everywhere." It is a very small, explicit composition module for the common process-local objects the application always needs.
reset()exists so tests can clear the singleton cache and get a fresh process model.That let me delete
polylogue/container.pyentirely and trimpolylogue/protocols.pyback to the pieces that still make sense as protocols: search, vector search, and rendering. Storage had become simpler to understand as a concrete backend plus repository than as a very large abstract protocol.Branch-aware storage and raw payload preservation
The biggest capability change is in
polylogue/storage/backends/sqlite.py. Schema migrations now add:parent_conversation_idbranch_typeparent_message_idbranch_indexraw_conversationsTogether, those let the archive preserve both conversation-level lineage (continuations, sidechains) and message-level lineage (edited branch siblings). Raw provider bytes are stored alongside the parsed archive data so later parsing/replay can happen from the database itself rather than from the original provider source.
That is an important shift. It means the ingest story becomes:
rather than "read provider export again and hope it is still there."
Added
iter_messages()andget_conversation_stats()to the backend so callers can work at summary/stream granularity without forcing full conversation loads.Unified repository and lazy messages
polylogue/storage/repository.pyandpolylogue/lib/repository.pyare consolidated into oneConversationRepositorymodel that can serve both write and read use cases. New traversal helpers likeget_parent(),get_children(),get_root(), andget_session_tree()make the branching data queryable instead of just stored.On the domain side,
polylogue/lib/messages.pyintroducesMessageCollection, andConversation.messagesis typed as that lazy collection rather than a plain eager list. The idea is:without paying the memory cost of loading the full message list up front unless the caller really needs to. For those cases, the eager path still exists.
This is one of the bigger review points in the branch because it changes the performance model of the domain object deliberately. Most archive consumers iterate; fewer need random indexing or immediate serialization of the whole message list.
Strict role normalization and branch-aware importers
polylogue/lib/roles.pyowns the canonicalRoleenum plusnormalize_role(). Empty strings raiseValueErrorinstead of silently collapsing to a default. That change forces importers to be explicit about missing-role fallbacks, which is healthier than letting invalid role data masquerade as a valid user/assistant event.The provider importers also emit lineage data:
parent_message_provider_idandbranch_indexfrom mapping children arraysparentUuidand marks sidechainssession_metarecordsprepare_ingest()inpipeline/ingest.pyresolves those provider IDs into internal archive IDs and persists them throughConversationRecordandMessageRecord.Acquisition stage and CLI
runI added
polylogue/pipeline/services/acquisition.pyso the pipeline can explicitly acquire and store raw provider payloads before parsing.pipeline/services/ingestion.pythen reads fromraw_conversationsrather than from the provider source directly.This also fits the CLI cleanup. The branch includes the staged
runcommand and removes the deprecatedsyncalias. That is a breaking CLI change, but it aligns the command surface with the actual pipeline stages much better than carrying two names for the same evolving behavior.QA, fuzzing, and corpus-backed tests
This branch also adds a lot of verification around the new behavior:
tests/test_branching.pyandtests/test_branching_pipeline.pytests/test_raw_conversations.pytests/test_pipeline_services_acquisition.pytests/test_cli_run.pytests/test_mcp_server.pytests/fuzz/*plusmutmut.tomlThe fuzzers target the sorts of inputs that become more important when you are preserving raw payloads and doing stricter role/path handling.
Testing
The new storage/pipeline model is exercised by branching, acquisition, raw-conversation, run-command, and MCP suites, plus fuzz coverage for FTS escaping, path handling, JSON importers, and timestamp parsing. Kept corpus-backed fixtures in the mix so the importer changes are not only validated against tiny synthetic samples.
Notes
Three reviewer-sensitive parts of this branch deserve extra attention.
First, confirm that the lazy
MessageCollectioncontract is clear enough for callers that previously assumed a plain list.Second, confirm that
raw_conversationsis storing enough metadata to make replay trustworthy without turning the database into a second, ambiguous source of truth.Third, check the CLI migration from
synctoruncarefully. The intent is to make staged execution more explicit, but it does remove a long-standing command alias.