Skip to content

fix(storage): unify cross-route revision authority - #2716

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/typed-raw-replay-outcomes
Jul 11, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/typed-raw-replay-outcomes

Conversation

@Sinity

@Sinity Sinity commented Jul 11, 2026 •

Copy link
Copy Markdown
Owner

Summary

Unify single-session full captures and multi-session export members under one typed semantic revision authority when they describe the same logical session.

Problem

Production post-repair catch-up proved the existing split was arrival-order dependent. An older Gemini full snapshot retried forever against a semantic head, while a ChatGPT browser capture for an account-export session collided at the same frontier. More seriously, a numerically larger but divergent single capture could pass cardinality-only CAS and overwrite the membership-governed session.

Ref polylogue-yla8.

Solution

  • Move only self-contained, append-independent full cohorts from byte revision fields into durable membership census rows.
  • Handle both bundle-first and single-first arrival, including raws already bound by a previous failed deployed attempt.
  • Transition a related byte head to semantic authority inside the same index transaction as the replacement and receipts.
  • Keep divergent or insufficiently ordered metadata variants ambiguous and retry-visible.
  • Accept metadata-only revisions only with pairwise-unique direct provider update timestamps.
  • Stop browser capture from substituting provenance capture time for missing provider updated_at.
  • Reuse one membership application helper and report the accepted cohort member's message count.

Verification

  • devtools test -k 'single_session_full or bundle_promotes_prior_single_full or live_multi_session_divergence or metadata_revision or browser_capture_does_not_launder' tests/unit/sources/test_live_batch_support.py tests/unit/archive/test_session_revision_membership.py tests/unit/sources/test_browser_capture.py — 7 passed.
  • devtools test tests/unit/archive/test_session_revision_membership.py — 5 passed.
  • devtools test tests/unit/storage/test_revision_replay.py::test_full_replay_preserves_semantic_head_and_rolls_back_regressions — 1 passed.
  • devtools verify --quick — run 20260711T220233Z-quick-1445786-3516ef36, 13/13 steps passed.
  • Full test_live_batch_support.py result was 47 passed / 6 failed; all six exact failures reproduced unchanged on a clean detached origin/master checkout and are unrelated baseline failures.
  • Three independent adversarial review rounds found and then verified closure of dual-governance, reverse-arrival, rebuild-stability, byte-head rollback, and timestamp-laundering blockers; final review found no release blocker.

Anti-vacuity: on origin/master, the older cross-route full rejects instead of becoming terminal, a larger divergent single full overwrites by cardinality, already-bound failed raws remain byte-selected during rebuild, and reverse arrival hits incomparable frontier authority. The new real ArchiveStore/source/index tests require all four outcomes to change while preserving ambiguous branches.

Summary by CodeRabbit

  • Bug Fixes
    • Improved revision selection when provider update timestamps distinguish otherwise equivalent membership data.
    • Prevented missing capture metadata from being treated as a provider update time.
    • Improved full-ingest membership precedence and handling of conflicting revisions.
    • Preserved previously accepted messages when divergent revisions are rejected.
  • Tests
    • Added coverage for timestamp-based selection, ambiguous metadata, browser capture timestamps, and live-ingest authority transitions.

Problem
Single-session full captures and multi-session export members used separate
revision authorities. Their result depended on arrival order: older inputs
could retry forever, while a larger divergent single capture could overwrite
a semantic membership head using cardinality alone.

What changed
Move full-only byte cohorts into membership governance when the same logical
session crosses acquisition routes. Retire the old source authority fields,
transition a proven related byte head atomically, and preserve ambiguous
branches as visible debt. Metadata-only variants require unique direct provider
timestamps; browser capture no longer substitutes acquisition time.

Verification
Focused cross-route and metadata matrix: 7 passed. Membership classifier file:
5 passed. Existing semantic CAS rollback: 1 passed. Quick verification run
20260711T220107Z-quick-1439990-e188c57b passed all 13 steps.

Ref polylogue-yla8.

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Membership revision classification now incorporates provider update timestamps. Full-ingest processing centralizes membership reconciliation and adds archive governance transitions for eligible full revisions, with coverage for timestamp ambiguity, authority precedence, divergent heads, and bundle promotion.

Changes

Membership governance

Layer / File(s) Summary
Timestamp-aware membership classification
polylogue/archive/session_revision_membership.py, polylogue/sources/parsers/browser_capture.py, polylogue/sources/revision_backfill.py, tests/unit/archive/test_session_revision_membership.py, tests/unit/sources/test_browser_capture.py
MembershipRevision carries provider_updated_at; classification can select the latest distinct parseable provider timestamp, while browser parsing avoids provenance fallback and backfill propagates session.updated_at.
Archive membership authority transitions
polylogue/storage/sqlite/archive_tiers/archive.py
Membership census replacement can retire eligible self-contained full revisions, convertible full raw IDs can be queried, and matching byte heads can be removed during membership classification.
Live full-ingest reconciliation
polylogue/sources/live/batch.py, tests/unit/sources/test_live_batch_support.py
Full-ingest membership handling delegates to _apply_membership_sessions, which re-replaces census data, classifies retained revisions, replays accepted sessions, and reports counts and authority completeness; tests cover precedence, divergence, and bundle promotion.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant FullIngest as _ingest_full_records_archive
  participant ArchiveStore
  participant MembershipSessions as _apply_membership_sessions
  FullIngest->>ArchiveStore: replace_raw_membership_census
  FullIngest->>MembershipSessions: apply retained membership sessions
  MembershipSessions->>ArchiveStore: convertible_full_revision_raw_ids
  MembershipSessions->>ArchiveStore: apply_raw_membership_classification
  ArchiveStore-->>MembershipSessions: accepted raw IDs and authority state
  MembershipSessions-->>FullIngest: session IDs and message counts
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed It concisely reflects the main change: unifying revision authority across routes.
Description check ✅ Passed It covers the required Summary, Problem, Solution, and Verification sections and is mostly complete.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/typed-raw-replay-outcomes

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 commented Jul 11, 2026

Copy link
Copy Markdown
Owner Author

GitHub-hosted checks failed before runner allocation: all affected jobs show approximately two-second lifetimes with no executed steps, matching the repository account billing lock already observed on PRs #2710, #2713, #2714, and #2715. This is external infrastructure state, not a code-gate result. Local final-head gate 20260711T220233Z-quick-1445786-3516ef36 passed 13/13; focused real-route authority tests are recorded in the PR body. GitGuardian passed. CodeRabbit review remains in progress and will be triaged before merge.

@Sinity

Sinity commented Jul 11, 2026

Copy link
Copy Markdown
Owner Author

CodeRabbit remained in progress without findings for more than four minutes after processing started. Three bounded independent adversarial review rounds already found and drove correction of substantive authority blockers; the final round found no release blocker. I am classifying the still-running bot as a delayed tool result, not an unresolved actionable finding, and proceeding under the documented admin merge exception for the pre-allocation CI billing lock.

@Sinity
Sinity merged commit 0653ebd into master Jul 11, 2026
3 of 15 checks passed
@Sinity
Sinity deleted the feature/fix/typed-raw-replay-outcomes branch July 11, 2026 22:08

@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: 7868046e6c

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

member_sessions[raw_id] = session
projections[raw_id] = projection
revisions.append(MembershipRevision(raw_id, projection))
revisions.append(MembershipRevision(raw_id, projection, session.updated_at))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Route mixed backfill cohorts through membership authority

Passing updated_at here only affects pure membership cohorts; during repair/cold rebuild, a pre-existing split source state with a single-session raw still bound in raw_sessions.logical_source_key and a bundle member for the same logical key is still skipped by the membership loop because the key is also in logical_keys. In that scenario backfill replays the byte full and never runs the new timestamp-aware membership classification/conversion, so rebuilding index.db can regress the cross-route unification that live ingest now applies and leave the newer bundle member ignored. Mixed keys need to be converted/classified through the membership path before byte replay is allowed to win.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai 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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@polylogue/archive/session_revision_membership.py`:
- Around line 29-59: Extract the per-content-group resolution logic from the
main membership revision grouping flow into a helper such as
_resolve_metadata_representative(metadata_variants), returning the selected
representative(s) and equivalent raw IDs. Preserve the existing session-hash
deduplication, timestamp tie-break, and ambiguity behavior exactly, and update
the caller to use the helper.

In `@polylogue/sources/live/batch.py`:
- Around line 1690-1764: The _apply_membership_sessions method combines two
independent responsibilities, making the high-complexity segment harder to read.
Extract the convertible FULL revision retirement logic into a private helper
such as _retire_convertible_full_revisions and the membership
classification/application logic into a helper such as
_classify_and_apply_members, then call both from the existing per-session loop
while preserving their current behavior and return-count handling.

In `@polylogue/storage/sqlite/archive_tiers/archive.py`:
- Around line 1752-1770: Update convertible_full_revision_raw_ids and its live
batch caller so linked FULL raws are retired from the chain tail toward the
head, rather than raw_id order. Return or iterate the cohort in
successor-to-predecessor chain order, ensuring each later raw is retired before
any predecessor and avoiding the active byte-revision-chain guard.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3d8ab634-f2d9-47ec-86ed-e0e65f4457ae

📥 Commits

Reviewing files that changed from the base of the PR and between 0e0cdda and 7868046.

📒 Files selected for processing (8)
  • polylogue/archive/session_revision_membership.py
  • polylogue/sources/live/batch.py
  • polylogue/sources/parsers/browser_capture.py
  • polylogue/sources/revision_backfill.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/archive/test_session_revision_membership.py
  • tests/unit/sources/test_browser_capture.py
  • tests/unit/sources/test_live_batch_support.py

Comment on lines +29 to +59
by_content: dict[tuple[tuple[bytes, ...], tuple[bytes, ...], frozenset[bytes]], list[MembershipRevision]] = {}
for revision in revisions:
by_session_hash.setdefault(revision.projection.session_hash, []).append(revision)
projection = revision.projection
key = (projection.message_hashes, projection.event_hashes, projection.attachment_hashes)
by_content.setdefault(key, []).append(revision)
representatives: list[MembershipRevision] = []
equivalents: list[str] = []
for group in by_session_hash.values():
ordered_group = sorted(group, key=lambda item: item.raw_id)
representatives.append(ordered_group[0])
equivalents.extend(item.raw_id for item in ordered_group[1:])
for group in by_content.values():
by_session_hash: dict[bytes, list[MembershipRevision]] = {}
for item in group:
by_session_hash.setdefault(item.projection.session_hash, []).append(item)
metadata_variants: list[MembershipRevision] = []
for hash_group in by_session_hash.values():
representative = min(hash_group, key=lambda item: item.raw_id)
metadata_variants.append(representative)
equivalents.extend(item.raw_id for item in hash_group if item.raw_id != representative.raw_id)
if len(metadata_variants) == 1:
representatives.extend(metadata_variants)
continue
timestamped = [
(parsed.timestamp(), item)
for item in metadata_variants
if (parsed := parse_timestamp(item.provider_updated_at)) is not None
]
timestamps = [timestamp for timestamp, _item in timestamped]
if len(timestamped) == len(metadata_variants) and len(set(timestamps)) == len(timestamps):
representative = max(timestamped, key=lambda pair: pair[0])[1]
representatives.append(representative)
equivalents.extend(item.raw_id for item in metadata_variants if item.raw_id != representative.raw_id)
else:
representatives.extend(metadata_variants)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Verified correct against all three new tests; recommend extracting the timestamp tie-break into a helper.

Traced the new grouping (content-hash → session-hash → timestamp tie-break) against test_metadata_only_revision_uses_latest_provider_timestamp, test_metadata_revision_without_complete_provider_time_is_ambiguous, and test_metadata_revisions_with_equal_provider_time_are_ambiguous: the logic correctly (a) only invokes timestamp resolution when there are 2+ distinct session_hash variants sharing identical message/event/attachment content, (b) requires every variant to have a parseable, pairwise-distinct timestamp before picking a representative, and (c) falls back to adding all variants as same-frontier representatives (which the later dominance check correctly turns into full ambiguity) otherwise. No functional issues found.

Given this function is flagged as high complexity and sits on a data-integrity-critical path, consider extracting the per-content-group representative resolution (lines 36-59) into a small helper (e.g. _resolve_metadata_representative(metadata_variants) -> tuple[MembershipRevision, list[str]]) to make the two resolution strategies (dedupe-by-session-hash vs. timestamp tie-break) easier to reason about independently. The existing tests give good coverage to do this safely.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/archive/session_revision_membership.py` around lines 29 - 59,
Extract the per-content-group resolution logic from the main membership revision
grouping flow into a helper such as
_resolve_metadata_representative(metadata_variants), returning the selected
representative(s) and equivalent raw IDs. Preserve the existing session-hash
deduplication, timestamp tie-break, and ambiguity behavior exactly, and update
the caller to use the helper.

Comment on lines +1690 to +1764
def _apply_membership_sessions(
self,
archive: Any,
source_raw_id: str,
sessions: list[Any],
*,
acquired_at_ms: int,
) -> tuple[list[str], int, int, bool]:
session_ids: list[str] = []
session_count = 0
message_count = 0
for session in sessions:
logical_source_key = f"{session.source_name.value}:{session.provider_session_id}"
for revision_raw_id in archive.convertible_full_revision_raw_ids(logical_source_key):
retained_sessions = (
sessions
if revision_raw_id == source_raw_id
else self._parse_retained_raw_sessions(archive, revision_raw_id)
)
matches = [
item
for item in retained_sessions
if f"{item.source_name.value}:{item.provider_session_id}" == logical_source_key
]
if len(retained_sessions) != 1 or len(matches) != 1:
raise RuntimeError(
f"full revision {revision_raw_id}:{logical_source_key} no longer parses uniquely"
)
archive.replace_raw_membership_census(
revision_raw_id,
retained_sessions,
parser_fingerprint=self._current_parser_fingerprint(),
censused_at_ms=acquired_at_ms,
detail="cross-route full revision governance",
retire_full_revision_governance=True,
)
member_sessions: dict[str, Any] = {}
projections: dict[str, Any] = {}
revisions: list[MembershipRevision] = []
for member_raw_id in archive.raw_membership_raw_ids(logical_source_key):
retained_sessions = (
sessions
if member_raw_id == source_raw_id
else self._parse_retained_raw_sessions(archive, member_raw_id)
)
matches = [
item
for item in retained_sessions
if f"{item.source_name.value}:{item.provider_session_id}" == logical_source_key
]
if len(matches) != 1:
raise RuntimeError(f"membership {member_raw_id}:{logical_source_key} no longer parses uniquely")
projection = session_revision_projection(matches[0])
member_sessions[member_raw_id] = matches[0]
projections[member_raw_id] = projection
revisions.append(MembershipRevision(member_raw_id, projection, matches[0].updated_at))
classification = classify_membership_revisions(revisions)
membership_session_id = archive.apply_raw_membership_classification(
logical_source_key,
classification,
member_sessions,
projections,
acquired_at_ms=acquired_at_ms,
)
if membership_session_id is not None:
session_ids.append(membership_session_id)
session_count += 1
message_count += len(member_sessions[classification.accepted_raw_ids[-1]].messages)
return (
session_ids,
session_count,
message_count,
archive.raw_membership_authority_complete(source_raw_id),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Correct, but consider splitting the two responsibilities for readability.

Verified this against all three new tests, including the tricky content-addressed-raw-id-reuse case in test_single_session_full_terminally_supersedes_older_membership_prefix (where revision_raw_id == source_raw_id) — the defensive len(retained_sessions) != 1 / len(matches) != 1 checks correctly guard against parser-fingerprint drift, and classification.accepted_raw_ids[-1] is safe since it's only read inside the membership_session_id is not None branch (which apply_raw_membership_classification only returns non-None when accepted_raw_ids is non-empty).

Given the "complexity high" flag on this segment, and that it does two fairly independent jobs per session (retiring convertible FULL revisions into membership, then classifying/applying the member cohort), consider splitting it into two private helpers (e.g. _retire_convertible_full_revisions(archive, source_raw_id, sessions, logical_source_key, acquired_at_ms) and _classify_and_apply_members(archive, source_raw_id, sessions, logical_source_key, acquired_at_ms)) called from the outer per-session loop. The existing tests give good coverage to do this safely.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/sources/live/batch.py` around lines 1690 - 1764, The
_apply_membership_sessions method combines two independent responsibilities,
making the high-complexity segment harder to read. Extract the convertible FULL
revision retirement logic into a private helper such as
_retire_convertible_full_revisions and the membership classification/application
logic into a helper such as _classify_and_apply_members, then call both from the
existing per-session loop while preserving their current behavior and
return-count handling.

Comment on lines +1752 to +1770
def convertible_full_revision_raw_ids(self, logical_source_key: str) -> tuple[str, ...]:
"""Return a full-only byte cohort that can join semantic membership."""
rows = (
self._ensure_source_conn()
.execute(
"""
SELECT raw_id, revision_kind
FROM raw_sessions
WHERE logical_source_key = ?
ORDER BY raw_id
""",
(logical_source_key,),
)
.fetchall()
)
if not rows or any(str(row[1]) != RawRevisionKind.FULL.value for row in rows):
return ()
return tuple(str(row[0]) for row in rows)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect classify_historical_full_revisions to see whether it can link two
# FULL-kind raws via predecessor_raw_id/baseline_raw_id, and whether any
# caller can reach convertible_full_revision_raw_ids with such a linked pair
# already present alongside existing raw_session_memberships rows.
rg -nP 'def classify_historical_full_revisions' -A 40
rg -nP 'convertible_full_revision_raw_ids' -C5

Repository: Sinity/polylogue

Length of output: 154


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the target file and locate relevant symbols.
git ls-files 'polylogue/storage/sqlite/archive_tiers/archive.py'
printf '\n-- outline --\n'
ast-grep outline polylogue/storage/sqlite/archive_tiers/archive.py --view expanded || true
printf '\n-- symbol search --\n'
rg -n 'convertible_full_revision_raw_ids|classify_raw_revision_cohort|predecessor_raw_id|baseline_raw_id|replace_raw_membership_census|raw_session_memberships|membership census|revision_kind' polylogue/storage/sqlite/archive_tiers/archive.py

Repository: Sinity/polylogue

Length of output: 29160


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1379,1490p' polylogue/storage/sqlite/archive_tiers/archive.py
printf '\n----\n'
sed -n '1665,1770p' polylogue/storage/sqlite/archive_tiers/archive.py
printf '\n----\n'
sed -n '1910,2095p' polylogue/storage/sqlite/archive_tiers/archive.py

Repository: Sinity/polylogue

Length of output: 19842


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '-- convertible_full_revision_raw_ids usages --'
rg -n 'convertible_full_revision_raw_ids\(' polylogue

printf '\n%s\n' '-- classify_historical_full_revisions definition/usages --'
rg -n 'classify_historical_full_revisions|HistoricalRawRevision|RevisionReplayPlan|RevisionApplicationReceipt|ApplicationDecision' polylogue

printf '\n%s\n' '-- membership application paths touching raw ids --'
rg -n 'retire_full_revision_governance|convertible_full_revision_raw_ids|replace_raw_membership_census|raw_revision_replay_plan|apply_raw_membership_classification|defer_raw_revision_adoption' polylogue/storage/sqlite/archive_tiers/archive.py

Repository: Sinity/polylogue

Length of output: 6073


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '-- revision_authority.py --'
sed -n '1,220p' polylogue/archive/revision_authority.py

printf '\n%s\n' '-- live batch call site --'
sed -n '1660,1735p' polylogue/sources/live/batch.py

printf '\n%s\n' '-- revision_replay.py --'
sed -n '1,240p' polylogue/archive/revision_replay.py

Repository: Sinity/polylogue

Length of output: 17085


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '-- retirement-order / backfill related code --'
rg -n 'revision_backfill|retire_full_revision_governance|convertible_full_revision_raw_ids|predecessor_raw_id|baseline_raw_id' polylogue -g '!**/__pycache__/**'

printf '\n%s\n' '-- live batch surrounding context --'
sed -n '1688,1725p' polylogue/sources/live/batch.py

Repository: Sinity/polylogue

Length of output: 12918


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '220,340p' polylogue/storage/raw_retention.py

Repository: Sinity/polylogue

Length of output: 7708


Retire linked FULL raws from the tail first.
polylogue/sources/live/batch.py:1703-1724 iterates convertible_full_revision_raw_ids(logical_source_key) in raw_id order, then retires each raw immediately. A chained FULL cohort can hit the an active byte-revision chain cannot move to membership governance guard if a predecessor is retired before its successor. Sort by chain order or skip predecessors already covered by a later raw.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/storage/sqlite/archive_tiers/archive.py` around lines 1752 - 1770,
Update convertible_full_revision_raw_ids and its live batch caller so linked
FULL raws are retired from the chain tail toward the head, rather than raw_id
order. Return or iterate the cohort in successor-to-predecessor chain order,
ensuring each later raw is retired before any predecessor and avoiding the
active byte-revision-chain guard.

Sinity added a commit that referenced this pull request Jul 11, 2026
## Summary

Allow the membership classifier's proven metadata-only successor to
replace an equal-frontier semantic head atomically.

## Problem

The first packaged retry after PR #2716 still rejected the production
ChatGPT capture. Membership classification selected the later metadata
revision using direct provider timestamps, but generic equal-frontier
CAS rejected the changed session hash before updating the head.

Ref polylogue-yla8.

## Solution

Retire an existing accepted head, byte or semantic, only when its
accepted raw belongs to the classifier's accepted/equivalent cohort and
its reparsed projection hash exactly matches the stored accepted hash.
Head retirement, authoritative replacement, FTS proof, immutable
receipts, and the new semantic head remain one index transaction.
Ambiguous/divergent classifications never reach this path.

## Verification

- Metadata-only live-route advancement plus larger-divergence
containment: 2 passed.
- `devtools verify --quick`: final-head run
`20260711T221806Z-quick-1498581-d007ebfe`, 13/13 passed.
- Independent adversarial review found no authority widening, rollback,
or anti-vacuity blocker.
- Packaged production evidence before this patch: classifier reached
equal-frontier CAS and failed with `raw revision CAS rejected a
conflicting accepted head`; the new test reproduces that exact pre-patch
failure.

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 20, 2026
…ULL (#3193)

## Summary

Narrows the polylogue-emx2 deferred-membership fix (PR #3129, commit
de0b2df) so it applies only to the genuinely async-pending case
(`decision IS NULL`), restoring the fail-closed invariant for decided
`'ambiguous'`/`'deferred'` membership conflicts that de0b2df's shipped
code had accidentally started treating as successes.

## Problem

The polylogue-lvz6 clean-master triage bisected 5 failing tests in
`tests/unit/sources/test_live_batch_support.py` to de0b2df:

- `test_rewrite_plus_growth_before_planning_fails_closed_to_full_route`
- `test_live_multi_session_divergence_reopens_raw_authority`
-
`test_bundle_replay_respects_unconvertible_single_session_head[bundle_texts1-False-False]`
- `test_single_session_full_cannot_overwrite_divergent_membership_head`
-
`test_append_cursor_redetects_source_rewrite_after_handoff[in-place-prefix]`

de0b2df's intent was narrow: treat only
`raw_session_memberships.decision
IS NULL` (genuinely async-pending, arbitrated later by the
raw-materialization conveyor, `sources/revision_backfill.py`) as
not-a-failure.
The shipped code used the pre-existing coarse boolean
`ArchiveStore.raw_membership_authority_complete()`, which returns
`False`
for `decision IS NULL` **or** `'ambiguous'` **or** `'deferred'` -- three
distinct states collapsed into one. Net effect: genuinely
divergent/ambiguous
raws (rewrites, multi-session divergence, unconvertible bundle heads,
divergent membership heads) were recorded as `SUCCEEDED` instead of
`FAILED`,
defeating the fail-closed invariants pinned by #2684/#2716/#2718/#2837.

A second injection point
(`classify_raw_revision_cohort(...).accepted_raw_ids`
empty, in the non-membership single-session route) was also treated as
deferred, but that classification is synchronous byte comparison with no
conveyor revisiting -- "empty" there is always terminal, never pending.

I also traced (direct DB inspection, see Verification) that de0b2df's
own
regression test exercises `decision = 'ambiguous'`, not `NULL` -- its
assertion that this must defer was itself an instance of the bug this PR
fixes.

## Solution

- `polylogue/storage/sqlite/archive_tiers/archive.py`: new
  `ArchiveStore.raw_membership_decision_pending(raw_id)` isolates the
`decision IS NULL` case. `raw_membership_authority_complete` had exactly
one caller in the whole tree (audited via grep), so it stays as-is for
its
  original "fully complete" semantics -- no other legitimate caller to
  preserve.
- `polylogue/sources/live/batch.py`:
  - The membership-governed injection point now branches: complete ->
    succeeded; `raw_membership_decision_pending` -> deferred (unchanged
    behavior for the true async-pending case); otherwise (decided
    `ambiguous`/`deferred`) -> falls through to the caller's existing
    failed-set aggregation in `_ingest_full_paths_sync`, now with a
`logger.warning` (the pre-fix path failed silently, no exception, no log
at all -- part of what made the original bug invisible in production).
  - The `classify_raw_revision_cohort` injection point drops the
    `deferred_raw_ids` branch entirely (empty accepted cohort is always
    terminal there) and logs a warning too.
- `tests/unit/sources/test_live_watcher.py`: corrected

`test_live_full_ingest_over_ambiguous_membership_defers_instead_of_failing`
-> `..._fails_closed_with_diagnostic`. Its
two-conflicting-browser-snapshot
scenario produces `decision = 'ambiguous'`, not `NULL` (verified by
direct
DB inspection); the original assertion that it must defer was wrong. It
now
asserts the corrected fail-closed outcome, the diagnostic log line, and
that
  the first accepted snapshot's content is untouched.
- `tests/unit/sources/test_live_batch_support.py`: added

`test_raw_membership_decision_pending_distinguishes_null_from_ambiguous`,
a
focused archive-tier regression test for the exact narrow scoping (NULL
->
pending; ambiguous -> decided/not-pending). This is archive-tier rather
than
a full watcher scenario because `LiveBatchProcessor`'s two call sites
into
`_apply_membership_sessions` both pass
`allow_current_complete_raw=True`,
which always resolves a raw's own decision synchronously within the same
call -- so NULL is never observed at that exact checkpoint via the live
watcher path. Genuine NULL persistence happens only across the
conveyor's
  decoupled census-then-classify phases
(`census_historical_revision_evidence` /
`backfill_historical_revision_evidence`
in `sources/revision_backfill.py`), which this test reproduces directly.

## Verification

- `devtools test tests/unit/sources/test_live_batch_support.py
tests/unit/sources/test_live_cursor_persistence.py
tests/unit/sources/test_live_watcher.py` -- 160 passed (was 5 failed on
clean master before this fix).
- `devtools verify --quick` -- exit 0 (format, lint, mypy --strict,
render all --check,
topology/layering/manifest/doc-commands/clock-hygiene/timeout/degrade-loudly
gates).
- Direct DB-state inspection (ad hoc script against the archive tier,
not committed) confirmed the emx2 regression test's second observation
produces `raw_session_memberships.decision = 'ambiguous'` for both raws,
not `NULL`, before deciding how to correct that test.
- Not run: the heavy `test` suite (skipped per-PR by CI policy, runs
post-merge).

Ref polylogue-emx2
Ref polylogue-lvz6

Co-authored-by: Claude <[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