Skip to content

feat(maintenance): typed planner contract (#1144) - #1157

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/typed-maintenance-planner
May 17, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/typed-maintenance-planner

Conversation

@Sinity

@Sinity Sinity commented May 17, 2026

Copy link
Copy Markdown
Owner

Summary

Replaces the narrow polylogue/maintenance/planner.py scaffold with a
typed planner contract every maintenance / backfill surface (CLI
maintenance, daemon HTTP, MCP, Python API) can rely on. The contract
covers 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 BackfillOperation instances that
carried only a free-form error string, a tuple of target names, and
ad-hoc results dicts. Three concrete consequences:

  • the planner called connection_context(None) and ignored
    config.db_path entirely, so multi-archive tests and downstream
    callers silently hit ambient defaults;
  • every surface that re-emitted the operation (daemon/http.py,
    mcp_write_surface.py, cli_write_surface.py,
    api_write_surface.py) lost the structured reason for the work;
  • unbounded raw failure detail had no place to live, and the
    resume/idempotency child (tracking: backfill replay planner (resurrected from #871) #996) could not name a cursor field.

Solution

  • New polylogue/maintenance/invalidation.py introduces a closed
    InvalidationReason enum (missing, stale_materializer_version,
    source_changed, parser_or_schema_changed,
    config_or_model_snapshot_changed, unknown).
  • polylogue/maintenance/planner.py replaces the scaffold:
    BackfillOperation keeps its existing fields and adds typed
    scope (MaintenanceScope = targets + filter), reason,
    resume_cursor, failure_samples (BoundedFailureSamples capped
    at MAX_FAILURE_SAMPLES = 50 with a truncated flag), and
    metrics. BackfillKind is 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 / BACKFILL aliases stay so
    existing surfaces round-trip unchanged.
  • preview_backfill and execute_backfill thread config.db_path
    through to connection_context; on a raised executor exception the
    planner now populates a single bounded FailureSample instead of
    swallowing the typed shape.
  • polylogue/maintenance/models.py adds
    DerivedModelStatus.invalidated_reason; the planner classifies any
    status without an explicit reason via a small helper
    (_derive_invalidation_reason).
  • polylogue/maintenance/targets.py declares invalidation_keys on
    every 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_embeddings target carries
    message_embeddings / embeddings_meta / embedding_status so the
    embeddings/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

nix develop -c pytest tests/unit/maintenance/test_planner_contract.py -q
# 39 passed in 12.56s

nix develop -c pytest tests/unit/daemon/test_maintenance_endpoints.py tests/unit/api/test_write_surface_contracts.py -q
# 26 passed in 10.02s

nix develop -c pytest tests/unit/maintenance tests/unit/storage -q
# 728 passed in 40.14s

nix develop -c mypy --strict polylogue/maintenance tests/unit/maintenance
# Success: no issues found in 7 source files

nix develop -c devtools verify --quick
# exit_code: 0, total_duration_s: 22.8

The new contract test file pins: every BackfillKind and
InvalidationReason value roundtripping through to_dict; cursor /
metrics / scope roundtrip; BoundedFailureSamples truncation; the
invalidation_keys for each required target; _derive_invalidation_reason
for every reason; and the regression that both preview_backfill and
execute_backfill pass config.db_path to connection_context.

Closes #1144

@coderabbitai

coderabbitai Bot commented May 17, 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 51 minutes and 59 seconds before requesting another review.

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 @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: c8a9fd93-8055-4a0b-a84c-15491445523d

📥 Commits

Reviewing files that changed from the base of the PR and between f4f7ef0 and 9303cd5.

📒 Files selected for processing (11)
  • CHANGELOG.md
  • docs/cli-reference.md
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • docs/verification-catalog.md
  • polylogue/maintenance/invalidation.py
  • polylogue/maintenance/models.py
  • polylogue/maintenance/planner.py
  • polylogue/maintenance/targets.py
  • tests/unit/maintenance/test_planner_contract.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/typed-maintenance-planner

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.

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]>

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

Comment thread polylogue/maintenance/targets.py Resolved
Comment thread polylogue/maintenance/planner.py Resolved
@Sinity
Sinity force-pushed the feature/feat/typed-maintenance-planner branch from 8515be8 to 9303cd5 Compare May 17, 2026 04:42
@Sinity
Sinity merged commit 7a04357 into master May 17, 2026
3 checks passed
@Sinity
Sinity deleted the feature/feat/typed-maintenance-planner branch May 17, 2026 04:42
Sinity added a commit that referenced this pull request May 17, 2026
## 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]>
Sinity added a commit that referenced this pull request May 17, 2026
## 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
@Sinity

Sinity commented Sep 30, 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.

feat(maintenance): typed planner contract (scope, reason, cursor, failures)

1 participant