Skip to content

feat(storage): wire literal_check into DDL, fix a drift CHECK gap - #3451

Merged
Sinity merged 6 commits into
masterfrom
feature/refactor/literal-check-generation
Jul 31, 2026
Merged

Sinity merged 6 commits into
masterfrom
feature/refactor/literal-check-generation

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Summary

Wires the literal_check generator (documented by name in CLAUDE.md but
never actually called) into two real call sites, fixes one live divergence
it exposed, and corrects CLAUDE.md's inaccurate example.

Problem

CLAUDE.md states: "CHECK constraints are generated from Python types —
literal_check("status", *get_args(RunStatus)) embeds typing.Literal args
into SQL, so Python type ↔ SQL constraint stay in lockstep." An invariants
audit (polylogue-u6tl) found literal_check had zero call sites — the cited
example does not run, and RunStatus has no SQL constraint at all. ~50
hand-written CHECK(col IN (...)) lists exist across
archive_tiers/{index,source,ops,user}.py with no tie to the Python type
they mirror.

Solution

  • delegation_facts.mapping_state / .result_status (index.db) now
    derive their CHECK from DelegationMappingState / DelegationResultStatus
    via literal_check, declared as index v50 (CONSTRAINT_ONLY, matching
    the v33/v36 precedent — no column added, no values change). Moved both
    type aliases from archive_tiers/archive.py to the dependency-free
    archive_tiers/types.py so index.py's DDL module can import them without
    a circular import (archive.py transitively imports back into
    archive_tiers via insights.archive → storage.repair → storage.raw_authority → migration_runner); archive.py re-exports both
    names, no call site changes.
  • Real bug found and fixed: schema_drift_samples.classification
    (ops.db) hand-listed only 3 of DriftClassification's 4 values, silently
    omitting known_field_unread. The writer
    (record_schema_drift_observations_to_ops_sync) passes a real
    DriftClassification value inside a bare
    except sqlite3.Error: return 0 best-effort guard — so every
    known_field_unread observation was silently dropped by the CHECK instead
    of raising. Confirmed live: 313 unseen_shape rows, 0
    known_field_unread rows, despite the classifier actively producing that
    label. ops.db is disposable (no version gate), so this needed only the
    corrected DDL.
  • Investigated but did not change: the bead's own example of a
    divergence, embedding_catchup_runs.status vs CatchupRunStatus
    (storage/embeddings/progress.py). Turned out to be two independent table
    definitions sharing one name, not one CHECK drifted from one type — the
    canonical, production-reachable table (archive_tiers/ops.py) is
    correctly in sync with its real writers; a second, richer definition in
    progress.py is correctly in sync with CatchupRunStatus but has zero
    production callers (only 2 test files exercise it directly). Cross-
    documented both DDL sites rather than merging two schemas or deleting a
    tested-but-orphaned path — that is a substrate-duplication question, not a
    CHECK-lockstep fix.
  • CLAUDE.md corrected: replaced the non-functional
    literal_check(..., RunStatus) example with the two mechanisms that are
    now real, and states plainly that RunStatus is intentionally
    storage-free (an in-memory projection, never a column) and most
    hand-written CHECK lists still have no generator tie.
  • Follow-up filed (polylogue-lbk1): 4 more hand-written CHECK lists
    with a matching Python type (assertions.status/AssertionStatus,
    query_edges.edge_kind/QueryEdgeKind,
    result_sets/query_runs.exactness/ResultSetExactness,
    sinex_publication_obligations.mode/LifecycleMode) — all durable-tier
    (user.db/source.db), so closing them needs a table-rebuild migration
    behind the verified-backup-manifest gate, a distinct unit of work with its
    own test burden (round-tripping a populated fixture DB through a rebuild
    migration) deserving its own PR rather than being folded in here.

Honest scope note: polylogue-u6tl's AC asks for every hand-written
CHECK list to be inventoried. This PR resolves/documents 7 of the ~50
(2 fixed via literal_check, 1 real bug fixed, 4 filed as a scoped
follow-up) via targeted cross-referencing, not an exhaustive line-by-line
sweep. The bead stays open with a comment recording this; it should not
be read as fully closed by this PR.

Verification

  • Live archive (read-only, sqlite3 "file:...?mode=ro"): 0
    delegation_facts rows outside either new CHECK's vocabulary
    (mapping_state ∈ {edge_only, resolved, unresolved} × 3, result_status
    ∈ {error, unknown} × 2 observed); schema_drift_samples has 313
    unseen_shape / 0 known_field_unread rows, consistent with the bug.
  • devtools lab policy schema-versioning — schema evolution policy intact.
  • devtools test tests/unit/storage/ -k "delegation or lifecycle or schema_drift or drift_sentinel" — 71 passed.
  • devtools test tests/unit/storage/test_schema_safety.py tests/unit/storage/test_index_fast_forward_lifecycle.py tests/unit/storage/test_embedding_contracts.py tests/unit/cli/test_embed_status_fast.py — 107 passed.
  • mypy --strict on all touched files — no issues.
  • devtools render all --check — no drift.
  • devtools verify --quick — exit 0 (format, lint, mypy, render-check,
    schema-versioning policy, and the rest of the quick lane).

Ref polylogue-u6tl

Sinity and others added 5 commits July 31, 2026 14:04
… gap

Problem: `literal_check` (storage/sqlite/archive_tiers/common.py) had zero
call sites despite CLAUDE.md documenting it by name as the mechanism that
keeps `typing.Literal` types and their SQL CHECK lists in lockstep. Two
concrete columns had typed Python counterparts (DelegationMappingState/
DelegationResultStatus) with no CHECK at all, and one hand-written CHECK
(schema_drift_samples.classification) had silently drifted 3-of-4 values
behind its Literal (DriftClassification), causing every
'known_field_unread' drift observation to be silently dropped by a bare
`except sqlite3.Error: return 0` write guard.

What changed:
- delegation_facts.mapping_state / .result_status (index.db) now derive
  their CHECK from DelegationMappingState / DelegationResultStatus via
  literal_check, declared as index v50 (CONSTRAINT_ONLY, matching the
  v33/v36 precedent -- no column added, no value changes).
- schema_drift_samples.classification (ops.db, disposable, no version
  gate) now derives its CHECK from DriftClassification, closing the
  known_field_unread gap.
- Moved DelegationMappingState/DelegationResultStatus from archive.py to
  the dependency-free archive_tiers/types.py so index.py's DDL module can
  import them without a cycle (archive.py transitively imports back into
  archive_tiers via insights.archive -> storage.repair ->
  storage.raw_authority -> migration_runner). archive.py re-exports both
  names; no call site changes.

Verification:
- Live archive (read-only): 0 delegation_facts rows outside either new
  CHECK's vocabulary; schema_drift_samples has 313 unseen_shape rows and
  0 known_field_unread rows despite the classifier producing that label.
- devtools lab policy schema-versioning: schema evolution policy intact.
- devtools test tests/unit/storage/ -k "delegation or lifecycle or
  schema_drift or drift_sentinel": 71 passed.
- devtools test tests/unit/storage/test_schema_safety.py
  tests/unit/storage/test_index_fast_forward_lifecycle.py: 35 passed.
- mypy --strict on the 5 touched files: no issues.
- devtools render all --check: no drift.

Ref polylogue-u6tl

Co-Authored-By: Claude <[email protected]>
Problem: polylogue-u6tl's audit flagged embedding_catchup_runs' CHECK
('running','completed','failed','cancelled') as diverged from
CatchupRunStatus (Literal, 5 values including 'stopped'/'interrupted'),
citing cli/commands/embed.py's status translation as evidence of a
papered-over mismatch.

Investigation: there are two independent table definitions sharing the
name `embedding_catchup_runs` -- the canonical one in
archive_tiers/ops.py (written only by ops_write.upsert_embedding_
catchup_run via cli/commands/embed.py and daemon/embedding_backlog.py,
which together only ever produce 'running'/'completed'/'failed'/
'cancelled') and a second, richer one in storage/embeddings/progress.py
(ensure_embedding_catchup_runs_table) whose own CHECK already matches
CatchupRunStatus's full 5-value vocabulary -- but whose write helpers
have zero production callers, only direct test exercise
(test_embed_status_fast.py, test_embedding_contracts.py). Widening the
canonical CHECK to 5 values would accept 'stopped'/'interrupted' its
real writer never produces; narrowing CatchupRunStatus would break the
tested-but-orphaned progress.py path. Neither is a CHECK-lockstep fix --
it is a substrate duplication (two implementations of "embedding
catch-up run tracking" under one name), out of this PR's scope.

What changed: doc-only. Cross-referenced both DDL sites so a future
reader does not mistake this for unexplained drift, satisfying the AC's
"or its translation ... is documented at both DDL sites" branch. No
schema, CHECK, or behavior change.

Verification: ruff check/format clean; OPS DDL still builds in-memory;
devtools test tests/unit/storage/test_embedding_contracts.py
tests/unit/cli/test_embed_status_fast.py: 72 passed (unchanged).

Ref polylogue-u6tl

Co-Authored-By: Claude <[email protected]>
Problem: CLAUDE.md cited `literal_check("status", *get_args(RunStatus))`
as the working example of "CHECK constraints are generated from Python
types," but literal_check had zero call sites (polylogue-u6tl audit) and
RunStatus (insights/run_projection.py) is an intentionally storage-free
in-memory projection with no backing column -- the cited example could
not have run.

What changed: replaced the fictional example with the two mechanisms
that are now real -- check()/nullable_check() over PolylogueStrEnum
(~20 existing call sites, e.g. Origin/Role) and literal_check over
typing.Literal (delegation_facts.mapping_state/.result_status, wired in
the preceding commit) -- and stated plainly that most hand-written
CHECK(col IN (...)) lists still have no generator tie, and that RunStatus
specifically has no SQL surface to generate one for.

Verification: devtools render all --check clean (CLAUDE.md is prose, not
a generated-surface source, so this is a no-op check confirming the edit
didn't disturb anything render-tracked).

Ref polylogue-u6tl

Co-Authored-By: Claude <[email protected]>
polylogue-u6tl's DDL sweep found 4 more hand-written CHECK lists with a
matching Python type (assertions.status/AssertionStatus,
query_edges.edge_kind/QueryEdgeKind, result_sets+query_runs.exactness/
ResultSetExactness, sinex_publication_obligations.mode/LifecycleMode),
each verified to reject 0 live rows -- but user.db/source.db are durable
tiers, so closing the gap needs a table-rebuild migration behind the
verified-backup-manifest gate rather than the CONSTRAINT_ONLY/disposable-
tier path used in this branch's other commits. Filed as polylogue-lbk1
with the exact column/type/value-set specs so the follow-up is
actionable without re-deriving this audit.

Ref polylogue-u6tl

Co-Authored-By: Claude <[email protected]>
Comment-only: documents what landed vs what remains open on the
literal_check bead so the partial-completion state is durable, not just
in this branch's commit history.

Ref polylogue-u6tl

Co-Authored-By: Claude <[email protected]>
@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, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 21 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 071c2ee1-3849-4433-a651-f8524d853b89

📥 Commits

Reviewing files that changed from the base of the PR and between c94b93f and 9e37dc3.

📒 Files selected for processing (7)
  • CLAUDE.md
  • polylogue/storage/embeddings/progress.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/storage/sqlite/archive_tiers/index.py
  • polylogue/storage/sqlite/archive_tiers/ops.py
  • polylogue/storage/sqlite/archive_tiers/types.py
  • polylogue/storage/sqlite/lifecycle.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.

# Conflicts:
#	.beads/issues.jsonl
#	polylogue/storage/sqlite/archive_tiers/index.py
#	polylogue/storage/sqlite/lifecycle.py
@Sinity
Sinity merged commit 42bafb0 into master Jul 31, 2026
1 of 3 checks passed
@Sinity
Sinity deleted the feature/refactor/literal-check-generation branch July 31, 2026 13:12
Sinity added a commit that referenced this pull request Jul 31, 2026
…#3459)

## Summary

Master cannot render. Restores an 11-line column definition that a
conflict resolution dropped.

## Problem

```
$ devtools render all --check
sqlite3.OperationalError: table blocks has no column named signature
```

That fails `devtools verify --quick`, which fails **every branch's
pre-push hook** — so master being red here blocks all concurrent work,
not just this file.

## Cause

Resolving #3451's conflict against master, I took the PR branch's
`index.py` wholesale and merged only its **header comments**. That
branch predates #3447, so it never carried the `blocks.signature` column
added by `polylogue-vf9x` — the provider attestation for empty-body
THINKING blocks, which is the only surviving evidence besides block
existence for Claude Code sessions since ~2026-06.

The result was the worst possible shape: the v50 header comment
*describing* the column survived, so the file read as correct on
inspection. The column itself was gone.

## Solution

Restores the column definition and its comment, taken from the
correctly-merged working copy. No other difference from master — `git
diff` is +11 lines, one file.

## Verification

```
devtools render all --check          clean (was OperationalError)
devtools lab policy schema-versioning "Schema evolution policy intact."
grep 'signature *TEXT' index.py      present in the blocks DDL
```

## Note

Two process lessons worth recording. Mechanically union-merging a schema
file is unsafe: the same resolution also collapsed two *different*
`IndexDeltaDeclaration(version=50, ...)` blocks — `vf9x` and `u6tl` —
into one, which would have silently dropped a declaration. That was
caught before landing; this was not.

And `devtools` invoked from a linked worktree resolves `polylogue`
through the venv's `.pth` to the **main checkout**, so a schema-version
check can compare one tree's constant against another tree's
declarations. `PYTHONPATH` does not override it.

Co-authored-by: Claude Opus 5 <[email protected]>
Sinity added a commit that referenced this pull request Jul 31, 2026
…sites (#3464)

## Summary

Restores `literal_check` in
`polylogue/storage/sqlite/archive_tiers/common.py`, deleted by #3458 as
a supposed zero-call-site dead shim. It has real call sites and master's
HEAD currently fails to import `archive_tiers/index.py` at all.

## Problem

#3458 (5798b3d, "collapse duplicate implementations, dead shims, and
split vocabularies") deleted `literal_check` from `common.py` on the
strength of a "zero call sites" grep (bead polylogue-u6tl). But #3451
(42bafb0, "wire literal_check into DDL, fix a drift CHECK gap") had
already landed *earlier the same day* and wired it into
`archive_tiers/index.py`'s `delegation_facts` DDL for
`DelegationMappingState`/`DelegationResultStatus` CHECK constraints.
#3458's grep predated #3451's merge and was never re-run against the
merged tree.

Net effect on current `master`: every module that imports
`archive_tiers/index.py` (i.e. essentially the whole storage substrate,
and by extension most of `tests/`) fails at collection with
`ImportError: cannot import name 'literal_check' from
'polylogue.storage.sqlite.archive_tiers.common'`. Discovered while
running `devtools test` for unrelated work on polylogue-cgfy — a fresh
`devtools test` on any file failed at conftest import.

## Solution

Restore `literal_check` verbatim (matching #3451's usage and
`CLAUDE.md`'s still-accurate description of it as real machinery for the
~20 enum-backed columns "and the handful of `literal_check` call sites
wired so far"), rather than migrating the two real call sites to
`check()`/`nullable_check()` — those only accept `PolylogueStrEnum`, not
the `typing.Literal` aliases
`DelegationMappingState`/`DelegationResultStatus` actually are. No other
part of #3458 touched.

## Verification

- `devtools test
tests/unit/sources/test_parsers_claude_code_artifacts.py
tests/unit/storage/test_archive_tiers_common.py` — 38 passed (previously
failed at collection with `ImportError`)
- `devtools verify --quick` — exit 0 (format, lint, mypy, render all
--check, schema-versioning policy) — ran automatically via the pre-push
hook
Sinity added a commit that referenced this pull request Jul 31, 2026
…#3465)

## Summary

Closes out the remainder of polylogue-cgfy's disposition work now that
PR #3442 landed the flagship consumption gap
(structuredPatch/originalFile/oldString -> file_edits, reachable via API
+ MCP + CLI `read --view file-edits`). Adds the two remaining
genuinely-unread, real-value wire keys (`requestId`,
`thinkingMetadata.maxThinkingTokens`) and records the full disposition
(read / measured-negative / deliberately-dropped-duplicate) for the rest
of the bead's "other unread keys of substance" list in the Claude Code
OriginSpec's `fidelity_notes`, satisfying AC1.

## Problem

polylogue-cgfy's 2026-07-29 corpus enumeration found 34 of the 70 most
common Claude Code wire keys with zero references in
`polylogue/sources/`. The structuredPatch/originalFile/oldString cluster
(105K/92K/86K rows) and most of the "other keys of substance" list
(`stop_reason`, `stop_sequence`, `cache_creation`, `ttftMs`, `todos`,
`toolUseResult.sandbox`/`filenames`/`numFiles`, `slug`) were captured by
prior sessions on this bead and PR #3442, but two items remained
genuinely unread with no recorded disposition either way: `requestId`
(1,171 sampled occurrences -- the Anthropic API's per-call request id)
and `thinkingMetadata.maxThinkingTokens` (34 occurrences -- the
extended-thinking token budget). The bead's remaining lower-value items
(`userType`, `sourceToolAssistantUUID`, `hookCount`/`hookInfos`,
`toolUseID`) also had no recorded disposition, so AC1 ("every key...
classified... recorded in the Claude Code OriginSpec fidelity
declaration") was incomplete.

Verified each of those lower-value items directly against a real
~/.claude/projects corpus before classifying:
- `userType` is the literal string `"external"` on every sampled record
(measured negative, same class as the bead's own `usage.service_tier`
finding).
- `sourceToolAssistantUUID` equals that same record's own `parentUuid`,
already captured as `ParsedMessage.parent_message_provider_id` -- a
duplicate spelling, not new evidence.
- `hookCount`/`hookInfos` describe hook firings already tracked durably
(with outcome, which `hookInfos` lacks) in `source.db`'s
`raw_hook_events`.
- `toolUseID` is already consumed for its real signal (the
`progress`/`agent_progress` delegation-edge disposition documented in
`code_parser.py`'s module docstring).

Also discovered en route: `master` HEAD (5798b3d) failed to import at
all (`ImportError: cannot import name 'literal_check'`) -- #3458 deleted
it as a supposed zero-call-site dead shim, but #3451 had wired real call
sites into it earlier the same day. Fixed and merged separately as #3464
so this branch could even run tests; this branch is rebased on top of
that fix.

## Solution

- `polylogue/sources/parsers/claude/code_parser.py`:
`_message_usage_event_payload` gains a `record` parameter (the top-level
record `item`, since `requestId`/`thinkingMetadata` live there, not
inside `message`); the sole call site now passes `record=item`. Both new
keys ride the existing `message_usage` session-event payload as
`request_id`/`max_thinking_tokens`.
- **Production callers exercising the new fields**:
`Session.session_events` -> CLI `read --view events`
(`polylogue/cli/read_views/events.py` -> `run_session_events`,
`polylogue/cli/messages.py`) and MCP `get(ref, projection="events")`
(`polylogue/mcp/server_cutover.py:905`) already render every
`session_events` row generically regardless of `event_type` -- no new
consumer code needed, verified by reading both call chains before
writing this PR (the generic `events` projection was wired by prior
work, not this PR).
- `polylogue/sources/origin_specs.py`: new `fidelity_notes` entry on the
Claude Code `OriginSpec` recording the full disposition table above.

## Verification

- `devtools test
tests/unit/sources/test_claude_code_unread_wire_fields.py
tests/unit/sources/test_parsers_claude_code_artifacts.py
tests/unit/sources/test_origin_specs.py` -> 57 passed
- `devtools verify --quick` -> exit 0 (format, lint, mypy, render all
--check, schema-versioning policy)
- Anti-vacuity: each new field has a paired "field absent" test
asserting the key is omitted from the payload, not fabricated

Ref polylogue-cgfy

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Enhancements**
- Claude Code usage events now capture available request identifiers and
maximum thinking-token settings.
- Missing metadata continues to be omitted, keeping usage records clean
and accurate.

- **Quality Improvements**
- Added coverage to verify that these Claude Code fields are preserved
and handled consistently.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sinity added a commit that referenced this pull request Jul 31, 2026
… select (#3466)

## Summary

Fixes the raw-authority-quarantine absorbing state (polylogue-u19l) by
making
its root cause (polylogue-w32w) structurally unrepresentable: a frontier
item's actuator must have a real apply() handler only if its state is in
the
executability gate's admitted set.

## Problem

Audit 2026-07-31 (live `source.db`, read-only) found: 4,147 open
`raw_authority_blockers` rows all reading "accepted raw authority
remains
quarantined pending exact refinement proof"; 15,205/17,384 frontier
plans
residual (87%); `fixed_point=0` on all 256 retained censuses; total gap
count
that only ever grew (16,874 -> 17,384, never shrinking).

Root cause: a quarantined raw whose refinement proof came back
"ineligible"
got no strategy override, so `_classify_frontier`'s default fallback
assigned
it `state=UNRESOLVED_PROVENANCE, actuator=REFINE_QUARANTINE`. But
`REFINE_QUARANTINE` has a real apply() dispatch branch that only ever
runs
for `_EXECUTABLE_STATES = {SAFELY_REKEYABLE, DUPLICATE_ALIAS}` — both
the
daemon and the operator break-glass path
(`apply_raw_authority_frontier`,
which raises `RuntimeError` on any non-executable selected item) select
only
executable items. The handler at `raw_reconciler.py:1297` was
unreachable
through every path that exists.

Two corrections from the audit preserved unchanged:
- `unresolved_raw_replay_blockers()` already deliberately excludes
frontier
  plan blockers from starving unrelated work.
- `REFINE_QUARANTINE` is not entirely dead — the strategy override for
  eligible/already_repaired quarantined raws (promoting to
`SAFELY_REKEYABLE`) is the real, executable 2,179-plan lane draining at
  8/pass. Only the ineligible complement was absorbing.

## Solution

- `_strategy_overrides` now records an override for "ineligible"
quarantine
  proofs too: state stays `UNRESOLVED_PROVENANCE` (still tracked in
`state_counts` and `raw_authority_blockers` — still an operator-visible
obligation), actuator becomes `NONE` with the real ineligibility reason
folded into the item's `reason` text. The ineligibility reasons
enumerated
in `_inspect_quarantined_accepted_raw` (missing rows, mismatched hashes,
  competing authority, incompatible typed envelopes) are permanent
structural facts about a raw's own data, not transient states — matching
the existing apply()-time code comment ("not transiently"). This is the
"record a terminal, countable, operator-visible state" branch of the two
legitimate options the bead named, chosen over building a
refinement-proof
  actuator that cannot exist for permanently mismatched bytes.
- Same fix applied to two more `classify_frontier` call sites with the
identical shape: the no-`logical_source_key` `REFINE_QUARANTINE`
fallback,
and `REPLAY` on a logical-source-key mismatch (confirmed 0 live rows
today
  via the `raw_authority_blockers` reason distribution; `REPLAY` has no
  apply() handler at all, fixed pre-emptively).
- `polylogue-w32w`'s invariant, made structurally enforceable:
`RawAuthorityFrontierItem.__post_init__` now rejects constructing an
item
  whose actuator has a real apply() dispatch branch
(`_APPLY_DISPATCHED_ACTUATORS`) paired with a non-executable state.
Fires
  on every construction path (`_item()`, `dataclasses.replace()` in
  `_apply_judgment_dispositions`). `REACQUIRE`/`REQUEST_JUDGMENT` are
deliberately exempt — both resolve out-of-band (ordinary re-acquisition;
an operator judgment assertion promoted by
`_apply_judgment_dispositions`).
- `test_apply_dispatched_actuators_match_apply_branches` regex-parses
the
actual apply() dispatch branches out of the module source and asserts
they
equal `_APPLY_DISPATCHED_ACTUATORS`, so the allowlist can't silently
drift.
- `test_quarantine_refinement_fanout_scopes_by_logical_source_key`
previously
asserted the now-fixed sibling's actuator as `REFINE_QUARANTINE` — it
was
  the direct reproduction case for this defect, encoded as expected
  behavior. Updated to assert `NONE`.
- Also restores `polylogue/storage/sqlite/archive_tiers/common.py`'s
`literal_check()` helper, deleted by #3458 on stale "uncalled" evidence
  after #3451 had already wired it into `archive_tiers/index.py` — broke
every import of `polylogue.storage` on `origin/master` HEAD. Discovered
  while setting up verification for this fix; restored as a prerequisite
  since nothing here (or in the wider suite) can import without it.

**What this fix does NOT do**: it does not reduce the 4,147 existing
blocker
rows or shrink `raw_authority_census_plans`' ~709K carried_forward rows
(polylogue-f4z9, tracked separately) — those are pre-existing durable
rows
from the old misclassification and need their own migration/backfill,
out of scope here. Going forward, every new census records these raws
with
the honest `NONE` actuator instead of reproducing the false promise.
**No
index rebuild is required** (`polylogue ops reset --index && polylogued
run`) — `source.db`'s `revision_authority` column is unaffected; only
the
derived frontier classification (an index-tier read model) changes on
the
next census.

## Verification

- `devtools test tests/unit/storage/test_raw_authority_ledger.py
tests/unit/storage/test_quarantined_accepted_raw_repair.py
tests/unit/storage/test_duplicate_raw_identity_repair.py
tests/unit/storage/test_browser_capture_origin_repair.py
tests/unit/storage/test_archive_tiers_common.py` — 81 passed
- `devtools verify --quick` — exit 0 (ruff format, ruff check, mypy
--strict, render all --check, layering, closure-matrix,
schema-versioning policy, and the rest of the quick-tier gates)
- Not run: full suite / testmon (fresh unseeded worktree); per-PR CI
skips the heavy `test` suite by design.
- Pre-existing, unrelated failure found and left alone (filed as
polylogue-jsxj):

`tests/unit/daemon/test_daemon_cli.py::test_maybe_run_raw_materialization_whale_pass_*`
(`TypeError: lambda got unexpected keyword '_bootstrap'`) — introduced
by
  #3455's `load_polylogue_config()` signature change, touches neither
  `raw_reconciler.py` nor `common.py`; reproduces identically on
  `origin/master` HEAD before this branch's changes.

Ref polylogue-u19l
Ref polylogue-w32w

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 31, 2026
## Summary

Wires the previously-unused `prepare_session_rows`/`PreparedSessionRows`
(polylogue-623q, #3219) into the offline/CLI bulk-rebuild path so
row-tuple
construction (message/block hashing, JSON encoding, enum lookups) runs
on a
background thread concurrently with the single SQLite writer's own work,
instead of inline inside the writer's hold.

## Problem

polylogue-fpid: this was the last unexplored performance lever for a
full
index rebuild, which the archive needs to run to pick up 5,300
misclassified
sessions and every parser fix landed today. Concurrency (#p0pw/#8249),
FTS-trigger deferral, and delete-cascade skip (#3460) were already
measured
and closed off; the remaining diagnosis was that bulk-build is
INSERT-bound
and `prepare_session_rows`/`PreparedSessionRows` existed complete,
tested,
and wired nowhere.

Instrumenting the real rebuild engine
(`tests/infra/rebuild_cost_model.py`'s
`_run_one_rebuild_pass`, not a microbenchmark) against the two largest
population strata (codex-session/d9: 7508 raws, claude-code-session/d9:
15954 raws — 57% of the 41,363-raw corpus by count) showed
`index.full_replace.field_path_union`'s timer wrapping
`_union_with_existing_rows`'s call expression — whose arguments
(`_build_message_rows`/`_build_block_rows`) evaluate before the function
body's own early return. On a from-empty bulk build (`existing_raw_id is
None`, always the early-return branch for this stratum shape) the entire
measured cost of that stage is pure row construction, not the union it's
named for: 0.355s/40 raws (42% of `full_replace`) on codex-d9, 0.072s/40
(11%) on claude-code-d9.

## Solution

- `polylogue/storage/sqlite/archive_tiers/revision_governance.py`:
threads
  `PreparedSessionRows`/`Future[PreparedSessionRows]` through
  `apply_raw_revision_replay` → `_index_parsed_for_retained_raw` →
`_write_parsed_precedence_result` → `write_parsed_session_to_archive`'s
existing (previously unwired) `prepared` parameter. Only ever resolved
at
chain position 0 (the sole full-replace write — every later position is
  `merge_append`, which never accepts prepared rows).
- `polylogue/sources/revision_backfill.py`:
`backfill_historical_revision_
  evidence`'s byte-proven replay loop submits `prepare_session_rows` for
  position 0's session to a one-worker `ThreadPoolExecutor` right when
  `parsed_by_raw_id` is built, so it runs concurrently with
`apply_raw_revision_replay`'s own attachment-preacquisition/blob-flush/
  head-lookup preamble on the calling thread. Gated on
`parallel_threads_effective()` (same guard the existing parse-thread
pool
  uses) — a GIL build gets `prepare_pool=None` and is byte-for-byte
  unchanged.
- `polylogue/storage/sqlite/archive_tiers/archive.py`: threads the new
  parameter through `ArchiveStore.apply_raw_revision_replay`'s wrapper.
- Correctness: `write_parsed_session_to_archive`'s existing validity
gate
(content-hash match, not `merge_append`, not prefix-sharing) already
made
a stale/wrong `prepared` argument always safe to pass — this change adds
  no new gating logic, only a new supplier.
- Also restores `literal_check` (deleted by #3458 despite live call
sites
  #3451 added the same day — polylogue-7qfq, already fixed on another
branch as `3fc622ecb`, cherry-picked here to unblock local verification
  on this worktree's `origin/master` base) and fixes a test double
  (`test_live_cursor_persistence.py`'s `_lock_first_index_persistence`
fixture, which re-declares `_write_parsed_precedence_result`'s
signature)
  to accept and forward the new `prepared` parameter.

## Verification

Re-instrumented after wiring, same two strata, 4 repeated runs each
under
host load 14–17 (contended, hence the repeats): `field_path_union`
collapsed
from 0.355s/0.072s to a consistent ~0.0002s (99.9%+ eliminated) in every
run.
`full_replace` dropped 25–45% (codex-d9: 0.85s → 0.46–0.63s;
claude-code-d9:
0.64s → 0.45–0.48s). `index_parsed_write` (the full per-session writer
hold)
dropped 19–22%. Weighted by raw count across the two dominant strata
(57% of
the corpus), this projects to roughly a 10–15% cut of writer apply time
on
the majority of a full rebuild — an estimated **25–40 minutes off the
calibrated 4h20m baseline**. Did not run the full ~40-pass population
projection benchmark (`test_full_population_projection`) — a concurrent
instance of the same benchmark was already running in another worktree
on
this host when this was measured; the per-stratum stage-level
measurement
above uses the same real rebuild engine, just without the two-point
regression's fixed-cost stripping.

- `devtools test tests/unit/sources/test_revision_backfill.py
tests/unit/storage/test_revision_replay.py
tests/unit/storage/test_raw_retention.py
tests/unit/storage/test_prepared_session_rows.py
tests/unit/storage/test_archive_tiers_write.py
tests/unit/sources/test_live_cursor_persistence.py` — 228 passed, 1
failed
(`test_parse_one_still_replays_real_claude_code_sessions_with_no_path_rule`,
confirmed pre-existing on unmodified `origin/master` via a diff-free
byte-for-byte rerun; filed as polylogue-6mpy, unrelated to this change).
- `devtools verify --quick` — exit 0 (ran twice: once pre-commit, once
via the pre-push hook).
- `mypy polylogue devtools` — Success, no issues found in 1277 source
files.
- Not run: full/testmon suite (per-PR CI skips it by design; the
affected-surface `devtools test` selection above covers every touched
call site).

Ref polylogue-fpid, polylogue-623q, polylogue-7qfq

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
Problem

polylogue-sd9s: DriftClassification has 4 members (unseen_shape, new_field,
field_changed, known_field_unread). PR #3451 already generated the
schema_drift_samples.classification CHECK from DriftClassification via
literal_check, but that fix only affects a *fresh* CREATE TABLE -- an
ops.db bootstrapped before #3451 keeps its stale 3-value CHECK forever,
since CREATE TABLE IF NOT EXISTS never rewrites an existing table's
constraints. Confirmed live: /realm/db/polylogue/ops.db still carries the
pre-fix CHECK.

Separately, record_schema_drift_observations_to_ops_sync wrapped its whole
per-observation write loop in one try/except sqlite3.Error, so a single
CHECK-rejected row (e.g. known_field_unread against a stale live CHECK, or
any bad origin token) aborted the loop immediately and returned 0 -- silently
discarding every other observation in the same batch, not just the bad one.

Solution

- bootstrap.py: add _ensure_schema_drift_samples_check, called from
  initialize_archive_tier's OPS branch. It inspects sqlite_master.sql for
  the live table; if the CHECK predates known_field_unread, drops and
  recreates the table from the new SCHEMA_DRIFT_SAMPLES_DDL constant
  (extracted from ops.py's OPS_DDL so the two can't drift apart). Losing
  the disposable telemetry rows on repair is accepted (ops.db is a
  disposable tier per CLAUDE.md).
- drift_sentinel_sampling.py: catch sqlite3.IntegrityError per observation
  inside the loop (log at warning, not debug, since a CHECK violation here
  means the schema and the writer have drifted apart -- the exact defect
  class this sentinel exists to surface) and continue to the next
  observation. A non-constraint sqlite3.Error (locked db, disk full) still
  stops the batch as before, since each record_schema_drift_sample call is
  already its own commit.

Verification

- devtools test tests/unit/schemas/test_drift_sentinel_sampling.py
  tests/unit/storage/test_schema_drift_samples.py -- 15 passed, including:
  a reproduction of the pre-fix stale-CHECK IntegrityError, a bootstrap
  convergence repair test, a known_field_unread persistence regression
  test, and a batch-continuation test (temporarily reverting the sampling
  fix reproduces the bug: written==0 instead of 2).
- devtools test tests/unit/storage/test_archive_tiers_ops_write.py
  tests/unit/cli/test_schema_drift_status.py
  tests/unit/daemon/test_fts_identity_convergence.py -- 24 passed.
- devtools verify --quick -- exit 0 (format, lint, mypy --strict,
  render-all-check, layering, schema-versioning policy).

Ref polylogue-sd9s

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 2, 2026
…ow (#3547)

## Summary

Repairs the last two live consequences of polylogue-sd9s: an
already-bootstrapped ops.db keeping a stale 3-value
`schema_drift_samples.classification` CHECK forever, and a batch-write
loop that silently discarded every other observation in a batch when one
row hit a CHECK violation.

## Problem

`DriftClassification` (`polylogue/schemas/drift_sentinel.py:48`) has 4
members: `unseen_shape`, `new_field`, `field_changed`,
`known_field_unread`. PR #3451 (merged 2026-07-31, same day this bead
was filed) already fixed the ops-tier DDL's hand-written 3-value CHECK
by generating it from `DriftClassification` via `literal_check` — but
that fix only changes the DDL text used by a *fresh* `CREATE TABLE`.
`CREATE TABLE IF NOT EXISTS` never rewrites an existing table's
constraints, so an ops.db bootstrapped before #3451 keeps rejecting
`known_field_unread` forever on every reopen. Confirmed live:
`/realm/db/polylogue/ops.db`'s `schema_drift_samples` table still
carries the old 3-value CHECK.

Separately, `record_schema_drift_observations_to_ops_sync`
(`polylogue/schemas/drift_sentinel_sampling.py`) wrapped its whole
per-observation write loop in one `try/except sqlite3.Error: return 0`.
Each `record_schema_drift_sample` call is already its own commit (`with
conn:`), so earlier rows in a batch were safely persisted on disk — but
the moment any single observation's INSERT violated a CHECK (a
stale-CHECK `known_field_unread` row, or any other constraint violation,
e.g. an unrecognized `origin` token), the function returned early with
`written=0`, meaning: (a) the caller's return-count lied about what
actually got written, and (b) every observation *after* the bad one in
that same batch call was silently skipped, never attempted.

## Solution

- `polylogue/storage/sqlite/archive_tiers/ops.py`: extracted
`SCHEMA_DRIFT_SAMPLES_DDL` as its own constant (embedded into `OPS_DDL`)
so it can be reused for repair without a second, hand-copied definition.
- `polylogue/storage/sqlite/archive_tiers/bootstrap.py`: added
`_ensure_schema_drift_samples_check`, called from
`initialize_archive_tier`'s `ArchiveTier.OPS` branch. It inspects
`sqlite_master.sql` for the live `schema_drift_samples` table; if the
CHECK predates `known_field_unread`, it drops and recreates the table
from `SCHEMA_DRIFT_SAMPLES_DDL`. `ops.db` is a disposable tier (per
CLAUDE.md), so losing the bounded telemetry rows on repair needs no
migration ceremony.
- `polylogue/schemas/drift_sentinel_sampling.py`: moved the connection
open/init into its own try/except (unchanged best-effort contract for a
missing/unreachable ops.db), then catch `sqlite3.IntegrityError` per
observation inside the loop — log at `warning` (not `debug`, since a
CHECK violation here means the schema and the writer have drifted apart,
the exact defect class this sentinel exists to surface) and continue to
the next observation. A non-constraint `sqlite3.Error` (locked db, disk
full) still stops the batch, as before.

## Verification

- `devtools test tests/unit/schemas/test_drift_sentinel_sampling.py
tests/unit/storage/test_schema_drift_samples.py` — 15 passed, including:
a reproduction of the pre-#3451-style stale-CHECK `IntegrityError`, a
bootstrap-convergence repair test (stale table →
`initialize_archive_tier` → CHECK now includes `known_field_unread`,
insert succeeds), a `known_field_unread` persistence regression test,
and a batch-continuation test. Anti-vacuity: temporarily reverting only
the `drift_sentinel_sampling.py` change reproduces the pre-fix bug on
the new test (`written == 0` instead of `2`).
- `devtools test tests/unit/storage/test_archive_tiers_ops_write.py
tests/unit/cli/test_schema_drift_status.py
tests/unit/daemon/test_fts_identity_convergence.py` — 24 passed.
- `devtools verify --quick` — exit 0 (format, lint, mypy --strict,
render-all-check, layering, schema-versioning policy). Also ran
automatically and passed via the pre-push hook.

Ref polylogue-sd9s

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 19, 2026
… reapply (#4021)

## Summary

Counts how each archive tier initialization actually resolved —
page-copy restore, fresh DDL, or whole-schema reapply — publishes the
tally into the run's pytest summary, and then uses it to find and fix
the actual cost: a redundant `PRAGMA user_version` write that turned
every same-version reapply into a full commit fsync. Measured on NVMe, a
reapply drops from 148.80ms to 0.62ms.

## Problem

The archive bootstrap turns out to be the suite's largest unmeasured
cost, and the split that matters is invisible from outside the process.

Measured on this machine, identical work (the full 6-tier DDL, 2.2 MB
written, one process):

| | wall | cpu |
| --- | --- | --- |
| NVMe, default `synchronous=FULL` | 7.78s | 0.24s |
| NVMe, `PRAGMA synchronous=OFF` | 0.03s | 0.03s |
| tmpfs, default | 0.02s | 0.02s |

Under concurrent lane load the NVMe figure reached 36–50s while tmpfs
stayed at 0.63–0.71s. Absolute NVMe numbers swing with contention; the
~200–260x ratio held across every measurement. cProfile attributes ~99%
of cold wall to `sqlite3.Connection.executescript` with the process
burning almost no CPU — it is durability wait, not computation.

This matters more than it looks, because `devtools/verify_runs.py` sets
`POLYLOGUE_PYTEST_TMPFS = "0"` under `default_full_suite_scratch`:
broad-suite runs deliberately use NVMe while focused runs get tmpfs. So
the penalty applies to the full corpus run and is **structurally
invisible to per-module focused profiling**, which is how it went
unnoticed.

To size any fix you need to know how many initializations happen and,
critically, which kind — and there was no way to know. All three
outcomes look identical to a caller. A throwaway instrumented run showed
the volume is real and wildly uneven (`live_batch_support`: 377 builds
for 138 tests; `schema_generation`: 6 for 35), but a throwaway patch is
not a measurement anyone can repeat, and the rate varies 16x across
modules so a handful of samples cannot be extrapolated.

## Solution

**`polylogue/storage/sqlite/archive_tiers/bootstrap.py`** —
`_TIER_INIT_COUNTS` keyed `(tier, outcome)` under its own lock, with
`archive_tier_init_counts()` / `reset_archive_tier_init_counts()` as the
read side. Three outcomes, because they have three different costs and
three different fixes:

- `prototype_hit` — restored by page copy from this process's cache.
- `ddl_fresh` — verifiably-empty database, real DDL. Once per tier per
process for cacheable tiers; once per archive for `EMBEDDINGS`, which is
excluded from the cache.
- `ddl_reapply` — non-empty database, whole-tier DDL re-executed. Each
one is a fully redundant `executescript` plus its commit fsync.

The counter is an integer increment against work that already runs SQL.
The one added query is a `COUNT(*)` over `sqlite_master` on the
`EMBEDDINGS` path, which bypasses the cacheable branch and so had no
emptiness check to reuse; without it that tier could not be classified
at all.

**`devtools/pytest_progress_plugin.py`** — `_flush_archive_ddl_counts()`
writes one `.archive-ddl.json` sidecar per worker at session end and
`read_archive_ddl_counts()` sums them, mirroring the existing
`_flush_counts` / `read_progress_counts` pair exactly. The controller
folds the total into the summary payload as `archive_tier_init_counts`.
Sidecars rather than a shared file because the counters live inside each
pytest process — the supervisor cannot sample them from outside the way
it samples RSS or I/O. Telemetry failures are swallowed: a counter must
never fail a run.

## Verification

```
devtools test tests/unit/storage/test_archive_tier_init.py tests/unit/devtools/test_pytest_progress_plugin.py
  => 23 passed in 9.63s

devtools verify --quick
  => "status": "success"
```

End-to-end on a real run (`tests/unit/cli/test_plain_cli_snapshots.py`),
read back out of `.cache/verify/current-pytest-summary.json`:

```
"archive_tier_init_counts": {
  "audit.ddl_fresh": 1,      "audit.prototype_hit": 2,
  "embeddings.ddl_fresh": 3,
  "index.ddl_fresh": 1,      "index.prototype_hit": 2,
  "ops.ddl_fresh": 1,        "ops.ddl_reapply": 8,   "ops.prototype_hit": 2,
  "source.ddl_fresh": 1,     "source.prototype_hit": 2,
  "user.ddl_fresh": 1,       "user.prototype_hit": 2
}
```

That single field already shows the two findings the instrument exists
to size: `embeddings` never gets a `prototype_hit`, and `ops` alone
accumulates `ddl_reapply`.

### What the instrument corrected while being built

Writing the tests disproved my own reading of the code, which is worth
recording because it narrows the follow-up considerably. I expected any
tier reopened at the same version to re-run its DDL. It does not:
`initialize_archive_database` treats a same-version tier three different
ways — `INDEX` gets its targeted benign-DDL convergence, `USER` gets its
annotation-schema ensure, and every other tier returns immediately.
**`OPS` alone** routes back through `initialize_archive_tier`, which
finds a non-empty database and re-executes the entire tier schema.

So the redundant-executescript problem is one tier wide, and the
precedent for fixing it is in the same function: give `OPS` the same
targeted treatment `INDEX` already has — run its convergence plan and
`_ensure_ops_*` helpers, skip the whole-schema `executescript`. That is
*not* done here; it needs its own change and a test proving
`_ensure_schema_drift_samples_check` still fires on an already-versioned
database, since that repair deliberately runs at an unchanged
`user_version` (#3451 / polylogue-u6tl) and a naive version-equality
skip would silently disable it.

### Anti-vacuity

`test_tier_init_counts_separate_page_copy_from_fresh_ddl` fails if the
restore and DDL outcomes share a counter — collapsing them is precisely
what hides the cost.
`test_tier_init_counts_expose_the_ops_only_whole_schema_reapply` asserts
`ops.ddl_reapply == 2` and `index.ddl_reapply` absent, so it fails both
if OPS stops reapplying and if another tier starts.
`test_read_archive_ddl_counts_sums_every_worker_sidecar` fails without
summation, and its truncated-sidecar leg fails if a JSON error escapes
and takes the run's telemetry with it.

## The fix the instrument found, and the one it ruled out

polylogue-c1jgh proposed skipping the whole-tier `executescript` on a
`user_version` match. Measuring the parts first showed that would have
been the wrong target *and* actively unsafe.

Isolating a no-op OPS reapply on NVMe:

| what runs | median |
| --- | --- |
| `executescript` + `PRAGMA user_version = N` + commit (before) |
148.80ms |
| `executescript` + commit, no version write | 0.34ms |
| `executescript` only | 0.33ms |
| no `executescript`, version write + commit | 147.49ms |
| connect + `PRAGMA foreign_keys` only | 0.01ms |

**The `executescript` costs 0.33ms.** Hundreds of no-op `CREATE TABLE IF
NOT EXISTS` statements write nothing and are effectively free. The
entire 148ms is `PRAGMA user_version = N`, which rewrites the database
header *even when N is already the stored value*, dirtying a page and
forcing the commit to fsync.

So this PR removes only the redundant header write. It does **not** skip
the schema pass, for two independent reasons:

1. The reapply is the declared delivery mechanism for same-version
additive OPS changes — `initialize_archive_database`'s own comment says
it exists so "existing same-version archives receive newly introduced
tables and indexes", and `OPS_BENIGN_DDL_CONVERGENCE_PLAN` is two index
statements whose docstring says it runs *after* canonical DDL
reapplication. It presumes the reapply rather than replacing it.
2. It would disable `_ensure_schema_drift_samples_check`, which repairs
a stale CHECK at an unchanged `user_version` (#3451 / polylogue-u6tl).

Point 2 is not an argument, it is a measurement: patching in the
proposed version-equality skip makes
`test_same_version_reapply_still_repairs_a_stale_drift_samples_check`
fail, and the shipped guard leaves it passing. That test is the
load-bearing red twin.

After the fix, `nvme OPS reapply` is 0.62ms against `tmpfs 0.66ms` — the
reapply is no longer I/O-bound at all.

### Audit of the same shape on other tiers

`initialize_archive_tier` is reached directly, on databases that may be
non-empty, from `daemon/fts_startup.py` (INDEX),
`daemon/cursor_lag_baseline.py` ×2, `daemon/convergence_stages.py`,
`daemon/embedding_backlog.py` (OPS),
`operations/durable_change_train.py` ×2 (AUDIT),
`storage/sqlite/durable_change_train.py` ×4 (SOURCE) and
`maintenance/schema_inference_gate.py` (any tier). The header write was
unconditional for all of them, so the fix is placed in
`_initialize_archive_tier_ddl` and covers every caller and tier rather
than special-casing OPS.

Via `initialize_archive_database` the picture is narrower and worth
recording: only OPS routes a same-version open back through the
whole-schema path. INDEX gets its targeted benign-DDL convergence, USER
its annotation-schema ensure, and every other tier returns immediately.

## Pre-existing failures, not caused by this PR

`tests/unit/storage/test_durable_change_train.py` fails 1–2 tests
order-dependently
(`test_bootstrap_reconciles_and_persists_interrupted_train_evidence`,
`test_bootstrap_finishes_persisted_applied_train_without_reapplying`).
**This reproduces on pristine `origin/master`** — 2, 1, 1 failures
across three runs with master's `bootstrap.py` and
`pytest_progress_plugin.py` checked out — and is identical with and
without this PR's changes under deterministic ordering (`-p
no:randomly`: 2 failed both ways, same two tests).

Worth stating how nearly this went wrong: I first "bisected" it to this
PR by comparing `-k`-isolated runs (which always pass) against
full-module runs (which flake), and briefly reverted a correct fix on
that false signal. The tests only fail as part of the full module. They
are unrelated to this change and want their own Bead.

## Bead disposition matrix

| Bead | Whole-Bead disposition | Evidence | Residual |
| --- | --- | --- | --- |
| polylogue-c1jgh | **satisfied** |
`tests/unit/storage/test_archive_tier_init.py`; the `devtools test`
command above | none — all three contract tests land, and the INDEX
audit it asked for is in the body above |

The three-part test contract is met, with one substitution the
measurement forced: the bead's item (2) asked to prove the
`executescript` is skipped on a version match. It is not skipped,
because the measurement showed it costs 0.33ms and skipping it would
break both same-version OPS additive delivery and the u6tl repair. The
equivalent proof for what this PR actually does —
`test_same_version_reapply_does_not_rewrite_user_version`, which traces
the connection and asserts no header assignment is issued — is in its
place. Items (1) drift-samples repair still fires and (3) fresh-db path
unchanged are as specified.

polylogue-yh20k (EMBEDDINGS excluded from the prototype cache) is
untouched and remains the larger per-event cost at ~259ms per fresh
archive against this reapply's former ~148ms.

Ref polylogue-l218h, polylogue-yh20k

<!-- polylogue-pr-scope:v2
{
  "assigned_beads": [
    "polylogue-c1jgh"
  ],
  "dispositions": [
    {
      "bead_id": "polylogue-c1jgh",
      "disposition": "satisfied",
      "evidence": [
        {
          "kind": "test",
          "ref": "tests/unit/storage/test_archive_tier_init.py"
        },
        {
          "kind": "command",
"ref": "devtools test tests/unit/storage/test_archive_tier_init.py
tests/unit/devtools/test_pytest_progress_plugin.py"
        }
      ],
      "successors": []
    }
  ],
  "mutated_beads": [],
"scope_digest":
"24c20c79e18517867f987fa2a0233856c6b7026743705d54d52b57f30f6e3962",
  "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