Skip to content

fix(backend): await google_api_request in Gmail tool - #8300

Closed
ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/gmail-tools-missing-await
Closed

ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/gmail-tools-missing-await

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

get_gmail_messages in the Gmail retrieval tool calls the async helper google_api_request without await, so it gets back a coroutine and immediately calls .get('messages', []) on it. That raises AttributeError: 'coroutine' object has no attribute 'get', so every Gmail tool call fails and the agent returns an error to the user instead of their emails. This PR makes get_gmail_messages (and its @tool wrapper) async and awaits both google_api_request calls, matching the sibling calendar tool. This is a proactive hardening change; there is no filed GitHub issue for it.

Root cause

backend/utils/retrieval/tools/gmail_tools.py defines get_gmail_messages as a plain def, but google_api_request (in the sibling utils/retrieval/tools/google_utils.py) is async def. The current code calls it without awaiting and then treats the return value as a dict:

def get_gmail_messages(
    access_token: str,
    query: Optional[str] = None,
    max_results: int = 10,
    label_ids: Optional[List[str]] = None,
) -> List[dict]:
    ...
    data = google_api_request(
        "GET",
        'https://www.googleapis.com/gmail/v1/users/me/messages',
        access_token,
        params=page_params,
    )

    ids = [msg['id'] for msg in data.get('messages', [])]

Calling an async def without await returns a coroutine object, not the response dict. The next line, data.get('messages', []), then raises AttributeError: 'coroutine' object has no attribute 'get'. The second call site in the per-message loop has the same problem. Both paths are hit on every invocation, so the tool is broken for all queries, not just an edge case. The calendar tool in the same package (get_google_calendar_events) already awaits google_api_request correctly, so this one was out of step.

Fix

Make get_gmail_messages async def and await both google_api_request calls. The @tool entry point get_gmail_messages_tool becomes async def too and awaits the helper, with the auth-retry handled by catching GoogleAPIError and refreshing the token, the same pattern the calendar tool uses:

async def get_gmail_messages(
    access_token: str,
    query: Optional[str] = None,
    max_results: int = 10,
    label_ids: Optional[List[str]] = None,
) -> List[dict]:
    ...
    data = await google_api_request(
        "GET",
        'https://www.googleapis.com/gmail/v1/users/me/messages',
        access_token,
        params=page_params,
    )
    ...
    msg_data = await google_api_request(
        "GET",
        f'https://www.googleapis.com/gmail/v1/users/me/messages/{msg_id}',
        access_token,
        params={'format': 'full'},
    )

With a real awaited response the dict access works as intended. For a valid token the returned messages are identical to what the code was meant to produce before; there is no change to the response shape or the formatted output.

Testing

Added backend/tests/unit/test_gmail_tools_await.py, registered in backend/test.sh. The utils/retrieval/tools/__init__.py aggregator eagerly imports every tool and pulls in typesense, pinecone, and friends, so the test does not import the package normally. It loads the real gmail_tools, integration_base, and google_utils modules by file path while a meta-path finder stubs only the heavy IO leaf modules (database, firebase_admin, google, pinecone, redis, typesense, utils.http_client, utils.log_sanitizer). It patches google_api_request with an async fake that returns plain dicts and asserts await get_gmail_messages(...) returns a concrete list of message dicts (never a coroutine), that the items are real dicts, and that the helper was called once for the list plus once per message. Verified red to green: the test fails on current main and passes with this change.

PR status check

No open PR changes this logic. The awaited calls and the async signature added here do not appear anywhere in this file's history, so this 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: 4/5

  • In backend/utils/retrieval/tools/gmail_tools.py, the token-refresh retry path can bypass the structured GoogleAPIError branch, so a second API failure may be reported as a generic unexpected error and reduce debuggability for users/operators; this looks low-to-moderate risk functionally, but it should be wrapped in the same GoogleAPIError handling before merging to keep error messages consistent and actionable.

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

Fix all with cubic | Re-trigger cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Hi @ZachL111 — thank you for finding and writing up this async/resource correctness issue. We consolidated this set into a smaller aggregate PR so the fixes share infrastructure and are easier to maintain/review: #8364.

Your original discovery, reproduction details, and candidate fix are credited in the new PR body and commit metadata. I’m closing this individual PR as superseded by #8364, not because the issue is invalid. Thanks again for surfacing it.

@Git-on-my-level

Copy link
Copy Markdown
Member

Superseded by #8364. Thanks again @ZachL111 — credited there for the original discovery and candidate fix.

@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. -->
Git-on-my-level pushed a commit to Git-on-my-level/omi that referenced this pull request Jun 25, 2026
Supersedes BasedHardware#8268, BasedHardware#8274, BasedHardware#8296, BasedHardware#8300, BasedHardware#8314, BasedHardware#8323.

Original issue discovery, reproductions, and candidate fixes by @ZachL111.

Co-authored-by: ZachL111 <[email protected]>
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.

2 participants