Skip to content

fix: Report unmeasurable embedding coverage and stop dropping vectors on read - #5048

Merged
Sinity merged 2 commits into
masterfrom
fix/embeddings-tier-integrity
Sep 14, 2026
Merged

Sinity merged 2 commits into
masterfrom
fix/embeddings-tier-integrity

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Closes polylogue-g827i and polylogue-go581, both P0. The index derived
identity moves, so this must land before the rebuild starts, never during one.

CLAUDE.md classes embeddings.db as "expensive to rebuild" and instructs
"preserve reusable vectors before replacement". One of these defects corrupted the
decision about whether the vectors survived; the other destroyed them from a read
path.

Bug 1 — a complete vector set reported as none

ArchiveEmbeddingStateProbe now separates three states that were previously two:

  • measured — counts present;
  • measured absence — no embeddings tier at all, still a genuine none, so a
    truly unembedded archive still gets its backfill prescription;
  • unmeasurable — sqlite-vec would not load, the refs schema predates message
    semantics, or the inspection timed out. Retains its reason.

An unmeasurable payload carries status: "unknown", coverage_measurable: false,
coverage_unmeasurable_reason, and None — never 0 — for embedded/pending
sessions, embedded messages, and coverage percent. next_action becomes
coverage_unmeasurable, not the paid drain_backlog.

Consumers were updated so that None renders as unknown rather than being
reformatted into a zero: cli/commands/status.py, cli/shared/embed_stats.py,
cli/shared/helper_summary.py (which would otherwise have crashed on :,
formatting), and readiness/capability.py, which now reports its already-existing
UNKNOWN state with a caveat.

Bug 2 — a semantic query could DROP every stored vector

_reconcile_vec0_dimension is deleted. _assert_vec0_dimension raises a typed
SchemaSkewError naming both dimensions.

Destruction survives only as an explicit operator route,
drop_vec0_for_dimension_change — which also clears the stale-dimension
message_embeddings_meta rows, because otherwise the archive keeps
CHECK(dimension = 1024) and re-embedding fails outright. That is the trap the
bead described.

Is it reachable from a pre-build check? No — traced specifically. No status,
readiness, conservation, census, preflight, or daemon-convergence path constructs
a writable provider and issues a semantic query: status surfaces read SQL
directly, and every operation/daemon read binds a snapshot connection where
_ensure_tables returns immediately. The reachable callers are genuine semantic
query/upsert routes. So an innocuous pre-build check could not have destroyed the
vectors — but polylogue find "text" after a dimension edit would have.

embedding_preservation under rebuild conditions — verified, not assumed

  • Extension unavailable: _connect raises loudly rather than silently
    producing an empty copy — but preservation is impossible until sqlite-vec
    loads, which the rebuild plan must account for.
  • Dimension changed: vectors are copied regardless of dimension, so nothing is
    lost on disk; _validated_metadata then refuses to restore rows whose dimension
    differs, reported as enumerated RestoreMiss entries rather than a silent drop.
  • Schema version moved: opens with validate_schema=False, tolerates absent
    tables, accepts the legacy embedding_input_hash column.

Verdict: it preserves; its restore leg is dimension-pinned by design.

Anti-vacuity

Bug 1: restoring the None → 0 collapse turns status back to none, counts to
0, next action to drain_backlog — red. The companion test goes red if the
tier-absent probe is marked unmeasurable (guarding against over-correction).

Bug 2: proved by counting stored vectors after the read, not by asserting a
call is absent. Restoring the DROP makes it red twice — the read stops raising,
and the post-read count falls to 0 — including across three repeated reads,
since there was never a once-per-process guard.

Schema identity

status_payload.py is out; sqlite_vec_runtime.py is IN. Both identities
computed rather than inferred: index 27c38bbe… → eb9eef48…, ops unchanged.
EMBEDDINGS_SCHEMA_VERSION stays 6; no DDL edited.

Same-shape defects found, deliberately not fixed

Sharpest: storage/embeddings/support.py::is_missing_table_error classifies
no such module: vec0 as a missing table, so an extension-load failure becomes
a measured 0
. The fix was implemented and then reverted —
test_embedding_stats.py::test_read_embedding_stats_sync_treats_missing_vec_module_as_optional
actively asserts that zero, and correcting it properly needs an unknown-capable
EmbeddingStatsSnapshot, which is a design change beyond these two beads.

Also: preflight.py:93-95 reports a missing database as an empty archive with no
backfill needed; embedding_stats.py falls back to embedded_sessions=0 while
the adjacent pending_sessions honestly substitutes a different measurement; and
four timeout coercions in status_payload.py reset stale_messages/
missing_provenance to 0 under a flag named for a different field.

Verification

devtools test <8 embeddings/readiness/status selectors>  PASSED
  receipt 20260914T065720Z-focused-test-1524813-4e426b6e
devtools verify --quick                                  exit 0

Two failures in the wider selection reproduce unchanged at base f84dd3b0c under
stash — including test_direct_status_keeps_source_ops_and_embeddings_on_the_pinned_snapshot
(asserts 0, gets 1 — an over-claim in the same tier, worth its own look).
Inherited, left unfixed.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Sinity and others added 2 commits September 14, 2026 08:59
Problem: `_reconcile_vec0_dimension` executed `DROP TABLE IF EXISTS
message_embeddings` whenever the stored vec0 dimension differed from the
configured one. It runs from `_ensure_tables`, which every semantic query
enters (`sqlite_vec_queries.py:174`) with no once-per-process guard, so
setting `embedding_dimension: 512` on an archive embedded at 1024 and
running one `polylogue --semantic` query physically destroyed every stored
vector. `message_embeddings_meta` survived carrying
`CHECK(dimension = 1024)`, leaving the archive with neither the vectors nor
a working path to recreate them. Pre-existing since #915 and never
exercised: `grep -rn "_reconcile_vec0_dimension" tests` had no matches.

Solution: a read never destroys the expensive-to-rebuild tier.
`_assert_vec0_dimension` raises a typed `SchemaSkewError` naming both
dimensions and the two ways forward. Discarding the vectors stays available
but only as a deliberate operator action, `drop_vec0_for_dimension_change`,
which also clears the stale-dimension `message_embeddings_meta` rows so
re-embedding at the new dimension can actually succeed.

Verification: devtools test tests/unit/storage/test_vec_dimension_refusal.py
tests/unit/storage/test_vec.py -> PASSED. The new tests count the stored
vectors after the read rather than asserting the absence of a call.
Anti-vacuity: restoring the DROP branch makes them red twice -- the read
stops raising and the post-read vector count falls to zero.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Problem: `_authoritative_archive_embedding_state` returned `None` whenever
it could not inspect readiness -- including when `try_load_sqlite_vec`
failed, which swallows every exception -- and the caller converted that into
`embedded_sessions = 0, pending_sessions = total`. An archive holding a
complete, reusable vector set therefore reported `status: none` and
prescribed a paid Voyage backfill. `embeddings.db` is the expensive-to-
rebuild tier whose reusable vectors must be preserved before replacement,
so this corrupts exactly the decision that gates a from-scratch rebuild.

Solution: three states that are never collapsed. `ArchiveEmbeddingStateProbe`
distinguishes measured counts, a measured absence (no embeddings tier at
all, still a genuine `none`), and unmeasurable -- the extension would not
load, the refs schema predates message semantics, or the inspection timed
out -- retaining the reason in the same spirit as a retained unknown-outcome
reason. An unmeasurable payload carries `status: unknown`,
`coverage_measurable: false`, its reason, and `None` (never `0`) for
embedded/pending sessions, embedded messages and coverage percent, and its
next action is `coverage_unmeasurable` rather than `drain_backlog`. The CLI
status lines, embed stats, helper summary and capability readiness render
it as unknown instead of formatting the absent counts as zero; readiness
reports the existing `UNKNOWN` state with a caveat.

Verification: devtools test on the embeddings and consumer selections ->
PASSED; devtools verify --quick -> exit 0. `devtools schema closure` reports
status_payload.py `out` of the derived closure and sqlite_vec_runtime.py
`IN`; the computed index identity moves 27c38bbe... -> eb9eef48..., ops
unchanged, so the archive must reconverge and this must land before a
rebuild starts. EMBEDDINGS_SCHEMA_VERSION is unchanged at 6 (no DDL edit).
Anti-vacuity: restoring the `None` -> `embedded_sessions = 0` collapse makes
the new tests red -- status returns to `none`, the counts to `0`, and the
next action to the paid `drain_backlog` prescription; marking the
tier-absent probe unmeasurable makes the companion test red instead.

Residual: two failures on this selection reproduce unchanged at the base
commit f84dd3b and are inherited, not introduced here --
test_daemon_status.py::test_direct_status_keeps_source_ops_and_embeddings_on_the_pinned_snapshot
and test_status.py::...malformed_convergence_debt_json_is_explicitly_unavailable.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
@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 Sep 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 30 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 84c7da98-216e-4f48-a3cc-69d63314e501

📥 Commits

Reviewing files that changed from the base of the PR and between d995eb4 and 15f2502.

📒 Files selected for processing (9)
  • polylogue/cli/commands/status.py
  • polylogue/cli/shared/embed_stats.py
  • polylogue/cli/shared/helper_summary.py
  • polylogue/readiness/capability.py
  • polylogue/storage/embeddings/status_payload.py
  • polylogue/storage/search_providers/sqlite_vec_runtime.py
  • tests/unit/cli/test_embed_status_fast.py
  • tests/unit/storage/test_embedding_freshness_invariant.py
  • tests/unit/storage/test_vec_dimension_refusal.py

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.

@Sinity
Sinity merged commit 981e268 into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the fix/embeddings-tier-integrity branch September 14, 2026 07:43
Sinity added a commit that referenced this pull request Sep 14, 2026
## Summary

Classifies an unloadable `vec0` extension as **unmeasurable** embedding
coverage instead of a measured zero, and carries that third state —
`None`, never `0` — through `EmbeddingStatsSnapshot`, `ArchiveStats`,
the vec provider's stats route, the CLI, MCP and the TUI.

Closes `polylogue-32ng2`.

Context: `polylogue-go581` and `polylogue-g827i` were already fixed on
master by #5048 (verified against current source, see Residuals). This
PR fixes the underlying predicate and the two consumers #5048 did not
route through the probe.

## Problem

`polylogue/storage/embeddings/support.py:is_missing_table_error` folded
`"no such module: vec0"` in with a genuinely absent relation.

Concrete input: an `embeddings.db` holding a complete, reusable vector
set, opened where the `sqlite-vec` extension cannot load (no
`sqlite_vec` wheel for the interpreter, a stripped deployment, an
`enable_load_extension` refusal).

Every `SELECT ... FROM message_embeddings` then raises `no such module:
vec0`, the predicate swallowed it, and each of the eight call sites in
`support.py` returned `0` / `None` / `[]`.

Wrong observable outcome, at the two consumers that bypass
`ArchiveEmbeddingStateProbe`:

- `storage/repository/vectors/repository_vectors.py` published
`ArchiveStats(embedded_sessions=0, embedded_messages=0,
pending_embedding_sessions=<whole corpus>)`, and
`ArchiveStats.embedding_readiness_status` answered `"none"`.
- `storage/search_providers/sqlite_vec_queries.py:get_embedding_stats`
published `{"embedded_messages": 0, "pending_sessions": <whole
corpus>}`.

`embeddings.db` is the *expensive to rebuild* tier: its vectors are
re-purchased from a paid provider, never replayed from source. An
archive whose vectors are intact therefore reported as un-embedded and
prescribed a full paid Voyage re-embed. An extension-load failure means
**cannot tell**, not **nothing embedded**.

Two tests enshrined the behavior:
`test_read_embedding_stats_sync_treats_missing_vec_module_as_optional`
and
`TestEmbeddingStatsLockedConnection::test_missing_vec_module_treated_as_optional`
both raised `no such module: vec0` and asserted the counts were `0`.

## Solution

- `EmbeddingCoverageUnmeasurableError` (new, in `support.py`) carries
"the tier could not be inspected" out of the optional-read helpers with
its reason retained. `_classify_optional_error` is the single
classification point all eight handlers now route through.
- `is_missing_table_error` narrows to genuine absence.
`is_unmeasurable_coverage_error` matches `no such module`.
- **`no such column` deliberately stays classified as absence.** The
audit proposed reclassifying it too; the first run of these tests
refuted that. These readers use it as optional-feature detection against
older derived shapes — `embedding_status.message_count_embedded` on the
repo's own fixture — where the relation is present and the missing
column genuinely means the feature is not recorded. Reclassifying it
turned a healthy fixture unmeasurable.
- `EmbeddingStatsSnapshot` / `ArchiveStats` type the coverage counts
`int | None` and carry `coverage_unmeasurable_reason`.
`read_embedding_stats_sync/async` convert the typed error into a
snapshot with `None` counts.
- `ArchiveStats.embedding_readiness_status` answers `"unknown"` (not
`"none"`); `embedding_coverage` and `retrieval_ready` return `None`;
`to_dict` publishes `embedding_coverage_measurable` and the reason.
- Surfaces render the unknown rather than a number: the CLI stats line
prints `Embeddings: unknown -- coverage could not be measured
(<reason>)`, the TUI dashboard shows `?`, and MCP emits `None`.
`_payload_from_stats` now honours the snapshot's own unmeasurable
verdict (the fast route builds no probe), so the status payload reaches
`status: "unknown"` / `next_action: coverage_unmeasurable` on that route
too.

## Verification

```
devtools test tests/unit/storage/test_embedding_stats.py \
  tests/unit/storage/test_embedding_contracts.py \
  tests/unit/storage/test_vec_dimension_refusal.py \
  tests/unit/storage/test_embedding_freshness_invariant.py \
  tests/unit/cli/test_embed_status_fast.py \
  tests/unit/archive/test_archive_stats.py
devtools test: PASSED exit=0 diagnosis=pytest_passed
  receipt=.cache/verify/runs/20260914T184344Z-focused-test-3816044-487e16b2/run.json

devtools verify --quick      all 17 gates ok
```

**Anti-vacuity, verified by reverting and observing the failure.**
Restoring the pre-fix predicate (`is_unmeasurable_coverage_error` →
`False`, `no such module: vec0` back in `is_missing_table_error`):

```
tests/unit/storage/test_embedding_stats.py::test_read_embedding_stats_sync_reports_missing_vec_module_as_unmeasurable
>       assert stats.embedded_sessions is None
E       assert 0 is None
E        +  where 0 = EmbeddingStatsSnapshot(embedded_sessions=0, embedded_messages=0, pending_sessions=0, ...,
                      coverage_unmeasurable_reason=None).embedded_sessions
```

Removing the `unknown` branch from
`ArchiveStats.embedding_readiness_status`:

```
tests/unit/storage/test_embedding_stats.py::test_archive_stats_never_renders_unmeasurable_coverage_as_none_status
>       if self.embedded_messages <= 0:
E       TypeError: '<=' not supported between instances of 'NoneType' and 'int'
```

## Schema closure

`devtools schema closure` on every touched file:

| file | closure |
| --- | --- |
| `polylogue/archive/stats.py` | **IN** |
| `polylogue/storage/embeddings/embedding_stats.py` | **IN** |
| `polylogue/storage/embeddings/models.py` | **IN** |
| `polylogue/storage/embeddings/support.py` | **IN** |
| `polylogue/storage/search_providers/sqlite_vec_queries.py` | **IN** |
| `polylogue/storage/embeddings/status_payload.py` | out |
| `polylogue/cli/query_stats.py` | out |
| `polylogue/mcp/payloads.py` | out |
| `polylogue/storage/repository/vectors/repository_vectors.py` | out |
| `polylogue/ui/tui/screens/dashboard.py` | out |

**Five files are IN the derived schema closure, so the derived identity
moves: this must land before a fresh rebuild starts, never during one.**

## Residuals

- **`polylogue-go581` and `polylogue-g827i` are already fixed on
master** by #5048 (`981e268d4`, landed today), which both beads' text
predates. `_reconcile_vec0_dimension` and its `DROP TABLE IF EXISTS
message_embeddings` are gone; `_assert_vec0_dimension` raises a typed
`SchemaSkewError` naming both dimensions, and discarding vectors is now
only reachable through the explicit `drop_vec0_for_dimension_change`
maintenance route. `ArchiveEmbeddingStateProbe` already separates
measured / measured-absence / unmeasurable. Neither is re-fixed here.
- `g827i` and `32ng2` are **not duplicates**: same defect shape,
different layers. `g827i` was the *status payload*, fixed at the probe;
`32ng2` is the *predicate underneath it* plus the two consumers that
never call the probe.
- `no such column` remains classified as absence, with the refuting
evidence recorded in the predicate's docstring. If a caller later needs
it to mean drift, it needs a per-call-site distinction, not a global
reclassification.
- `docs/plans/sqlite-degradation-baseline.json`: the four `support.py`
anchors are re-fingerprinted 1:1 (same four sites, same counts, new
digests because the handler bodies changed shape). Total is unchanged at
268; no new degradation site is baselined.
- Broad/affected suites not run — focused evidence only, per the repo's
verification policy.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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