Skip to content

feat: persist embedding catch-up progress - #1523

Merged
Sinity merged 3 commits into
masterfrom
feature/feat/embedding-catchup-progress
May 25, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/feat/embedding-catchup-progress

Conversation

@Sinity

@Sinity Sinity commented May 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

Persist bounded semantic-embedding backfill progress in the archive and expose the latest catch-up run through polylogue embed status so operators can see what happened after an interruption, OOM, restart, cost stop, or error stop.

Problem

#1503 requires semantic embeddings to become operational on live archives. After the bounded backfill work in #1522, an embedding pass could be stopped safely, but there was still no durable run-level recovery point: aggregate status showed coverage, not the last attempted window, terminal state, stop reason, embedded-message count, or estimated cost.

Solution

  • Add polylogue.storage.embeddings.progress with a local embedding_catchup_runs ledger.
  • Wire polylogue embed backfill to record planned work, per-conversation progress, terminal status, stop reason, errors, embedded messages, and estimated cost.
  • Expose latest_catchup_run from embedding_status_payload and render it in polylogue embed status.
  • Keep the default status path cheap by reporting exact pending-message counts only in --detail mode.
  • Document the operational recovery point in architecture, daemon, and search docs, and update generated topology/proof surfaces.

Ref #1503

Verification

  • pytest -q tests/unit/cli/test_embed.py tests/unit/cli/test_embed_status_fast.py tests/unit/storage/test_embedding_contracts.py tests/unit/storage/test_embedding_stats.py tests/unit/daemon/test_embedding_readiness.py --tb=short — 61 passed.
  • ruff format --check — passed.
  • ruff check — passed.
  • python -m mypy — passed.
  • git diff --check — passed.
  • devtools render-all --check — passed.
  • devtools verify --quick — passed.
  • devtools verify — passed: 9444 passed, 2 xfailed via pytest-testmon.
  • Pre-push devtools verify --quick — passed.

Summary by CodeRabbit

Release Notes

  • New Features

    • Embedding backfill is now bounded, resumable, and persists run progress.
    • Embed status displays latest catch-up snapshot with processed conversations/messages and estimated costs.
    • Added --detail flag for complete cost and pending-message accounting.
  • Documentation

    • Updated embedding documentation covering new backfill resumability and status reporting features.

Review Change Stack

Problem: semantic embedding catch-up can take bounded windows over large archives, but an interrupted run left no durable operator-visible recovery point. Operators could see aggregate coverage, not what the last backfill attempted, where it stopped, or whether it ended by policy, interruption, or failure.

What changed: add an embedding_catchup_runs ledger, wire embed backfill to record planned work, per-conversation progress, terminal state, stop reason, embedded-message counts, errors, and estimated cost, and expose the latest run through embed status. Keep the default status path cheap by reporting pending messages only in --detail mode.

Verification: pytest -q tests/unit/cli/test_embed.py tests/unit/cli/test_embed_status_fast.py tests/unit/storage/test_embedding_contracts.py tests/unit/storage/test_embedding_stats.py tests/unit/daemon/test_embedding_readiness.py --tb=short; ruff format --check; ruff check; python -m mypy; git diff --check; devtools render-all --check; devtools verify --quick; devtools verify.

Ref #1503
@coderabbitai

coderabbitai Bot commented May 25, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, we couldn't start this review because you've used your available PR reviews for now.

Your plan includes 1 review of capacity. Refill in 52 minutes and 21 seconds.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more review capacity refills, 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 trial, open-source, and free plans. In all cases, review capacity refills continuously over time.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 848b12d9-b415-4527-b806-e07bbf86200e

📥 Commits

Reviewing files that changed from the base of the PR and between 7b394c4 and 7f54d4d.

📒 Files selected for processing (2)
  • polylogue/storage/embeddings/progress.py
  • tests/unit/storage/test_embedding_contracts.py
📝 Walkthrough

Walkthrough

This PR adds embedding catch-up run progress tracking by introducing a SQLite-backed ledger that persists backfill execution state. The backfill command now creates a run, records per-conversation outcomes with cost estimates, and finalizes it with terminal status and stop reason. The status payload exposes the latest run metadata, and CLI rendering displays progress summaries to operators.

Changes

Embedding catch-up run tracking

Layer / File(s) Summary
Progress ledger storage contract and implementation
polylogue/storage/embeddings/progress.py
New module with CatchupRunStatus enum, EmbeddingCatchupRunPayload schema, and CatchupRunStart/CatchupRunDelta dataclasses. Implements ensure_embedding_catchup_runs_table, start_embedding_catchup_run, record_embedding_catchup_progress, finish_embedding_catchup_run, and latest_embedding_catchup_run with atomicity and timestamp-based ordering.
Status payload extension and latest-run integration
polylogue/storage/embeddings/status_payload.py
EmbeddingStatusPayload gains optional latest_catchup_run and pending_messages_exact fields. Entry point conditionally queries the catch-up ledger if the table exists and threads latest-run data into payload construction.
Backfill refactoring to use progress ledger
polylogue/cli/commands/embed.py
Backfill imports ledger helpers and refactors the embedding loop to start a run, record per-conversation deltas (embedded, skipped, errored) with cost, and finalize on completion, interruption, or error with appropriate terminal status.
Embedding stats rendering for latest catch-up run
polylogue/cli/shared/embed_stats.py
Adds "Latest catch-up" section rendering run status, conversation/message counts, estimated cost, and stop reason. Pending message display branches on pending_messages_exact to show exact count or suggest --detail mode.
Test coverage for ledger and status payload
tests/unit/storage/test_embedding_contracts.py, tests/unit/cli/test_embed_status_fast.py, tests/unit/cli/test_embed.py
New unit test for ledger persistence and aggregation; status tests validate payload fields and conditional table queries; existing mocks patched to simulate absent ledger.
Documentation updates for catch-up run feature
AGENTS.md, docs/architecture.md, docs/daemon.md, docs/search.md, docs/plans/topology-target.yaml, docs/verification-catalog.md, docs/topology-status.md
Backfill and status commands documented as bounded/resumable with persistent progress; latest catch-up snapshot and --detail mode explained; new embedding_catchup_runs substrate primitive noted; topology files updated.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Sinity/polylogue#1327: Prior backfill orchestration changes (cost-cap and stop-reason behavior) that this PR builds upon with persistent progress tracking.

Suggested labels

type:test, area:pipeline, area:storage, area:cli, area:qa

Poem

🐰 A catch-up runs ledger now keeps,
Each embedding batch's secrets deep,
With progress tracked and cost in sight,
The backfill runs both day and night,
Resumable, durable, and right! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: persist embedding catch-up progress' clearly and concisely summarizes the main change: adding persistence for embedding catch-up progress, which is the core feature added across storage, CLI, and documentation.
Description check ✅ Passed The description covers all required template sections: Summary, Problem, Solution, and Verification with comprehensive details. Changelog and Risks sections are appropriately handled (Changelog noted as referencing issue, Risks section omitted per instructions).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/embedding-catchup-progress

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.

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

ℹ️ 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".

Use insertion order rather than random run_id text as the tie-breaker for catch-up runs that share the same second-level started_at timestamp.

Verification: pytest -q tests/unit/storage/test_embedding_contracts.py::test_embedding_catchup_latest_run_uses_insert_order_for_timestamp_ties tests/unit/storage/test_embedding_contracts.py::test_embedding_catchup_run_ledger_persists_progress tests/unit/cli/test_embed_status_fast.py::test_status_json_includes_latest_catchup_run --tb=short; ruff format --check polylogue/storage/embeddings/progress.py tests/unit/storage/test_embedding_contracts.py; ruff check polylogue/storage/embeddings/progress.py tests/unit/storage/test_embedding_contracts.py; python -m mypy polylogue/storage/embeddings/progress.py tests/unit/storage/test_embedding_contracts.py; git diff --check.

Addresses Codex review on #1523.

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

Actionable comments posted: 2

🤖 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/storage/embeddings/progress.py`:
- Around line 133-156: The UPDATE statement against embedding_catchup_runs can
silently affect 0 rows when run_id is missing; change the code that calls
conn.execute(...) (the block that updates
processed_conversations/embedded_conversations/etc.) to capture the returned
cursor (e.g., cur = conn.execute(...)), check cur.rowcount after executing and
before conn.commit, and raise a clear exception (including the run_id and the
fact the update affected 0 rows) so the process fails fast; apply the same
pattern to the other update/finalization block around the later UPDATE (the
second block referenced at lines ~170-181) so both update operations validate
that a run was actually updated.
- Around line 195-196: The current SQL ORDER BY (ORDER BY started_at DESC,
run_id DESC) can return the wrong "latest" when started_at has second
resolution; update the ORDER BY to use a higher-precision timestamp as the first
tie-breaker and keep run_id as the final tie-breaker (e.g. ORDER BY started_at
DESC, started_at_ns DESC, run_id DESC), or if started_at_ns isn't available use
the higher-precision created_at/started_at_us column instead, ensuring the query
in progress.py that currently contains "ORDER BY started_at DESC, run_id DESC"
is changed to a deterministic ordering as described.
🪄 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: 95b03186-1d15-49f5-92e5-afbee55bf9ea

📥 Commits

Reviewing files that changed from the base of the PR and between 28abc7e and 7b394c4.

📒 Files selected for processing (14)
  • AGENTS.md
  • docs/architecture.md
  • docs/daemon.md
  • docs/plans/topology-target.yaml
  • docs/search.md
  • docs/topology-status.md
  • docs/verification-catalog.md
  • polylogue/cli/commands/embed.py
  • polylogue/cli/shared/embed_stats.py
  • polylogue/storage/embeddings/progress.py
  • polylogue/storage/embeddings/status_payload.py
  • tests/unit/cli/test_embed.py
  • tests/unit/cli/test_embed_status_fast.py
  • tests/unit/storage/test_embedding_contracts.py

Progress and finalization updates now raise if the target run id is absent, so DB/path mismatches cannot silently drop operator recovery state.

Verification: pytest -q tests/unit/storage/test_embedding_contracts.py::test_embedding_catchup_progress_fails_for_missing_run tests/unit/storage/test_embedding_contracts.py::test_embedding_catchup_latest_run_uses_insert_order_for_timestamp_ties tests/unit/storage/test_embedding_contracts.py::test_embedding_catchup_run_ledger_persists_progress tests/unit/cli/test_embed_status_fast.py::test_status_json_includes_latest_catchup_run --tb=short; ruff format --check polylogue/storage/embeddings/progress.py tests/unit/storage/test_embedding_contracts.py; ruff check polylogue/storage/embeddings/progress.py tests/unit/storage/test_embedding_contracts.py; python -m mypy polylogue/storage/embeddings/progress.py tests/unit/storage/test_embedding_contracts.py; git diff --check.

Addresses CodeRabbit review on #1523.
@Sinity
Sinity merged commit b6b4737 into master May 25, 2026
7 checks passed
@Sinity
Sinity deleted the feature/feat/embedding-catchup-progress branch May 25, 2026 00:19
Sinity added a commit that referenced this pull request May 25, 2026
## Summary

Expose semantic-embedding backlog and latest catch-up progress through the daemon `/metrics` Prometheus surface, so operational dashboards can see whether semantic search is ready, catching up, or stalled without running `polylogue embed status` manually.

## Problem

#1503 is about making semantic embeddings operational on live archives. #1523 added a durable catch-up ledger and CLI status visibility, but daemon observability still missed the embedding backlog and latest run state. That meant normal ops tooling could not see the semantic-search readiness gap.

## Solution

- Add bounded `/metrics` series for embedding conversation totals, embedded/pending/failed counts, embedded message count, and coverage percentage.
- Add latest `embedding_catchup_runs` metrics for run status, rebuild mode, planned/processed/embedded/skipped/failed conversations, planned/embedded messages, and estimated cost.
- Keep scrapes bounded by deliberately not calculating exact pending-message counts on every Prometheus scrape.
- Tolerate fresh and partial embedding table sets without 5xx or query failures.
- Extend the metrics endpoint contract tests and internals docs.

Ref #1503

## Verification

- `pytest -q tests/unit/daemon/test_metrics_endpoint.py --tb=short` — 15 passed.
- `ruff format --check polylogue/daemon/metrics.py tests/unit/daemon/test_metrics_endpoint.py` — passed.
- `ruff check polylogue/daemon/metrics.py tests/unit/daemon/test_metrics_endpoint.py` — passed.
- `python -m mypy polylogue/daemon/metrics.py tests/unit/daemon/test_metrics_endpoint.py` — passed.
- `timeout 10 python ... format_metrics(get_config().db_path)` against live archive — completed; reported 7,951 pending embedding conversations, 0 embedded, no catch-up run.
- `devtools verify --quick` — passed.
- `devtools verify` — passed: 9448 passed, 2 xfailed via pytest-testmon.
- Pre-push `devtools verify --quick` — passed.
- GitHub Actions: CodeQL, container builds, Pages Preview, GitGuardian — passed.
Sinity added a commit that referenced this pull request May 25, 2026
## Summary

Daemon embedding convergence now records the same durable
`embedding_catchup_runs` progress ledger as manual `polylogue embed
backfill`. Daemon status also carries and renders the latest embedding
catch-up run, so operator surfaces can explain daemon-driven embedding
work without relying only on Prometheus metrics.

## Problem

#1523 made manual embedding backfill resumability visible, and #1524
exposed that ledger in metrics. The daemon embed stage still ran bounded
batches without starting/updating/finalizing a catch-up run. That made
daemon-driven semantic-search catch-up opaque: a live daemon could be
doing embedding work, but `embed status`, `/metrics`, and daemon status
had no shared run record to explain the current or latest daemon batch.

## Solution

`_embed_conversations_sync` now selects the pending daemon batch up
front, starts an `embedding_catchup_runs` row with planned
conversation/message counts, records per-conversation
embedded/skipped/error progress, and finalizes the run as completed,
stopped, or failed with a stop reason. The legacy unit-test seam where
the helper is called against an empty touched DB remains supported by
treating the provided IDs as the pending window.

`embedding_readiness_info` now includes the latest catch-up run when
present, and `polylogued status` plain output shows the latest embedding
catch-up status/progress inline with the embedding readiness section.

## Verification

- `pytest -q
tests/unit/daemon/test_embedding_readiness.py::test_embed_loop_counts_errors_and_returns_false
tests/unit/daemon/test_embedding_readiness.py::test_embed_loop_halts_when_cost_cap_exceeded
tests/unit/daemon/test_embedding_readiness.py::test_embed_loop_no_cost_cap_processes_all
tests/unit/daemon/test_embedding_convergence_progress.py
tests/unit/daemon/test_metrics_endpoint.py::TestFormatMetricsReadsArchiveState::test_embedding_backlog_and_latest_catchup_state
--tb=short` — 7 passed.
- `pytest -q tests/unit/ui/test_tui.py::test_search_flow --tb=short` —
passed when rerun individually after the first broad run exposed a
transient UI failure.
- `pytest -q
tests/unit/storage/test_scale.py::TestPerformanceBudget::test_get_many_performance_budget
--tb=short` — passed when rerun individually after the first broad run
exposed a transient setup/perf failure.
- `ruff check polylogue/daemon/convergence_stages.py
polylogue/daemon/embedding_readiness.py polylogue/daemon/status.py
tests/unit/daemon/test_embedding_convergence_progress.py
tests/unit/daemon/test_embedding_readiness.py` — passed.
- `python -m mypy polylogue/daemon/convergence_stages.py
polylogue/daemon/embedding_readiness.py polylogue/daemon/status.py
tests/unit/daemon/test_embedding_convergence_progress.py
tests/unit/daemon/test_embedding_readiness.py` — passed.
- `devtools verify --quick` — passed.
- `devtools verify` — passed: 9,454 passed, 2 xfailed under
pytest-testmon.

Ref #1503
@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.

1 participant