Skip to content

Systematic discard-detection audit: valid relevance decisions at every terminal path - #23370

Closed
Git-on-my-level wants to merge 13 commits into
mainfrom
lane/discard-detection-audit
Closed

Git-on-my-level wants to merge 13 commits into
mainfrom
lane/discard-detection-audit

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Systematic discard-detection audit: every visible row carries a valid relevance decision

Why

Production row "Huh?" (doc ed296267… on a user account) surfaced VISIBLE with an EMPTY
relevance_decision: finalization dead-lettered after retries and nothing stored a
verdict — the row appeared as an undecided keep. Audit found that gap was not unique to
dead-letter: several terminal paths could surface rows without decisions.

What

  1. Mandatory decisions at every terminal state — dead-letter, orphans, BYOK
    abandonment, imports, external text, sync promotion, merge rollback, legacy restore,
    oversized captures: each now stamps a bounded-reason decision atomically in the same
    write as the terminal state. A document that cannot fit decision metadata becomes
    failed (hidden) rather than undecided-visible.
  2. New module backend/utils/conversations/terminal_relevance.py — total
    terminal-decision function: valid prior decisions preserved (regardless of discarded
    value); only explicit user restore replaces a discard; malformed keeps repaired before
    any rule discard; contentless rows → rules tier (filler_only/empty_transcript);
    ambiguous → bounded policy keep; calendar overlap always protects.
  3. decided_by/reason vocabulary extended in bounded label sets
    (conversation_relevance_labels.py), decisions counted on the existing relevance
    metrics conventions.
  4. Guard rails: lifecycle write tripwire extended — a status=completed write
    without relevance_decision fails the check; is_visible_conversation excludes
    failed; calendar overlap fetch moved out of the dead-letter transaction (bounded
    probe, commit-keep on timeout).
  5. Audit document backend/docs/audits/discard-decision-paths.md: full
    path → terminal-states → decision-guarantee table.

Deliberately NOT done

No jev/nano threshold or lexicon changes (a 0.78-vs-0.80 near-miss keep is calibration),
no historical row backfill, recovery-keep semantics unchanged except provenance
retention, tombstone contract untouched.

Testing

  • New suites: test_terminal_relevance.py, test_dead_letter_visible_row_title.py
    (incl. the "Huh?" replay fixture: dead_letter + empty decision → atomic rule decision),
    extended lifecycle-contract tests (merge-rollback preserves a legacy hidden rule
    discard), tripwire self-test.
  • Round-trip: codex gpt-6.1-sol built; cursor grok-4.7-high round 1 REQUEST_CHANGES
    (completion stamp un-hid legacy rule discards) → round 2 verified the fix in-tree:
    APPROVE, 120 targeted tests + tripwire green; independent parent verification 372
    tests green across relevance/terminal/dead-letter/lifecycle suites.
  • backend/test-preflight.sh green.

Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 2652 -> 2661 | dead-letter terminal decision stamping at the job terminal write (bounded +9 lines)
Line-Count-Exception: backend/database/conversations.py | 4015 -> 4022 | claim_conversation_status preserves valid prior decisions + public accessor for the post-write search index convergence (net +7 lines)

Product invariants affected

  • INV-MEM-4 (memory-promotion-authority): process_conversation.py changes only
    terminal-decision stamping; no memory intake/promotion path touched.
  • INV-TASK-2 (task-capture-suggestion-only): no task extraction or candidate writing.

Failure-Class

Failure-Class: FC-contentless-recovery-surfaced-visible

View guided diff Turn on auto-fix

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 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-10-23T06:15:19.334677Z 93b9e48 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.

Close decision gaps in dead-letter, orphan, BYOK, imports, external text, sync promotion, merge rollback, and legacy restore paths. Preserve calendar, photo, wake-word, rule-keep, and tombstone protections; keep mandatory decisions through terminal size guards.

Failure-Class: FC-contentless-recovery-surfaced-visible
Keep the large conversation modules below their existing line budgets by moving snapshot status storage, deferred retry storage, pure terminal payload serialization, and bounded metric vocabulary to their owning modules. Migrate callers and behavioral/static coverage together.

Failure-Class: FC-contentless-recovery-surfaced-visible
Cover the direct batch fixture writer with an explicit fixture-seed policy and bounded telemetry vocabulary. Preserve the local/offline account fence and extract the payload builder to keep its owner below the existing line budget.

Failure-Class: FC-contentless-recovery-surfaced-visible
Invalidate people-stats and refresh search after terminal discards or document-ceiling failures commit. Isolate observer failures and publish no effects on aborted transactions. Document terminal relevance and size behavior in the lifecycle owner guide.

Failure-Class: FC-contentless-recovery-surfaced-visible
Narrow prior decision before subscripting, return str-keyed entries from
the preserve path, and expose a public accessor for the post-write search
index convergence instead of touching the private name.

@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: 8f3f9a2d76

ℹ️ 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 +813 to +816
if (
is_soft_deleted(conversation)
or getattr(conversation.get('status'), 'value', conversation.get('status')) == 'failed'
):

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 Preserve failed conversations in export and recovery views

Move the failed exclusion into the normal product-list branch rather than applying it before include_discarded. As written, every include_discarded=True caller also drops failed rows: this removes existing fail_and_discard_processing captures from Show Discarded (and they remain invisible even after restore), and iter_all_conversations(..., include_discarded=True) at services/users/data_export.py:256 now omits both those rows and the content-bearing oversized rows introduced by this commit from the portability export.

Useful? React with 👍 / 👎.

Comment on lines +279 to +283
record_conversation_relevance(
trigger=decision['trigger'],
verdict=decision['verdict'],
decided_by=decision['decided_by'],
reason=decision['reason'],

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 Emit relevance metrics only after terminal commits

Defer this counter update until the transaction has committed. with_terminal_relevance runs inside the dead-letter, orphan, BYOK, and oversized Firestore transaction callbacks, which Firestore may invoke repeatedly on contention or invoke before an ultimately failed commit; each invocation increments the process-local counter, so one durable decision can be counted multiple times—or counted without being stored at all. The newly added stamp_terminal_decision has the same issue when called from _transition and _claim; these metrics should use the post-commit effect collection already introduced for visibility refreshes.

Useful? React with 👍 / 👎.

Comment on lines +25 to +27
meetings = calendar_meetings.get_meetings_in_time_range(uid, start - tolerance, end + tolerance)
if select_overlapping_meeting(meetings, started_at=start, finished_at=end) is not None:
return True

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 Treat a full stored-meeting page as uncertain

Return an uncertain result when this lookup yields its full page without finding a match. get_meetings_in_time_range sorts by start time and hard-limits the result to 10 (database/calendar_meetings.py:153-158), so when more than ten records overlap the tolerance window, earlier long or screen-derived records can fill the page while a genuinely overlapping calendar meeting is omitted. For a user without a connected Google integration, this code then returns False, allowing a contentless failed-finalization capture from that meeting to be rule-discarded even though the stated conservative policy requires bounded/truncated evidence to keep it.

Useful? React with 👍 / 👎.

Comment on lines +76 to +78
if isinstance(prior, Mapping) and valid_decision(prior) and not (prior['verdict'] == 'discard' and user_restore):
prior_entries = {str(k): v for k, v in prior.items()}
return prior_entries

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 Replace prior keeps with the user's restore verdict

Handle user_restore before returning a valid prior keep. A normal manual discard only sets discarded=True and leaves the existing relevance decision untouched, so restoring a previously kept conversation reaches this branch with user_restore=True and a valid rule/model/policy keep. The early return preserves that old provenance instead of writing the promised decided_by='user', reason='restored' decision, and the restore is absent from the relevance metrics as well.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level force-pushed the lane/discard-detection-audit branch from 8f3f9a2 to 00b5510 Compare October 23, 2026 05:33

@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: 00b5510582

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

):
return False
terminal = {**data, 'status': 'completed', 'deferred': True}
stamp_terminal_decision(terminal, path='deferred_retry')

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 Handle document-limit failures when re-arming deferred rows

When a legacy deferred conversation has no valid relevance_decision and is already near Firestore's 1 MiB limit, this stamp adds a full decision record before the update. Unlike the other newly added terminal paths, this transaction has no size check or shrinking fallback, so Firestore rejects the entire update and a failed first-open enrichment leaves the row in processing with deferred=False instead of publishing the intended retryable terminal. Apply the same size-aware fallback used by fit_document_limit here.

Useful? React with 👍 / 👎.

calendar_retains=lambda: (
calendar_probe(conversation)
if calendar_probe is not None
else calendar_retains(uid, conversation) if path != 'dead_letter' else 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 Badge Move calendar provider calls out of every terminal transaction

For an empty or filler-only audio row on the orphan, BYOK-abandonment, or oversized terminal paths, this branch invokes calendar_retains from inside the Firestore transaction callback. That helper performs additional Firestore reads and, for connected Google Calendar users, can spend up to ten seconds on provider I/O; contention retries repeat the provider call while holding the transaction open. The dead-letter wrapper explicitly precomputes the same evidence to avoid consuming the transaction deadline, so these other terminal wrappers should do likewise.

Useful? React with 👍 / 👎.



def _has_wake_word(texts: Sequence[str]) -> bool:
from utils.conversations.wake_word import find_wake_word_matches

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 Hoist the new terminal-relevance imports to module scope

_has_wake_word and stamp_terminal_decision introduce function-scoped imports in this new module. The backend's strict import rule requires every import at module scope, so hoist these dependencies—or resolve any resulting cycle structurally—rather than adding lazy imports to a shared lifecycle path.

AGENTS.md reference: backend/AGENTS.md:L161-L163

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level marked this pull request as draft November 4, 2026 07:01
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review November 4, 2026 07:27

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

24 issues found across 43 files

Confidence score: 2/5

  • terminal_calendar.py can treat the first ten meetings as complete evidence, so a matching eleventh meeting may be missed and a filler row discarded. Treat a full bounded result as incomplete.
  • lifecycle.py can overwrite a stored valid decision when a partial payload omits it. Preserve the stored decision when the incoming payload has none.
  • Terminal paths run calendar/provider I/O inside retryable Firestore transactions, which can repeat slow probes and exhaust transaction deadlines. Prefetch the calendar probe before each transaction.
  • lifecycle.py can stamp a keep decision while a row is still processing, blocking terminal repair from reassessing the transcript. Stamp decisions only for terminal statuses.
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/utils/conversations/deterministic_minimum.py">

<violation number="1" location="backend/utils/conversations/deterministic_minimum.py:179">
P2: This helper drops external-integration transcript text because `ExternalIntegrationCreateConversation` stores it in `conversation.text`, not `transcript_segments`. Deferred external rows therefore lose their usable title and appear as generic `Recording`; include the external `text` representation when deriving the placeholder title.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_recovery_discard_pipeline.py:299">
P3: These assertions accept any syntactically valid keep decision, so they will not catch wrong provenance or reason for the decode-failure dead-letter path. Assert `trigger == 'dead_letter'` and `reason == 'dead_letter_default'` here.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_terminal_relevance.py:319">
P2: This codebase-wide AST scan runs in the fast unit lane because the test is unmarked, while the repository requires codebase scans to use `@pytest.mark.slow` and the slow-guardrail manifest. Mark this guardrail slow and add the file to `tests/slow_guardrail_manifest.txt` rather than masking its cost with the fast-duration allowlist.</violation>
</file>

<file name="backend/utils/sync/assignment.py">

<violation number="1" location="backend/utils/sync/assignment.py:615">
P2: `stamp_terminal_decision` increments the relevance counter while `plan()` is still speculative. Rollover and transaction retries can therefore count one committed intake multiple times, including plans never written. Emit this metric only after the Firestore write succeeds.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_conversation_finalization_jobs.py:1863">
P3: This assertion does not verify that the deferred terminal decision is valid or keeps the row visible. Assert the complete decision shape (or call `valid_decision`) so regressions in `verdict`, `decided_by`, or `trigger` fail.</violation>
</file>

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

<violation number="1" location="backend/database/oversized_conversation_terminal.py:72">
P2: This path makes calendar-overlap probing run inside the Firestore transaction. The non-transactional reads and provider call are outside the transaction’s consistency/retry fence, can substantially delay or repeat transaction attempts, and may base a discard on stale calendar evidence; pre-resolve the probe before starting this transaction and pass a window-validated result into the callback, as the dead-letter path does.</violation>
</file>

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

<violation number="1" location="backend/database/conversation_terminal_title.py:261">
P2: The orphan, BYOK, and oversized terminal paths now perform calendar-provider I/O inside retryable Firestore transactions. Prefetch a calendar probe before each transaction and pass it in, as the dead-letter path does, so provider latency and failures cannot consume transaction retries.</violation>

<violation number="2" location="backend/database/conversation_terminal_title.py:279">
P2: This records relevance metrics inside a retryable transaction callback, so contention can count one terminal decision multiple times. Emit the metric after a successful commit or make the recording idempotent.</violation>
</file>

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

<violation number="1" location="backend/utils/conversations/terminal_calendar.py:25">
P1: This helper performs blocking Firestore and provider I/O inside orphan, oversized, and BYOK transaction callbacks. Precompute the calendar result outside every transaction and pass a probe into `with_terminal_relevance`, as the dead-letter path does, so retries do not repeat external I/O or delay terminalization.</violation>

<violation number="2" location="backend/utils/conversations/terminal_calendar.py:26">
P1: This treats the first ten stored meetings as complete evidence. A matching eleventh meeting can be omitted, causing a filler row to be discarded for disconnected users; return `None` when the bounded result is full or remove the limit.</violation>
</file>

<file name="backend/utils/conversation_relevance_labels.py">

<violation number="1" location="backend/utils/conversation_relevance_labels.py:33">
P3: The new canonical `DECIDERS` set is not reused by the relevance metric labels, so adding a valid decider can be recorded as `other`. Import `DECIDERS` in `metrics.py` and use it for `decided_by`.</violation>
</file>

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

<violation number="1" location="backend/database/conversation_finalization_jobs.py:1393">
P2: The pre-transaction path lacks the string guards used by `_mark_finalization_dead_letter_txn`; a malformed leased job can fail while constructing its conversation reference and remain leased instead of being terminalized. Apply the same `isinstance(..., str)` and non-empty checks before this preflight read.</violation>

<violation number="2" location="backend/database/conversation_finalization_jobs.py:2338">
P2: This invokes calendar/provider I/O inside the BYOK/orphan Firestore transaction. A slow provider or transaction retry can exhaust the transaction deadline, repeat the probe and metrics, and leave the job or conversation unterminalized; precompute a calendar probe before entering the transaction, as the dead-letter path does, and pass the fenced probe into this helper.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_conversation_finalization_jobs_resilience.py:189">
P2: These tests can pass an incomplete relevance decision, so they do not verify the valid-decision contract this PR is adding. Assert `decided_by`, the exact bounded `reason`, and `rules_version` in both patches.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_byok_abandonment_reconciliation.py:391">
P2: This partial assertion no longer verifies that an existing structured title is preserved. Assert the complete terminal patch, including `discarded` and `relevance_decision`, and keep `structured` absent.</violation>

<violation number="2" location="backend/tests/unit/test_byok_abandonment_reconciliation.py:406">
P2: The document-limit test no longer verifies its stated “without growth” contract. Assert the complete base terminal patch, including the relevance fields and the absence of `structured`.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_conversation_terminal_effects.py:40">
P2: This parametrized test never executes any terminal transaction body, so it cannot prove those entrypoints stage refreshes or preserve their real outcomes; it only tests the decorator with a manually staged event. Invoke the supplied transaction callback against path-specific fakes (or use the existing transaction fixtures) and assert each entrypoint's actual result.</violation>
</file>

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

<violation number="1" location="backend/utils/conversations/lifecycle.py:205">
P1: This stamps only the incoming payload, so partial processor writes can overwrite a stored valid decision. `minimal_redrive._title_new_conversation` sends no decision, replacing an existing `sync_intake` or rule decision with `lifecycle_terminal_default` and potentially leaving `discarded=True` paired with a keep verdict; preserve the stored decision during the transaction before stamping or merging this payload.</violation>

<violation number="2" location="backend/utils/conversations/lifecycle.py:205">
P2: This stamps a terminal keep decision while the row is still `processing`, preventing later terminal repair from reassessing the transcript. Stamp only terminal statuses, or mark provisional decisions so terminal repair can replace them.</violation>
</file>

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

<violation number="1" location="backend/database/conversations.py:2729">
P2: This transaction records relevance metrics before commit, so Firestore contention retries overcount terminal decisions. Stamp without metrics inside the transaction, then record the metric once after a successful commit.</violation>
</file>

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

<violation number="1" location="backend/utils/conversations/terminal_relevance.py:153">
P3: `_has_wake_word` can never detect a wake word because `find_wake_word_matches` requires a stable segment ID before returning a match. Pass segment identity (and timing where available) through this helper instead of constructing text-only mappings, so wake-word evidence really bypasses transcript-only repair.</violation>
</file>

<file name="backend/docs/audits/discard-decision-paths.md">

<violation number="1" location="backend/docs/audits/discard-decision-paths.md:3">
P2: This contract is broader than the implemented guarantee: historical completed rows without `relevance_decision` can still appear in the default list. Scope the invariant to rows newly terminalized by the audited writers, or add a reader/backfill guard if it is intended to cover all rows.</violation>
</file>

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

<violation number="1" location="backend/database/conversation_status_transitions.py:7">
P3: Move `verified_recovery_discard` to a module-level import and adjust the isolated harness stubs instead of introducing a function-local import.</violation>
</file>

<file name="backend/scripts/check_conversation_lifecycle_writes.py">

<violation number="1" location="backend/scripts/check_conversation_lifecycle_writes.py:183">
P2: The completed-write tripwire silently ignores non-literal payloads, so a completed raw write can pass without `relevance_decision`. Resolve supported `dict(...)`/name payloads or fail closed on unknown payload shapes.</violation>
</file>

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

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

return None
tolerance = timedelta(minutes=MEETING_SEARCH_TOLERANCE_MINUTES)
meetings = calendar_meetings.get_meetings_in_time_range(uid, start - tolerance, end + tolerance)
if select_overlapping_meeting(meetings, started_at=start, finished_at=end) is not 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: This treats the first ten stored meetings as complete evidence. A matching eleventh meeting can be omitted, causing a filler row to be discarded for disconnected users; return None when the bounded result is full or remove the limit.

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/utils/conversations/terminal_calendar.py, line 26:

<comment>This treats the first ten stored meetings as complete evidence. A matching eleventh meeting can be omitted, causing a filler row to be discarded for disconnected users; return `None` when the bounded result is full or remove the limit.</comment>

<file context>
@@ -0,0 +1,50 @@
+        return None
+    tolerance = timedelta(minutes=MEETING_SEARCH_TOLERANCE_MINUTES)
+    meetings = calendar_meetings.get_meetings_in_time_range(uid, start - tolerance, end + tolerance)
+    if select_overlapping_meeting(meetings, started_at=start, finished_at=end) is not None:
+        return True
+    # The normal linker deliberately maps provider errors to None. A failed
</file context>

ConversationStatus.failed,
)

stamp_terminal_decision(conversation_data, path='lifecycle_terminal')

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: This stamps only the incoming payload, so partial processor writes can overwrite a stored valid decision. minimal_redrive._title_new_conversation sends no decision, replacing an existing sync_intake or rule decision with lifecycle_terminal_default and potentially leaving discarded=True paired with a keep verdict; preserve the stored decision during the transaction before stamping or merging this payload.

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/utils/conversations/lifecycle.py, line 205:

<comment>This stamps only the incoming payload, so partial processor writes can overwrite a stored valid decision. `minimal_redrive._title_new_conversation` sends no decision, replacing an existing `sync_intake` or rule decision with `lifecycle_terminal_default` and potentially leaving `discarded=True` paired with a keep verdict; preserve the stored decision during the transaction before stamping or merging this payload.</comment>

<file context>
@@ -198,6 +202,8 @@ def persist_processed_conversation(
         ConversationStatus.failed,
     )
 
+    stamp_terminal_decision(conversation_data, path='lifecycle_terminal')
+
     def _observe_first_completion() -> None:
</file context>

# No trustworthy window means the terminal cannot disprove overlap.
return None
tolerance = timedelta(minutes=MEETING_SEARCH_TOLERANCE_MINUTES)
meetings = calendar_meetings.get_meetings_in_time_range(uid, start - tolerance, end + tolerance)

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: This helper performs blocking Firestore and provider I/O inside orphan, oversized, and BYOK transaction callbacks. Precompute the calendar result outside every transaction and pass a probe into with_terminal_relevance, as the dead-letter path does, so retries do not repeat external I/O or delay terminalization.

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/utils/conversations/terminal_calendar.py, line 25:

<comment>This helper performs blocking Firestore and provider I/O inside orphan, oversized, and BYOK transaction callbacks. Precompute the calendar result outside every transaction and pass a probe into `with_terminal_relevance`, as the dead-letter path does, so retries do not repeat external I/O or delay terminalization.</comment>

<file context>
@@ -0,0 +1,50 @@
+        # No trustworthy window means the terminal cannot disprove overlap.
+        return None
+    tolerance = timedelta(minutes=MEETING_SEARCH_TOLERANCE_MINUTES)
+    meetings = calendar_meetings.get_meetings_in_time_range(uid, start - tolerance, end + tolerance)
+    if select_overlapping_meeting(meetings, started_at=start, finished_at=end) is not None:
+        return True
</file context>

opens it (which triggers the real enrichment). A non-empty title is required — an empty one
marks the conversation discarded in `_get_conversation_obj`."""
text = ''
for seg in list(getattr(conversation, 'transcript_segments', None) or []):

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 helper drops external-integration transcript text because ExternalIntegrationCreateConversation stores it in conversation.text, not transcript_segments. Deferred external rows therefore lose their usable title and appear as generic Recording; include the external text representation when deriving the placeholder title.

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/utils/conversations/deterministic_minimum.py, line 179:

<comment>This helper drops external-integration transcript text because `ExternalIntegrationCreateConversation` stores it in `conversation.text`, not `transcript_segments`. Deferred external rows therefore lose their usable title and appear as generic `Recording`; include the external `text` representation when deriving the placeholder title.</comment>

<file context>
@@ -168,3 +168,19 @@ def build_deterministic_minimum_structured(
+    opens it (which triggers the real enrichment). A non-empty title is required — an empty one
+    marks the conversation discarded in `_get_conversation_obj`."""
+    text = ''
+    for seg in list(getattr(conversation, 'transcript_segments', None) or []):
+        seg_text = (getattr(seg, 'text', '') or '').strip()
+        if seg_text:
</file context>

assert calls == [False] * len(TERMINAL_PATHS)


def test_production_terminal_assessment_call_sites_are_pinned():

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 codebase-wide AST scan runs in the fast unit lane because the test is unmarked, while the repository requires codebase scans to use @pytest.mark.slow and the slow-guardrail manifest. Mark this guardrail slow and add the file to tests/slow_guardrail_manifest.txt rather than masking its cost with the fast-duration allowlist.

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 319:

<comment>This codebase-wide AST scan runs in the fast unit lane because the test is unmarked, while the repository requires codebase scans to use `@pytest.mark.slow` and the slow-guardrail manifest. Mark this guardrail slow and add the file to `tests/slow_guardrail_manifest.txt` rather than masking its cost with the fast-duration allowlist.</comment>

<file context>
@@ -0,0 +1,350 @@
+    assert calls == [False] * len(TERMINAL_PATHS)
+
+
+def test_production_terminal_assessment_call_sites_are_pinned():
+    import ast
+    from pathlib import Path
</file context>

Comment on lines +299 to +300
assert valid_decision(row['relevance_decision'])
assert row['relevance_decision']['verdict'] == 'keep'

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: These assertions accept any syntactically valid keep decision, so they will not catch wrong provenance or reason for the decode-failure dead-letter path. Assert trigger == 'dead_letter' and reason == 'dead_letter_default' here.

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_recovery_discard_pipeline.py, line 299:

<comment>These assertions accept any syntactically valid keep decision, so they will not catch wrong provenance or reason for the decode-failure dead-letter path. Assert `trigger == 'dead_letter'` and `reason == 'dead_letter_default'` here.</comment>

<file context>
@@ -295,7 +296,8 @@ async def test_decode_failure_preserves_blob_and_uses_existing_terminal_path(pip
     assert row['transcript_segments'] == blob
     assert row['status'] == 'completed' and row['discarded'] is False
-    assert 'relevance_decision' not in row
+    assert valid_decision(row['relevance_decision'])
+    assert row['relevance_decision']['verdict'] == 'keep'
     assert pipeline.store.rows[JOB_PATH]['last_failure_code'] == 'recovery_structure_unavailable'
</file context>
Suggested change
assert valid_decision(row['relevance_decision'])
assert row['relevance_decision']['verdict'] == 'keep'
assert valid_decision(row['relevance_decision'])
assert row['relevance_decision']['verdict'] == 'keep'
assert row['relevance_decision']['trigger'] == 'dead_letter'
assert row['relevance_decision']['reason'] == 'dead_letter_default'

assert ref is expected
assert patch['status'] == 'completed'
assert patch['deferred'] is True
assert patch['relevance_decision']['reason'] == 'deferred_retry_default'

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: This assertion does not verify that the deferred terminal decision is valid or keeps the row visible. Assert the complete decision shape (or call valid_decision) so regressions in verdict, decided_by, or trigger fail.

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_finalization_jobs.py, line 1863:

<comment>This assertion does not verify that the deferred terminal decision is valid or keeps the row visible. Assert the complete decision shape (or call `valid_decision`) so regressions in `verdict`, `decided_by`, or `trigger` fail.</comment>

<file context>
@@ -1834,14 +1852,16 @@ def test_recover_deferred_processing_failure_atomically_rearms_retry():
+        assert ref is expected
+        assert patch['status'] == 'completed'
+        assert patch['deferred'] is True
+        assert patch['relevance_decision']['reason'] == 'deferred_retry_default'
+    assert len(transaction.updates) == 2
 
</file context>
Suggested change
assert patch['relevance_decision']['reason'] == 'deferred_retry_default'
assert patch['relevance_decision'] == {
'verdict': 'keep',
'decided_by': 'policy',
'reason': 'deferred_retry_default',
'trigger': 'deferred_retry',
'rules_version': 1,
}

'backfill',
}
)
DECIDERS = frozenset({'policy', 'user', 'rule', 'model', 'jev', 'override', 'deterministic'})

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: The new canonical DECIDERS set is not reused by the relevance metric labels, so adding a valid decider can be recorded as other. Import DECIDERS in metrics.py and use it for decided_by.

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/utils/conversation_relevance_labels.py, line 33:

<comment>The new canonical `DECIDERS` set is not reused by the relevance metric labels, so adding a valid decider can be recorded as `other`. Import `DECIDERS` in `metrics.py` and use it for `decided_by`.</comment>

<file context>
@@ -0,0 +1,76 @@
+        'backfill',
+    }
+)
+DECIDERS = frozenset({'policy', 'user', 'rule', 'model', 'jev', 'override', 'deterministic'})
+
+# Terminal defaults have a closed vocabulary, independent of exception text.
</file context>

def _has_wake_word(texts: Sequence[str]) -> bool:
from utils.conversations.wake_word import find_wake_word_matches

return bool(find_wake_word_matches([{'text': text} for text in texts]))

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: _has_wake_word can never detect a wake word because find_wake_word_matches requires a stable segment ID before returning a match. Pass segment identity (and timing where available) through this helper instead of constructing text-only mappings, so wake-word evidence really bypasses transcript-only repair.

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/utils/conversations/terminal_relevance.py, line 153:

<comment>`_has_wake_word` can never detect a wake word because `find_wake_word_matches` requires a stable segment ID before returning a match. Pass segment identity (and timing where available) through this helper instead of constructing text-only mappings, so wake-word evidence really bypasses transcript-only repair.</comment>

<file context>
@@ -0,0 +1,170 @@
+def _has_wake_word(texts: Sequence[str]) -> bool:
+    from utils.conversations.wake_word import find_wake_word_matches
+
+    return bool(find_wake_word_matches([{'text': text} for text in texts]))
+
+
</file context>

def recovery_discard_payload(write_data: dict) -> bool:
# Imported lazily: several unit harnesses load this module with a stubbed
# ``utils`` package that has no ``utils.conversations`` subpackage.
from utils.conversations.recovery import verified_recovery_discard

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: Move verified_recovery_discard to a module-level import and adjust the isolated harness stubs instead of introducing a function-local import.

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/conversation_status_transitions.py, line 7:

<comment>Move `verified_recovery_discard` to a module-level import and adjust the isolated harness stubs instead of introducing a function-local import.</comment>

<file context>
@@ -0,0 +1,9 @@
+def recovery_discard_payload(write_data: dict) -> bool:
+    # Imported lazily: several unit harnesses load this module with a stubbed
+    # ``utils`` package that has no ``utils.conversations`` subpackage.
+    from utils.conversations.recovery import verified_recovery_discard
+
+    return verified_recovery_discard(write_data.get('discarded'), write_data.get('relevance_decision'))
</file context>

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Folded into #24602 (the consolidation of this batch onto the age-gate survivor branch lane/freshtitles-agegate, head e2e0767). Survivor #24580 merged separately at 11:59Z without the batch folds, so #24602 carries this PR's changes on top of current main for review. Every behavior change from this PR is preserved in the fold; conflicts were reconciled against main's newer contracts (details in #24602's description). Closing as folded — follow #24602.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Hey @Git-on-my-level 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

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