Skip to content

fix: Report an absent index tier as a typed first-run outcome - #5162

Merged
Sinity merged 1 commit into
masterfrom
fix/fresh-archive-root-typed-outcome
Sep 14, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/fresh-archive-root-typed-outcome

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

A read against a fresh or wiped archive root leaked a raw sqlite3.OperationalError to the CLI. It now raises the typed ArchiveTierUnavailableError at the read boundary, and the CLI's existing missing-archive handling — which was unreachable on the routes that matter — now catches it.

Evidence

Full-corpus verify_all on frozen master (890a2921e), job 1570, receipt .cache/verify/runs/20260914T200510Z-all-4027943-f8bc83ff, 22,524 selected, 147 failures with zero schema skew. Two of them are this defect:

tests/integration/test_installed_package_smoke.py::test_installed_polylogue_entrypoints_under_fresh_xdg
tests/integration/test_installed_package_smoke.py::test_installed_polylogue_writes_only_under_xdg_roots
  E   Error: unexpected error: OperationalError: unable to open database file

Reproduced at head in one command with a fresh HOME/XDG:

polylogue --diagnose find polylogue
Error: unexpected error: OperationalError: unable to open database file   (exit 1)

Filed as polylogue-wwjy6 (P1, open).

Per-failure classification

Failure Classification
test_installed_polylogue_entrypoints_under_fresh_xdg Product defect — fixed the product
test_installed_polylogue_writes_only_under_xdg_roots Product defect — same cause, same fix

Both tests are correct as written: polylogue --plain analyze --count and polylogue --plain status against a fresh XDG root are exactly what a first run does, and both have a correct answer. Neither test was touched.

Problem

Route (re-diagnosed at head, after #5152 changed it): cli/archive_query.py → cli/operation_kernel.py → operations/daemon_execution.py → operations/operation_context.py::open_operation_read → archive_tiers/archive.py::open_existing → _initialize_store → connection_profile.py::open_readonly_connection → sqlite3.connect(..., mode=ro).

Nothing on that route converted an absent index.db into the typed missing-archive report the first-run surface is supposed to give, and cli/machine_main.py then printed it as unexpected error.

archive_query.py already had _missing_archive_refusal, which renders the right answer per mode (count/stats/browse → the correct empty result; search → a refusal naming the path). It was reachable only behind OperationKernelError, which this failure is not, and only on the page route — the aggregate route that analyze --count takes had no handler at all.

Solution

  1. archive_tiers/archive.py — a read-only open that fails is classified by the file, not the driver message. SQLite reports a missing file under mode=ro with the same opaque unable to open database file it uses for a permission failure or a broken path, so index_db_path.exists() decides: absent → ArchiveTierUnavailableError(tier="index", ...) with a first-run remedy; present → the original exception propagates untouched.
  2. cli/archive_query.py — both the page route and the aggregate route now take _missing_archive_refusal on that typed error, so analyze --count answers 0 and find names the path it looked for.
  3. cli/commands/status.py — status reached its diagnose_first_run diagnostic by catching the raw sqlite3.Error. ArchiveTierUnavailableError is not a sqlite3.Error, so it is now named explicitly; without this the fix in (1) would have broken status, which is how the smoke test caught it mid-change.
  4. docs/plans/sqlite-degradation-baseline.json — the status.py except-clause edit re-texts one anchored degradation seam. Re-anchored to the new digest; the site count is unchanged at 230 (one removed, the same seam re-added), so the ratchet does not grow.

Verification

devtools test tests/integration/test_installed_package_smoke.py
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260914T220651Z-focused-test-4181032-1538359f/run.json

devtools test tests/unit/storage/test_absent_index_tier_is_typed.py
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260914T221741Z-focused-test-21251-3a7b6dcd/run.json

devtools verify --quick   # all 17 gates ok, including layering and schema-manifest

Manual, fresh HOME/XDG, at head of this branch:

polylogue --plain analyze --count   ->  0
polylogue --plain analyze           ->  outcome: empty (no_rows_in_scope) / Sessions: 0 ...
polylogue --plain status            ->  Daemon: not running / No archive found. / Run `polylogue init` ...
polylogue --diagnose find polylogue ->  Error: archive index database not found at <path>   (exit 1)

tests/unit/storage/test_absent_index_tier_is_typed.py is new and names its anti-vacuity condition per test: letting sqlite3.OperationalError propagate makes the first red; dropping the exists() guard makes the second red by reporting a present but unreadable tier as "not found, run polylogue ingest".

Schema closure

IN   polylogue/storage/sqlite/archive_tiers/archive.py
out  polylogue/cli/archive_query.py
out  polylogue/cli/commands/status.py
out  tests/unit/storage/test_absent_index_tier_is_typed.py

archive_tiers/archive.py is IN the derived-schema identity closure — this must land before the archive rebuild starts, never during one.

Residuals

  • The defect is fixed at the read boundary for the index tier specifically. Other tiers opened read-only elsewhere are untouched; no evidence was gathered that they have the same leak.
  • polylogue-wwjy6 names fix: Read verbs no longer take the exclusive maintenance-writer lease #5043 (d995eb4e4) as the best regression candidate. Not bisected — this PR fixes the observable behaviour and does not claim to identify the introducing commit.
  • The layering gate reports stale_baseline_count: 43 on master today; this PR neither adds to nor reduces that.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

A read against a fresh or wiped archive root reached the operator as
"Error: unexpected error: OperationalError: unable to open database file"
with no path and no remedy (polylogue-wwjy6). SQLite reports a missing
file under mode=ro with the same opaque text it uses for a permission
failure, so the read boundary now decides from the file, not the message,
and raises ArchiveTierUnavailableError -- the archive-shaped error every
surface already maps.

The CLI's existing missing-archive handling was only reachable behind
OperationKernelError, so the aggregate route (`analyze --count`) and the
page route both bypassed it; both now take the same refusal, which gives
browse and aggregate modes their correct empty answer and names the path
it looked for on a search. `status` caught the raw sqlite3.Error to reach
its first-run diagnostic; it now names the typed error too, which is not
a sqlite3.Error.

The sqlite-degradation baseline re-anchors the status.py seam that this
edit re-texts. The site count is unchanged at 230: one anchor removed,
the same seam re-added.

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
🔒 Security Review ✅ Completed 2026-09-14T22:28:13.946394Z ed9b295 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 40 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: 6c003d5f-6321-4d72-a874-18a7230d95ff

📥 Commits

Reviewing files that changed from the base of the PR and between 890a292 and ed9b295.

📒 Files selected for processing (5)
  • docs/plans/sqlite-degradation-baseline.json
  • polylogue/cli/archive_query.py
  • polylogue/cli/commands/status.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/storage/test_absent_index_tier_is_typed.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 817eec6 into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the fix/fresh-archive-root-typed-outcome branch September 14, 2026 23:09
Sinity added a commit that referenced this pull request Sep 15, 2026
Five `TestResourceErrorEnvelopes` cases asserted a code they never reached.
`read_server` builds a server with no archive at all, so each resource opened
an absent index tier and returned before touching whatever the test had
patched. The three `internal_error` cases were reaching the generic handler
via a bare `sqlite3.OperationalError`; the two `not_found` cases were reaching
an `except sqlite3.OperationalError` arm. Both were green for the wrong
reason. #5162 typed that refusal as `archive_tier_unavailable` and the
coincidence stopped holding.

The expected codes were right; the fixtures were not. `seeded_read_server`
installs a real seeded archive as the runtime service scope, so the injected
faults now actually fire. The two `not_found` cases drop their
`_get_polylogue` patch entirely -- it was inert, since neither resource calls
it -- and rely on the resource resolving an unresolvable token itself.

Anti-vacuity, measured rather than asserted: deleting the injected fault from
`test_sessions_resource_internal_error` now fails the test. Before this change
it still passed.

The behaviour #5162 introduced keeps deliberate coverage of its own, against
the bare `read_server`, instead of being an accident three other tests
depended on.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
Sinity added a commit that referenced this pull request Sep 15, 2026
)

## Summary

Five MCP resource-error tests were asserting a code they never reached.
This clears them, and adds deliberate coverage for the behaviour that
exposed them.

## Evidence

Receipt `.cache/verify/runs/20260914T233651Z-all-207009-89ddea6b`
(`verify_all`, job 1699, 22,540 selected, 29 failed).

**Caveat on that receipt:** its `run.json` records `git_head:
f7964ac` — the tip of branch
`rebase-5165`, *not* `master` and not an ancestor of it — and
`final_git_head: 724d175`. The shared checkout advanced across 7
merged PRs during the run, so it is not evidence of a frozen tree. I
re-ran all 29 node ids at true `master` HEAD: 17 reproduce, 12 do not.
These 5 are among the 17.

## Root cause

All five come from one place, and in none of them did the intended
trigger execute. The `read_server` fixture builds a server with **no
archive at all**. Every one of these resources opens the index tier
first, so it returned before touching what the test had patched.

They were green for the wrong reason on both sides:

- the three `internal_error` cases: absent tier raised a bare
`sqlite3.OperationalError`, which fell into the generic `else` of
`server_support._exception_to_error_json` → `internal_error`;
- the two `not_found` cases: the same `OperationalError` hit an explicit
`except sqlite3.OperationalError: … code="not_found"` arm in
`server_resources.py`.

#5162 typed that refusal as `archive_tier_unavailable`, and the
coincidence stopped holding. `git show --stat 817eec6` touches no MCP
file — these tests were never considered.

Separately, the two `not_found` cases patched
`polylogue.mcp.server._get_polylogue`, which **neither resource calls**.
That patch was inert regardless of the tier.

## Per-failure classification

| Failure | Classification | What it was actually proving |
| --- | --- | --- |
| `test_stats_resource_internal_error` | **stale test (vacuous)** |
absent-tier `OperationalError` → generic handler, not the patched
`ArchiveStore.stats` fault |
| `test_sessions_resource_internal_error` | **stale test (vacuous)** |
same; patched `archive_session_list_payload` never called |
| `test_origin_recent_resource_internal_error` | **stale test
(vacuous)** | same |
| `test_session_resource_not_found` | **stale test (vacuous)** |
absent-tier `OperationalError` → the `not_found` arm; `_get_polylogue`
patch inert |
| `test_messages_resource_not_found` | **stale test (vacuous)** | same |

No product defect. `archive_tier_unavailable` is the correct answer for
the input these fixtures actually presented. Notably the expected
**codes were right all along** — the fixtures were wrong — so this does
not retarget a single assertion downward.

## Solution

- `seeded_read_server`: a read-role server whose runtime service scope
is a real, seeded archive. `build_server()` is what installs the scope,
so it runs before the scope is read back and swapped.
- The three `internal_error` cases move to it, keeping their patches and
their expected code. The injected `RuntimeError("boom")` now actually
fires.
- The two `not_found` cases move to it and **drop the inert
`_get_polylogue` patch**, relying on the resource resolving an
unresolvable token itself (`resolve_session_id` → `KeyError` →
`code="not_found"`). Present tier, absent session — which is what the
test names claim.
- `_seed_archive` is hoisted to module scope;
`TestNativeReadSurfaceHonorsContract._seed` now delegates to it rather
than duplicating the body.
- New `test_resource_on_an_absent_index_tier_is_typed_not_internal`,
against the bare `read_server`, so #5162's behaviour has coverage of its
own instead of being an accident three other tests leaned on.

## Anti-vacuity

Measured, not asserted. With the injected fault deleted from
`test_sessions_resource_internal_error`:

```
devtools test tests/unit/mcp/test_envelope_contracts.py::TestResourceErrorEnvelopes::test_sessions_resource_internal_error
devtools test: FAILED exit=1 diagnosis=pytest_failed receipt=.cache/verify/runs/20260915T013517Z-focused-test-318227-eaf3d166/run.json
```

Before this change that same deletion still passed — the definition of
vacuous.

- `not_found` cases: red if `resolve_session_id` stops raising
`KeyError` for an unresolvable token, or if `server_resources` stops
catching `(KeyError, ValueError)` and lets it reach the generic handler
as `internal_error`.
- New tier-absent case: red if the `ArchiveTierUnavailableError` branch
in `_exception_to_error_json` is removed — it returns to
`internal_error`.

## Verification

```
devtools test tests/unit/mcp/test_envelope_contracts.py
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260915T013612Z-focused-test-320419-2a0dc239/run.json
```
26 passed (21 + the 5 repaired, of which one is new).

## Schema closure

```
devtools schema closure tests/unit/mcp/test_envelope_contracts.py
out  tests/unit/mcp/test_envelope_contracts.py
```

**OUT of the derived schema-identity closure.** Test-only change; no
product file touched. Does not need to land before an archive rebuild.

## Residuals

- I did not audit whether any test elsewhere still depends on the
absent-tier-through-MCP path returning `internal_error`; the full suite
will say.
- The three sibling `internal_error` tests that patch a pre-archive call
site (`tags`, `session_tree`, `readiness`) were already non-vacuous and
are untouched.

🤖 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]>
Sinity added a commit that referenced this pull request Sep 15, 2026
## Summary

Three unrelated tests on `master` still describe the world before a
landed product change. Each names the PR that moved the product. None is
a product defect; in each case the product is right and the test was
left behind.

## Evidence

Receipt `.cache/verify/runs/20260914T233651Z-all-207009-89ddea6b`
(`verify_all`, job 1699, 22,540 selected, 29 failed).

**Caveat on that receipt:** its `run.json` records `git_head:
f7964ac` — the tip of branch
`rebase-5165`, *not* `master` and not an ancestor of it — and
`final_git_head: 724d175`. The shared checkout advanced across 7
merged PRs during the run, so it is not evidence of a frozen tree. I
re-ran all 29 node ids at true `master` HEAD: 17 reproduce, 12 do not.
These 3 are among the 17.

## Per-failure classification

| Failure | Classification | Which PR moved the product |
| --- | --- | --- |
|
`test_schema_policy_contracts::test_read_only_archive_open_does_not_bootstrap_missing_tiers`
| **stale test** | #5162 (`817eec6f4`) typed the refusal as
`ArchiveTierUnavailableError` |
|
`test_write_path_state_machine::test_positional_branch_point_alias_is_typed_dangling`
| **stale test** (premise no longer constructible) | #5103 (`398c60458`)
made id-less message identity content-derived |
|
`test_compare_command::test_compare_with_verdict_records_and_is_readable_via_calibration`
| **stale test** | #5172 (`724d17535`) routed CLI facade writes through
declared daemon operations |

## Solution

**#5162 leftover.** `ArchiveTierUnavailableError` is a `DatabaseError`,
not an `sqlite3` exception, so it propagated straight through
`pytest.raises(sqlite3.OperationalError)`. #5162 landed its own
replacement (`test_absent_index_tier_is_typed.py`); this was the other
half. The test's actual subject — `assert not
any(tmp_path.glob("*.db"))`, that a read-only open of nothing creates
nothing — is untouched.

**#5103 leftover — the one worth reading closely.** The old test
renumbered the parent (`A,B` → `X,A,B`) so the child's
`p:<position>.<variant>` branch-point alias would land on a different
row. Under content-derived identity that alias no longer exists:
`message_id` is now `'c:' || content_identity || '.' ||
content_occurrence`, so "B" resolves to the same real message wherever
it sits, the content witness matches, and the composed prefix `X, A, B`
was **legitimately correct**. The writer was not wrongly resolving
anything — there was no longer a dangling reference to detect.

The dangling rule itself is intact and still worth proving, so I rebuilt
the premise rather than relaxing the rule: the replacement now **drops
"B" outright**, so the child's branch point genuinely vanishes and the
envelope must truncate to the child's own tail. Renamed to
`test_vanished_branch_point_is_typed_dangling` to say what it actually
tests.

**#5172 leftover.** Requiring a daemon for `compare --verdict` is not an
over-reach — it is the stated single-writer route, and `judge` moved the
same way. #5172 migrated `test_judge_command`,
`test_mark_note_identity`, `test_verb_cardinality`,
`test_cli_action_contracts` and `test_assertion_candidates`, but missed
this file. The verdict case moves onto the same `cli_daemon_archive`
stack (a real `DaemonOperationRuntime` behind a real UDS listener), so
the file's whole stated premise — a real production caller for
`blind_items`, `ClaimWithControls`, `compute_calibration` and
`upsert_comparative_judgment_assertion` — survives rather than being
mocked away. Its sibling `test_compare_without_verdict…` still passes
untouched because it records nothing.

## Anti-vacuity

- **Read-only open:** restore bootstrap on the read-only path
(`initialize = not read_only`) and the no-`*.db` assertion goes red.
Keeping the expected type narrow (rather than the `DatabaseError` base)
keeps it red if the boundary re-leaks a raw driver error.
- **Vanished branch point:** delete the content-witness guard in
`write.py` (`if witness is not None: … composed = own; break`) and the
child composes the wrong parent prefix instead of truncating. This is
the condition the test always named — it just could not reach it any
more.
- **Compare:** mock the facade instead of supplying a daemon and the
file's premise is lost; stub the storage chokepoint and the
`--calibration` agreement rate goes wrong.

## Verification

```
devtools test tests/unit/storage/test_write_path_state_machine.py tests/unit/storage/test_schema_policy_contracts.py
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260915T014134Z-focused-test-325111-9b54466f/run.json

devtools test tests/unit/cli/test_compare_command.py
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260915T014228Z-focused-test-325880-7bf93813/run.json
```

## Schema closure

```
out  tests/unit/cli/test_compare_command.py
out  tests/unit/storage/test_write_path_state_machine.py
out  tests/unit/storage/test_schema_policy_contracts.py
```

**All OUT.** Test-only change; no product file touched. Does not need to
land before an archive rebuild.

## Residuals

- `CLAUDE.md`'s identity section still documents the retired `p:`
positional fallback that #5103 replaced with `c:`. Not corrected here —
it is doc text, not a closure input, and belongs with whoever owns that
section.
- `test_cli_operation_authority.py` covers the daemon-down refusal
matrix for `mark` and `judge` but not `compare`. Adding that case is
worthwhile follow-up; it is new coverage rather than part of this
red→green repair, so I have not claimed it.

🤖 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