Skip to content

fix(sources): stop miscounting deferred membership as a full-ingest failure - #3129

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/emx2-adoption-idempotency
Jul 18, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/emx2-adoption-idempotency

Conversation

@Sinity

@Sinity Sinity commented Jul 18, 2026

Copy link
Copy Markdown
Owner

Summary

Watcher catch-up over already-acquired files was silently marking the overwhelming majority of them as "failed" — with no exception raised and no log line written — because the aggregation layer conflated "membership decision not yet made" (a legitimate async hand-off to the raw-materialization conveyor) with "genuine failure". This directly fixes the emx2 restore-class gap: a rebuilt-index-over-intact-source scenario can now self-heal without retry-churning the entire population.

Problem

Live evidence from the mid-restore archive (2026-07-18 evening): every watcher catch-up chunk was reporting succeeded=0 failed=35-50/50, but only 2 of ~400+ "failed" files in that window had a matching exception logged (RuntimeError: raw revision CAS rejected an older accepted frontier). Direct read-only inspection of source.db found the real cause:

  • raw_membership_census had 25,324 rows with status='complete'.
  • Of those, 24,626 (97.2%) had at least one raw_session_memberships row with decision IS NULL or 'ambiguous' — i.e. the raw-authority protocol's own async classification correctly hadn't decided the winner yet (arbitration deferred to the raw-materialization conveyor, by design).
  • _ingest_full_paths_sync (polylogue/sources/live/batch.py) computed the failed set as every raw not present in archive_write.raw_ids — which only gets populated when raw_authority_complete is True. A raw with a pending decision has no exception, no log, but also never lands in raw_ids — so it was silently added to failed, triggering mark_failed on its cursor (retry churn) forever with zero net progress.

This is polylogue-emx2 ("Watcher catch-up trusts ingest cursors that the index cannot corroborate"), evidenced through a different live mechanism than the bead's originally-hypothesized ValueError diagnostic (which never fired on the current, post-#3114 deployed daemon — 0 log hits either format).

Solution

  • _ArchiveFullWriteResult gains deferred_raw_ids: dict[str, str], populated at both no-exception non-completion points in _ingest_full_records_archive:
    • raw_authority_complete=False after _apply_membership_sessions (census complete, decision pending/ambiguous).
    • classify_raw_revision_cohort returning no accepted candidates in the non-membership-governed single-session path.
  • _ingest_full_paths_sync's aggregation now excludes deferred_raw_ids from the failed set and folds them into the succeeded raw-id remap, so the cursor for that path is recorded as a normal succeeded full-ingest — the bytes ARE durably acquired, only the membership decision is outstanding, which is the conveyor's job, not the watcher's.
  • Genuine exceptions (the CAS RuntimeError, ValueErrors, "no longer parses uniquely" guards) are unaffected — still caught by the existing except Exception block, still call mark_raw_parse_failed, still fail loudly.

Verification

  • New regression test test_live_full_ingest_over_ambiguous_membership_defers_instead_of_failing (tests/unit/sources/test_live_watcher.py): ingests two genuinely conflicting browser-capture snapshots of one session (classify_membership_revisions correctly returns ambiguous, not accepted) and proves the second observation lands as succeeded/idempotent with failure_count == 0 on the cursor, including a third identical re-observation.
  • Anti-vacuity: confirmed this test fails against the pre-fix code (failed_file_count=1, zero exceptions/log lines in captured output) before restoring the fix.
  • devtools test tests/unit/sources/test_live_watcher.py — 88 passed.
  • devtools verify --quick — exit 0 (format, lint, mypy --strict, render all --check, topology/layering/manifest/doc-commands/clock-hygiene/timeout/degrade-loudly gates).
  • Not run: the heavy test suite (skipped per-PR by CI policy, runs post-merge).

Ref polylogue-emx2

…ailure

Problem: live evidence from the mid-restore archive (2026-07-18) showed
watcher catch-up chunks failing near-100% (succeeded=0, failed=35-50/50 per
50-file chunk) with almost no matching exception logged -- only 2 of ~400+
"failed" files had a traceback. Direct read-only inspection of source.db
found the actual cause: 24,626/25,324 (97.2%) of raw_membership_census rows
with status='complete' had a raw_session_memberships row with decision IS
NULL or 'ambiguous' -- i.e. the raw-authority protocol's own async
classification (arbitration deferred to the raw-materialization conveyor)
correctly hadn't decided yet. _ingest_full_paths_sync (batch.py) treated
any raw where raw_authority_complete was False as a failure regardless of
whether an exception was ever raised, so every one of these hand-offs got
mark_failed-ed and cursor failure_count churned forever with zero net
progress -- the "watcher catch-up trusts ingest cursors the index cannot
corroborate" gap described in polylogue-emx2.

What changed: _ArchiveFullWriteResult gains deferred_raw_ids, populated at
both no-exception non-completion points in _ingest_full_records_archive
(raw_authority_complete=False, and classify_raw_revision_cohort returning
no accepted candidates). The aggregation layer in _ingest_full_paths_sync
now excludes deferred_raw_ids from the failed set and folds them into the
succeeded remap, so re-observing a file whose bytes are already durably
acquired -- but whose membership decision is legitimately pending --
records a normal succeeded cursor instead of retry churn. A genuine
exception (ValueError, the CAS RuntimeError, "no longer parses uniquely")
is unaffected and still fails loudly via the existing except block plus
mark_raw_parse_failed.

Verification: new regression test
test_live_full_ingest_over_ambiguous_membership_defers_instead_of_failing
constructs two genuinely conflicting browser-capture snapshots of one
session (classify_membership_revisions correctly returns ambiguous, not
accepted) and proves the second observation is treated as
succeeded/idempotent with zero cursor failure_count. Confirmed the test
fails against the pre-fix code (failed_file_count=1, no exception logged)
before restoring the fix. devtools test tests/unit/sources/test_live_watcher.py
-- 88 passed. devtools verify --quick -- exit 0.

Ref polylogue-emx2

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Jul 18, 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: 26 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: 7c3bfb5d-8de9-4cbd-b32e-201c4156b17b

📥 Commits

Reviewing files that changed from the base of the PR and between 39f6c39 and 854bcb0.

📒 Files selected for processing (2)
  • polylogue/sources/live/batch.py
  • tests/unit/sources/test_live_watcher.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/emx2-adoption-idempotency

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 de0b2df into master Jul 18, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/emx2-adoption-idempotency branch July 18, 2026 21:36
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]>
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 27, 2026
… mutation canaries (#3341)

## Summary

Fixes a stale VM-step anti-vacuity mutation in two archive query tests
(polylogue-1ldl) and verifies a previously-stale live-batch assertion
(polylogue-5202) is already resolved on master by an unrelated prior PR.

## Problem

**polylogue-1ldl**:
`test_exact_session_action_count_bounds_pairing_before_global_ranking`
(tests/unit/storage/test_archive_tiers_archive.py) and
`test_exact_session_multi_aggregate_work_is_not_amplified_by_irrelevant_growth`
(tests/unit/archive/query/test_execution_control.py) each monkeypatch
`_action_relation_for_query` to fall back to the plain `"actions"`
relation name, simulating pre-z9gh.2 "global-first" behavior, and assert
the resulting query costs `>= 50000` SQLite VM steps as an anti-vacuity
control. Since PR #3018 (z9gh.2) replaced the old windowed-CTE `actions`
compatibility view with one backed by the small, pre-materialized,
session_id-indexed `action_pairs` table, renaming the relation to
`"actions"` no longer forces any meaningfully different/expensive path —
both tests measured 0/400 VM steps for the "mutant" query, well under
the 50000 threshold. The canary had silently stopped discriminating the
exact regression it exists to catch.

**polylogue-5202**:
`test_live_multi_session_divergence_reopens_raw_authority`
(tests/unit/sources/test_live_batch_support.py) was reported failing
with a stale `failed == [second]` assertion predating PR #3129's
deferred-membership semantics change. Investigation found the assertions
were already updated to the current-correct `failed == [] / succeeded ==
[second]` shape by PR #3282 (commit 4120c40, merged 2026-07-26, Ref
polylogue-6mvg) as part of unrelated FTS-repair-deferral work. The test
already passes on current master with no further code change needed.

## Solution

- Replaced the now-inert `lambda **_kwargs: ("", "actions", [])`
mutation at both polylogue-1ldl sites with one that forces the
actually-expensive "global-first" branch that still exists in
`action_relation_select_sql(session_placeholders=None)` — the unbounded
windowed tool_use/tool_result pairing recomputation across every block
in the archive, instead of a read against the materialized
`action_pairs` table. Verified this reproduces genuinely archive-wide
cost (measured 53500 VM steps for the count-only path vs 400 bounded).
- Added inline comments at both mutation sites recording what changed
(#3018) and why the old mutation stopped discriminating.
- No code change for polylogue-5202 — verified its test and the broader
`raw_materialization`/`raw_authority` selection are green on master, and
closing the bead by reference to PR #3282.
- Filed polylogue-0twa for an unrelated, pre-existing stale
`query_units` vs `api.query_units` call-log naming assertion noticed in
the same test file (out of scope for this PR).

## Verification

- `devtools test tests/unit/storage/test_archive_tiers_archive.py
tests/unit/archive/query/test_execution_control.py` → 60 passed, 2
failed (pre-existing, out-of-scope polylogue-0twa naming mismatch; both
polylogue-1ldl tests pass)
- `devtools test -k "raw_materialization or raw_authority"` → 198 passed
(includes polylogue-5202's test)
- `ruff check` / `ruff format --check` on both changed files → clean
- `mypy --strict` on both changed files → no issues
- `devtools render all --check` → no drift
- pre-push `devtools verify --quick` → all steps ok

Ref polylogue-1ldl, polylogue-5202

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