Repository navigation
feat: add demand-driven conversation processing - #21905
Conversation
# Conflicts: # backend/tests/unit/test_sync_reprocess_coalesce.py # backend/utils/sync/reprocess.py
# Conflicts: # backend/route_policy_manifest.yaml
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Automations to automatically generate PRs for you. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6e8905579b
ℹ️ 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".
| if getattr(getattr(request, 'url', None), 'path', None) in {'/v1/telemetry/fleet', '/v1/users/client-state'}: | ||
| validate_byok_request(uid) |
There was a problem hiding this comment.
Skip BYOK validation for content-free surface heartbeats
When surface reporting is enabled, clients call this endpoint every 30 seconds, but validate_byok_request() calls get_cached_byok_state(), whose cache also expires after 30 seconds, causing a recurring users/{uid} Firestore read per reporting user and contradicting the no-user-document-lookup contract. It also rejects BYOK-active Mac users because the new reporter explicitly builds headers with includeBYOK: false, so those users never establish a surface lease. Treat this content-free endpoint like a credential-free authenticated signal rather than validating provider keys.
Useful? React with 👍 / 👎.
| from config.demand_processing import tool_enabled | ||
|
|
||
| if not tool_enabled(): | ||
| core_tools = [tool for tool in core_tools if tool.name != 'process_recent_conversations'] |
There was a problem hiding this comment.
Apply the processing-tool gate to the current user
During an allowlist or percentage rollout, this UID-less call reaches enabled(None), which returns true whenever the master switch is on, so every app/Telegram/Linq chat receives process_recent_conversations even when only one owner was admitted. Non-cohort invocations then return disabled, wasting a tool turn and defeating the staged exposure boundary; filter with tool_enabled(uid). The same UID-less cohort leak exists in mcp_server/transport.py::_tools_for_scopes and should be corrected at the same boundary.
Useful? React with 👍 / 👎.
| await makeApiCall( | ||
| url: '${Env.apiBaseUrl}v1/users/client-state', | ||
| headers: {}, | ||
| method: 'POST', | ||
| body: jsonEncode({...value.toJson(), 'session_id': _surfaceSession}..remove('type')), |
There was a problem hiding this comment.
Bind mobile surface reports to the originating auth session
If the user signs out and another account signs in while this asynchronous request is acquiring or refreshing its token, makeApiCall can send the old surface snapshot using the new account's credentials because no AuthSessionSnapshot or canSend generation check is supplied. This incorrectly opens or closes the replacement account's processing lease; capture the current auth-session generation before awaiting and fence the send and any 401 replay against that snapshot, as the Mac reporter already does.
Useful? React with 👍 / 👎.
| extract_memories(uid, conversation) | ||
| person_ids = list(set(conversation.get_person_ids())) | ||
| people = Person.deserialize_many_safe(users_db.get_people_by_ids(uid, person_ids)) if person_ids else [] | ||
| _save_action_items(uid, conversation, people, ProcessingTrigger.SYNC_UPDATE) |
There was a problem hiding this comment.
Preserve the original trigger for deferred task enrichment
Every lazy job is replayed as SYNC_UPDATE, even when it originated from USER_REPROCESS, FIRST_OPEN, or normal capture. That trigger changes task persistence: action_item_refresh.preserve treats SYNC_UPDATE as an automatic refresh that retains existing task rows, whereas user reprocessing previously used the replacement path. Consequently, when a user reprocesses a conversation and the new extraction removes or rewrites a task, the deferred worker can retain the obsolete task instead of applying the reprocessed result. Persist the originating trigger in the effects outbox and pass it through here.
Useful? React with 👍 / 👎.
| if token is not None and token != payload.get('dispatch_generation', payload.get('task_token')): | ||
| return True # Let the durable worker acknowledge the stale delivery. |
There was a problem hiding this comment.
Refresh stale scheduler rows after generation rollover
When finalization reconciliation advances a job from generation 1 to generation 2, services/conversation_finalization.py directly enqueues the new generation without updating this Redis row. The generation-2 delivery therefore takes this mismatch branch and completes durably while leaving the generation-1 row in the ready queue. A stale tier-0 or tier-1 row can then make unrelated lower-tier obligations postpone repeatedly until their 59-minute starvation escape, and the row remains for up to the two-day TTL. Reconciliation must replace or retire the indexed payload when it advances the dispatch generation.
Useful? React with 👍 / 👎.
…0261017 # Conflicts: # backend/deploy/runtime_env.yaml
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d3548f9db5
ℹ️ 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".
| Future<void> _reportSurface({bool heartbeat = false}) async { | ||
| if (!_reportingEnabled || _reportInFlight || (heartbeat && !value.foreground)) return; |
There was a problem hiding this comment.
Queue the latest surface state while a report is in flight
If the app backgrounds while an open/heartbeat request is still running, _publish() calls this method but the _reportInFlight guard drops the close transition. Because heartbeats are skipped once foreground is false, that state is never retried, so the server keeps the surface lease open for up to 90 seconds and can incorrectly classify newly scheduled work as tier 0. Preserve a pending snapshot and send it after the current request completes; the macOS reporter has the same drop-on-in-flight pattern.
Useful? React with 👍 / 👎.
| conversation = deserialize_conversation(row) | ||
| digest = fingerprint(conversation) | ||
| if row.get(CHECKPOINT) == digest: | ||
| return | ||
| apply_settled_enrichment(uid, conversation) |
There was a problem hiding this comment.
Fence lazy effects against concurrent conversation deletion
If a user deletes the conversation after the read/check above but while apply_settled_enrichment() is running, the delete path can finish removing its memories, tasks, and Pinecone vector before this stale worker writes them back. The final checkpoint update merely returns false when the conversation is gone and does not undo those recreated derived records, so deleted content can remain searchable or produce orphaned tasks. Claim or revalidate the conversation deletion/privacy fence transactionally at each derived-write boundary rather than relying on this initial snapshot.
Useful? React with 👍 / 👎.
| if save_structured_vector(uid, conversation) is False: | ||
| raise RuntimeError('conversation vector is not ready') |
There was a problem hiding this comment.
Treat missing structured data as a terminal vector skip
For a completed, non-discarded conversation whose structured field is absent, save_structured_vector() intentionally returns False without attempting an index write, but this turns that valid skip into an exception. The effects outbox therefore retains and redelivers the row indefinitely, and each delivery repeats memory extraction before reaching this line; this code path is reachable because process_conversation() enrolls lazy debt even when the completed conversation has structured = None. Skip vector creation terminally when there is no structure, while retaining retries for actual index failures.
Useful? React with 👍 / 👎.
| return False | ||
| if uid is None: | ||
| return True | ||
| import hashlib |
There was a problem hiding this comment.
Move the new backend imports to module scope
This function-local import, along with the new local imports throughout the scheduler, finalizer, receiver, and reprocess paths, violates the backend's strict import-layer contract. Move these dependencies to module scope and resolve any resulting cycles at the layer boundary so shared backend, pusher, and diarizer startup behavior remains auditable.
AGENTS.md reference: backend/AGENTS.md:L161-L169
Useful? React with 👍 / 👎.
| if ( | ||
| demand_enabled() | ||
| and surface_reporting_enabled() | ||
| and demand_enabled(self.host.request.uid) | ||
| and ('surface_open' in payload or self._telemetry_platform() in {'ios', 'android', 'mobile'}) |
There was a problem hiding this comment.
Update the listen/pusher pipeline contract
This branch changes the /v4/listen client_state wire behavior by turning mobile state frames into scheduling leases, and the same change set alters conversation-finalization dispatch, but the owning backend/docs/listen_pusher_pipeline.mdx map was not updated. Document the new signal, Redis handoff, and finalization scheduling boundary in that file in this PR as required for listen WebSocket and lifecycle changes.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
| def client(): | ||
| from database.redis_db import create_bounded_redis_client | ||
|
|
||
| return create_bounded_redis_client(0.5) |
There was a problem hiding this comment.
Reuse the bounded Redis client across scheduler calls
When surface reporting is enabled, every 30-second heartbeat calls observe_surface(), which calls this factory and creates a fresh redis.Redis instance and connection pool; scheduling, admission, metrics, and promotion do the same, with promotion even creating another client from inside one report. At fleet scale this causes continuous TCP/pool churn and can exhaust Redis or process connection resources. Cache one thread-safe bounded client per process, as the existing Redis-backed caches and lease helpers do, or close each short-lived client deterministically.
Useful? React with 👍 / 👎.
# Conflicts: # config/feature-flags.yaml
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 94d62d0c32
ℹ️ 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".
| r = client() | ||
| if not r.set(owner_key(uid) + ':process_recent_rate', '1', ex=30, nx=True): | ||
| return {'status': 'rate_limited', 'retry_after_seconds': 30, 'ready': False} | ||
| return promote(uid, hours=hours, limit=limit) |
There was a problem hiding this comment.
Handle Redis loss in the processing tool
When Redis is unavailable, either client(), the rate-limit SET, or promote() raises out of this function; the MCP adapter catches only validation/auth errors and the chat adapter catches nothing, so a transient cache outage can fail the tool invocation and potentially the surrounding chat turn. Catch and log Redis failures here and return a non-ready/degraded response so the request can proceed under the backend's fail-open Redis contract.
AGENTS.md reference: backend/AGENTS.md:L183-L183
Useful? React with 👍 / 👎.
| demand_enabled() | ||
| and surface_reporting_enabled() | ||
| and demand_enabled(self.host.request.uid) | ||
| and ('surface_open' in payload or self._telemetry_platform() in {'ios', 'android', 'mobile'}) |
There was a problem hiding this comment.
Require the explicit mobile surface marker
For mobile builds without the new Dart define, ListenClientStateSnapshot.toJson() omits surface_open, but the existing recording socket still sends foreground every 60 seconds; this platform fallback therefore passes those legacy frames to observe_surface(), which treats foreground as open. Enabling the server flags for a cohort consequently grants tier-0 leases to old or explicitly unopted clients whenever they record, corrupting the staged surface-intent experiment; require surface_open instead of inferring opt-in from the platform.
Useful? React with 👍 / 👎.
Keep sync trailing-edge coalescing through priority and Redis failure, drain client closes across in-flight reports, and reject legacy socket telemetry as surface intent. Failure-Class: none
Failure-Class: none
# Conflicts: # backend/docs/listen_pusher_pipeline.mdx # backend/routers/listen/receiver.py
Failure-Class: none
# Conflicts: # backend/docs/feature-flag-registry.md
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a0571cc9c6
ℹ️ 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".
| ) | ||
| async def report_surface_state( | ||
| body: SurfaceStateRequest, | ||
| uid: str = Depends(auth.with_rate_limit(auth.get_current_user_uid, 'users:surface_state', fail_closed=True)), |
There was a problem hiding this comment.
Keep surface reporting fail-open during Redis failures
When the rate-limiter Redis call fails, fail_closed=True returns 503 before observe_surface can run, so opted-in clients stop renewing their 90-second surface leases during a transient dependency failure and can lose tier-0 classification. This endpoint should use the default fail-open rate-limit behavior, consistent with other first-party Redis-backed paths.
AGENTS.md reference: backend/AGENTS.md:L183-L183
Useful? React with 👍 / 👎.
| stage = 'derived_effects' | ||
| from utils.conversations.demand_processing import lazy_enrichment_enabled | ||
|
|
||
| lazy_effects = lazy_enrichment_enabled(uid) and not skip_derived_effects and not conversation.discarded |
There was a problem hiding this comment.
Apply lazy vector gating before completed-fanout returns
When server recovery or another re-finalization observes fanout['status'] == 'completed', the function returns through the earlier branch that calls _save_summary_vector_fail_soft before this lazy-enrichment gate is evaluated. For a lazy-enabled user whose durable effects job is still pending, that replay therefore performs an eager duplicate embedding/index write instead of leaving vector work coalesced in the effects outbox; determine lazy_effects before the completed-fanout branch and apply it there as well.
Useful? React with 👍 / 👎.
| def fingerprint(conversation) -> str: | ||
| # Only effective inputs, not processing/engagement timestamps or this checkpoint. | ||
| row = conversation.model_dump(mode='json') | ||
| fields = ('transcript_segments', 'structured', 'photos', 'source', 'language') |
There was a problem hiding this comment.
Include every enrichment input in the checkpoint fingerprint
A new effects delivery is skipped whenever these five fields are unchanged, but the deferred writers consume additional persisted inputs: _extract_memories_canonical reads external_data and started_at for source text, meeting context, and date grounding, while save_structured_vector derives metadata from external_data and created_at. A reprocess that changes only calendar/external content or corrects timestamps therefore matches the old checkpoint and retires its outbox delivery without refreshing memories or vector metadata; fingerprint all inputs consumed by apply_settled_enrichment.
Useful? React with 👍 / 👎.
# Conflicts: # backend/charts/pusher/dev_omi_pusher_values.yaml # backend/charts/pusher/prod_omi_pusher_values.yaml # backend/tests/unit/test_sync_reprocess_coalesce.py # backend/tests/unit/test_verify_pusher_config_references.py # backend/utils/conversations/process_conversation.py # backend/utils/sync/reprocess.py # config/deployment-setting-classification.json # config/feature-flags.yaml
# Conflicts: # backend/docs/feature-flag-registry.md
Demand-driven processing
Add default-off surface leases, immediate dispatch with tier priority under contention through existing Cloud Tasks workers, open-time promotion, and coalesced lazy memory/vector/task work. Expose
process_recent_conversationsto app chat, shared Telegram/Linq chat and hosted MCP with authenticated owner binding, six-hour/twenty-obligation bounds and a shared rate limit.Phone and Mac reporters renew explicit intent independently of audio sockets. Mac intent measures the main window. The end-of-day hook is omitted under David's updated 2026-10-16 KB rulings. Daytime merge decisions and proactive notification priority remain unchanged.
Product invariants affected
Failure-Class: none
UI-Evidence: none -- changes report lifecycle intent; no rendered view or navigation changes.
Rollout plan
Config trains are documented in
backend/docs/runbooks/demand-driven-processing.md: default-off image -> explicit owner client reporting and scheduler allowlist (0%) -> lazy work -> agent tool -> 1% -> 5% with >=30 minutes of clean sentinel readouts at each step -> 25/50/100 only after acceptance. No production flag change or deployment is included.Measure per-tier queue age, existing end-to-end finalization journeys, retry/dead-letter and outbox repair counts, visible quality, memory/task completeness and live p95. Qualification requires tier 0 <=1m, tier 1 p95 <=5m, tier 2 <=60m; newest 20m <=2m and newest hour <=4m on simultaneous opens. Scheduling headroom is not a measured freshness guarantee. Roll back admission flags while retaining workers/sweeps to drain durable debt. No GPU/cost saving is claimed.
Validation
nice -n 19. Includes tier assignment/promotion/drain/ceiling and idle-capacity dispatch, shared outbox recovery, visible/lazy split, synthetic-owner ASGI auth, registration/recovery-read avoidance, tool auth/bounds.listen_client_state_test.dart: 8 passed. Focused MacListenClientStateTests: 9 passed, including URL normalization; the final incremental run compiles the regenerated additive API types.Limits
The earlier upstream daily-summary decoder inventory failure is fixed by #21925, now integrated from main (
bfd3a973ed4). The Grok fix commits do not implement that unrelated client migration. Full CI is not claimed green.The tool promotes the caller's indexed recent debt and reports
ready=false; it does not scan Firestore for pre-rollout historical work. Existing durable reconciliation owns unindexed debt. Full peak-load and provider qualification are rollout gates. The newer KB rulings remove item 5 from this PR; #21836 and lazy speaker refinement remain separate work.Grok fixes
surface_opencounts as listen intent. Released iOS/Android/mobile/Mac telemetry remains unchanged when server flags turn on.BACKEND_UNIT_TEST_FILE_LIST,nice -n 19. Mac lifecycle/race tests: 9 passed. Phone lifecycle/race tests: 8 passed. Detailed receipts are recorded in the run handoff.a4cce4c3099) while retaining strict surface intent and both documentation sections; telemetry and demand policy regression tests pass.acfcd8ed0d4), regenerated runtime/registry output, and verified all 96 demand defaults remain off/empty/zero while every other runtime value exactly matches main. Sync settle remains 600 seconds; 55 Helm/cohort/parity checks pass.fb698130b3emerge of main, without rebasing. The two desktop deploy workflows retain only six additive default-off env lines each; David approved these exact workflow lines in the final-main-sync instruction. No merge, deploy or runtime configuration change is included.Main sync 2026-10-17
Merged
origin/mainat6e7007e3e35without rebasing. Resolved eight conflicts by retaining both additive config/registry/test sets and both post-persistence processing paths. Demand mode retains its 59-minute ceiling and 600-second trailing settle; upstream revision reuse alone retains its 60-minute ceiling. Both enabled use the existing demand headroom, covered by the four-way flag matrix and Redis/open-state settle tests. No intentional change to Grok-approved semantics.Targeted merge validation: 434 passed across nine files, canonical
BACKEND_UNIT_TEST_FILE_LISTrunner,BACKEND_PYTEST_WORKERS=1,nice -n 19. All 96 demand defaults remain off/empty/zero and every other runtime value matches main. The two workflow diffs remain exactly six additive default-off lines each; David has approved these exact workflow lines. Detailed conflict resolutions and final publication receipts are appended to the run handoff.Final main sync
Merged
origin/mainat3a4fe148259without rebasing. The only conflict was generatedbackend/docs/feature-flag-registry.md; regenerated it from the merged sources with--as-of 2026-09-24, and recomposed/checked runtime env. Seven key Grok-reviewed production files are byte-identical to66bdc353202; all 96 demand defaults remain off/empty/zero and every other runtime value matches main. No reviewed semantic change.303 targeted tests passed across four files, using
BACKEND_UNIT_TEST_FILE_LIST,BACKEND_PYTEST_WORKERS=1andnice -n 19, serially. The workflow edits remain exactly six additive default-offDEMAND_PROCESSING_*lines in each approved file and are unchanged from the Grok-reviewed head. David's scoped approval is recorded. No PR merge or deployment is included. Final head and publication receipts are appended under “Final main sync” in the run handoff.Integration size exceptions
Line-Count-Exception: backend/database/conversations.py | 4107 -> 4120 | Small blind metadata writer; avoids a new hot-path Firestore read and stays with database ownership.
Line-Count-Exception: backend/routers/listen/receiver.py | 2618 -> 2632 | Small guarded ingestion hook reuses existing client_state; scheduling lives in its own module.
Line-Count-Exception: backend/routers/users.py | 2576 -> 2598 | Small typed authenticated lifecycle endpoint; all lease logic lives in the demand module.
Line-Count-Exception: backend/utils/conversations/process_conversation.py | 3566 -> 3592 | Small integration seams retain canonical memory/task writer ownership; scheduler and outbox worker are separate modules.
Line-Count-Exception: backend/utils/retrieval/agentic.py | 1993 -> 1999 | Register and gate one tool implemented in its own module.
Line-Count-Exception: backend/utils/sync/pipeline.py | 3385 -> 3391 | Small flag/coalescing and explicit-demand hooks preserve the existing sync owner.
Line-Count-Exception: app/lib/pages/home/page.dart | 1126 -> 1127 | One startup hook starts the opt-in reporter even without a recording socket; no view construction changes.
Line-Count-Exception: desktop/macos/Desktop/Sources/OmiApp.swift | 1683 -> 1684 | One startup hook starts the opt-in reporter after environment/auth setup; implementation remains in ListenClientState.