Repository navigation
Fix 20 reviewed storage defects in schema identity, writer and vectors - #4594
Conversation
Attachment records gained direction, producer_ref and caption under SEMANTICS_VERSION 3, so the encoder emitted bytes the declared version did not describe and the checked-in cross-repo fixture went stale. Bump to 4 and regenerate the fixture. Two gaps let a reader trust bytes it does not implement: resolve_anchor verified an anchor's digest but never the manifest's semantics version, and RevisionManifest.from_dict coerced the declared version with int(), so a declared 3.9 truncated into a supported 3. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YGi8wLWGR2HYBh8p8fXFXz
PRAGMA user_version is a migration cursor, not a proof that a tier's read models are interpretable by this runtime, and the bootstrap routes rewrite it while materialising. The post-materialisation check therefore validated a value it had just written, and the derived identity stamp it should have checked was never committed. - initialize_archive_tier commits the stamp, which lands after the materialisation commit and otherwise rolls back on close. - open_initialized_tier_connection admits the stored version before materialisation can restamp it. - Tier admission asserts the derived identity alongside the version. - assert_readable_archive_layout distinguishes a SQLite failure that never inspected the schema from a manifest mismatch, instead of prescribing a rebuild for both. - The canonical manifest is cached per declared schema rather than re-executed into a fresh in-memory database on every read open, and excludes FTS5 shadow tables so an FTS5 build change is not reported as archive drift. - Raw-failure admission and frontier source selection read through the schema-enforcing open instead of bypassing validation. - schema_identity is classified in the rebuild differential, which otherwise raises on every current archive. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YGi8wLWGR2HYBh8p8fXFXz
…dence Three places where the writer copied one piece of evidence and ignored another that had since arrived: - An attachment on a model turn whose provider supplied no message id derived a producer-less model_output, and the writer then refused the whole session. The producer names the turn, so the archive's own message_id identifies it when the provider offered nothing. - A block merge coalesced tool_outcome, tool_result_is_error and tool_result_exit_code independently, so a merge could persist a fresh outcome beside stale error flags that contradict it. The four columns describe one verdict and are now taken from one row together. - Hook evidence resolved into session_links refreshes a session's branch_type, but session_kind was derived once at admission from parser evidence alone, so a subagent child discovered after admission stayed PRIMARY forever. test_writer_refuses_attachment_without_derived_direction encoded the refusal contract #4561 replaced and had been failing since; it is replaced by tests for the derivation that now happens. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YGi8wLWGR2HYBh8p8fXFXz
count_session_embeddings counted rows in the eligible-message projection, which says a message should be embedded rather than that a vector exists, so a session mid-materialization or with failed embeds reported embedded messages it did not have -- surfaced to users as "N embedded messages" via source_embedded_messages. It now counts stored refs joined to vector metadata. ATTACH creates a missing database, so a missing active index silently became an empty one and the projection reported an archive with no eligible messages. The path is checked before attaching. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YGi8wLWGR2HYBh8p8fXFXz
The provider reports one total per session, attributed to the single model in play. A full replace clears session_model_usage first, so only the current model survives; a merge-append leaves the prior model's row in place with its own attributed total, and usage.py's SUM(provider_cost_usd) then counts the same dollars twice. test_merge_append_replaces_prior_provider_total_on_model_switch asserted this contract and has been failing since #4505 added it. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YGi8wLWGR2HYBh8p8fXFXz
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars. ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Team Run ID: 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. Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d52111db7c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Devtools half of the unaddressed-Codex-review sweep (26 findings verified against current master, 41 tests). Sibling PRs: #4580, #4582, #4583, #4587, #4594. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01YGi8wLWGR2HYBh8p8fXFXz --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
The upward walk that resolves a session's repository stopped at nothing, so with the managed temp trees inside the checkout every scratch path resolved to the checkout itself. The walk now stops before a listed ceiling, as git does, and the ceiling is part of the normalization cache key. Tests: tool results without structural evidence are admitted as unknown with not_reported (#4539) and the writer refusal is exercised on a block with no evidence at all; block payloads carry tool_outcome (#4502); a provider-reported cost rolls up as "exact" (#4493); the v61 replace-table keeps the surviving canonical columns; the bulk-delete canaries and the naive-join survivor use TEMP objects on the opened connection so the schema manifest check at open no longer refuses them (#4472, #4594). Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YGi8wLWGR2HYBh8p8fXFXz
Summary
Fixes 20 of the 22 Codex review findings recorded for storage. One is refuted
with evidence, one is confirmed only in part, and two are deferred with
reasons. Five commits, one per seam:
material-protocol— semantics versioning and read gatingstorage— derived schema identity, manifests, lifecycle admissionstorage— writer provenance, tool verdicts, session kindstorage— vector counting and index attachmentstorage— provider cost attribution on appendEvery finding was re-confirmed by behavior at this branch's base
(
c1d2544f0); the recorded line numbers were treated as hints, since they werecaptured against
cc58ef3e6.Problem
Semantics versioning (#4554, #4557)
material_protocol/v1/constants.py:22:SEMANTICS_VERSIONwas 3while attachment records had gained
direction,producer_refandcaption, so the encoder emitted bytes the declared version did notdescribe.
test_checked_in_bytes_match_a_fresh_encodewas red on master.Confirmed by decoding both sides: the fresh encode carries the three keys,
the checked-in fixture does not.
material_protocol/v1/verify.py:50-92:resolve_anchorverified ananchor's digest, record id and seq but never the manifest's semantics
version. Only
verify_revisioncalledrequire_current_semantics, so thesingle-record read path decoded records whose shape this reader may not
implement.
material_protocol/v1/manifest.py:194:int(payload["semantics_version"])coerced before comparison, so a declared3.9truncated to a supported3.Schema identity, manifests, lifecycle (#4544, #4546, #4548, #4560, #4556)
archive_tiers/index.pyappendsschema_identitytoINDEX_DDL,but
tests/infra/reindex_differential.py::compared_table_censusraises onany DDL table with no declared classification, so the rebuild differential
raised on every current archive.
schema_manifest.py:canonical_schema_manifestexecuted the wholetier DDL into a fresh
:memory:database on every call, and every read openasserts against it.
schema.py:73:except (RuntimeError, sqlite3.Error)reportedrebuild_indexfor both, so a SQLite failure that never inspected the schemawas indistinguishable from real drift — and told the operator to destroy a
sound index.
schema_manifest.py:33: the projection filtered onlyNOT LIKE 'sqlite_%', so FTS5 shadow tables were compared and an FTS5 buildchange would read as archive schema drift.
archive_tiers/bootstrap.py:open_initialized_tier_connectionraninitialize_archive_tierbeforeassert_tier_schema_supported._apply_archive_tier_convergencerewritesuser_versionto the spec version(bootstrap.py:387-388), so the check validated a value the same call had just
written: a tier at some other version was restamped into apparent currency
and admitted.
initialize_archive_databasegets this right (it reads thestored version first, bootstrap.py:553); this route did not.
stamp_derived_schema_identityissues anINSERT ... ON CONFLICTand never commits. It runs after
_materialize_archive_tier's own commit,so it sits in its own open transaction and rolls back on close. Some callers
committed afterwards;
open_initialized_tier_connectionand the OPSsame-version reapply did not.
connection_profile.py: the post-materialization check read onlyPRAGMA user_versionand never the derived identity — the one thing thestamp exists for, and the only one of the two that materialization has not
just overwritten.
raw_failure_lifecycle.py:111:validate_schema=Falseon theadmission path (callers
bulk_rebuild.py,archive_verification.py).archive_readiness.py:269: baresqlite3.connect(...mode=ro)withno version check, reached from
readiness/capability.py's frontiersource-selection. Its result is surfaced to users as
source_embedded_messages.Writer (#4506, #4561)
write.py:session_kindis derived once at admission fromsession.branch_typealone._refresh_session_projectionlater re-derivesbranch_typefrom resolvedsession_links— including hook-authoritativeedges the parser never saw — but its
UPDATEs never touchedsession_kind,so a subagent child discovered after admission stayed
PRIMARYpermanently.write.py::_coalesce_block_row:tool_outcome,tool_result_is_error,tool_result_exit_codeandtool_result_outcome_unknown_reasonwere each coalesced independently by_coalesce_scalar, so a merge could persist a freshsuccessbeside a staleis_error=1/exit_code=1that contradicts it.write.py::_attachment_provenance: with nomessage_idfallback, amodel turn whose provider supplied no message id derived
("model_output", None), which the writer then rejects — failing the wholesession write. Superseded during this work: fix(sources): correct eleven reviewed acquisition and proof defects #4587 landed the same fix
with a better implementation (
resolved_message_id, applied to theparser-declared path as well as the role-derived one). This branch drops its
own version and keeps master's. Finding 5 is still fixed here, because fix(sources): correct eleven reviewed acquisition and proof defects #4587
did not touch the stale test.
tests/.../test_archive_tiers_write.py:test_writer_refuses_attachment_without_derived_directionstill asserted therefusal contract fix(storage): derive attachment direction from the owning turn #4561 replaced, and was red on master with
DID NOT RAISE.Embeddings and vector search (#4538)
sqlite_vec_runtime.py:98:ATTACH DATABASE ?with no existencecheck. ATTACH creates the file, so a missing active index silently became an
empty database and the projection reported an archive with no eligible
messages.
sqlite_vec_queries.py:277-293:count_session_embeddingscountedrows in
current_embedding_messages— the eligible-message projection,which has no relation to
message_embeddings— so a session midmaterialization or with failed embeds reported vectors it did not have. The
value reaches users through
repository_vectors.py→daemon/similarity.py→web_shell_similar.pyas "N embedded messages".Solution
Semantics: bump
SEMANTICS_VERSIONto 4 and regenerate the checked-incross-repo fixture; gate
resolve_anchoron the version asverify_revisionalready was; read the declared version as an exact integer, rejecting
bool,non-integral floats and strings.
Schema identity: commit the stamp inside
initialize_archive_tier, the singlechoke point every derived-tier materialization passes through; admit the
stored version in
open_initialized_tier_connectionbefore materializationcan restamp it; assert the derived identity in
assert_tier_schema_supportedalongside the version; split
assert_readable_archive_layout's handler so aSQLite failure reports a new
retrylifecycle action instead ofrebuild_index; cache the canonical manifest per declared schema, keyed on theDDL so a substituted schema cannot take a stale hit; exclude FTS5 shadow tables
by exact suffix; route raw-failure admission and frontier source selection
through the schema-enforcing open; classify
schema_identityin the rebuilddifferential as comparable, since a rebuild producing a different identity is
exactly what that differential is for.
Writer: take all four tool-verdict columns from one row together; re-derive
session_kindthroughadmitted_session_kindwherever the projection writesbranch_type; replace the stale attachment-direction refusal test with testsfor the derivation #4587 introduced.
Vectors: count distinct stored refs joined to vector metadata; refuse a missing
active index instead of creating one.
Half-refuted, half-fixed
3 — "
_seed_session_model_usage_rowsnever clears rows for a previousmodel, so
usage.py'sSUM(provider_cost_usd)double-counts after a modelswitch."
Refuted for the full-replace path, which is the mechanism as stated.
Every full-replace write first calls
_clear_session_projection_rows, whosetable list includes
session_model_usage(write.py:1217), so no stale rowsurvives to be summed. Two existing tests cover exactly this and pass:
test_provider_usage_model_switch_on_reingest_does_not_double_countandtest_provider_usage_model_vanishing_on_reingest_leaves_no_stale_rollup.Confirmed for merge-append, which that clearing cascade does not cover.
master already carries a test for the intended contract —
test_merge_append_replaces_prior_provider_total_on_model_switch, added byfix(storage): triage deferred review findings #4505 — and it has been failing ever since, because nothing clears the prior
model's
provider_cost_usd. Verified by exercising the writer directly atmaster's
write.pyand at this branch's: both returned[gpt-new 2.0, gpt-old 1.0]where the test requiresgpt-oldto beNone.The fifth commit clears the prior attribution, and that same probe now
returns
[gpt-new 2.0, gpt-old None].Refuted, not fixed
SameVersionSchemaVarianthas no upper bound; the index tier is atv85 while the v78 SEMANTIC_REPARSE entry's variant is still unbounded." There
is no v78 variant.
INDEX_SAME_VERSION_SCHEMA_VARIANTScontains exactly oneentry,
introduced_version=63(remove_fts_bulk_guardon three trigramtriggers), and always has. The named entity does not exist, so there is no
concrete input with a wrong outcome. The open-ended applicability of that one
entry is a deliberate property of a permanently retained benign trigger-body
variant, not a defect.
Deferred, with reasons
Two findings are real and unfixed here because each is a design change rather
than a review-sweep patch. Both warrant their own tracked work:
non-atomically, and both
writer_lock()andrecover_interrupted()call_generations(), which raises on the resulting mismatch with no path out.Confirmed still true. A fix means making
generation.jsonpublicationcrash-safe and giving recovery a way to re-derive the contract from the
committed database; that is the embeddings lifecycle's durability contract,
not a patch.
sqlite_vec_runtime._get_connectionrebuilds the fullcurrent_embedding_messagesprojection — a whole-archive scan and join witha per-row hash — on every connection, and every query opens its own
connection. Confirmed still true. A fix needs a cache keyed on index
generation or a pooled connection, with the invalidation and concurrency
design that implies.
Also worth noting: there is no
devtoolscommand to regenerate thematerial-protocol golden fixture. It was regenerated here through
encode_session_revision+write_revisionand verified byte-for-byte againsta fresh encode; a supported regeneration route would be a reasonable follow-up.
Verification
All twelve static gates pass, including
schema-versioning.Anti-vacuity was checked by mutation, not assumed. Reverting the
conn.commit()in
initialize_archive_tierturnstest_schema_identity_stamp_survives_the_connection_that_wrote_itred;deleting the stored-version admission from
open_initialized_tier_connectionturns
test_a_skewed_tier_is_refused_before_materialisation_restamps_itred.Both were run and observed. Every new test's docstring names the specific
mutation that makes it fail.
Residual risk
assert_tier_schema_supportedrefuses atier at the current version whose stamp does not match this runtime. That is
the intent, and
initialize_archive_databasealready enforced the same checkon its own route, so an archive in normal use is already stamped. The check
is deliberately not on every
open_connection— an earlier draft put it in_assert_schema_supported, which would have made every read open recomputederived_schema_identity(uncached, over three fingerprints) and would haverefused any never-stamped archive on a read-only path.
lifecycle_action="retry"is a new value in that field. It is free-form andforwarded to MCP payloads; no closed vocabulary or dispatch consumes it.
name prefix. A prefix would have wrongly dropped
messages_fts_identityandthe three
messages_fts_a{i,d,u}triggers, which are ours; the test assertsboth halves.
SEMANTICS_VERSIONto 4 makes this reader reject v3 bytes bycontract.
constants.pynotes the fixture is checked in "in lockstep withthe Sinex counterpart (sinex-4j2.1)"; that repo pins the same version and
will need the corresponding bump. Nothing in this repo reads v3 bytes from
disk outside the regenerated fixture.
tests/unit/storage/test_archive_readiness.pybuilds stub two-table indexdatabases to exercise gap classification. Now that the probe reads through
the schema-enforcing open, those fixtures stamp the precondition explicitly
via a named helper rather than relying on the probe not checking.
Inherited failure
tests/unit/storage/test_connection_profile.py::test_open_readonly_connection_uses_descriptor_bound_databasefails identically on clean
origin/master(verified by stashing this branch'schanges and rerunning). It is not touched or fixed here.
test_merge_append_replaces_prior_provider_total_on_model_switchwas alsoinherited-red, confirmed the same way; unlike the above it is fixed here,
because it is the merge-append half of finding 3.
🤖 Generated with Claude Code
https://claude.ai/code/session_01YGi8wLWGR2HYBh8p8fXFXz