Skip to content

refactor(conversations): atomic terminal-family claims (phase 2a) - #24756

Merged
Git-on-my-level merged 8 commits into
mainfrom
lane/lcphase2a
Nov 6, 2026
Merged

Git-on-my-level merged 8 commits into
mainfrom
lane/lcphase2a

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Followup candidate: 5c951758ea6bdc6cf2bc8ada83393aa4f6834162 is committed locally and undergoing the normal push hook. Published head remains 99a68812c57242ffe6f12a53725b801a2ff23694 until that hook passes.

Late processor results could overwrite failure state or regress an already-completed conversation back to processing. Phase 2a extracts a pure claim core and commits content plus an accepted completion in one Firestore update. With serving enabled, failure state can become success only with explicit sync_relevance_user_kept restore authority. Retry-trigger provenance alone never bypasses this refusal. A completed row also retains its status when a non-completed payload arrives; content still merges.

Explicit restoration atomically supersedes the old failure classifier and clears legacy dead-letter status with success. Real caller tests establish that SERVER_RECOVERY fences failed rows before invoking the processor; a user reprocess of a discarded row passes user_kept, and the real processor persists the explicit restore marker with its completion. No retry-trigger allowlist remains.

Committed status refusals increment omi_conversation_terminal_claim_refusals_total{family,reason} with distinct terminal_failure and completed_status_regression reasons. Failed commits do not increment it. Existing CAS/privacy guards, transaction-bound projection checks, quiet-check restoration and post-commit hooks stay in their owners. The core takes a snapshot and returns a patch or refusal without IO or hooks. terminal_family=success and terminal_family_at are backend-only; no API model changes.

Flag: CONVERSATION_TERMINAL_FAMILY_MODE=on|off, default on, through refactor_modes.default_on and refactor_modes.serving_for, registered as an ops kill switch. Registered in the flag budget, feature registry, deployment classification and inherited runtime configuration. Rollback: set off and roll the environment; legacy claim dictionaries and all persist status merges return byte-for-byte, and stored classifier fields remain inert. Desktop uses the code default because inline workflow edits are outside this PR's scope.

The intended behavior changes are refusing processor completion over failure state without explicit restoration, and refusing non-completed status regressions over completed rows. Content still merges in both cases. Other writer-family routing (phase 2b), meeting receipts, backfills, API fields, finalizer/lifecycle/jobs runtime files, drain and privacy behavior are excluded.

Validation: the initial 146 B1/B2 and real retry caller tests passed. CI then required the new metric reason expression to be visibly closed; it now uses only the two intended literal reasons plus unknown, without adding a debt allowance. The focused tests plus the reason-label ratchet are being rerun at the final head. The normal HTTPS pre-push hook passed with credentials unset and the lead-authorized BACKEND_UNIT_FILE_BUDGET_SECONDS=900, without a bypass, cap override or force. Its 54-check preflight passed in 487.39 seconds, followed by the backend typecheck and selected unit tests. Final exact-head CI will be checked after the bounded-label followup is pushed; the PR remains ready for review. Flag-off goldens cover claim call shapes, failed/restored rows and completed-row non-completion payloads. Existing local emulator evidence proves nested update/merge mask equivalence; hermetic E2E previously passed 206 tests (3 skipped, 2 expected failures).

Review: lead2's focused Luna delta identified B1 (retry-trigger bypass) and B2 (completed-status regression); both are addressed here. Lead2 will run the next focused delta at the new head. The configured Grok route previously timed out; no Grok approval is claimed.

Not measured: production contention or pod-death fault injection, production failure-marker stock/refusal rates, latency/cost, deployed/runtime behavior or UI acceptance. No GCP tier used; no production access, merge or deploy.

Invariant: INV-MEM-4 — canonical memory promotion authority is unchanged; only conversation status persistence changes.
Failure-Class: FC-split-mutation-authority
Line-Count-Exception: backend/database/conversations.py | 4681 -> 4854 | Keep the approved pure claim core and atomic persist in the existing storage owner; splitting production files would expand phase 2a scope.

@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 6, 2026 09:21
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-06T10:39:46.843563Z 5c95175 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

5 issues found across 33 files

Confidence score: 3/5

  • In backend/database/conversations.py, a refused late completion can overwrite the stored relevance classifier. Preserve the existing relevance_decision on that path.
  • The regression checks are not dependable: CI omits backend/tests/integration/test_conversation_terminal_family_firestore.py, and the AST guard in backend/tests/unit/test_terminal_relevance.py can miss an identical assessment call elsewhere. Add the integration test to the emulator workflow and make the guard verify the call’s enclosing function.
  • The emulator guard in backend/tests/integration/test_conversation_terminal_family_firestore.py rejects valid IPv6 loopback addresses. Allow ::1 and [::1]:port.
  • backend/tests/unit/test_conversation_terminal_family.py has an unused import that makes the Ruff pre-commit hook fail. Remove transcript_sha256_for_binding.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/tests/unit/test_conversation_terminal_family.py">

<violation number="1" location="backend/tests/unit/test_conversation_terminal_family.py:13">
P3: Remove the unused `transcript_sha256_for_binding` import; otherwise the Ruff pre-commit hook rejects this test file.</violation>
</file>

<file name="backend/tests/integration/test_conversation_terminal_family_firestore.py">

<violation number="1" location="backend/tests/integration/test_conversation_terminal_family_firestore.py:20">
P2: This regression proof is not run by repository CI: unit tests exclude integration files, and the emulator workflow’s explicit proof list omits it. Add the file to the emulator proof command and workflow path filters so the merge-semantics regression cannot ship untested.</violation>

<violation number="2" location="backend/tests/integration/test_conversation_terminal_family_firestore.py:22">
P2: This guard rejects a Firestore emulator bound to IPv6 loopback `::1`, causing valid hermetic runs to fail. Allow the IPv6 loopback host, including bracketed `[::1]:port` form.</violation>
</file>

<file name="backend/tests/unit/test_terminal_relevance.py">

<violation number="1" location="backend/tests/unit/test_terminal_relevance.py:352">
P3: `ast.dump` does not prove this call is inside `claim_conversation_status_in_txn`, because it drops source locations; an identical call added elsewhere would evade this guardrail and allow an extra assessment site. Compare the call and core-node source locations, or use nodes from one parsed tree.</violation>
</file>

<file name="backend/database/conversations.py">

<violation number="1" location="backend/database/conversations.py:1516">
P2: A refused late completion can still overwrite the stored relevance classifier: `persist_processed_conversation` stamps the incoming payload with `relevance_decision`, and this branch removes only lifecycle fields before `_processing_result_update_fields(write_data)` sends the update. Omit `relevance_decision` here so the existing failure classifier remains unchanged while content merges.</violation>
</file>

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

View guided diff | Turn on auto-fix | Re-trigger cubic

@pytest.mark.parametrize('parent', [None, 42, {}, {'kept': 'old', 'nested': None}])
def test_atomic_processor_update_matches_legacy_merge_over_nonmap_parents(parent):
host = os.environ['FIRESTORE_EMULATOR_HOST']
assert host.startswith(('127.0.0.1:', 'localhost:')), 'This proof is local-only'

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: This guard rejects a Firestore emulator bound to IPv6 loopback ::1, causing valid hermetic runs to fail. Allow the IPv6 loopback host, including bracketed [::1]:port form.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/integration/test_conversation_terminal_family_firestore.py, line 22:

<comment>This guard rejects a Firestore emulator bound to IPv6 loopback `::1`, causing valid hermetic runs to fail. Allow the IPv6 loopback host, including bracketed `[::1]:port` form.</comment>

<file context>
@@ -0,0 +1,43 @@
[email protected]('parent', [None, 42, {}, {'kept': 'old', 'nested': None}])
+def test_atomic_processor_update_matches_legacy_merge_over_nonmap_parents(parent):
+    host = os.environ['FIRESTORE_EMULATOR_HOST']
+    assert host.startswith(('127.0.0.1:', 'localhost:')), 'This proof is local-only'
+    client = firestore.Client(project='demo-lcphase2a', credentials=AnonymousCredentials())
+    collection = client.collection('phase2a_merge_proof')
</file context>
Suggested change
assert host.startswith(('127.0.0.1:', 'localhost:')), 'This proof is local-only'
assert host.startswith(('127.0.0.1:', 'localhost:', '::1:', '[::1]:')), 'This proof is local-only'



@pytest.mark.parametrize('parent', [None, 42, {}, {'kept': 'old', 'nested': None}])
def test_atomic_processor_update_matches_legacy_merge_over_nonmap_parents(parent):

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: This regression proof is not run by repository CI: unit tests exclude integration files, and the emulator workflow’s explicit proof list omits it. Add the file to the emulator proof command and workflow path filters so the merge-semantics regression cannot ship untested.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/integration/test_conversation_terminal_family_firestore.py, line 20:

<comment>This regression proof is not run by repository CI: unit tests exclude integration files, and the emulator workflow’s explicit proof list omits it. Add the file to the emulator proof command and workflow path filters so the merge-semantics regression cannot ship untested.</comment>

<file context>
@@ -0,0 +1,43 @@
+
+
[email protected]('parent', [None, 42, {}, {'kept': 'old', 'nested': None}])
+def test_atomic_processor_update_matches_legacy_merge_over_nonmap_parents(parent):
+    host = os.environ['FIRESTORE_EMULATOR_HOST']
+    assert host.startswith(('127.0.0.1:', 'localhost:')), 'This proof is local-only'
</file context>

terminal_refusal_family = failure_family
# Keep the legacy marker too if a stale payload carries it.
write_data.pop('finalization_status', None)
write_data.pop('discarded', None)

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: A refused late completion can still overwrite the stored relevance classifier: persist_processed_conversation stamps the incoming payload with relevance_decision, and this branch removes only lifecycle fields before _processing_result_update_fields(write_data) sends the update. Omit relevance_decision here so the existing failure classifier remains unchanged while content merges.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/conversations.py, line 1516:

<comment>A refused late completion can still overwrite the stored relevance classifier: `persist_processed_conversation` stamps the incoming payload with `relevance_decision`, and this branch removes only lifecycle fields before `_processing_result_update_fields(write_data)` sends the update. Omit `relevance_decision` here so the existing failure classifier remains unchanged while content merges.</comment>

<file context>
@@ -1476,12 +1484,62 @@ def _persist(transaction) -> bool:
+                    terminal_refusal_family = failure_family
+                    # Keep the legacy marker too if a stale payload carries it.
+                    write_data.pop('finalization_status', None)
+                    write_data.pop('discarded', None)
+                else:
+                    if dead_letter:
</file context>
Suggested change
write_data.pop('discarded', None)
write_data.pop('discarded', None)
write_data.pop('relevance_decision', None)

from database import conversations as db
from models.conversation_enums import ConversationStatus as Status
from tests.unit.fixtures.strict_firestore_transaction import StrictFirestore
from utils.conversations.transcript_hash import transcript_sha256_for_binding

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: Remove the unused transcript_sha256_for_binding import; otherwise the Ruff pre-commit hook rejects this test file.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_conversation_terminal_family.py, line 13:

<comment>Remove the unused `transcript_sha256_for_binding` import; otherwise the Ruff pre-commit hook rejects this test file.</comment>

<file context>
@@ -0,0 +1,354 @@
+from database import conversations as db
+from models.conversation_enums import ConversationStatus as Status
+from tests.unit.fixtures.strict_firestore_transaction import StrictFirestore
+from utils.conversations.transcript_hash import transcript_sha256_for_binding
+
+PATH = ('users', 'synthetic', 'conversations', 'capture')
</file context>

for node in ast.walk(ast.parse(file.read_text()))
if isinstance(node, ast.FunctionDef) and node.name == 'claim_conversation_status_in_txn'
)
assert any(ast.dump(call) == ast.dump(node) for node in ast.walk(core))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: ast.dump does not prove this call is inside claim_conversation_status_in_txn, because it drops source locations; an identical call added elsewhere would evade this guardrail and allow an extra assessment site. Compare the call and core-node source locations, or use nodes from one parsed tree.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_terminal_relevance.py, line 352:

<comment>`ast.dump` does not prove this call is inside `claim_conversation_status_in_txn`, because it drops source locations; an identical call added elsewhere would evade this guardrail and allow an extra assessment site. Compare the call and core-node source locations, or use nodes from one parsed tree.</comment>

<file context>
@@ -343,6 +343,21 @@ def test_production_terminal_assessment_call_sites_are_pinned():
+                            for node in ast.walk(ast.parse(file.read_text()))
+                            if isinstance(node, ast.FunctionDef) and node.name == 'claim_conversation_status_in_txn'
+                        )
+                        assert any(ast.dump(call) == ast.dump(node) for node in ast.walk(core))
+                        assert any(
+                            kw.arg == 'path'
</file context>
Suggested change
assert any(ast.dump(call) == ast.dump(node) for node in ast.walk(core))
assert any(
(call.lineno, call.col_offset) == (node.lineno, node.col_offset)
for node in ast.walk(core)
)

@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: 99a68812c5

ℹ️ 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 on lines +1506 to +1510
if failure_family and not user_restored:
terminal_refusal = (failure_family, 'terminal_failure')
# Keep the legacy marker too if a stale payload carries it.
write_data.pop('finalization_status', None)
write_data.pop('discarded', None)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Propagate terminal refusal before permitting derived effects

When a processor starts with a kept row and another writer marks it failed/discarded before persistence, this branch preserves the stored failure but _persist still returns True. process_conversation treats that result as permission to continue at backend/utils/conversations/process_conversation.py:2956-2957, and _emit_derived_effects uses the stale in-memory discarded value to run apps and emit the conversation-created webhook. Consequently, a refused completion can still publish integrations and other completion effects for a row that remains failed/discarded. Distinguish content persistence from an accepted completion and suppress completion effects on refusal.

Useful? React with 👍 / 👎.

Comment on lines +1504 to +1507
if not failure_family and existing.get('status') == ConversationStatus.failed:
failure_family = 'failed'
if failure_family and not user_restored:
terminal_refusal = (failure_family, 'terminal_failure')

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 Establish restore authority for explicit retries of visible failures

For a failed row with discarded=False and no prior restore marker, an explicit user reprocess cannot complete anymore: reprocess_conversation derives user_kept only from was_discarded or an existing sync_relevance_user_kept marker, so this new check refuses its completed payload and leaves the stored status failed even though the endpoint returns a completed result. Such undiscarded failed rows are produced by conversation_terminal_title.fit_document_limit. Have the explicit retry admission establish the necessary authority rather than requiring the row to have been hidden first.

Useful? React with 👍 / 👎.

Comment on lines +1486 to +1487
if family_enabled:
requested_status = write_data.get('status')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add the required conversation lifecycle change note

This commit changes conversation completion authority and introduces a default-on lifecycle kill switch, but its changed-file list contains no pipeline change note. backend/AGENTS.md explicitly requires a note under backend/docs/listen_pusher_pipeline/changes/ for conversation lifecycle changes. Add the required note documenting the refusal behavior, restoration path, rollout/rollback state, and verification evidence; the batch pipeline contract update does not replace that requirement.

AGENTS.md reference: backend/AGENTS.md:L164-L164

Useful? React with 👍 / 👎.

def _terminal_family_serving(uid: str) -> bool:
# The on|off operator surface maps on to the shared serve mode. The shared
# parser retains its cohort support for a later ramp without changing defaults.
from config.refactor_modes import default_on

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the new function-local imports to module scope

The new _terminal_family_serving helper imports default_on inside its body, and the new claim core likewise imports terminal_decision locally. These additions violate the explicit module-top-level import requirement in backend/AGENTS.md. Extend the existing module-level config.refactor_modes import and place the terminal-relevance dependency at module scope as required.

AGENTS.md reference: backend/AGENTS.md:L166-L168

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit cc9c71b into main Nov 6, 2026
63 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/lcphase2a branch November 6, 2026 11:01
Git-on-my-level added a commit that referenced this pull request Nov 6, 2026
… alerts (#24788)

## Purpose

PR-A adds observational PCM byte accounting around pusher custody
`commit_pcm_window`, plus chart-only storage queue and memory alerts.
Follows phase 2a (#24756, cc9c71b) and the approved metrics-first
split.

- `omi_pusher_storage_pcm_inflight_bytes`: increment payload length
before storage submission; decrement in `finally` on success, exception
or caller cancellation. Defensive metric failures never affect
commit/ACK behavior. Cancellation can leave a running thread completing
storage; this gauge measures the await lifetime, not total retained RSS.
- `omi_pusher_storage_pcm_budget_limit_bytes`: constant zero, meaning no
budget is enforced. Both gauges are zero-initialized, label-free and
registered in the source-backed metric inventory. Pusher exports
directly through `/metrics` to the unfiltered `pusher-metrics`
Prometheus scrape; no GMP sidecar allowlist applies.

## Alert thresholds

| Grafana UID | Threshold | Pending | Tier |
|---|---|---|---|
| omi-pusher-storage-queue-warning | Queued storage tasks >256 per
pusher target | 10m | agent |
| omi-pusher-storage-queue-critical | Queued storage tasks >512 per
pusher target | 10m | page |
| omi-pusher-memory-working-set-high | Pod working set / 3.5 GiB >0.75 |
15m | page |

Queue thresholds are 2x/4x the configured 128 storage workers. The real
executor label is `storage`; custody work has task label `other`, so
queries sum all task kinds per target. RSS uses the same
container/workload selectors as `dashboards/gke/pusher.json`, normalized
by the chart's 3.5 GiB limit. The 75% bar (2.625 GiB) follows the #24699
gate. These are sustained current-state gauges, not rates over
historical incidents. Each source series must be younger than 120s
before aggregation; absent data does not page. Rules have
human-impact/verification/runbook annotations and agent/page routing.
Split/combined rules and generated query inventory are synchronized.

## Scope and rollback

No byte budget, semaphore, refusal logic/counter/alert, flags, extra
reads, executor behavior, ACK/1011/close changes, deployment settings or
`.github` changes. PR-B remains later and must first add a saturation
test. No GCP/prod access, merge or deployment. Rollback: revert this PR;
metrics are inert. Alert definitions require normal monitoring
provisioning to become live.

## Verification

- Targeted metric lifecycle/registration, monitoring alert contracts and
generated inventory: 118 passed.
- Component suites through `bin/omi-heavy` + file-isolated
`backend/test.sh`: 252 passed, 2 existing executor Future timeouts.
Isolated rerun reproduced both. An archived `origin/main` source
snapshot at cc9c71b reproduced the
identical 2 failures / 34 passes with the same Python environment. No
executor source/tests are changed. Other suites include durable outbox
(102 passed), queue wait (28 passed), executor backpressure,
metrics/cardinality/export and monitoring contracts.
- PR metadata validation: 4 checks passed. `make preflight`: all 42
checks passed with the approved 900s file budget. Normal pre-push
passed: 42 contract checks, backend type check (0 errors), all 83
selected tests, OpenAPI/client compatibility and formatting (HTTPS
through the gh credential helper,
`BACKEND_UNIT_FILE_BUDGET_SECONDS=900`, no skip hatches). The first
Firestore guard exceeded its 300s file budget; rerunning with the
approved `BACKEND_UNIT_FILE_BUDGET_SECONDS=900`, without skipping
checks.
- Required Grok review completed via agentctl on m5-mbp with read-only
access: no findings on b103608.
Reviewed gauge accounting/cancellation, metric-failure isolation, queue
aggregation, per-series freshness, 3.5 GiB memory normalization, alert
routing, tests and inventories.

## Product invariants affected

none

Line-Count-Exception: backend/routers/pusher.py | 1857 -> 1872 | Keep
the defensive observational increment/finally next to the sole custody
storage await without changing its control flow.
Line-Count-Exception: backend/utils/metrics.py | 1673 -> 1683 | Register
two label-free pusher gauges alongside the existing shared pusher
collectors used by the metrics endpoint.
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