Skip to content

feat(canary): classify reindex diffs against declared index deltas - #4007

Merged
Sinity merged 4 commits into
masterfrom
feature/reindex/0x7nh-canary-differ
Aug 19, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/reindex/0x7nh-canary-differ

Conversation

@Sinity

@Sinity Sinity commented Aug 19, 2026 •

Copy link
Copy Markdown
Owner

Summary

The reindex canary already rebuilds a bounded sample into an inactive --no-promote
generation and row-diffs it against the active index. What it could not do was say
which of those differences the reindex is supposed to make: run_reindex_canary
called the comparator with no expected-difference input at all, so every row came
back unexpected, and the only way to get an expected classification was a
hand-written review manifest. This wires the classifier to the declarations the
repo already ships — IndexDeltaDeclaration.expected_canary_changes in
storage/sqlite/lifecycle.py — so the canary derives its own expected signatures
from the deltas crossed between the active generation's schema version and the
version the candidate was built at.

Problem

Two concrete gaps, both visible in the source rather than inferred:

  1. run_reindex_canary invoked compare_reindex_generations(...) without the
    expected= argument. expected had exactly one caller in the whole tree — the
    test suite. Every production canary difference was therefore unexpected by
    construction, which makes an unexpected count uninformative: it counts the whole
    diff, not the surprising part of it.
  2. _validate_expected_review_authorities sourced a delta's comparable table scope
    from declaration.operations. A SEMANTIC_REPARSE declaration ships no
    fast-forward SQL by design — it routes to a full rebuild instead — so that set is
    empty for all 19 semantic declarations currently in the table. Every one of them
    was structurally unable to authorize a difference, failing with "delta N does not
    declare comparable table scope". The one declaration that could approve anything
    was v44, and only because it is SHAPE_FORWARD_TARGETED_REPROCESS and so carries
    operations. The class of change a reindex exists to make was exactly the class
    that could never be marked expected.

Solution

polylogue/storage/sqlite/lifecycle.py

  • index_delta_declarations_between(source, target) returns the declarations crossed
    by a version pair. Deliberately unlike index_fast_forward_plan, it does not
    require contiguity or fast-forward eligibility, because the canary exists for the
    semantic-reparse case where no plan is available.
  • undeclared_index_delta_versions(source, target) names crossed versions that ship
    no declaration. Such a version authorizes nothing, so its effects land in the
    unexpected bucket; naming it keeps that a stated gap instead of an unexplained pile
    of rows.

polylogue/maintenance/reindex_canary.py

  • New DeltaExpectation: the derived counterpart to the hand-authored
    ExpectedDifference. A declaration is written before the rebuild runs and cannot
    know which rows it will touch, so it states a shape — table, operations, permitted
    columns, and (for a targeted reprocess) the session scope — rather than an exact
    row identity.
  • index_delta_expectations(source, target) builds those from the packaged
    declarations. Only declarations claiming semantic work contribute.
  • compare_reindex_generations accepts delta_expectations and records
    source_index_version / undeclared_delta_versions under a delta_coverage key
    in the receipt. The comparison fingerprint is untouched, so it stays independent of
    classification, as before.
  • run_reindex_canary reads the active generation's own PRAGMA user_version and
    derives the expectations from it. The classifier input comes from the archive under
    test, not from ambient configuration.
  • The review validator now also reads table scope from a declaration's
    expected_canary_changes, which is the only surface a semantic delta declares.

Matching stays strict, which is the point. changed_columns must be a non-empty
subset of the declared columns, so a row that also changed an undeclared column is
unexpected in whole and never partly waived; a declared reprocess scope narrows by
origin and session id. These are the same rules the human review path already
enforced, applied automatically at comparison time.

Rejected alternative: loosening ExpectedDifference to allow an absent identity
instead of adding a second type. That would have weakened the manifest path — whose
exact-identity requirement is deliberate — to serve the derived path.

Verification

devtools test tests/unit/maintenance/test_reindex_canary.py
  => 78 passed in 30.64s

devtools test tests/unit/maintenance/test_reindex_campaign.py \
  tests/unit/daemon/test_maintenance_endpoints.py \
  tests/unit/infra/test_pathology_zoo.py \
  tests/unit/storage/test_incremental_rebuild_equivalence.py
  => 30 passed, 1 xfailed in 40.41s

devtools test tests/unit/storage/test_index_fast_forward_lifecycle.py
  => 17 passed in 2.17s

devtools test tests/unit/cli/test_reindex_canary_cli.py
  => 32 passed in 54.08s

devtools verify --quick
  => mypy ... ok / render all ... ok / lab policy schema-versioning ... ok  (exit 0)

The 1 xfailed is test_real_inactive_rebuild_and_canary_preserve_active_and_reject_parser_as_duplicate,
the pre-existing polylogue-tjr4z red. It is unaffected by this change: its archive is
built at the current INDEX_SCHEMA_VERSION, so source and target versions are equal and
no expectations are derived.

Red-first evidence

94e51ec2f commits the tests with the table-scope bug still present.
test_semantic_reparse_delta_can_authorize_a_reviewed_difference fails there with:

UnclassifiedCanaryDiffError: expected canary authority does not cover the reviewed
difference: delta 41 does not declare comparable table scope

16677f8c1 is the fix.

Anti-vacuity

polylogue-tjr4z exists because a canary once reported unexpected_count == 0 where a
real diff was required, so a classifier that quietly absorbs differences is the specific
failure mode to guard. Three tests plant real read-model divergence against a delta that
declares a neighbouring signature:

  • test_declared_delta_does_not_swallow_a_planted_undeclared_change — a changed
    blocks.text and a changed session_profiles.tags_json, against a delta declaring
    session_profiles.message_count. Both stay unexpected; expected_count == 0.
  • test_declared_delta_cannot_absorb_a_row_that_also_changed_an_undeclared_column —
    one row changing a declared and an undeclared column stays unexpected in whole.
  • test_declared_delta_scope_does_not_reach_another_origin — a scoped delta classifies
    its own origin and leaves the identical change on another origin unexpected.

This covers tjr4z's class (a classifier must not report zero where a real diff exists).
It does not diagnose tjr4z's own root cause, which is about that test's campaign corpus
producing no divergence; that bead stays open.

Fixture demo

Run against two real canonical index.db generations (never the live root), active at
v43, candidate at current code, with one planted session_profiles.tags_json change and
a sessions.title_ref change on two origins:

{
  "delta_expectations": [
    {"version": 44, "table": "sessions",
     "columns": ["title_ref", "title_confidence"], "origin": "codex-session"}
  ],
  "delta_coverage": {"source_index_version": 43, "undeclared_delta_versions": []},
  "summary": {"difference_count": 4, "expected_count": 1,
              "unexpected_count": 3, "unclassified_count": 0,
              "counts_by_table": {"session_profiles": 2, "sessions": 2}}
}

The one expected row is sessions{origin=codex-session, native_id=alpha} changing
title_ref, rationale index delta 44: declared canary change for sessions.title_ref/title_confidence. The same column change on chatgpt-export:beta
stays unexpected, because v44's reprocess scope names only codex-session — the
discrimination the classifier exists to make.

Read this demo as a mechanism check, not as the real v44 signature. Both fixture
generations are built from the current DDL and the "active" one is then stamped
user_version = 43 — a state no real archive reaches, since a genuine pre-v44 index has
no title_ref column at all. _compare_table compares only the columns present in
both databases, so on a real pre-v44 index this same rebuild surfaces as schema-level
column-added rows (currently unexpected) rather than as the row-level changed
signature v44 declares. What the demo does establish is that the derivation, the
column-subset rule, and the origin-scope narrowing all work on real read models; what it
does not establish is that v44's declared signature matches the diff shape a real v43
archive produces. Three advisory gaps of this kind are recorded on polylogue-0x7nh
and are not in this PR's scope.

Bead disposition matrix

Bead Disposition Basis
polylogue-0x7nh partial AC 1 was already satisfied before this PR (selection + no-promote rebuild + row-diff of sessions/messages/blocks/session_links/derived). This PR supplies AC 2's mechanism: a derived expected/unexpected classifier bound to the packaged delta declarations, with a machine-readable receipt carrying delta coverage. AC 2's data is not complete — only v44 currently declares expected_canary_changes, so the remaining 18 semantic declarations contribute no signatures yet and their effects will surface as unexpected. AC 3 (report attached to the 818fy runbook) and AC 4's live red→green canary loop require the live run, which happens in the operator window, not here. Successor polylogue-ox2iz ("execute and classify the canary changelog report") is open and carries the residual.

Deliberately not done: authoring expected_canary_changes for the remaining 18
semantic declarations. Each needs the delta's own semantics read and a signature
decided, and the error directions are asymmetric — an under-declared delta is safe
(its rows show as unexpected and get reviewed) while an over-declared one silently
waives a real bug. Writing 18 speculative signatures to satisfy a count would invert
the property this instrument exists for. The carrier is in place and each can now be
added with evidence under polylogue-ox2iz.

Ref polylogue-0x7nh
Ref polylogue-tjr4z
Ref polylogue-ox2iz

🤖 Generated with Claude Code

https://claude.ai/code/session_01HWcPJJJvuF25CqVwTFgSQC

Sinity and others added 2 commits August 19, 2026 02:24
… change

The reindex canary classifier derives expected-difference signatures from
the crossed index delta declarations. A SEMANTIC_REPARSE declaration ships
no fast-forward SQL by design, so sourcing comparable table scope only from
its operations leaves every semantic delta unable to approve anything --
the exact class of change a reindex exists to make.

Ref polylogue-0x7nh

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWcPJJJvuF25CqVwTFgSQC
@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 Aug 19, 2026 •

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 759b122f-7153-4185-a84f-9c8b147a9fa4


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.

…tions

The shared-runner CLI test stubs compare_reindex_generations with a fixed
keyword signature, so adding delta_expectations to the real comparator broke
it with a TypeError. Accept the provenance keywords the same way the three
maintenance-suite stubs do.

Ref polylogue-0x7nh

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWcPJJJvuF25CqVwTFgSQC
@Sinity
Sinity merged commit 4711220 into master Aug 19, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the feature/reindex/0x7nh-canary-differ branch August 19, 2026 07:57
Sinity added a commit that referenced this pull request Aug 19, 2026
…find (#4027)

## Summary

The canary's anti-vacuity assertion failed because **the corpus side
moved, not the comparison**. A faithful rebuild of the campaign corpus
now reproduces the active index exactly, so there was no divergence left
for the canary to surface. The `> 0` assertion and the differ are both
untouched; instead the fixture now creates the authority drift it claims
to detect.

## Problem


`test_real_inactive_rebuild_and_canary_preserve_active_and_reject_parser_as_duplicate`
asserted `canary.comparison.unexpected_count > 0` and got 0.

The ledger asked which side moved. Dumping both sides inside the fixture
answers it unambiguously — the canary compared everything it was
supposed to and found nothing:

```
counts_by_table: {}
differences:     ()
missing_tables:  ()   missing_columns: ()
compared_tables: (... 'dirs', 'sessions', 'thread_sessions', 'web_content_constructs' ...)

ACTIVE    raw_revision_applications: 20     raw_revision_heads: 18
CANDIDATE raw_revision_applications: 20     raw_revision_heads: 18
```

Identical row counts on both tables, zero differences across every
compared table, nothing missing. The comparison is reading the
candidate's real read model perfectly well — there is simply nothing to
report. The divergence the assertion depended on was an incidental
rebuild discrepancy that has since been fixed, which makes the assertion
vacuous rather than wrong.

This is the class the lead flagged from #4007's review advisories
(fixture not genuinely divergent), and it lands on the fixture rather
than on the comparison — so per that direction, the fix is to make the
fixture genuinely divergent.

## Solution

Before the canary runs, perturb the **active** index's accepted
authority semantically: reverse one
`raw_revision_heads.accepted_content_hash`, and flip one
`raw_revision_applications.decision` to `superseded`.

The column choice is the load-bearing part.
`reindex_canary._VOLATILE_COLUMNS_BY_TABLE` deliberately ignores
`decided_at_ms` (and `decision_id`) on exactly these two tables, with
the comment that their *semantic decision tuple* stays compared "so
accepted/superseded/rejected authority drift stays visible". A timestamp
nudge would therefore be correctly ignored and prove nothing; perturbing
the accepted tuple is precisely the drift class the canary exists to
surface.

**This strengthens the anti-vacuity property rather than relaxing it.**
The assertion previously rode on an accidental discrepancy; it now rides
on a divergence the test declares itself. The paired assertion —
`set(counts_by_table) == {"raw_revision_applications",
"raw_revision_heads"}` — passes because the canary reported *that
specific drift and nothing else*, which a fabricated summary could not
produce. That is the mutation the docstring names.

The untouched-active digest is re-anchored immediately after the
deliberate edit, so the post-canary `_digest(root / "index.db") ==
active_before` assertion still means "the canary did not write to the
active index" instead of silently absorbing it.

I did not weaken the `> 0` assert, and I did not touch `_compare_table`
or the delta-expectation classification #4007 introduced.

## Verification

- `devtools verify --quick` — all ten steps ok.
- `devtools test tests/unit/maintenance/test_reindex_campaign.py` — **4
passed**, with the `xfail` marker removed in the same commit (the file
previously reported `1 xfailed`).
- **Red→green**: on `origin/master` the test fails `assert 0 > 0` under
`--runxfail`; with the drift in place it passes, and reverting only the
drift restores the identical failure.
- Full `devtools verify` deliberately skipped per the lane gate policy
for bootstrap-predicted lanes; focused + quick is the gate and the merge
receipt is recorded centrally.

## Bead disposition matrix

| Bead | Disposition | Evidence | Residual |
| --- | --- | --- | --- |
| `polylogue-tjr4z` | **satisfied** | Bisected by dumping both sides:
comparison healthy, corpus no longer divergent. Fixture made genuinely
divergent on the two named tables; `> 0` assert and differ untouched;
xfail removed. | None. The three #4007 advisories on `polylogue-0x7nh`
(intersection-only column diffs, the "v43" fixture carrying current DDL,
row-declarations waiving schema diffs) are untouched and remain that
bead's scope. |

Ref polylogue-tjr4z
<!-- polylogue-pr-scope:v2
{
  "assigned_beads": [
    "polylogue-tjr4z"
  ],
  "dispositions": [
    {
      "bead_id": "polylogue-tjr4z",
      "disposition": "satisfied",
      "evidence": [
        {
          "kind": "test",
"ref":
"tests/unit/maintenance/test_reindex_campaign.py::test_real_inactive_rebuild_and_canary_preserve_active_and_reject_parser_as_duplicate"
        },
        {
          "kind": "command",
"ref": "fixture dump: differences=() counts_by_table={} with identical
20/18 rows on both sides"
        }
      ],
      "successors": []
    }
  ],
  "mutated_beads": [],
"scope_digest":
"9c92a3c1cba9c9afed54288550ca0001e84efb390f10fc47b17483b28463d6f0",
  "scope_kind": "bead",
  "version": 2
}
-->
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