Skip to content

fix(backend): close audio file handle in speech profile matching predictions - #8314

Closed
ZachL111 wants to merge 2 commits into
BasedHardware:mainfrom
ZachL111:fix/speech-profile-fd-leak
Closed

ZachL111 wants to merge 2 commits into
BasedHardware:mainfrom
ZachL111:fix/speech-profile-fd-leak

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

get_speech_profile_matching_predictions in backend/utils/stt/speech_profile.py opens the user's audio file and hands the raw file object to httpx.post(...) inside the files=[...] list, but it never closes it. httpx does not close caller-provided file objects, so every call to this function leaks one open file descriptor. This function runs during conversation post-processing for speaker matching, so on a busy backend the leaked descriptors accumulate until the process hits its open-files limit, after which open() starts raising OSError: [Errno 24] Too many open files and any code in that process that opens a file or socket begins failing. This PR opens the file inside a with block so the descriptor is released when the call returns. This is a proactive hardening change; there is no filed GitHub issue for it.

Root cause

In backend/utils/stt/speech_profile.py, get_speech_profile_matching_predictions opens the audio file inline as an argument to the files payload:

def get_speech_profile_matching_predictions(uid: str, audio_file_path: str, segments: List) -> List[dict]:
    logger.info('get_speech_profile_matching_predictions')
    files = [
        ('audio_file', (os.path.basename(audio_file_path), open(audio_file_path, 'rb'), 'audio/wav')),
    ]
    response = httpx.post(
        os.getenv('HOSTED_SPEECH_PROFILE_API_URL') + f'?uid={uid}', data={'segments': json.dumps(segments)}, files=files
    )

The file object created by open(audio_file_path, 'rb') is only referenced from the files list. httpx reads from it to build the multipart body but does not take ownership and does not close it, and nothing in this function closes it either. There is no close(), no with, and no try/finally, so the handle is left open on every path: success, a non-200 response, and an exception out of httpx.post. Each invocation leaks one descriptor. The sibling helper _read_file in the same module already reads its file under with open(path, 'rb') as f:, so the safe pattern was right there but this function did not use it.

Fix

Open the file inside a with block that encloses the httpx.post call, so the descriptor is closed deterministically when the block exits, on every return path including when httpx.post raises:

def get_speech_profile_matching_predictions(uid: str, audio_file_path: str, segments: List) -> List[dict]:
    logger.info('get_speech_profile_matching_predictions')
    default = [{'is_user': False, 'person_id': None}] * len(segments)
    with open(audio_file_path, 'rb') as audio_f:
        files = [
            ('audio_file', (os.path.basename(audio_file_path), audio_f, 'audio/wav')),
        ]
        response = httpx.post(
            os.getenv('HOSTED_SPEECH_PROFILE_API_URL') + f'?uid={uid}',
            data={'segments': json.dumps(segments)},
            files=files,
        )

httpx finishes reading the file while building the request body inside the with block, so closing on exit is safe. The request payload, the return values, and the response handling below are unchanged, so behavior for valid input is identical apart from no longer leaking the handle.

Testing

Added backend/tests/unit/test_speech_profile_fd_leak.py, registered in backend/test.sh. The module pulls in heavy and native dependencies (firebase, pinecone, opuslib, pydub, redis, and the storage and executor utils), so the test installs a stub meta-path finder for those packages and imports utils.stt.speech_profile under it, while keeping httpx real so httpx.post can be patched on the module. Two cases: one patches httpx.post to capture the file object from the files payload and asserts the handle is .closed after a successful call returns, and one makes httpx.post raise mid-request and asserts the handle is still closed afterward. Cleanup closes any leaked handle before removing the temp file so the assertion, not the temp-file removal, is what fails on the buggy code (this matters on Windows where an open handle blocks deletion). 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 most recent commit to touch this file, the async-native HTTP refactor (#7343 / #6369), added the separate async_get_speech_profile_matching_predictions variant and the _read_file helper but left this synchronous function with the unguarded inline open(), so it does not fix the leak. The with-block fix added here does 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.

No issues found across 3 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Tip: cubic could auto-approve low-risk PRs like this, if it thinks it's safe to merge. Learn more

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