Skip to content

fix(storage): Close a lineage cycle escape and two read-path defects - #5338

Merged
Sinity merged 3 commits into
masterfrom
fix/small-defects-batch
Sep 21, 2026
Merged

Sinity merged 3 commits into
masterfrom
fix/small-defects-batch

Conversation

@Sinity

@Sinity Sinity commented Sep 21, 2026

Copy link
Copy Markdown
Owner

⚠ Cross-repo: SEMANTICS_VERSION 4 → 5

The v1 record/manifest SHA-256s Sinex consumes did move. Sinex
(sinex-4j2.1) must regenerate its counterpart small-session fixture and accept
v5, or it gets a typed UnsupportedSemanticsVersionError instead of a silent
digest change. The bytes moved regardless — the version bump only makes the
coordination visible.

Exactly what moved: all six message record sha256s; all three transcript segment
sha256s; content_digest.polylogue_sha256 and revision_id
(add375b3e749… → 3ceb100d8a84…); size_bytes 7811 → 7877.
Not moved: head.ndjson, and every block, attachment, session, lineage and
usage record sha256.

Three beads, three verdicts

8v15p — intended change, not an encoder defect

Cause named: a9d2ffb (#5293), which moved MessageInput.*_tokens from
int = 0 to int | None = None. Proven by reverting exactly those four defaults
— a fresh encode then matched the checked-in fixture byte-for-byte. The only
moved values were the four token lanes going 0 → null on five messages
declaring no counters.

Three other commits touching material_protocol since the fixture was last
regenerated were excluded with reasons.

Because the record keys did not change — only an integer field's value domain
— the existing attachment key-set pin could not see the drift. That is why the
version bump is the fix rather than a quiet regeneration.

nzf93 — my single-hop hypothesis was refuted

The guard is full-chain by design: _would_create_cycle walks upward bounded
by _CYCLE_WALK_BUDGET = 1024, and an existing test builds a literal 1024-hop
chain.

The real escape is a read-after-write ordering gap: the walk read
sessions.parent_session_id, a projection _resolve_session_graph refreshes only
after its inbound-parent loop — so an edge resolved earlier in the same write
was invisible. The walk now follows the same authority
_refresh_session_projection derives that column from.

Outcome chosen: the closing edge is quarantined, the legitimate half keeps its
resolution. A→B becomes quarantined with cycle_path [A,B,A]; B→A stays
resolved.

No visited set was added, deliberately: termination is already bounded by the
budget, a loop not containing child_id is not producible through the two guarded
routes once the authority is correct (traced on a 3-cycle), and a third outcome
would need an evidence reason the census cannot classify.

3sic0 — five of eight claims already satisfied

Struck as already-done: comma-bearing session ids (the audit's line numbers were
stale), the capacity gate (duplicate of nru50), embeddings bootstrap, the
descriptor path, and _read_user_version. No work manufactured for any.

Three real fixes:

  • Tool pairing fan-out. run_projection_relations.py joined blocks to blocks
    on (session_id, tool_id) alone, so one re-emitted tool_id with N uses and M
    results yielded N×M tool_finished events. The ranking rule is now
    mirrored rather than depended on — reading the trigger-maintained
    action_pairs would make an un-refreshed table report zero events, a worse
    failure than the fan-out. That form was tried first and backed out.
  • Ownership claim refuted, different defect found and fixed.
    assert_owns_archive_location does check holds_ownership first, and a
    released token fails closed — the claim as written is wrong. But
    holds_ownership read the owner registry under root_identity while
    acquire/release key it on anchor_identity. Those coincide in an ordinary root
    — which is why no existing test sees it — and differ in exactly the generation
    symlink farm the product manufactures on every promotion
    . Proven producible: a
    live owner was refused its own lock.
  • Debt-read cancellation. The dedicated connection is required and stays
    (documented: ATTACH on the long-lived connection can fail with "database is
    locked"), so the bead's proposed remedy is refuted. But those handles started
    with no progress handler, outside every deadline boundary. Now wired through the
    existing configure_operation_read_connection hook.

Verification

  • devtools verify --quick via agentctl job 1901 — exit 0, all static gates
  • devtools render all --check — exit 0, zero out of sync
  • Final combined run — 224 passed, 1 inherited failure
  • Six mutations executed, each isolating its own test: restoring int = 0 → 3
    red; laundering a measured zero into unknown → exactly 1 red; reverting
    _walk_parent_of → only the new mutual-pair test red while four pre-existing
    cycle tests passed; a plain equality join → 4 events instead of 2; dropping the
    connection wiring → DID NOT RAISE OperationalError; reverting to
    root_identity → only the new farm test red, 31 passed.

⚠ Landing constraint

write.py, archive.py, archive_identity.py and run_projection_relations.py
are IN the closure. The identity moves and the archive must fully reconverge.
constants.py and input_model.py are out, so the material-protocol commit
carries no reconvergence cost.

Residuals

  • Two inherited reds, neither on the known-red list, both proven at base:
    test_material_adapter.py::test_naive_timestamps_are_utc_and_unordered_metadata_is_deterministic
    (pipeline/ids.py:524 hashes a block metadata payload containing a Python
    set → TypeError: Object of type set is not JSON serializable), and
    test_write_path_state_machine.py rule stale_replace_attempt.
  • A declared scope expansion into archive_identity.py: leaving it would have
    meant reporting "ownership validation is fixed" while it fails closed on
    legitimate maintenance work.
  • test_envelope.py's _seed_coordination_archive declared a messages table and
    inserted no rows while its blocks referenced m1 — not a producible state. The
    owning row is now seeded rather than weakening the join.

Closes polylogue-8v15p, polylogue-nzf93. Advances polylogue-3sic0.

🤖 Generated with Claude Code

https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq

Sinity and others added 3 commits September 21, 2026 08:03
The checked-in v1 fixture stopped matching a fresh encode at head. The
cause is #5293 (a9d2ffb), which changed MessageInput's four token
counters from `int = 0` to `int | None = None` so an absent per-message
counter stays unknown instead of being fabricated as a measured zero.

Proven, not assumed: reverting exactly those four defaults in the
worktree makes a fresh encode byte-identical to the checked-in fixture,
and the field-level diff shows the only moved values are
usage.{input,output,cache_read,cache_write}_tokens going 0 -> null on
the five fixture messages that declare no counters. Nothing else in the
encoder moved.

That is an intended change, and it moved public bytes. Every message
record digest, all three transcript segment digests, content_digest.
polylogue_sha256 and revision_id changed (revision_id
add375b3... -> 3ceb100d...); the head segment and every block,
attachment, session, lineage and usage record digest did not. Sinex
must regenerate its counterpart fixture.

Because the record keys did not change, the existing attachment key-set
pin could not see the drift, so SEMANTICS_VERSION goes to 5: the value
domain of an integer field changed, which breaks a typed consumer
exactly as a renamed key would, and the bump turns a silent digest
change into a typed UnsupportedSemanticsVersionError on the Sinex side.

Two new pins assert the v5 distinction directly rather than only
through bytes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
…ycle guard

polylogue-nzf93. The guard is full-chain by design, not single-hop -- the
1024-hop walk budget and its dedicated over-budget test settle that. The
mutual-parent escape is a read-after-write gap instead.

_would_create_cycle walked sessions.parent_session_id, a projection that
_resolve_session_graph refreshes only AFTER its inbound-parent loop, so
every edge resolved earlier in the SAME write was invisible to it.
Reproduced through real ArchiveStore writes: A(parent=B) lands before B
exists and stays unresolved; B(parent=A) then resolves B -> A outbound,
and the inbound loop's walk out of B still read a NULL column and called
A -> B acyclic. Both edges resolved and sessions.parent_session_id itself
closed a two-node loop, which is a cycle in the walk lineage reads
recompose with.

The walk now reads the authority _refresh_session_projection derives that
column from: the first composing resolved session_links edge, in the same
order, falling back to the column when a session carries no such edge.
Guard and projection can no longer disagree, which is also why the
recorded cycle_path still validates against the census's projection check.

No visited set: the walk stays bounded by _CYCLE_WALK_BUDGET, a loop that
does not contain child_id is not producible through the two guarded
resolution routes, and a third outcome would need an evidence reason the
census cannot classify.

Outcome for a mutual pair: the closing edge is quarantined with
cycle_rejected evidence, the legitimate half keeps its resolution, and a
reader walking parent_session_id terminates from either end.

write.py is IN the derived schema closure (devtools schema closure):
the identity moves and the archive must reconverge, so this must land
before a rebuild starts, never during one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
…aims

polylogue-3sic0, verified claim by claim at head rather than re-fixing
what already landed.

Already satisfied, no work done:
- Comma-bearing session ids in the dedup aggregates. archive.py:343
  decodes a typed JSON array and the four aggregates emit
  json_group_array(DISTINCT ...) at :3162/:3193/:3436/:3507. No
  GROUP_CONCAT aggregate and no split(",") remain in the file.
- Capacity gate filesystem. candidate_capacity.py:518 measures the
  store's generations root, wired at :671 from :572. This item is a
  strict duplicate of polylogue-nru50 and is struck from the scope.
- Embeddings same-version opens. bootstrap.py:383 has the EMBEDDINGS
  branch and raises when sqlite-vec will not load.
- Linux-only descriptor paths. index_generation.py:1733/:1884 route
  through descriptor_alias_path.
- Diagnostic schema reads. archive_debt.py:211 documents that it must
  not validate, which is the claimed fix.

Fixed here:

1. Tool pairing fabricated pairs. run_projection_relations.py joined
   blocks to blocks on (session_id, tool_id) alone, so one re-emitted
   tool_id with N uses and M results produced all N*M tool_finished
   events -- each pairing a use with a result it never produced. xnkf
   fixed this fan-out for action_pairs after verifying it live; the
   ranking rule is mirrored here rather than depended on, because
   polylogue-dab made these relations read durable rows only and a
   stale action_pairs would report zero events instead of too many.

2. Debt reads ran outside every cancellation boundary. The dedicated
   short-lived connection is deliberate and stays (its own test proves
   ATTACH on the long-lived handle races a caller's transaction), but
   it started with no progress handler, so a disconnected caller or an
   expired deadline could not interrupt those scans. It now passes
   through configure_operation_read_connection, the existing hook for a
   sibling handle.

3. OwnedArchiveLocation refused its own owner. holds_ownership read the
   process-local owner registry under root_identity while acquire and
   release key it on anchor_identity. Those agree in an ordinary root
   -- which is why the existing never-acquired/released test cannot see
   it -- and differ in exactly the generation symlink farm the anchoring
   exists for (polylogue-81v76), which the product manufactures on every
   promotion. Reproduced through the real acquire route: a token holding
   a live flock reported holds_ownership False and
   assert_owns_archive_location raised "never acquired or has been
   released". The rest of that claim is refuted: the holds_ownership
   gate is present and correct at :622.

The coordination fixture gains the messages row its own schema implies:
blocks.message_id is an FK into messages in the real index tier, and
rank pairing orders by message position, so a block without its message
is not a producible state.

All three production files are IN the derived schema closure
(devtools schema closure), as is write.py from the previous commit:
the identity moves, the archive must reconverge, and this must land
before a rebuild starts.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
@coderabbitai

coderabbitai Bot commented Sep 21, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 49 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: f5a22b4b-d537-4e68-b158-fc998ac2643e

📥 Commits

Reviewing files that changed from the base of the PR and between dadfc35 and ddd4df7.

📒 Files selected for processing (15)
  • polylogue/material_protocol/v1/constants.py
  • polylogue/storage/archive_identity.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • polylogue/storage/sqlite/run_projection_relations.py
  • tests/fixtures/material_protocol/v1/small-session/manifest.json
  • tests/fixtures/material_protocol/v1/small-session/segments/seg-00000.ndjson
  • tests/fixtures/material_protocol/v1/small-session/segments/seg-00001.ndjson
  • tests/fixtures/material_protocol/v1/small-session/segments/seg-00002.ndjson
  • tests/unit/coordination/test_envelope.py
  • tests/unit/insights/test_run_projection_materialization.py
  • tests/unit/material_protocol/v1/test_semantics_version_gate.py
  • tests/unit/storage/test_archive_identity.py
  • tests/unit/storage/test_archive_tiers_archive.py
  • tests/unit/storage/test_topology_cycle_quarantine_live.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.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 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
📝 Code Review ✅ Completed 2026-09-21T06:10:52.189607Z ddd4df7 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.

@Sinity
Sinity enabled auto-merge (squash) September 21, 2026 06:04

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ddd4df71ba

ℹ️ 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".

@Sinity
Sinity merged commit bdeac28 into master Sep 21, 2026
3 checks passed
@Sinity
Sinity deleted the fix/small-defects-batch branch September 21, 2026 06:14
@Sinity

Sinity commented Sep 29, 2026

Copy link
Copy Markdown
Owner Author

Closing out open Codex review threads on this PR (evidence checked against master at c950478):

Resolving every thread listed; confirmed defects are fixed under the named bead.

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