Skip to content

fix(backend): offload persona twitter Firestore writes to db_executor - #8265

Closed
ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/social-persona-async
Closed

ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/social-persona-async

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

upsert_persona_from_twitter_profile in backend/utils/social.py is an async def that runs two sync Firestore-backed calls, upsert_app_to_db and create_memories_from_twitter_tweets, directly on the event loop. The Firestore sync SDK is blocking, so each call stalls the whole loop for the duration of the writes, which freezes health checks and every other connection on the pod while a persona is being created or refreshed. This PR offloads both calls to db_executor via run_blocking so they run on a thread pool instead of the loop. This is a proactive hardening change; there is no filed GitHub issue for it.

Root cause

In backend/utils/social.py, upsert_persona_from_twitter_profile calls the blocking functions inline:

    # Save persona to database
    upsert_app_to_db(persona)
    save_username(username, uid)
    delete_generic_cache('get_public_approved_apps_data')

    # Create memories from persona prompt and tweets
    create_memories_from_twitter_tweets(uid, persona['id'], timeline.timeline)

upsert_app_to_db is a database.* function backed by the sync Firestore SDK, and create_memories_from_twitter_tweets does Firestore writes underneath. The backend async rules require offloading blocking work in async def with await run_blocking(executor, fn, args); calling them directly holds the event loop for the full round trip to Firestore, blocking unrelated requests and health checks on the same worker. The two functions are awaited sequentially elsewhere, but here they ran on the loop.

Fix

Import db_executor and run_blocking from utils.executors and dispatch both blocking calls through the db_executor pool, which is the pool for Firestore and Redis CRUD:

    # Save persona to database
    await run_blocking(db_executor, upsert_app_to_db, persona)
    save_username(username, uid)
    delete_generic_cache('get_public_approved_apps_data')

    # Create memories from persona prompt and tweets
    await run_blocking(db_executor, create_memories_from_twitter_tweets, uid, persona['id'], timeline.timeline)

Both calls still run exactly once and in the same order, so behavior for valid input is unchanged; they just execute on a worker thread instead of the loop.

Testing

New backend/tests/unit/test_social_persona_async.py (registered in test.sh). utils.social pulls in a heavy import graph, so the test keeps the real utils, utils.executors, and utils.social and stubs only the heavy leaves (database, firebase_admin, models, utils.llm, utils.conversations, and similar) through a meta-path finder, then calls upsert_persona_from_twitter_profile directly with the surrounding helpers patched. One case patches run_blocking to record the function it is handed and asserts both upsert_app_to_db and create_memories_from_twitter_tweets are dispatched through it against db_executor; the other makes run_blocking a no-op and asserts neither blocking function runs inline, which fails on current main where they are called directly. Verified red to green: the test fails on current main and passes with this change.

PR status check

No open PR changes the logic this PR fixes. The offload wiring added here does not appear anywhere in this file's history, so it is not a previously reverted fix being resubmitted. No filed GitHub issue matches.

Review in cubic

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

1 issue found across 3 files

Confidence score: 3/5

  • In backend/utils/social.py, routing memory extraction through db_executor mixes LLM/post-processing with DB-bound work, which can exhaust DB worker threads under load and delay Firestore/Redis operations for users; move this path to a non-DB executor (or split DB vs compute steps) before merging.

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

Fix all with cubic | Re-trigger cubic

Comment thread backend/utils/social.py Resolved

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Backend hardening bug fix with regression test; matches established pattern. (auto-review)

@ZachL111
ZachL111 force-pushed the fix/social-persona-async branch from a1cf9c7 to 82d701f Compare June 24, 2026 18:41
@Git-on-my-level

Copy link
Copy Markdown
Member

Hi @ZachL111 — thank you for finding this and writing up a candidate fix.

We reviewed it during the ZachL111 aggregate triage. This one needs a bit more product/API/design decision than we want to bundle into the current aggregate PRs (#8362, #8364, #8366, #8367), so we’re deferring rather than merging this exact patch.

I’m closing the individual PR to keep the review queue manageable. The report is still appreciated and may be revisited as a more explicit follow-up. Thanks again for the contribution.

@Git-on-my-level

Copy link
Copy Markdown
Member

Closing after aggregate triage: deferring this design/API decision rather than merging the one-off patch. Thanks @ZachL111 for surfacing it.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @ZachL111 👋

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 roadmap and vision

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! 💜

Git-on-my-level added a commit that referenced this pull request Jun 25, 2026
## Summary

This aggregates ZachL111's async/resource correctness fixes into one
maintained PR:

- Offload synchronous Firestore/database reads from async code with
`utils.executors.run_blocking(..., db_executor, ...)` in app
integrations, notification memories, and the fair-use classifier.
- Make the Gmail retrieval path async end-to-end: the tool is async,
message list/fetch Google API calls are awaited, and auth refresh goes
through a shared `retry_on_auth_async` helper beside the existing sync
helper.
- Add the missing `asyncio` import in `routers/agent_tools.py` and
verify changed modules with a static undefined-name check.
- Ensure speech-profile matching closes the uploaded audio file handle
deterministically.
- Teach `scan_async_blockers.py` that work wrapped by repository
`run_blocking` is executor-offloaded.
- Add a focused async/resource regression test module to the backend
test runner.

Supersedes #8268, #8274, #8296, #8300, #8314, #8323. Original issue
discovery, reproductions, and candidate fixes by @ZachL111.

Deferred: #8265, per the aggregation plan, because it mixes Firestore
writes, cache work, and potentially expensive memory/LLM postprocessing
and needs a fuller executor design.

## Tests

- `uv run --with pytest --with pytest-asyncio --with httpx --with pydub
pytest tests/unit/test_async_resource_correctness.py -v`
- `uv run python -m py_compile routers/agent_tools.py
utils/app_integrations.py utils/llm/notifications.py
utils/retrieval/tools/gmail_tools.py
utils/retrieval/tools/integration_base.py
utils/llm/fair_use_classifier.py utils/stt/speech_profile.py
scripts/scan_async_blockers.py
tests/unit/test_async_resource_correctness.py`
- `uv run python scripts/scan_async_blockers.py --dirs routers utils`
(exit 0; reports 0 high network I/O / 0 file I/O / 0 no-await endpoints,
plus pre-existing async helper/sync DB findings elsewhere)
- `uv run --with pyflakes pyflakes routers/agent_tools.py
utils/retrieval/tools/gmail_tools.py
tests/unit/test_async_resource_correctness.py`


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/8364?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="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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.

3 participants