Skip to content

fix(sources): fail closed on decided ambiguous membership, not just NULL - #3193

Merged
Sinity merged 1 commit into
masterfrom
fix/sources/deferred-membership-fail-closed
Jul 20, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/sources/deferred-membership-fail-closed

Conversation

@Sinity

@Sinity Sinity commented Jul 20, 2026

Copy link
Copy Markdown
Owner

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

Problem

de0b2df (PR #3129, polylogue-emx2) added a deferred_raw_ids escape
hatch so the watcher's full-ingest aggregation would not silently
mismark a raw with a pending membership decision as a failure. The
shipped code used the pre-existing coarse boolean
raw_membership_authority_complete(), which returns False for
decision IS NULL *or* 'ambiguous' *or* 'deferred' -- three distinct
states collapsed into one. Only NULL (censused, not yet arbitrated by
the async raw-materialization conveyor, sources/revision_backfill.py)
is a legitimate hand-off; 'ambiguous'/'deferred' means arbitration
already ran and concluded a genuine, decided conflict that needs new
evidence, not time, to resolve. Treating that as deferred defeated the
fail-closed invariants pinned by #2684/#2716/#2718/#2837 and
regressed 5 tests in tests/unit/sources/test_live_batch_support.py
(bisected to de0b2df by the polylogue-lvz6 clean-master triage). A
second injection point (classify_raw_revision_cohort's empty
accepted_raw_ids) is purely synchronous byte comparison with no
conveyor revisiting it, so "empty" there is always terminal, never
pending.

Solution

- New ArchiveStore.raw_membership_decision_pending(raw_id): isolates
  the decision-IS-NULL case from raw_membership_authority_complete's
  coarse False. Audited: raw_membership_authority_complete had exactly
  one caller (the site this PR fixes), so it stays as-is for its
  original "fully complete" semantics.
- batch.py's membership-governed injection point now branches
  complete -> succeeded, decision_pending -> deferred (unchanged
  behavior for the true async-pending case), else (ambiguous/deferred)
  -> falls through to the caller's existing failed-set aggregation,
  with a new warning log line (the pre-fix path failed silently with
  no exception and no log at all).
- batch.py's classify_raw_revision_cohort injection point drops the
  deferred_raw_ids branch entirely -- an empty accepted cohort is
  always a terminal failure there -- and logs a warning.
- Corrected the emx2 regression test
  (test_live_full_ingest_over_ambiguous_membership_fails_closed_with_diagnostic
  in test_live_watcher.py): traced empirically (direct DB inspection)
  that its two-conflicting-browser-snapshot scenario produces decision
  'ambiguous', not NULL, so its original assertion ("must defer, not
  fail") was itself the bug this PR fixes. It now asserts the correct
  fail-closed outcome plus the diagnostic log line.
- Added test_raw_membership_decision_pending_distinguishes_null_from_ambiguous
  (test_live_batch_support.py): a focused archive-tier regression test
  for the exact narrow scoping, since LiveBatchProcessor's own two call
  sites always pass allow_current_complete_raw=True and therefore
  always resolve a raw's own decision synchronously within the same
  call -- genuine NULL persistence only happens across the conveyor's
  decoupled census-then-classify phases, which this test reproduces
  directly against the archive tier.

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).
- devtools verify --quick -- exit 0.
- Not run: full non-integration suite (per-PR CI policy skips it;
  runs post-merge).

Ref polylogue-emx2
Ref polylogue-lvz6

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

coderabbitai Bot commented Jul 20, 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: 18 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

Run ID: 4311ecf1-60c7-43ed-9910-a66bac62cf2d

📥 Commits

Reviewing files that changed from the base of the PR and between 5d37086 and 57cedcf.

📒 Files selected for processing (4)
  • polylogue/sources/live/batch.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/sources/test_live_batch_support.py
  • tests/unit/sources/test_live_watcher.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/sources/deferred-membership-fail-closed

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity merged commit f6cc1dd into master Jul 20, 2026
3 checks passed
@Sinity
Sinity deleted the fix/sources/deferred-membership-fail-closed branch July 20, 2026 05:13
Sinity added a commit that referenced this pull request Jul 20, 2026

@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: 57cedcf481

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

Comment thread polylogue/sources/live/batch.py Resolved
Sinity added a commit that referenced this pull request Jul 20, 2026
Problem

polylogue-emx2 (Finding 8 of perf-investigation-2026-07-18): watcher
catch-up trusted ops.db ingest_cursor rows as proof of full
materialization. After an index reset/rebuild, source.db retained
14,879 cursors recording "acquired and parsed", but index.db started
empty. `_needs_work_from_state`'s hot-skip fast path (byte-size +
content-fingerprint match) never checked whether the index actually
held a materialized session for the cursor's raw -- it skipped the
file outright, leaving 100% of the restore drain to the 1-per-30s
background conveyor.

PRs #3129 and #3193 (merged) fixed a related but distinct bug: batch.py
was misclassifying a raw with a pending/decided membership arbitration
as a full-ingest failure. That repaired the accounting *after* a file
was resubmitted for ingest, but never addressed the original finding --
the cursor-trust fast path in the watcher still never consults the
index at all.

Solution

`polylogue/sources/live/watcher.py`:
- `_archived_cursor_reconciliation_scope` now computes, once per
  catch-up planning pass (reusing its already-shared source.db/index.db
  connections), whether the index tier is globally uncorroborated:
  `_index_lacks_all_corroboration` returns True when source.db holds at
  least one successfully parsed raw row but index.db's `sessions` table
  is completely empty -- the exact post-reset signature from Finding 8.
- `_needs_work_from_state` (renamed inner decision logic to
  `_needs_work_from_state_uncorroborated`) now wraps that logic: when it
  would skip a file and the index is flagged uncorroborated, a cheap
  per-candidate existence check (`_cursor_skip_corroborated_by_index`,
  reusing the existing `_archived_cursor_row` raw->session join) decides
  whether to honor the skip or demote it to "needed".
- The gate defaults to trusted (no behavior change) whenever the index
  has any session at all, so the common case adds zero queries.
- Demoted files re-enter the normal batch ingest path, which is already
  content-hash idempotent, so no bytes are re-acquired for unchanged
  files (AC: "no re-acquisition of unchanged bytes").

Verification

- `devtools test tests/unit/sources/test_live_catchup_planning.py`:
  19 passed (16 pre-existing + 3 new).
- `devtools test tests/unit/sources/test_live_watcher.py
  tests/unit/sources/test_live_watcher_catchup_order.py
  tests/unit/sources/test_live_watcher_locking.py`: 101 passed.
- `mypy --strict polylogue/sources/live/watcher.py
  tests/unit/sources/test_live_catchup_planning.py`: no issues.
- `devtools verify --quick`: exit 0 (ruff format/check, mypy, render
  all, topology/layering/manifests/doc-commands/etc. all ok).
- Anti-vacuity: reverted only the watcher.py fix (kept the new tests)
  and reran `test_catch_up_demotes_hot_skip_cursor_when_index_holds_no_sessions`
  -- it failed with the exact live symptom (`plan.needed == ()` instead
  of the healthy-cursor file), and
  `test_catch_up_index_lacks_all_corroboration_detects_empty_index_with_parsed_raw`
  failed with `AttributeError` for the missing method. Restoring the
  fix turned both green.

Ref polylogue-emx2
Sinity added a commit that referenced this pull request Jul 20, 2026
#3223)

## Summary

Watcher catch-up's hot-skip fast path trusted `ops.db` ingest cursors as
proof of full materialization without ever checking whether `index.db`
actually holds the corresponding session. This PR adds a corroboration
check that demotes cursor-trust skips to "needed" when the index tier
cannot back up the claim.

## Problem

polylogue-emx2 (Finding 8 of perf-investigation-2026-07-18): after an
index reset/rebuild, `source.db` retained 14,879 ingest cursors
recording "acquired and parsed", but `index.db` started empty.
`_needs_work_from_state`'s hot-skip fast path (byte-size +
content-fingerprint match) never checked whether the index actually
held a materialized session for the cursor's raw — it skipped every
one of those files outright, leaving 100% of the restore drain to the
1-per-30s background conveyor.

PRs #3129 and #3193 (merged, both linked to this bead) fixed a related
but distinct bug: `batch.py` was misclassifying a raw with a
pending/decided membership arbitration as a full-ingest *failure*. That
repaired the accounting after a file was resubmitted for ingest, but
never addressed the original finding — the cursor-trust fast path in
the watcher still never consulted the index at all. This PR closes
that remaining gap.

## Solution

`polylogue/sources/live/watcher.py`:
- `_archived_cursor_reconciliation_scope` now computes, once per
  catch-up planning pass (reusing its already-shared source.db/index.db
  connections), whether the index tier is globally uncorroborated:
  `_index_lacks_all_corroboration` returns `True` when `source.db`
  holds at least one successfully parsed raw row but `index.db`'s
  `sessions` table is completely empty — the exact post-reset
  signature from Finding 8.
- `_needs_work_from_state` (the prior single-purpose decision method,
  renamed `_needs_work_from_state_uncorroborated`) now wraps that
  logic: when it would skip a file and the index is flagged
  uncorroborated, a cheap per-candidate existence check
  (`_cursor_skip_corroborated_by_index`, reusing the existing
  `_archived_cursor_row` raw→session join) decides whether to honor the
  skip or demote it to "needed".
- The gate defaults to trusted (no behavior change) whenever the index
  has any session at all, so the common healthy case adds zero extra
  queries.
- Demoted files re-enter the normal batch ingest path, which is already
  content-hash idempotent, so no bytes are re-acquired for unchanged
  files.

## Verification

- `devtools test tests/unit/sources/test_live_catchup_planning.py`:
  19 passed (16 pre-existing + 3 new).
- `devtools test tests/unit/sources/test_live_watcher.py
  tests/unit/sources/test_live_watcher_catchup_order.py
  tests/unit/sources/test_live_watcher_locking.py`: 101 passed.
- `mypy --strict polylogue/sources/live/watcher.py
  tests/unit/sources/test_live_catchup_planning.py`: no issues found.
- `devtools verify --quick`: exit 0.
- Anti-vacuity: reverted only the production fix (kept the new tests)
and reran the suite —
`test_catch_up_demotes_hot_skip_cursor_when_index_holds_no_sessions`
  failed with the exact live symptom (`plan.needed == ()` instead of
  the healthy-cursor file), and

`test_catch_up_index_lacks_all_corroboration_detects_empty_index_with_parsed_raw`
  failed with `AttributeError` for the missing method. Restoring the
  fix turned both green.
- Not run: full `devtools verify --all` / integration suite (out of
  scope for a focused fix; the touched-file testmon selection above is
  the relevant net).

Ref polylogue-emx2
Sinity added a commit that referenced this pull request Jul 29, 2026
…y promotion

Problem: the 2026-07-29 structural-merge promotion (c53ad94) regenerated
every provider schema and dropped the x-polylogue-semantic-role overlay for
codex/claude-code/claude-ai, so SyntheticCorpus filled role-discriminator
fields with opaque `synthetic-<n>` placeholders instead of real user/
assistant values (polylogue-c66i). This normalized every generated message
to Role.UNKNOWN and broke property tests, plus regressed 3 stale test
contracts elsewhere on this branch's schema/parser lanes.

What changed:
- devtools/inject_semantic_annotations.py: re-ran the sanctioned re-
  annotation tool, then fixed 3 real gaps it hit against the promoted
  schema shape (not just re-running it blindly):
  - claude-code/codex message_body: the promotion flattened these fields
    from an anyOf-of-type-variants union to `type: [array, string]` with
    `items` present directly; the injector's anyOf:array DSL step no
    longer matched anything. Updated both paths.
  - claude-code message_container: this entry was simply missing from the
    ANNOTATION_MAP (not a promotion regression) — added `properties.message`.
  - claude-code message.role and codex flat properties.role: the promotion
    also unioned in a second legitimate codex record shape (flat
    `{"type": "message", "role": ...}`, no `payload` wrapper — the real
    parser already accepts this, sources/parsers/codex.py) and
    claude-code's `message.role` mirrors top-level `type` but was never
    itself annotated. Added both so synthetic generation never leaves a
    role field unannotated regardless of which record shape it produces.
- polylogue/schemas/synthetic/build_batch.py: `_record_role` now checks
  both codex record shapes (payload.role and flat role) so tool-heavy-style
  synthetic generation places its tool_use/tool_result blocks after an
  assistant turn regardless of which shape got generated
  (test_generation_plants_independent_wire_facts_before_ingest was
  asserting non-empty tool_use_ids and getting `()` from the untouched
  flat-shape record).
- Removed the test-layer workaround this regression required
  (tests/infra/strategies/providers.py:repair_role_discriminators and its
  tests/conftest.py:synthetic_source repair loop): empirically confirmed
  zero placeholder-triggered records across 60 seeds x 2 providers with the
  schema fix in place, so the workaround is now dead weight.
- tests/unit/sources/test_live_cursor_persistence.py,
  tests/unit/sources/test_source_laws.py: updated two test doubles whose
  monkeypatched signatures had drifted from their real counterparts
  (`_write_parsed_precedence_result` gained `defer_fts_rebuild`;
  `claude.parse_code` gained `tool_result_sidecars`) and one bundle-item
  fixture that no longer satisfies chatgpt.looks_like_fragment after #3391
  tightened bundle-item shape validation.
- tests/unit/sources/test_live_watcher.py: rewrote the ambiguous-membership
  regression test to the contract PR #3282 (4120c40) deliberately shipped
  — a decided ambiguous/deferred membership conflict is now preserved as
  durable authority debt and NOT retried as a file failure, superseding the
  narrower fail-closed-as-failure framing PR #3193 (f6cc1dd) shipped
  earlier for the same injection point. The still-fail-closed
  classify_raw_revision_cohort injection point (empty accepted cohort) is
  untouched and still covered by
  test_rewrite_plus_growth_before_planning_fails_closed_to_full_route et al.
- docs/plans/demo-corpus-construct-audit.md: regenerated
  (`devtools render demo-corpus-datasheet`) — the schema fix also repaired
  real demo-corpus embedding-candidate detection (verifier result flipped
  failed -> ok; synthetic_message_embedding_rows/embedding_status_rows went
  from `missing` (0) to `ok` (1)), confirming this is a genuine parser-
  facing improvement, not just a test-fixture patch.

Verification:
- python3 devtools/inject_semantic_annotations.py --dry-run -> 0 annotations
  would be injected (idempotent).
- devtools test tests/unit/core/test_synthetic_semantic_wiring.py
  tests/unit/core/test_synthetic_semantics.py
  tests/unit/sources/test_parsers_props.py
  tests/unit/sources/test_null_guard_properties.py -> 238 passed.
- devtools test tests/unit/sources/test_live_watcher.py
  tests/unit/sources/test_live_cursor_persistence.py
  tests/unit/sources/test_source_laws.py -> 216 passed.
- devtools verify --quick -> exit 0 (ruff format/check, mypy --strict,
  render all --check, all lab/policy gates).
- Not run: the full non-integration suite (in progress in parallel).

Ref polylogue-c66i

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

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 70.F053 / P1: fixed-already at the checked revision: A full-only cohort with no unique byte-chain head now records DEFERRED_CAS_FRONTIER and returns the retained raw in deferred_raw_ids at polylogue/sources/live/batch.py:5129-5131. It no longer falls through as an unaccounted failed acquisition while awaiting semantic/frontier reconciliation.

Only the rows listed above are dispositioned. Held findings remain open.

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