Skip to content

Durable conversation finalization: Cloud Tasks job seam so listen conversations cannot stay stuck in_progress/processing #9453

Closed

Description

@Git-on-my-level

Prerequisites

None — this is independent of other in-flight tech-debt work and can start immediately. The two things to have read before starting:

  • PR Make account deletion cleanup durable #9117 (merged): the reusable Cloud Tasks durable-work pattern (named/deduplicated tasks, OIDC handler, Firestore transactional claim, Redis run lock, retry semantics) this issue prescribes reusing.
  • docs/doc/developer/backend/listen_pusher_pipeline.mdx: must be updated in the same PR series per repo rules, since this changes conversation lifecycle.

Production changes (queue creation, deploy, rollout) require separate review/approval as stated in the acceptance criteria — design and vertical-slice PRs do not.

Problem

The listen path deliberately keeps conversation processing out of the backend request path: backend/routers/transcribe.py moves a content-bearing conversation from in_progress to processing and sends protocol frame 104 to pusher. When pusher is unavailable, backend/utils/listen_pusher_session.py retains that request only in pending_conversation_requests for reconnect. After retry exhaustion it remains buffered in the live listen session; cleanup_processing_conversations() only re-sends processing conversations when a later listen session runs.

That preserves the “backend never processes conversations inline” invariant, but it does not provide a durable completion guarantee if the listen pod/session dies while pusher is unavailable. A core user artifact can remain in_progress or processing indefinitely.

Recent changes reduce symptoms but do not close this gap:

Scope

Add a durable finalization-job seam for listen conversations. Pusher, or a narrow pusher-equivalent worker, remains the processor; the backend must not run process_conversation() inline as a fallback.

The initial implementation should cover a small, observable vertical slice of the existing listen-to-pusher finalization path, not a broad redesign of transcription, pusher protocol, or all conversation processing entry points.

Design requirements

Durable intent and idempotency

  • Persist a finalization job/intent before relying on a live pusher send for a content-bearing conversation.
  • Use deterministic identity or an equivalent idempotency strategy keyed by the conversation being finalized.
  • Give the worker an atomic claim transition. Concurrent Cloud Tasks deliveries, reconnect re-sends, and manual reconciliation must not process the same finalization side effects twice.
  • Model retryable, running, completed, and terminal/final-attempt outcomes explicitly; do not mark a failed finalization complete merely to acknowledge a task.
  • Preserve existing lazy/deferred conversation behavior: the current get_processing_conversations() intentionally excludes deferred conversations from background pusher sweeping.

Worker boundary

  • Decide and document whether Cloud Tasks invokes a protected pusher handler directly or a narrow backend dispatch handler that forwards only to the pusher worker boundary.
  • Authenticate task traffic with the existing OIDC pattern from utils.cloud_tasks.verify_cloud_tasks_oidc; task handler routes remain internal/non-OpenAPI unless there is a reviewed reason otherwise.
  • Reuse the Make account deletion cleanup durable #9117 patterns where applicable: named/deduplicated tasks, Redis run lock, Firestore transactional claim, retry status codes, cancellation-safe locking, and reconciler support.
  • Do not add a local process_conversation() fallback to the listen WebSocket path.

Payload and data-safety boundary

  • A durable job must contain only the identifiers and reviewed metadata needed to process persisted conversation data.
  • Do not persist raw BYOK keys in Firestore, Cloud Tasks payloads, logs, metrics, or dead-letter diagnostics. The current frame-104 payload carries session BYOK keys, so BYOK finalization needs an explicit reviewed policy before durable dispatch (for example, an approved secure retrieval path or an explicit non-durable/blocked behavior with user-visible recovery).
  • The job starts only after the conversation’s required persisted data is available. This issue does not claim to make unsent in-memory audio/transcript buffers durable; that is separate scope unless the design proves it is required for correct finalization.

Recovery and observability

  • Add a reconciler/runbook for stale pending/running finalization jobs, including safe replay behavior.
  • Expose age of oldest nonterminal job, retry/final-attempt counts, and terminal failures/dead-letter state. Use the shared fallback telemetry conventions for degraded pusher handoff rather than inventing one-off fallback metrics.
  • Resolve or explicitly account for existing pending WebSocket requests so reconnect behavior cannot duplicate or bypass durable job ownership.

Initial delivery plan

  1. Design + schema PR: document the state machine, worker ownership, Cloud Tasks queue/handler configuration, BYOK policy, idempotency key, and recovery semantics. Add unit coverage for the claim/state transitions.
  2. Vertical-slice PR: enqueue/claim/process one normal listen finalization path through the durable worker and retain current pusher semantics. Add Cloud Tasks retry/idempotency tests.
  3. Recovery/operations PR: reconciler, metrics/alerts, runbook, and controlled rollout/flag removal plan.

Acceptance criteria

  • A content-bearing listen conversation can be finalized after the original listen session/pod disappears and pusher is temporarily unavailable, without inline backend processing.
  • Duplicate delivery, reconnect re-send, and manual reconciliation are idempotent at the finalization-job boundary.
  • A nonterminal failure remains retryable; a final attempt is visible and recoverable rather than silently marked completed.
  • BYOK material is never persisted in the durable job path; its durable-finalization policy is explicitly documented and tested.
  • Tests cover normal dispatch, duplicate delivery, worker crash/retry, stale-job reconciliation, and pusher-unavailable recovery.
  • A runbook documents job inspection, replay, and the operational signals for stuck finalization age/retries/terminal failures.
  • No production deploy, Cloud Tasks queue creation, Firestore mutation, or rollout occurs under this issue without separately reviewed implementation and approval.

Grounded code references

  • backend/routers/transcribe.py — _process_conversation() transitions a conversation to processing and calls request_conversation_processing().
  • backend/utils/listen_pusher_session.py — in-memory pending request buffer, timeout/retry/reconnect behavior, and frame-104 payload including BYOK keys.
  • backend/routers/pusher.py — frame 104 currently spawns _process_conversation_task(...) from a live WebSocket request.
  • backend/database/conversations.py — existing claim_conversation_status() and processing-conversation query semantics.
  • backend/services/users/account_deletion.py, backend/routers/users.py, backend/utils/cloud_tasks.py — durable Cloud Tasks/OIDC/claim/lock/retry reference from PR Make account deletion cleanup durable #9117.
  • backend/tests/unit/test_listen_fallback_removal.py and backend/tests/unit/utils/test_listen_pusher_session.py — current no-inline-fallback and buffering contracts.

Activity

  1. Git-on-my-level commented on Jul 13, 2026

    @Git-on-my-level
    MemberAuthor

    Implementation packet — source and cloud discovery complete (2026-07-13)

    Confirmed failure seam

    • backend/utils/listen_pusher_session.py keeps pending_conversation_requests only in process memory. At capacity it evicts the oldest request; after retry exhaustion it retains requests only until pusher recovery. A process/session loss can therefore strand a conversation without a durable retry record.
    • The opcode-104 payload currently includes conversation_id, language, and byok_keys. Do not put that payload, raw BYOK keys, or equivalent material into Cloud Tasks, Firestore, logs, or dead-letter diagnostics.
    • backend/utils/cloud_tasks.py already provides the implementation pattern: named task de-duplication, OIDC authentication, bounded deadlines, and handlers protected by verify_cloud_tasks_oidc. Existing feature toggles cover sync, audio merge, and account deletion; there is no listen-finalization dispatch mode yet.

    Live configuration facts

    Name-only Cloud Tasks inventory:

    Environment Existing queues
    prod audio-merge, sync-backfill, sync-jobs
    dev sync-backfill, sync-jobs

    There is no dedicated conversation-finalization queue. Do not silently reuse sync-jobs or audio-merge; finalization has distinct retry, latency, and idempotency semantics.

    Self-contained implementation direction

    1. Add a LISTEN_FINALIZATION_DISPATCH_MODE feature flag, defaulting to inline.
    2. Add an explicit finalization queue, handler URL/audience, retry-limit settings, a named task id based on the conversation/version, and an atomic Firestore claim/state transition.
    3. Reuse the account-deletion/sync OIDC and named-task helpers rather than creating a second task client/auth pattern.
    4. Add unit coverage for duplicate delivery, reconnect resend, claim races, terminal failure, and recovery/reconciliation.
    5. Define the BYOK branch before enabling durable dispatch: either obtain keys through an approved secure retrieval path or keep BYOK on an explicit non-durable path with visible recovery. Do not guess or persist keys.

    Remaining non-code boundary

    A new Cloud Tasks queue, service IAM/OIDC binding, and production rollout are separate reviewed infrastructure changes. They are not needed to implement and test the code path locally, but are required before enabling the flag in an environment.

  2. Git-on-my-level commented on Jul 13, 2026

    @Git-on-my-level
    MemberAuthor

    Architecture decision packet — Firestore outbox + dedicated finalizer worker

    For the durable design, make Firestore the canonical finalization-job ledger and use Cloud Tasks only as an at-least-once wake-up mechanism. Neither the Cloud Task body nor the live pusher frame may be the source of truth.

    Required boundary

    1. In one Firestore transaction, create/update one finalization job per (conversation_id, finalization_revision), persist queued, and transition the conversation to processing only where the current content/deferred guards permit it.
    2. After commit, enqueue a named task. If enqueue fails, leave the job queued; a reconciler re-enqueues it. This closes the Firestore-write/Cloud-Tasks-enqueue gap.
    3. Task body contains only opaque job_id plus dispatch_generation—no UID, transcript, language, raw errors, fingerprint, or credential material.
    4. A dedicated finalizer worker transactionally leases the job, loads persisted conversation data, finalizes it, and marks completed only after the persisted terminal result. Cloud Tasks duplicate delivery is expected; named tasks do not replace the Firestore lease.

    A direct task-to-pusher handler is a valid small slice, but not the long-term boundary: the current pusher is WebSocket-oriented and autoscaled by active connections. Extract a shared persisted-conversation finalizer callable, then run it in a dedicated worker with independent concurrency, timeout, queue, and failure budgets.

    BYOK policy

    • Platform-key work can use durable finalization.
    • BYOK jobs must persist blocked_credentials / blocked_byok and expose user-visible recovery until the user presents a valid request-scoped key again.
    • Never omit the key and silently use Omi credentials.
    • Durable offline BYOK would require an explicitly approved separate credential broker/vault; it must store only an opaque credential reference in the job and needs privacy, retention, rotation, deletion, audit, and IAM review. Do not put such a vault in Firestore or Cloud Tasks.

    Agent-ready slices

    1. Add transactional job repository/state machine: queued → leased → completed | dead_letter | blocked_credentials, with lease expiry and replay generation.
    2. Add finalization-specific task configuration and OIDC handler; default LISTEN_FINALIZATION_DISPATCH_MODE=inline.
    3. Extract the finalizer from pusher and implement the non-BYOK vertical slice behind the flag.
    4. Add reconciler, bounded replay, backlog/dead-letter metrics, and runbook.

    Non-negotiable tests

    • duplicate listen/reconnect and duplicate task delivery claim once;
    • enqueue failure leaves a discoverable queued job;
    • crash/lease expiry reconciles safely;
    • completed/dead-letter jobs do not execute again;
    • task/schema/log fields contain no raw BYOK key, transcript, header material, or raw exception text;
    • BYOK without a broker blocks before platform-key processing;
    • closing the originating listen session after intent persistence still completes the finalization exactly once after recovery.

    The only remaining owner decision is whether Omi ever wants opt-in durable background custody of BYOK credentials. All non-BYOK work is now fully specified.

  3. added a commit that references this issue on Jul 13, 2026
    300e76f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions