Skip to content

refactor(backend): converge conversation lifecycle onto a single mutation owner #9516

Closed

Description

@Git-on-my-level

Summary

Converge the backend conversation lifecycle onto a single mutation owner. Today the conversation document is the canonical noun everyone agrees on, but the lifecycle verbs — create, claim for processing, transition status, finalize, discard, merge, reprocess — are performed independently by ten different modules. This is the backend's closest analogue of the macOS convergence in #9515 ("centralized nouns, plural verbs"), and it should follow the same playbook: characterization tests first, one exclusive mutation API, migrate every caller, delete every alternative path.

Sequencing requirement (deliberate): Phase 1 (characterization/contract tests) lands first as its own PR on main, before any refactor work. Current lifecycle coverage is edge-focused (listen/pusher e2e + chaos, sync idempotency) and there is no contract suite for the lifecycle state machine itself. The tests are pure additive safety and also protect the ongoing unrelated churn in transcribe.py / sync. The refactor itself then lands as one convergence PR per the #9515 execution model.

Evidence

Churn since 2026-05-15: utils/conversations/ 83 commits, routers/transcribe.py 57, routers/conversations.py 47.

Plural mutation authority, verified in the tree:

  • Ten modules write conversation documents directly through database/conversations.py: routers/transcribe.py (live WebSocket), routers/pusher.py, routers/conversations.py, routers/sync.py, routers/developer.py, utils/sync/pipeline.py, utils/conversations/process_conversation.py, utils/conversations/postprocess_conversation.py, utils/conversations/merge_conversations.py, utils/imports/limitless.py.
  • The mutation API is effectively update_conversation(uid, id, update_data: dict) (database/conversations.py:444) — a generic dict write. Any caller can set any field, including lifecycle fields. There is no typed state machine for in_progress → processing → completed / discarded.
  • The scar tissue from past races already exists: claim_conversation_status() (database/conversations.py:878) is a compare-and-swap added because two writers raced on status. This is the lifecycle equivalent of the "save-versus-poll suppression machinery" refactor(macOS): converge chat, PTT, agents, tools, and continuity onto single owners #9515 identifies — a patch on a race between co-equal writers instead of a single owner.
  • Processing is re-entered from at least five directions with independent admission logic: live transcription finalization, sync/backfill pipeline, imports, manual reprocess via router, and merge (process_conversation.py is ~60K lines-adjacent of orchestration; merge_conversations.py ~22K).

Per AGENTS.md ("Bug Fixes: Close the Failure Class"), the unit of work is the violated contract — single ownership of lifecycle transitions — not any one race.

Locked target architecture

Event sources (transcribe WS, pusher, sync pipeline, imports, routers, merge)
    |
    | typed lifecycle intents (finalize, reprocess, merge, discard, import)
    v
Conversation lifecycle service (one module)
    - owns the status state machine: in_progress -> processing -> completed | discarded
    - owns processing admission: single claim point, idempotent by conversation id
    - owns finalization/merge/reprocess entry (one orchestrator, callers submit intents)
    - all transitions typed; invalid transitions fail closed
    |
    v
database/conversations.py
    - typed transition functions only for lifecycle fields
    - generic field updates (title, starred, visibility, events, ...) remain
      plain writes — they are content, not lifecycle

Field-level content writes stay as they are. The convergence is scoped to lifecycle verbs: status transitions, processing admission/claim, finalization, discard, merge, and reprocess.

Ownership matrix after the refactor

Concern Exclusive owner Allowed projections/drivers
Status transitions & claim lifecycle service readers everywhere
Processing admission (all entry directions) lifecycle service transcribe/pusher/sync/imports/routers as intent submitters
Finalization / merge / reprocess orchestration lifecycle service postprocess steps as called stages
Content fields (title, starred, events, apps_results, ...) unchanged — plain updates —

Execution plan

Phase 1 — characterization & contract tests (separate PR, lands first)

  • Behavioral contract tests for the current lifecycle state machine through controllable seams (fake Firestore/Redis per backend/docs/test_isolation.md): every legal transition, every illegal transition, double-claim, concurrent finalize-vs-reprocess, sync-vs-live collision, merge during processing, import of an already-processed conversation.
  • Register the lifecycle workflow in backend/testing/workflow_contracts.json (the mechanism exists; this flow is not registered).
  • Add counters/traces for each current write path so the convergence PR can demonstrate zero legacy-path use before deletion.
  • These tests assert current behavior, including current quirks — they are the lock, not the spec.

Phase 2 — convergence PR (one PR, #9515 execution model)

  1. Introduce the lifecycle service and typed transition API behind existing behavior.
  2. Migrate every caller by direction: live finalization, pusher, sync pipeline, imports, manual reprocess, merge, developer router.
  3. Delete before merge:
    • direct lifecycle-field writes through update_conversation / conversation_ref.update outside the service;
    • claim_conversation_status as a public seam (its CAS survives inside the service);
    • per-caller admission/dedup logic superseded by the single claim point.
  4. Guard: CI check failing on new lifecycle-field writes ('status', 'discarded', processing markers) outside the service module. Ratchet to zero, no nonzero baseline.

If scope must shrink, drop an entire direction (e.g. imports) from both implementation and issue — never land half a direction with dual authorities (#9515's rule).

Acceptance matrix (behavioral)

  • Exactly one processing run per finalized conversation under concurrent finalize triggers (live + sync + manual).
  • Reprocess during active processing either queues or rejects deterministically — never two concurrent processors.
  • Merge during processing has one deterministic outcome; no orphaned processing status.
  • Discard is terminal; subsequent processing intents are rejected and observable.
  • Sync/backfill of an already-live-processed conversation is idempotent (no duplicate side effects: memories, notifications, integrations).
  • Crash between claim and completion is recoverable — no conversation stuck in processing forever.

Verification

  • backend/test.sh green locally; new contract tests hermetic and discovered by the runner.
  • Live exercise: real transcription session end-to-end plus a sync upload of overlapping audio; inspect logs for single-claim behavior.
  • Legacy-path counters at zero during exercise before deletion commit.
  • make preflight; invariant IDs via scripts/pr-preflight --suggest.

Definition of done

  • Phase 1 contract tests merged first and green in CI.
  • Lifecycle verbs have exactly one mutation owner; matrix above holds.
  • All ten current writer modules migrated; deletion inventory removed, not deprecated.
  • Guard ratchet at zero.
  • Acceptance matrix passes behaviorally.
  • docs/doc/developer/backend/listen_pusher_pipeline.mdx and AGENTS.md service map updated if boundaries move.
  • PR body records root cause, recurrence evidence, durable guard, real-path evidence, rollback plan.

Non-goals

  • Changing conversation content processing quality/prompts (utils/llm work is tracked separately — see the LLM gateway exit-criteria issue).
  • Changing the sync admission architecture (backend-sync lanes are the model to emulate, not a patient).
  • Firestore schema migration; the document shape stays readable by current clients.
  • Touching macOS; the desktop analogue is refactor(macOS): converge chat, PTT, agents, tools, and continuity onto single owners #9515.

Related

Activity

  1. added
    backend
    maintainer
    on Jul 12, 2026
  2. Git-on-my-level commented on Jul 12, 2026

    @Git-on-my-level
    MemberAuthor

    Phase 1 characterization, lifecycle-writer telemetry, and workflow-contract coverage: #9532

  3. Git-on-my-level commented on Jul 14, 2026

    @Git-on-my-level
    MemberAuthor

    Parent/executor issue: #9687 — binds this issue and its sibling into one PR with the shared meta-machinery (ordering fuzzer, anti-regrowth guards, checks-manifest registration) and per-child closure criteria. Note: #9687 supersedes the separate-PR sequencing in #9516; the tests-before-refactor ordering is preserved as strict commit ordering within the single PR.

  4. added a commit that references this issue on Jul 14, 2026
    4c6fd68
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

    backendmaintainerpythonrefactorstability

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions