Skip to content

test: daemon resilience and ingest pipeline correctness (#1735, #1736) - #1741

Merged
Sinity merged 5 commits into
masterfrom
feature/feat/daemon-resilience-ingest-correctness
May 29, 2026
Merged

Sinity merged 5 commits into
masterfrom
feature/feat/daemon-resilience-ingest-correctness

Conversation

@Sinity

@Sinity Sinity commented May 29, 2026 •

Copy link
Copy Markdown
Owner

73 new integration/unit tests. Daemon SIGKILL recovery, WAL checkpoint, memory pressure, large sessions, concurrent safety. Ingest pipeline full replay, edge case corpus, provider contracts with #1617 regression.

Summary by CodeRabbit

  • New Features

    • Enhanced context subcommand support in CLI.
    • Improved error handling for MCP tools with structured error responses.
  • Bug Fixes

    • Adjusted message inclusion behavior: summary detail level now excludes messages, full level includes them.
    • Enhanced embedding fallback logic with better error feedback.
  • Tests

    • Added comprehensive integration tests for daemon resilience and recovery scenarios.
    • Added provider edge-case and contract validation tests.
  • Chores

    • Updated CI/CD workflow to use Nix environment for mutation testing.
    • Updated documentation index and topology metadata.

Review Change Stack

)

Full-pipeline replay, edge case corpus, provider contracts.
68 new tests. Regression coverage for #1617.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0ef35bd0-5c17-4f64-a6fd-c90dc5cc6320

📥 Commits

Reviewing files that changed from the base of the PR and between a96e80f and 25e40fc.

📒 Files selected for processing (14)
  • .github/workflows/mutation-testing.yml
  • README.md
  • devtools/command_catalog.py
  • docs/plans/test-coverage-domains.yaml
  • docs/plans/topology-target.yaml
  • polylogue/cli/click_command_registration.py
  • polylogue/insights/otlp_correlation.py
  • polylogue/mcp/server_context_tools.py
  • polylogue/mcp/server_insight_tools.py
  • tests/integration/test_daemon_resilience.py
  • tests/integration/test_ingest_pipeline_correctness.py
  • tests/unit/insights/test_otlp_correlation.py
  • tests/unit/schemas/test_corpus_edge_cases.py
  • tests/unit/sources/test_provider_contracts.py

📝 Walkthrough

Walkthrough

This PR introduces substantial test coverage expansion alongside targeted production refactoring: core message query logic now uses sort_key epoch timestamps for timing, MCP tools standardize error responses, the CLI context command wires via lazy group dispatch, mutation testing migrates to Nix, and four new test modules comprehensively validate parser contracts, corpus edge cases, ingest pipeline determinism, and daemon failure recovery.

Changes

Production Code Changes and Wiring

Layer / File(s) Summary
Database: Sort_key schema refactoring for message timing
polylogue/insights/otlp_correlation.py, tests/unit/insights/test_otlp_correlation.py
Message and work-event queries now use sort_key (epoch seconds) instead of parsed ISO timestamps. Helpers _query_work_events() and updated _query_messages() fetch message_id, role, sort_key. LLM timing fallback derives assistant turn boundaries from sort_key deltas converted to UTC ISO strings with float parsing safeguards.
MCP Tools: Standardized error envelopes for insight and context operations
polylogue/mcp/server_insight_tools.py, polylogue/mcp/server_context_tools.py
aggregate_sessions returns structured hooks.error_json with invalid_argument code and supported values. find_similar_sessions logs embedding exceptions and falls back to metadata similarity, returning embeddings_unavailable when embedding-only mode lacks fallback. Detail level defaults adjusted: summary disables message inclusion, full enables it.
CLI: Context command group lazy dispatch registration
polylogue/cli/click_command_registration.py
Extended CLI registry to map context subcommand as lazy group. Adds short help entry and _GROUP_ATTRS mapping to dispatch via _LazyGroup mechanism instead of default command dispatch.
Configuration and Metadata: Generated topology and coverage plans updated
README.md, devtools/command_catalog.py, docs/plans/test-coverage-domains.yaml, docs/plans/topology-target.yaml
Removed polylogue/proof/* modules from topology projection, adjusted line-of-code values for CLI/daemon/verification modules, removed verification_reports domain, and updated documentation surface table to reference unified docs/devtools.md.

Comprehensive Test Suite

Layer / File(s) Summary
Unit: Provider contracts and payload validation
tests/unit/sources/test_provider_contracts.py
End-to-end provider contract tests: generated payloads parse correctly, conform to committed schemas, handle unknown fields without crashing, and properly skip bookkeeping records (progress/init/result lifecycle) in Claude Code. Parametrized tests validate all providers with schema conformance and detection accuracy.
Unit: Synthetic corpus edge cases and parser robustness
tests/unit/schemas/test_corpus_edge_cases.py
Parametrized unit tests covering synthetic corpus generation with message-count extremes (1–50 messages), text content presence, varied Claude Code block types, and parser robustness under empty/null content and role-only patterns. Validates that system records and bookkeeping types do not produce message rows.
Integration: Ingest pipeline helpers and database snapshots
tests/integration/test_ingest_pipeline_correctness.py
Shared infrastructure for end-to-end ingest testing: synthetic corpus generation from provider specs, async ingestion via prepare_records, database snapshots capturing row counts (conversations, messages, content blocks), FTS docsize metrics, and distinct content hashes.
Integration: End-to-end ingest determinism and idempotency
tests/integration/test_ingest_pipeline_correctness.py
End-to-end tests validating ingest correctness and determinism: generates and ingests synthetic corpora, asserts presence of key tables, verifies FTS relationships, compares deterministic content-hash reproduction across independent databases, validates idempotency by re-ingesting and asserting unchanged counts/hashes, and confirms per-provider content-block coverage.
Integration: Daemon process lifecycle and introspection utilities
tests/integration/test_daemon_resilience.py
Test infrastructure for subprocess-driven daemon testing: binary discovery via PATH and repo-local fallback, session corpus generation (small sessions and 50K-message variants), SQLite polling for ingestion progress with timeout/retry, FTS trigger enumeration, content hash sampling, blob reference leak detection, WAL measurement, subprocess cleanup with escalating termination, and systemd cgroup availability checks.
Integration: Daemon failure recovery and safety under load
tests/integration/test_daemon_resilience.py
Comprehensive daemon resilience tests: SIGKILL recovery validates FTS triggers, conversation counts, content hash preservation, blob cleanup; WAL checkpoint recovery tests PRAGMA wal_checkpoint(TRUNCATE) with SIGKILL and verifies WAL boundedness; memory-pressure test runs under systemd cgroup with 2GB limit; large session test ingests 50K messages and enforces VmPeak budget; concurrent access test confirms pidfile locking prevents duplicate daemon while status/count commands succeed during ingest.

Build System and Workflow Updates

Layer / File(s) Summary
Workflow: Nix-based mutation testing and freshness verification
.github/workflows/mutation-testing.yml
Migrated mutation-testing workflow from uv/setup-uv to Nix-based execution. Module subset selection now runs inside nix develop . --command bash -c. Added separate "Check freshness budget" step running devtools verify-mutation-freshness --strict within Nix environment. Removed stray merge-conflict artifacts.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

  • Sinity/polylogue#1731: The new daemon resilience integration test suite directly implements the daemon chaos-testing scenarios (SIGKILL recovery, WAL checkpoint recovery, FTS/index checks, memory-pressure and concurrency) described in this issue.

Possibly related PRs

  • Sinity/polylogue#1738: Both PRs modify the same OTLP/session correlation and MCP insight tooling code—polylogue/insights/otlp_correlation.py (message/work-event queries and LLM timing fallback) and polylogue/mcp/server_insight_tools.py (embedding/insight error-handling behavior)—alongside their corresponding tests and workflows.
  • Sinity/polylogue#1206: Both PRs add daemon-focused concurrency/resilience test coverage around the same DB-level invariants—FTS trigger lifecycle recovery and blob/pending_blob_refs correctness—aligning new integration checks with prior concurrency unit test assertions.

Suggested labels

type:test, area:pipeline, area:storage, area:schema, area:qa, area:parser

Poem

🐰 A rabbit's ode to tests and refactored schemes:
With sort_key timestamps in moonlit dreams,
We built resilience in daemon schemes,
Parser contracts flowing like forest streams,
And corpus edges tested to extremes!
The pipeline gleams, the coverage beams! 🌙✨

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/daemon-resilience-ingest-correctness

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

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

Sinity and others added 4 commits May 29, 2026 03:14
SIGKILL recovery, WAL checkpoint, memory pressure, large sessions,
concurrent access safety. 5 tests, all pass in 25s.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
… broken link

- Distinguish transient SQLite errors from permanent ones in daemon helpers
- Fix UnboundLocalError in _table_row_count
- Remove merge conflict markers from mutation-testing.yml
- Fix broken README link to deleted verification-lab.md

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Findings addressed:
- #5: SIGKILL test uses min_count=N_SESSIONS*MESSAGES//2 not 1,
  so kill lands during active ingestion.
- #6: VmRSS replaced with VmPeak (high-water mark) so the memory
  assertion measures peak rather than post-cleanup RSS.
- #7: _wait_for_daemon_ready uses proc.poll() instead of
  os.kill(pid, 0), avoiding PID-reuse TOCTOU. SIGKILL via raw
  PID is kept where proc.poll() guards it.
- #8: _has_systemd_scope() memoised to avoid repeated fork+exec
  at module-load / collection time.
- #9: Dead assert snap1["session_profiles"] >= 0 replaced with
  explicit == 0 assertion documenting daemon-only materialization.
- #10: _parse_code_records (private API) replaced with
  parse_payload("claude-code", ...) in test_provider_contracts
  and test_corpus_edge_cases.
- #11: test_concurrent_access_safety docstring updated to
  document that --no-api mode tests WAL read-during-write, not
  daemon API concurrency.
- #12: _write_corpus_files dead return value removed; callers
  iterate corpus_dir directly.
- #13: topology-target.yaml regenerated via build-topology-projection.
- #14: Stale verification_reports domain entry removed from
  test-coverage-domains.yaml (all referenced files deleted).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Production bugs:
- _query_messages used non-existent columns (id, timestamp, created_at)
  on real messages table; fixed to use message_id, sort_key
- _DETAIL_DEFAULTS swapped summary/full semantics (summary returned
  full messages, full returned nothing)
- Removed SQL injection via f-string column interpolation in
  _query_work_events
- Bare except Exception in embedding fallback path now logs before fall
- aggregate_sessions error format now consistent with other MCP tools
- find_similar_sessions no longer silently falls back to metadata when
  embedding explicitly requested

Integration:
- context CLI command added to _GROUP_ATTRS (same bug as blackboard fix)
- Missing _SHORT_HELP entries for context and correlate
- Duplicate verify-test-coverage-contracts CommandSpec removed
- OTLP test schema updated to match production column names

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@Sinity
Sinity merged commit c99919a into master May 29, 2026
5 of 6 checks passed
@Sinity
Sinity deleted the feature/feat/daemon-resilience-ingest-correctness branch May 29, 2026 02:28
github-actions Bot pushed a commit that referenced this pull request May 29, 2026
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.

1 participant