Repository navigation
feat(maintenance): typed planner contract (#1144) - #1157
Conversation
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more 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 (11)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Replaces the narrow planner scaffold with a typed contract every maintenance/backfill surface depends on: * New `InvalidationReason` enum (polylogue/maintenance/invalidation.py) with the six values from #1144. * `BackfillOperation` gains typed `scope` (`MaintenanceScope`), `reason`, `resume_cursor`, bounded `failure_samples` (`BoundedFailureSamples` capped at 50 with `truncated` flag), and `metrics`. * `BackfillKind` extended with the source-replay / archive-subset / derived-rebuild / index-repair / semantic-rematerialize / config-driven taxonomy; legacy aliases preserved for surfaces still rounding through `BACKFILL`. * `MaintenanceTargetSpec.invalidation_keys` declared for messages FTS, action-event read model, session insights, and embeddings/vector index; new `message_embeddings` target documents the dormant embedding-pipeline invalidation surface (#828). * `DerivedModelStatus.invalidated_reason` carries the typed reason from derived-status modules to the planner without losing structure. * `preview_backfill` / `execute_backfill` thread `config.db_path` through to `connection_context` instead of calling it with `None`; regression test pins the threading. Existing surfaces (CLI maintenance, daemon HTTP, MCP write surface, API write surface) continue to work — every new field is additive with a default. Closes #1144 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8515be8ce4
ℹ️ 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".
8515be8 to
9303cd5
Compare
## Summary Adds the execute half of the typed maintenance planner: a per-target replay loop with idempotent re-runs, durable resume via an on-disk cursor, isolated per-target failure handling, and structured progress reporting. Wires it into `polylogue maintenance run` behind `--operation-id` and `--resume`. ## Problem #1144 landed the typed `BackfillOperation` contract (with `resume_cursor`, `failure_samples`, `metrics`, `scope`) via PR #1157, but no executor used those fields end-to-end. The existing `execute_backfill` path drove `run_selected_maintenance` as one atomic op, which meant: - a kill mid-run could not be resumed without re-running every target; - one failing target aborted the rest; - the `resume_cursor` field on `BackfillOperation` was always `None`. #1147 closes this gap so that maintenance work survives interruptions without re-doing committed targets and without skipping uncommitted ones. ## Solution New module `polylogue/maintenance/replay.py`: - `execute_replay(config, targets, *, operation_id, resume_cursor, dry_run, persist_state, progress_callback)` runs the resolved targets in catalog order, dispatching through a typed `_REPLAY_DISPATCH` table to the existing repair functions (`repair_session_insights`, `repair_action_event_read_model`, `repair_dangling_fts`, `repair_message_type_backfill`, `repair_wal_checkpoint`). - Cursor is the opaque string `target:N` (next target index) with sentinel `done` for completion. `_decode_cursor` clamps invalid values to 0 so a corrupt state file cannot silently skip work. - State is persisted to `<archive_root>/.maintenance-state/<operation_id>.json` after each target. Successful completion clears the file; failure leaves it so resume picks up where the operation stopped. - Per-target raises become typed `FailureSample` entries (`kind=ExceptionClassName`, `locator=target:<name>`); repair functions reporting `success=False` become `RepairReportedFailure`; unsupported targets become `UnsupportedReplayTargetError`. Failure samples remain bounded by `BoundedFailureSamples.from_samples` (`MAX_FAILURE_SAMPLES=50`). - `ReplayProgress` snapshots are passed to an optional callback, including `operation_id`, `target`, `processed/total`, `cursor`, and `in_flight_failures`. CLI `polylogue maintenance run`: - new `--operation-id` (resume by id) and `--resume` (explicit cursor) flags; - per-target progress lines emitted on stderr; - failure-sample block in the post-run summary including `kind`, `locator`, and `message`; - replaces the previous `execute_backfill` call. Topology manifest updated (`docs/plans/topology-target.yaml`) to register `polylogue/maintenance/replay.py`; `render-all` regenerated `docs/topology-status.md` and `docs/verification-catalog.md` to match. Alternatives rejected: persisting state in a new SQLite table — explicitly out of scope for this PR (`polylogue/storage/sqlite/` is owned by another agent worktree). A JSON state file under `archive_root` is sufficient for the AC and inherits free atomic writes via the `tmp + replace` pattern. ## Verification ``` nix develop -c pytest tests/unit/maintenance/ \ tests/unit/cli/test_maintenance_registration.py \ tests/unit/daemon/test_maintenance_endpoints.py -x 77 passed in 10.62s nix develop -c mypy polylogue/maintenance/replay.py \ polylogue/cli/commands/maintenance.py \ tests/unit/maintenance/test_resume.py \ tests/unit/maintenance/test_idempotency.py Success: no issues found in 4 source files nix develop -c devtools verify --quick exit_code=0 (34.55s) ``` AC matrix (issue #1147): - [x] Running `maintenance run --target X` twice converges — pinned by `test_second_run_makes_no_further_changes` (second op reports `affected_rows == 0`). - [x] Kill mid-run + same `operation_id` resumes from stored cursor; no target rebuilt twice, none skipped — pinned by `test_kill_mid_run_resumes_from_persisted_cursor` (asserts exact per-target call counts across the two invocations). - [x] FTS, action events, session insights supported — pinned by `test_supported_targets_cover_ac_required_set`. - [x] Per-target failure isolation, bounded samples — pinned by `test_single_target_failure_does_not_abort_others`, `test_repair_reported_failure_surfaces_as_failure_sample`, `test_failure_samples_remain_bounded`, `test_unsupported_target_is_typed_failure_not_silent`. - [x] Status output includes operation_id / target / processed-total / last cursor / in-flight failures — pinned by `test_progress_callback_fires_per_target`; mirrored by the new stderr progress block in the CLI. - [x] Clean execute, resume after kill, idempotent re-run, single- target failure isolation — covered by the new test files. Closes #1147 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
## Summary Two unrelated test failures had accumulated on master and were inherited into every feature branch's verify run. This PR clears both so the master baseline goes green again. Closes #1180. ## Problem Reproduced on a clean `origin/master` checkout: ``` pytest tests/unit/cli/test_check.py::TestCheckCommandSupplementary \ tests/unit/mcp/test_tool_schema_witness.py ``` 5 failures (4 + 1): - `tests/unit/cli/test_check.py::TestCheckCommandSupplementary` — `test_json_output_with_repair`, `test_repair_with_no_issues_shows_message`, `test_vacuum_with_repair`, `test_json_output_with_repair_and_vacuum_is_machine_safe` all raised `KeyError: 'message_embeddings'` from `polylogue/storage/repair.py:run_safe_repairs`. The `message_embeddings` maintenance target was added to `polylogue/maintenance/targets.py` in #1157 (typed planner contract) with `mode=REPAIR`, but no matching entry was added to `_REPAIR_HANDLERS`. `run_safe_repairs` then iterated every name from `SAFE_REPAIR_TARGETS` and crashed on the missing key. - `tests/unit/mcp/test_tool_schema_witness.py::test_mcp_tool_catalog_matches_witness` failed because the committed witness in `tests/data/witnesses/mcp-tool-schemas.json` still contained the pre-#1168 catalog. PR #1168 added `cost_outlook` to the MCP server (`polylogue/mcp/server_insight_tools.py`); the witness needed regeneration. The current registry exposes 64 tools — both `cost_outlook` and `cost_rollups`. ## Solution - `polylogue/storage/repair.py`: add `repair_message_embeddings()` as a no-op handler that records the embedding rebuild as dormant (#828). The embedding pipeline is daemon-owned and has no synchronous rebuild path, so a `doctor --repair` invocation that touches this target should report dormancy rather than crash. The catalog continues to list the target so planners and surfaces can name the dormant work. - `tests/data/witnesses/mcp-tool-schemas.json`: regenerate from `build_server(role="admin")` per the regeneration recipe in the test module docstring. No production semantics changed: the embedding stub is the smallest change that closes the crash without inventing a new rebuild contract that #828 will eventually own. ## Verification ``` pytest tests/unit/cli/test_check.py::TestCheckCommandSupplementary \ tests/unit/mcp/test_tool_schema_witness.py # => 25 passed in 10.59s (was 5 failed, 20 passed) devtools verify --quick # => "exit_code": 0 ``` Closes #1180
|
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. |
|
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
Replaces the narrow
polylogue/maintenance/planner.pyscaffold with atyped planner contract every maintenance / backfill surface (CLI
maintenance, daemon HTTP, MCP, Python API) can rely on. The contractcovers scope, invalidation reason, resume cursor, bounded failure
samples, and metrics, and lays the substrate every other #996 child
depends on.
Problem
The previous scaffold returned
BackfillOperationinstances thatcarried only a free-form
errorstring, a tuple of target names, andad-hoc
resultsdicts. Three concrete consequences:connection_context(None)and ignoredconfig.db_pathentirely, so multi-archive tests and downstreamcallers silently hit ambient defaults;
daemon/http.py,mcp_write_surface.py,cli_write_surface.py,api_write_surface.py) lost the structured reason for the work;resume/idempotency child (tracking: backfill replay planner (resurrected from #871) #996) could not name a cursor field.
Solution
polylogue/maintenance/invalidation.pyintroduces a closedInvalidationReasonenum (missing,stale_materializer_version,source_changed,parser_or_schema_changed,config_or_model_snapshot_changed,unknown).polylogue/maintenance/planner.pyreplaces the scaffold:BackfillOperationkeeps its existing fields and adds typedscope(MaintenanceScope= targets + filter),reason,resume_cursor,failure_samples(BoundedFailureSamplescappedat
MAX_FAILURE_SAMPLES = 50with atruncatedflag), andmetrics.BackfillKindis extended with the source-replay /archive-subset / derived-rebuild / index-repair /
semantic-rematerialize / config-driven taxonomy from feat(maintenance): typed planner contract (scope, reason, cursor, failures) #1144; the
legacy
REBUILD/REINDEX/RESET/BACKFILLaliases stay soexisting surfaces round-trip unchanged.
preview_backfillandexecute_backfillthreadconfig.db_paththrough to
connection_context; on a raised executor exception theplanner now populates a single bounded
FailureSampleinstead ofswallowing the typed shape.
polylogue/maintenance/models.pyaddsDerivedModelStatus.invalidated_reason; the planner classifies anystatus without an explicit reason via a small helper
(
_derive_invalidation_reason).polylogue/maintenance/targets.pydeclaresinvalidation_keysonevery target the AC lists —
dangling_fts->messages_fts;session_insights-> the five session-insight subkeys;action_event_read_model->action_events+action_events_fts;and a new dormant
message_embeddingstarget carriesmessage_embeddings/embeddings_meta/embedding_statusso theembeddings/vector index invalidation surface is named (no behaviour
change pending feat(daemon): post-ingest embedding task — voyage-4 integration, cost tracking, status surface #828).
Existing surfaces are unchanged at the API boundary — every new field
is additive with a default. Other adapters in scope (
storage/sqlite/,api/,daemon/) were not touched.Verification
The new contract test file pins: every
BackfillKindandInvalidationReasonvalue roundtripping throughto_dict; cursor /metrics / scope roundtrip;
BoundedFailureSamplestruncation; theinvalidation_keysfor each required target;_derive_invalidation_reasonfor every reason; and the regression that both
preview_backfillandexecute_backfillpassconfig.db_pathtoconnection_context.Closes #1144