Skip to content

fix(backend): drop only the ungrounded memory candidate, not the whole run (#11685) - #11688

Merged
kodjima33 merged 1 commit into
mainfrom
watchdog/issue-11685-ungrounded-candidate-aborts-run
Aug 16, 2026
Merged

kodjima33 merged 1 commit into
mainfrom
watchdog/issue-11685-ungrounded-candidate-aborts-run

Conversation

@kodjima33

@kodjima33 kodjima33 commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #11685.

Bug

_extract_memories_canonical raised ValueError("canonical memory extraction returned evidence without a unique source binding") as soon as one L1 candidate's evidence quotes failed to bind to exactly one transcript segment. That is a per-candidate trust verdict, but raising it aborted the whole run — and because _extract_memories is called synchronously near the end of process_conversation (:1532), the rest of finalization went with it: the run's correctly-grounded candidates, _save_action_items, _update_goal_progress, the desktop meeting Chat receipt, and the lazy-enrich handler's terminal transition (it re-marks the conversation deferred: True, so the user sees no summary until they reopen it). On backend-sync there is no retry at all — the merged conversation just keeps its stale enrichment.

Root cause

_grounded_l1_evidence_quotes returns [] when any one quote of a candidate does not match exactly one segment: 0 matches (the model paraphrased, or quoted across a segment boundary) or 2+ matches (a short phrase repeated in two segments). The caller escalated that per-candidate [] to a run-scope raise.

Fix

Skip the ungrounded candidate and continue. The fence is unchanged — nothing unbound is ever written — and the run's grounded siblings survive. Every candidate failing to ground still raises: replace_conversation_memories is called unconditionally at :1012, so continuing there would submit an empty replacement and retract the source's existing memories on the strength of a run we just decided not to trust. Dropped candidates emit a bounded logger.warning plus the shared record_fallback (outcome=degraded), per docs/agents/fallback-telemetry.md.

Production evidence (based-hardware, 2026-08-16 03:00Z → 15:30Z)

  • lazy enrich outcomes: 42 complete / 39 failed, and 27 of the 39 failures are this error — ~1 in 3 of all lazy enrichments.
  • Same error fires continuously on backend-sync (_reprocess_merged_conversations).
  • Extraction is not systematically broken in that window: 332 conversations saved ≥1 canonical memory (209 of them ≥2) and 468 extracted none. Candidates fail grounding individually, which is exactly what this PR stops from being fatal.

Verification

  • New regression test test_canonical_capture_drops_only_the_ungrounded_candidate (two candidates, one ungrounded): fails on pre-fix process_conversation.py with the verbatim production ValueError, passes with the fix.
  • The existing fail-closed guard test_canonical_capture_preserves_prior_state_when_candidate_has_any_ungrounded_quote is untouched and still passes — its single ungrounded candidate is now the "every candidate ungrounded" case, so no source replacement is submitted.
  • BACKEND_UNIT_TEST_FILE_LIST=… bash backend/test.sh on tests/unit/test_memory_replace_policy.py: 15 passed.
  • make preflight green.

Line-Count-Exception: backend/utils/conversations/process_conversation.py | 1781 -> 1806 | +25 lines: a continue branch with its rationale, the all-candidates-ungrounded fail-closed guard, and the required record_fallback site. Splitting this 1.8k-line module is unrelated to a live production fix.

🤖 automated by hourly watchdog — tested and merged

Failure-Class: none

Review in cubic

…e run (#11685)

Canonical L1 extraction raised ValueError as soon as any single candidate's
evidence quotes failed to bind to exactly one transcript segment. That verdict
is per candidate, but raising it aborted the entire run — and, because
_extract_memories runs synchronously inside process_conversation, the rest of
conversation finalization with it (action items, goal progress, the deferred
flag reset, the desktop meeting Chat receipt).

In prod over 2026-08-16 03:00Z-15:30Z that was 27 of 39 failed lazy
enrichments (42 completed in the same window), plus a continuous stream on
backend-sync where the merged conversation just keeps its stale enrichment.
Grounding is not systematically broken there: 332 conversations saved >=1
canonical memory in that window and 209 of them saved >=2, so candidates fail
grounding individually.

Skip the ungrounded candidate instead. The capture fence is unchanged —
nothing unbound is ever written — and the run's grounded siblings survive.
Every candidate failing to ground still raises: replace_conversation_memories
is called unconditionally, so continuing there would submit an empty
replacement and retract the source's existing memories on the strength of a
run we just decided not to trust.

Failure-Class: none

@cubic-dev-ai cubic-dev-ai 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.

1 issue found across 2 files

Confidence score: 4/5

  • In backend/utils/conversations/process_conversation.py, the all-ungrounded guard can raise before the new warning and record_fallback path, which means degraded-mode failures won’t be captured in telemetry and can be hard to detect/diagnose in production — emit the warning and call record_fallback before raising (or route this branch through the same fallback path).
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/utils/conversations/process_conversation.py">

<violation number="1" location="backend/utils/conversations/process_conversation.py:952">
P2: When every extracted candidate is ungrounded, this guard raises before the new warning and `record_fallback` call, so the all-ungrounded failure is invisible to the promised degraded telemetry. Emit the warning and fallback event before raising, while keeping the exception to preserve prior source state.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment on lines +952 to +970
if extracted_candidates and not capture_candidates:
# Every candidate failed grounding: the run itself is untrustworthy,
# so it must not submit the empty replacement that would retract the
# source's existing memories.
raise ValueError("canonical memory extraction returned evidence without a unique source binding")
if ungrounded_candidates:
logger.warning(
"canonical memory extraction dropped %s of %s ungrounded candidates conversation=%s",
ungrounded_candidates,
len(extracted_candidates),
conversation.id,
)
record_fallback(
component='other',
from_mode='canonical_memory_extraction',
to_mode='grounded_candidates_only',
reason='other',
outcome='degraded',
)

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: When every extracted candidate is ungrounded, this guard raises before the new warning and record_fallback call, so the all-ungrounded failure is invisible to the promised degraded telemetry. Emit the warning and fallback event before raising, while keeping the exception to preserve prior source state.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/conversations/process_conversation.py, line 952:

<comment>When every extracted candidate is ungrounded, this guard raises before the new warning and `record_fallback` call, so the all-ungrounded failure is invisible to the promised degraded telemetry. Emit the warning and fallback event before raising, while keeping the exception to preserve prior source state.</comment>

<file context>
@@ -943,6 +949,25 @@ def _extract_memories_canonical(
                     True,
                 )
             )
+        if extracted_candidates and not capture_candidates:
+            # Every candidate failed grounding: the run itself is untrustworthy,
+            # so it must not submit the empty replacement that would retract the
</file context>
Suggested change
if extracted_candidates and not capture_candidates:
# Every candidate failed grounding: the run itself is untrustworthy,
# so it must not submit the empty replacement that would retract the
# source's existing memories.
raise ValueError("canonical memory extraction returned evidence without a unique source binding")
if ungrounded_candidates:
logger.warning(
"canonical memory extraction dropped %s of %s ungrounded candidates conversation=%s",
ungrounded_candidates,
len(extracted_candidates),
conversation.id,
)
record_fallback(
component='other',
from_mode='canonical_memory_extraction',
to_mode='grounded_candidates_only',
reason='other',
outcome='degraded',
)
if ungrounded_candidates:
logger.warning(
"canonical memory extraction dropped %s of %s ungrounded candidates conversation=%s",
ungrounded_candidates,
len(extracted_candidates),
conversation.id,
)
record_fallback(
component='other',
from_mode='canonical_memory_extraction',
to_mode='grounded_candidates_only',
reason='other',
outcome='degraded',
)
if extracted_candidates and not capture_candidates:
# Every candidate failed grounding: the run itself is untrustworthy,
# so it must not submit the empty replacement that would retract the
# source's existing memories.
raise ValueError("canonical memory extraction returned evidence without a unique source binding")

@kodjima33
kodjima33 merged commit 5af7e53 into main Aug 16, 2026
43 checks passed
@kodjima33
kodjima33 deleted the watchdog/issue-11685-ungrounded-candidate-aborts-run branch August 16, 2026 16:04
kodjima33 added a commit that referenced this pull request Aug 16, 2026
… not container truthiness (#11702)

PR #11688 added a guard that raises when every extracted L1 candidate fails
evidence grounding, so the run cannot submit an empty replacement that would
retract the source's existing memories. It gated that raise on
`extracted_candidates and not capture_candidates` — the truthiness of whatever
extract_canonical_l1_memory_candidates returned.

Truthiness is not a count. Any truthy object that yields nothing when iterated
reads as "candidates existed and all of them failed grounding", so the guard
fires on a conversation that simply produced no candidates and aborts
conversation finalization for it. That is exactly what broke Backend Unit Tests
on main from 5af7e53 onward: test_app_summary_results_reach_the_database
stubs the extractor with a bare MagicMock, which is truthy and iterates empty.

Count the candidates the loop actually yielded and gate on that. Behaviour for
a real list is unchanged; the guard now states what it means.

Verification:
  cd backend
  : > /tmp/f.txt
  echo tests/unit/test_process_conversation_usage_context.py >> /tmp/f.txt
  echo tests/unit/test_memory_replace_policy.py >> /tmp/f.txt
  BACKEND_UNIT_TEST_FILE_LIST=/tmp/f.txt bash test.sh
    -> 30 passed (usage_context, was 1 failed/29 passed), 16 passed (replace_policy)
Reverting only the process_conversation.py hunk fails the new test
(test_canonical_capture_accepts_an_extractor_that_yields_no_candidates),
so the regression test does catch this.

Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Aug 18, 2026
…+ converge cascade-retract CAS (#11684, #11726) (#11731)

## What changed and why

Two production 5xx classes from the 2026-08-17 incident window (watchdog
`75afe342f6f8`, serving SHA `6316415` = merged #11627), fixed in two
independent commits:

1. **Missing opposite-direction Firestore list-scan indexes → 503
(#11684).** Serving queries order `updated_at DESC, __name__ ASC`
(`read_canonical_scan_page`, plus the historical dual-stream scans and
the review-queue status scan). Firestore automatic single-field indexes
only cover `field+__name__` in the *same* direction, so these need real
composites — but `_query_spec_index_requirements()` dropped every spec
with ≤1 non-`__name__` field. Prod answered `FailedPrecondition: The
query requires an index`, mapped to 503 `Canonical memory unavailable` /
`Historical memory unavailable` on `GET /v3/memories` and the
cascade-delete skip-guard scan. Fix: the predicate now declares exactly
the opposite-direction pairs and regenerates the manifest with the four
missing indexes (`memory_items` `updated_at DESC`+`__name__ ASC`;
`memories` `updated_at DESC`+`__name__ ASC`; `memories` `created_at
DESC`+`__name__ ASC`; `memory_review_queue` `status ASC`+`__name__
DESC`). Same-direction singles and array-contains pairs stay out (deploy
rejects those as redundant).

2. **Cascade-retract CAS exhaustion → 500 (#11726).** Concurrent
same-uid canonical writes all bump the one account-global
`memory_state/apply_control` document.
`replace_conversation_sourced_memories`' three *immediate* CAS attempts
exhausted under that contention and raised an unhandled `RuntimeError` →
`DELETE /v1/conversations/{id}?cascade=true` returned 500 while the
Flutter client retried one conversation up to 12× and kept the storm
fed. A repeat delete whose committed receipt went stale (another
conversation's replacement advanced `source_generation`) livelocked on
`source replacement operation already exists` the same way. Fix on the
retract entry only (cascade delete + merge; the extraction replace path
keeps its existing contract): bounded backoff retry (5 rounds,
0.05→0.5s), and after each conflict an epoch-guarded empty-cohort check
— the same double-read control fence the replacement loop uses — returns
the committed-empty result when a peer already retracted the source.
Exhaustion raises typed `ConversationReplacementConflictError` (a
`RuntimeError` subclass, so existing callers are unchanged), which
`delete_conversation` maps to a retryable **503** *before anything is
deleted*: the #11627 never-orphan-live-memories fence holds, and a
retried delete is idempotent (receipt replay / already-retracted
short-circuit).

Closes #11684
Closes #11726

## Relationship to open work

- **Supersedes #11687** (aryanorastar's index fix). That branch
conflicts with current main — main refactored the predicate into
`_query_spec_index_requirements()` — so this PR re-expresses the same
semantic change there, ports its test fix verbatim
(`test_firestore_config_does_not_declare_same_direction_single_field_composites`
+ the four-tuple declaration test), and regenerates the manifest through
the generator rather than hand-patched JSON hunks. Credit for the
measured predicate direction belongs to #11684/#11687.
- **Does not replace #11727** (draft: zero-write retraction while intake
is paused). That PR targets the fenced-intake path; this PR converges
the open-intake CAS path. Whichever lands second will need a small
rebase; the touched regions barely overlap.
- Out of scope, per #11726: #11685/#11688 extract abort,
MEMORY_MODE/cohort/control-schema redesign, client-only backoff.

## Merge sequencing (required)

`firestore_readiness` runs `reconcile_firestore_indexes.py --check-only`
on backend deploys and **fails closed until every manifest index is
READY**. Merge only after a human runs `Reconcile Firestore Indexes` →
`prod` → `APPLY_FIRESTORE_INDEXES` (dev first is fine) — that APPLY
alone stops the 503s even before this PR merges. Split-merging
(declaration after APPLY lands separately) is a later human decision;
nobody should run APPLY from this PR.

## How it was verified

- `pytest tests/unit/test_firestore_index_config.py
tests/unit/test_firestore_indexes.py
tests/unit/test_reconcile_firestore_indexes.py
tests/unit/test_firestore_query_contract.py` → **62 passed** (was 61 on
the wrong predicate; the renamed same-direction test no longer codifies
the bug and the new opposite-direction declaration test pins all four
indexes).
- `python3 backend/scripts/generate_firestore_indexes.py --write` then
read-mode → `firestore.indexes.json matches the Firestore index
registry`; diff adds exactly the 4 entries (+56 lines, same shape as
#11687).
- `python3 backend/scripts/firestore_query_coverage.py --check-ratchet`
→ exit 0 (coverage keys on query signatures; QUERY_SPECS unchanged → no
baseline drift).
- `pytest tests/unit/test_cascade_retract_convergence.py
tests/unit/test_delete_conversation_cascade_retraction_fence.py` → **7
passed**: injected `ConversationSourceReplacementConflict` rounds
converge with bounded backoff; repeat retract with a stale receipt
returns already-retracted instead of livelocking; exhausted conflicts
with live items still raise (conversation + memories intact, #11627
fence); route maps the typed conflict to 503 before any delete.
- Affected memory suites: `pytest tests/unit/test_ws_i_hardening.py
tests/unit/test_ws_j_delete_privacy.py
tests/unit/test_memory_apply_store.py
tests/unit/test_memory_replace_policy.py
tests/unit/test_merge_conversations_canonical_delete.py
tests/unit/test_merge_skips_retraction_without_canonical_memories.py
tests/unit/test_universal_memory_service.py
tests/unit/test_atomicity_lifecycle_regressions.py` → **173 passed**.
- Scan-read/fake-contract: `pytest
tests/unit/test_bounded_firestore_list_reads.py
tests/unit/test_firestore_fake_contract.py` → **12 passed**.
- `scripts/pr-preflight --suggest` → INV-MEM-1 required; failure-class
protocol honored below.

Not verified here: live Firestore behavior (no APPLY, no prod/dev writes
— the four indexes must be provisioned by a human via the workflow
above).

## Tests

- Index half regression:
`backend/tests/unit/test_firestore_index_config.py::test_firestore_config_declares_opposite_direction_universal_list_scans`
(fails on main's manifest) and the renamed same-direction test (fails if
the predicate over-declares).
- CAS half regression:
`backend/tests/unit/test_cascade_retract_convergence.py` (three
behavioral tests: convergence under injected conflicts, stale-receipt
idempotency, fail-closed exhaustion) +
`test_delete_conversation_cascade_retraction_fence.py::test_exhausted_replacement_conflict_maps_to_retryable_503_before_any_delete`.

## Product invariants affected

INV-MEM-1

## Failure class (fixes)

Failure-Class: FC-undeclared-serving-query-index

(That class covers the index half exactly — a serving query's composite
index missing from the registry manifest. The CAS half has no existing
class in the registry; it is a candidate for a new class —
"account-global CAS exhaustion surfaced as an unhandled 500 on a
retryable, idempotent operation" — to be registered separately per the
transition-narrative protocol, not inline in this fix PR.)

Line-Count-Exception: backend/routers/conversations.py | 1515 -> 1527 |
retryable-503 mapping for the cascade-retract conflict (#11726) is a few
lines inside the existing delete route; splitting the router is out of
scope for an incident fix
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py |
2388 -> 2491 | retract convergence loop + epoch-guarded completion check
+ typed conflict error live with the CAS loop they wrap (#11726);
extraction into a new module would split the replace/retract boundary
mid-incident

## Residual risk

- The 503-after-exhaustion path is still a 5xx by design — but only
after 5 backoff rounds *and* a proven-non-empty source, with nothing
deleted and a safe client retry; the incident's unbounded 12×-retry 500
loop is gone (converges or fails closed).
- The already-retracted short-circuit trusts the same double-read fence
the replacement loop uses; it cannot skip a retract that still has live
items (live items → keep retrying → raise).
- Multi-instance Cloud Run: the backoff converges cross-instance via the
control CAS itself; there is no cross-instance lock (deliberately — the
smallest shape #11726 sanctioned).


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/11731?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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.

One ungrounded memory candidate aborts the whole conversation: ~1 in 3 lazy enrichments fails on 'evidence without a unique source binding'

1 participant