Repository navigation
feat(backend): restore chat search freshness and expose retrieval degradation - #21111
Conversation
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: e4c908d6eb
ℹ️ 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 not persisted: | ||
| # Summary vectors are idempotent and are not owned by the durable folder/apps obligation. | ||
| if not discarded and conversation.structured: | ||
| submit_with_context(postprocess_executor, save_structured_vector, uid, conversation) |
There was a problem hiding this comment.
Do not upsert from a processor that lost persistence
When persistence loses to a conversation deletion or newer sync revision, this branch now queues an upsert from the stale in-memory object. lifecycle.persist_processed_conversation explicitly defines False as those cases and tells callers to stop derived effects; idempotent vector IDs do not help because the future can run after delete_vector or overwrite the current revision's vector. Re-read and revision-fence the authoritative conversation, or skip the write, before enqueueing.
Useful? React with 👍 / 👎.
| vector_id = f"{uid}-{metadata['id']}" | ||
| existing = vector_db.index.fetch(ids=[vector_id], namespace='ns1') | ||
| existed = bool(existing.vectors) | ||
| if not save_structured_vector(uid, deserialize_conversation(row)): |
There was a problem hiding this comment.
Fail the repair row when metadata extraction fails
During --apply, if chat-extraction metadata generation times out or fails while embeddings and Pinecone remain available, save_structured_vector still succeeds because retrieve_metadata_fields_from_transcript catches that provider exception and returns empty people/topics/entities/dates. The ensuing upsert replaces existing metadata, while this script records created/updated and never consumes the 10% error budget, so a repair can silently make metadata-filtered searches lose hits; use a strict repair writer or preserve existing metadata on extraction failure.
Useful? React with 👍 / 👎.
| def _typesense_connection_timeout_seconds() -> int: | ||
| # Lazy env resolution, like CONVERSATION_INDEX_WRITES_ENV. Bound request wait to 1–30s. | ||
| try: | ||
| value = int(os.getenv('TYPESENSE_CONNECTION_TIMEOUT_SECONDS', '5')) |
There was a problem hiding this comment.
Bind the new timeout in every backend runtime
In the repository-managed dev/prod deployments I checked, neither backend/deploy/runtime_env*.yaml nor the generated backend-listen Helm values bind this new name; the GKE ConfigMap renderer only emits declared entries and Cloud Run env is manifest-driven. Consequently the advertised override cannot reach a normal serving deployment, so every client stays on 5 seconds even if operators set it in deployment input. Add the binding to the source runtime manifest and regenerate all surfaces.
AGENTS.md reference: backend/AGENTS.md:L151-L151
Useful? React with 👍 / 👎.
| from database._client import get_firestore_client | ||
| from database.conversations import conversations_collection | ||
| from google.cloud.firestore_v1.base_query import FieldFilter |
There was a problem hiding this comment.
Keep the new script's imports at module scope
This file introduces function-local imports in metadata_rows, write_summary, and main, while the backend import contract requires imports at module scope and strict layering. Refactor the lazy provider seam, for example through module-level dependency injection or a lazy client getter, so dry-run behavior remains intact without function-scoped imports.
AGENTS.md reference: backend/AGENTS.md:L159-L165
Useful? React with 👍 / 👎.
| ] | ||
| }, | ||
| { | ||
| "id": 69, |
There was a problem hiding this comment.
Assign the row an unused Grafana panel ID
The existing nested Cohort age now stat already has ID 69 at line 3609, so the new row reuses a dashboard-wide identity. Grafana uses these IDs for panel addressing and persisted edits/links, making the two panels ambiguous and risking edits or links targeting the wrong object; assign the row an unused ID such as 72 or later.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6fa53efd25
ℹ️ 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".
| current = conversations_db.get_conversation(uid, str(metadata['id'])) | ||
| if not current or current.get('deleted') or current.get('discarded'): |
There was a problem hiding this comment.
Fence backfill writes against conversation revisions
During --apply, if a sync append or reprocess changes the summary after the first read but leaves the row visible, an interleaving where the new processor writes first and this backfill writes second leaves the old embedding in Pinecone; this post-write reread only tests deletion/discard and accepts the newer row. This is an independent backfill writer from the processor branch already discussed, so fence updated_at/sync_content_revision or retry from the authoritative row before reporting success.
Useful? React with 👍 / 👎.
| .collection(conversations_collection) | ||
| .where(filter=FieldFilter('created_at', '>=', since)) | ||
| .order_by('created_at', direction='DESCENDING') | ||
| .select(['id', 'created_at', 'status', 'discarded', 'deleted', 'structured']) |
There was a problem hiding this comment.
Apply canonical visibility before selecting repair rows
When a user has legacy completed rule-discard rows whose stored discarded flag is false, this raw projection includes neither relevance_decision nor the curation fields needed by is_completed_rule_discard, and eligible consequently selects rows the canonical read layer hides. The dry run overstates selected, while --apply rereads the same rows through get_conversation, rejects each one, and can exhaust the 10% error budget before repairing valid rows; run canonical visibility semantics during selection.
Useful? React with 👍 / 👎.
| - As a last resort, expand the time window (e.g., from "today" to "last 3 days") | ||
|
|
||
| 5. **When to use each retrieval tool:** | ||
| - For recency questions ("when did we last talk", "my latest conversation", "most recent", "last time"), call **get_conversations_tool** with a small limit and NO dates (newest-first), and answer from that. This overrides the datetime-filter guidance above. Never claim recency from **search_conversations_tool** alone. |
There was a problem hiding this comment.
Preserve topic filtering for last-time questions
A topic-qualified recency request such as “When did I last discuss Project X?” matches both this rule and the specific-event/thematic-search guidance below it. If the model follows this instruction, get_conversations_tool returns only a small unfiltered newest-first page, so the most recent matching conversation is absent whenever it is older than that page; restrict this rule to unqualified latest-conversation requests or require semantic candidate search followed by timestamp comparison.
Useful? React with 👍 / 👎.
|
|
||
| def with_keyword_note(result: str) -> str: | ||
| if keyword_degraded: | ||
| return result + '\n\n[Keyword index temporarily unavailable; results are semantic-only]' |
There was a problem hiding this comment.
Do not claim semantic results without a vector index
When Typesense fails while Pinecone is unconfigured, as in supported self-hosted/offline deployments, keyword_degraded is true but the vector and transcript paths cannot search anything; nevertheless every return is annotated as “results are semantic-only.” In the no-match case this tells the chat model that semantic coverage existed when no retrieval backend ran, undermining the new degradation disclosure; condition this wording on vector availability or use a neutral keyword-unavailable message.
Useful? React with 👍 / 👎.
| overview qualify. Dry-run reads metadata/summary fields only, with no transcripts, | ||
| embedding calls or vector reads/writes. Output contains counts, never content or | ||
| conversation IDs. Obtain cost and production-write sign-off on the selected count | ||
| before `--apply`: each selected row costs one fresh embedding plus vector fetch/upsert |
There was a problem hiding this comment.
Include metadata extraction in the backfill cost estimate
For an ordinary eligible conversation, save_structured_vector calls retrieve_metadata_fields_from_structured, which invokes the chat_extraction LLM under usage tracking before the embedding/upsert, so a default 500-row apply can issue roughly 500 additional chat-model requests and associated usage writes. This line is the operator's cost-signoff basis but lists only one embedding plus vector and conversation I/O; include the extraction cost or use a repair writer that reuses metadata.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ea58756408
ℹ️ 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".
| and not getattr(conversation, 'discarded', False) | ||
| and getattr(conversation, 'structured', None) | ||
| ): | ||
| await run_blocking(postprocess_executor, save_structured_vector, uid, conversation) |
There was a problem hiding this comment.
Skip managed vector calls for terminal minimums
When FREE_TIER_LOCAL_PROCESSING returns deterministic_minimum or store_projection, FreeTierProcessingPlan.managed_calls_allowed is false (backend/utils/free_tier_processing_policy.py:86-88), but this call runs before the skip_derived_effects branch. save_structured_vector always calls generate_embedding, and its nonempty deterministic title then reaches retrieve_metadata_fields_from_structured and get_llm('chat_extraction') (process_conversation.py:2185-2208, chat.py:1245-1247), so every terminal basic-desktop finalization now incurs managed provider spend despite the cost gate; skip terminal rows or use a genuinely provider-free indexing path.
Useful? React with 👍 / 👎.
| and not getattr(conversation, 'discarded', False) | ||
| and getattr(conversation, 'structured', None) | ||
| ): | ||
| await run_blocking(postprocess_executor, save_structured_vector, uid, conversation) |
There was a problem hiding this comment.
Fence the vector upsert against post-claim deletion
When a completed-row replay overlaps a conversation DELETE after claim_finalization_fanout, the delete route can remove the row and call delete_vector (backend/routers/conversations.py:1346-1349) while save_structured_vector is still doing embedding/metadata work, after which this call upserts the stale vector with no later visibility or revision check. Fresh evidence in the revised path is this post-claim provider window, so moving the write from the old future did not close the ordering inversion; re-read/fence the authoritative row after the upsert or serialize the write with deletion to avoid retaining deleted content in Pinecone.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 35bd3bec50
ℹ️ 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".
| - For recency questions ("when did we last talk", "my latest conversation", "most recent", "last time"), call **get_conversations_tool** with a small limit and NO dates (newest-first), and answer from that. This overrides the datetime-filter guidance above. Never claim recency from **search_conversations_tool** alone. | ||
| - When citing time spans from search results, describe them as similarity matches, not a complete recent history. |
There was a problem hiding this comment.
Apply the recency rule to the prompt production serves
When LANGCHAIN_API_KEY is present and Client.pull_prompt() succeeds—the normal backend-listen production path (backend/charts/backend-listen/prod_omi_backend_listen_values.yaml:364-368)—get_agentic_system_prompt_template returns the hosted template at backend/utils/observability/langsmith_prompts.py:160-165; these lines belong only to _get_fallback_agentic_prompt_template, and the matching block in chat.py is reached only after fetch/render raises (backend/utils/llm/chat.py:659-675). Unless the external omi-agentic-system prompt is changed separately, deployed chat never sees the new chronological-recency rule and keeps answering “latest/last” from semantic search; append the invariant after rendering or version/publish the served template with this change.
Useful? React with 👍 / 👎.
| res = index.upsert(vectors=[data], namespace="ns1") | ||
| OMI_CONVERSATION_SUMMARY_VECTOR_UPSERTS_TOTAL.labels(outcome='error').inc() | ||
| return False | ||
| try: |
There was a problem hiding this comment.
Count write-fence failures in the vector error metric
When external_write_fence raises before the provider call, for example on a transient Firestore authority read failure, the _account_external_data_write decorator exits before this inner try is entered. _save_summary_vector_fail_soft then catches that exception under the assumption that the writer already counted it, so omi_conversation_summary_vector_upserts_total{outcome="error"} never moves even though no vector is written and the fanout is completed; count failures around the decorated boundary without double-counting provider errors so the new success panel cannot report a clean rate while writes are being fenced.
Useful? React with 👍 / 👎.
Verdict chain (coordinator-managed implement→review lane)
Non-blocking nits accepted with rationale (coordinator)
Reviewed head == merged candidate: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5f11b24744
ℹ️ 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".
| "targets": [ | ||
| { | ||
| "refId": "A", | ||
| "expr": "100 * sum(rate(omi_conversation_summary_vector_upserts_total{outcome=\"success\"}[$__range])) / sum(rate(omi_conversation_summary_vector_upserts_total{outcome=~\"success|error\"}[$__range]))", |
There was a problem hiding this comment.
Ingest backend-sync before aggregating vector writes
In the checked Cloud Run deployment, conversation-finalization Cloud Tasks execute on backend-sync, but .github/actions/deploy-backend-stack/action.yml:697-716 deploys that service without the GMP sidecar that is attached only to backend at lines 628-648; backend/charts/monitoring/README.md:193-202 likewise documents that backend-sync metrics remain dark until that sidecar is added. Consequently this unqualified aggregation omits queued/fallback finalization upserts and can show a healthy success rate while writes in that runtime are failing; attach the metrics ingestion path to backend-sync or explicitly scope the panel as partial.
AGENTS.md reference: backend/AGENTS.md:L115-L120
Useful? React with 👍 / 👎.
## What Adds `scripts/fleet_backfill_summary_vectors.py`: a retry-safe fleet driver for the per-user `backfill_summary_vectors.py` operator tool, plus `--all-users` enumeration from `conversation_finalization_jobs` (created_at ascending, uid+created_at projection only). ## Why The chat-vector freshness repair (#21111) fixed new conversations; the pre-repair backlog needs the per-user backfill run for every affected account. Doing that by hand for ~27.6k uids is error-prone; the driver adds durable per-uid state (atomic tmp+rename), resume-on-rerun, failed-uid quarantine with `--retry-failed`, and a 10%-per-batch error budget inherited from the per-user script. ## Cost/execution notes - Dry-run by default; `--apply` refuses without a configured vector index. - Per conversation: one embedding + the existing metadata-extraction LLM call. Fleet-scale cost was estimated at ~$40-230 for 50k-300k conversations before execution is authorized. - Designed to run inside the production backend environment (Cloud Run job or an attended operator shell); no secrets are read by this repo change. ## Tests - Offline behavioral test of the driver: dry-run totals, resume skips done uids, error-budget stop marks the uid failed and continues, `--retry-failed` recovers only failed uids (writes verified per uid). - `tests/unit/test_backfill_summary_vectors.py` still green (16 passed). - `--all-users` enumeration verified against an independent REST enumeration of `conversation_finalization_jobs` since 2026-08-25 (27,595 vs 27,596, +1 from boundary drift; missing=0). Failure-Class: none <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/21135?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
…anout indexing (#21141) ## What Adds `scripts/fleet_backfill_summary_vectors.py`: a retry-safe fleet driver for the per-user `backfill_summary_vectors.py` operator tool, plus `--all-users` enumeration from `conversation_finalization_jobs` (created_at ascending, uid+created_at projection only). ## Why The chat-vector freshness repair (#21111) fixed new conversations; the pre-repair backlog needs the per-user backfill run for every affected account. Doing that by hand for ~27.6k uids is error-prone; the driver adds durable per-uid state (atomic tmp+rename), resume-on-rerun, failed-uid quarantine with `--retry-failed`, and a 10%-per-batch error budget inherited from the per-user script. ## Cost/execution notes - Dry-run by default; `--apply` refuses without a configured vector index. - Per conversation: one embedding + the existing metadata-extraction LLM call. Fleet-scale cost was estimated at ~$40-230 for 50k-300k conversations before execution is authorized. - Designed to run inside the production backend environment (Cloud Run job or an attended operator shell); no secrets are read by this repo change. ## Tests - Offline behavioral test of the driver: dry-run totals, resume skips done uids, error-budget stop marks the uid failed and continues, `--retry-failed` recovers only failed uids (writes verified per uid). - `tests/unit/test_backfill_summary_vectors.py` still green (16 passed). - `--all-users` enumeration verified against an independent REST enumeration of `conversation_finalization_jobs` since 2026-08-25 (27,595 vs 27,596, +1 from boundary drift; missing=0). Failure-Class: none UI-Evidence: none -- generated desktop Swift DTO regeneration only (no UI source change); required by the Public Developer API contract check after main's spec drift (#21129 messaging spec).
Summary
Completed conversation-finalization replays skipped the processing bundle and therefore never emitted summary vectors; terminal intelligence suppression also skipped indexing. Persistence-loss vector dispatch could resurrect deleted rows or overwrite a smart-merge winner. Production diagnosis:
/Users/dazheng/workspace/omi/data/run-2026-10-10-chat-stale-data/FINDINGS.md(private coordinator evidence; not committed).TYPESENSE_CONNECTION_TIMEOUT_SECONDS(default 5 seconds, valid 1–30). An opt-in keyword-helper error signal lets the chat tool disclose semantic-only degradation without changing successful output or other callers' fail-open behavior. Recency questions require a small, undated newest-firstget_conversations_toolread; search time spans are similarity matches.Validation
make lane-backendalready completed).bash scripts/typecheck.sh: 0 errors; existing warnings remain.OMI_PR_BODY_FILE=/tmp/chat-vector-pr-body.md make preflight: 36 checks passed onea58756408af6ba15487d4f82ef52a870f85a383in 119.52s (UV cache redirected to/tmp/chat-vector-uv-cache; shared Git temporary objects required sandbox escalation). The shallow-history failure-class guard reports its documented skip.scripts/pr-preflight --metadata-only --pr-body-file /tmp/chat-vector-pr-body.md: 4 checks passed.process_conversation.pyremeasured at 3,472 lines.OMI_PR_BODY_FILE=/tmp/chat-vector-pr-body.md git push fork lane/chat-vector-fix: bounded pre-push gate passed, including repeated 36-check preflight, zero-error typecheck, 16-image source closure, pinned formatting, and 212 tests across 9 changed unit files. The selector's 1,704-file full backend request exceeds the local hook cap; this is not a full backend-suite claim.ea58756408af6ba15487d4f82ef52a870f85a383. Remote CI is separate from the completed local gates.Product invariants affected
Line-Count-Exception: backend/utils/conversations/process_conversation.py | 3448 -> 3472 | Retain bounded vector outcomes and eager-call dispatch beside processing; durable job indexing runs behind its winning fanout claim.
Line-Count-Exception: backend/utils/llm/chat.py | 1502 -> 1504 | Add the approved recency contract directly to existing retrieval guidance without prompt restructuring.
Failure-Class: FC-split-mutation-authority