omi icon indicating copy to clipboard operation
omi copied to clipboard

Defer Typesense client setup for conversation search

Open tianmind-studio opened this issue 5 months ago • 2 comments

Summary

  • lazily initialize the conversation-search Typesense client so importing backend routers does not require TYPESENSE_* env vars
  • validate missing Typesense config only when search is actually used, preserving config errors as RuntimeError
  • guard first-use initialization with a lock so concurrent callers share one client
  • add unit coverage for import-time safety, missing config, first-use construction, and concurrent initialization

Verification

  • python -m pytest tests\unit\test_conversation_search_typesense_config.py -q
    • 4 passed
  • python -m black utils\conversations\search.py tests\unit\test_conversation_search_typesense_config.py --check
    • 2 files would be left unchanged
  • python -m py_compile utils\conversations\search.py tests\unit\test_conversation_search_typesense_config.py
  • git diff --check origin/main..HEAD

tianmind-studio avatar Jun 06 '26 09:06 tianmind-studio

Greptile Summary

This PR defers Typesense client construction from module-import time to first use, so importing utils.conversations.search (and any router that pulls it in) no longer requires TYPESENSE_* environment variables to be present. Focused unit tests and a test.sh entry accompany the change.

  • _get_typesense_client() replaces the module-level typesense.Client(...) call with a lazy singleton, validating all three env vars only when search is first invoked.
  • Three new unit tests verify that import succeeds without env vars, that a missing TYPESENSE_API_KEY raises at call time, and that a successful first call constructs the client with the expected config.
  • The singleton is not guarded by a lock, so concurrent first-calls can create duplicate typesense.Client instances (minor, benign in CPython due to the GIL, but worth hardening). The existing broad except Exception catch also repackages the config RuntimeError as a generic Exception, which may complicate error-type-based handling upstream.

Confidence Score: 4/5

Safe to merge — the lazy-init change is self-contained, the tests cover the main scenarios, and the identified concerns are non-blocking quality improvements.

The core change is straightforward and achieves its goal. The singleton lacks a threading lock (benign in practice but not future-proof), and the broad exception handler silently changes the type of config errors, making them harder to distinguish from runtime search failures. Neither issue causes incorrect behavior today.

backend/utils/conversations/search.py — the singleton initialization pattern and exception-wrapping logic are the two spots worth a second look before this pattern is replicated elsewhere.

Important Files Changed

Filename Overview
backend/utils/conversations/search.py Replaces module-level Typesense client construction with a lazy singleton; _get_typesense_client() defers env-var validation to first use. The singleton is not guarded by a lock (minor race under concurrency), and config RuntimeError is swallowed by the pre-existing broad except block.
backend/tests/unit/test_conversation_search_typesense_config.py New unit tests cover import-time safety, missing-env-var error on first use, and successful client construction. Module isolation via sys.modules.pop is correct. Missing a test asserting that the second call reuses the cached client rather than constructing a new one.
backend/test.sh Adds the new test file to the CI test script in the correct position alongside similar unit tests; no issues.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant search_conversations
    participant _get_typesense_client
    participant typesense.Client

    Caller->>search_conversations: search_conversations(uid, query)
    search_conversations->>_get_typesense_client: _get_typesense_client()
    alt _typesense_client is None
        _get_typesense_client->>_get_typesense_client: _get_required_env_var(TYPESENSE_HOST)
        _get_typesense_client->>_get_typesense_client: _get_required_env_var(TYPESENSE_HOST_PORT)
        _get_typesense_client->>_get_typesense_client: _get_required_env_var(TYPESENSE_API_KEY)
        note over _get_typesense_client: raises RuntimeError if any var missing
        _get_typesense_client->>typesense.Client: Client(config)
        typesense.Client-->>_get_typesense_client: client instance
        _get_typesense_client->>_get_typesense_client: "_typesense_client = client (cached)"
    else _typesense_client already initialized
        note over _get_typesense_client: return cached singleton
    end
    _get_typesense_client-->>search_conversations: client
    search_conversations->>typesense.Client: collections['conversations'].documents.search(params)
    typesense.Client-->>search_conversations: results
    search_conversations-->>Caller: "{items, total_pages, current_page, per_page}"

Comments Outside Diff (1)

  1. backend/utils/conversations/search.py, line 87-88 (link)

    P2 Config RuntimeError is repackaged as a generic Exception

    When _get_required_env_var raises RuntimeError (missing env vars), the outer except Exception catch-all wraps it into a plain Exception("Failed to search conversations: ..."). This changes the exception type, so callers cannot use except RuntimeError to distinguish a misconfiguration from a network/search error. The tests pass because pytest.raises matches the substring, but any production error-handling code that inspects exception type will treat a missing TYPESENSE_API_KEY identically to a Typesense timeout. Letting the RuntimeError propagate uncaught (or re-raising it explicitly before the broad catch) would preserve the distinction.

Reviews (1): Last reviewed commit: "Defer Typesense client setup for convers..." | Re-trigger Greptile

greptile-apps avatar Jun 06 '26 09:06 greptile-apps

I rebased and force-pushed this branch onto the current main. The latest commit includes the review follow-ups: lazy initialization is lock-guarded, missing config remains a RuntimeError, and there is a concurrent first-use test. I reran python -m pytest tests\unit\test_conversation_search_typesense_config.py -q: 4 passed.

tianmind-studio avatar Jun 08 '26 13:06 tianmind-studio

Updated this branch for the June 26 CHANGES_REQUESTED review.

What changed:

  • Rebased on current main (5de6546f62456f3160fd9957a71380945e369680).
  • Updated all 5 TestSearchRedaction sites in tests/unit/test_lock_bypass_fixes.py that previously patched the removed utils.conversations.search.client symbol.
  • The tests now import the search module and use patch.object(search_module, '_get_typesense_client', return_value=mock_client), so they still exercise the real search_conversations() function while injecting the lazy Typesense client.

Validation from backend/:

  • python -m pytest tests/unit/test_conversation_search_typesense_config.py tests/unit/test_lock_bypass_fixes.py::TestSearchRedaction -q --tb=short -> 9 passed
  • python -m py_compile utils/conversations/search.py tests/unit/test_conversation_search_typesense_config.py tests/unit/test_lock_bypass_fixes.py
  • python -m black --line-length 120 --skip-string-normalization --check utils/conversations/search.py tests/unit/test_conversation_search_typesense_config.py tests/unit/test_lock_bypass_fixes.py

I also reran the async blocker scan and pre-commit; both completed with exit 0.

tianmind-studio avatar Jun 29 '26 02:06 tianmind-studio

Thanks @tianmind-studio — the lazy-init refactor is clean and well-tested, and the previous review feedback has been fully addressed.

What landed well:

  • The double-checked locking pattern in _get_typesense_client() is correct, and the 8-thread concurrency test confirming a single shared client is a nice touch.
  • All five TestSearchRedaction patch sites now use patch.object(search_module, '_get_typesense_client', ...) instead of the removed client symbol — good.
  • The RuntimeError for missing config is raised before the try/except in search_conversations, so it propagates unwrapped with a clear message (verified against test_search_requires_typesense_api_key_when_used).
  • Both CI checks pass.

One operational note for maintainers (not a blocker): shifting client construction from import time to first use means a missing TYPESENSE_* config will no longer fail fast at startup — it will only surface when a user first searches. That's the intended improvement, just worth keeping in mind for monitoring.

The needs-tests label looks satisfied by the added coverage, but I'll leave it for a human maintainer to confirm and clear before merge. The code itself is good to go once that's resolved.

Git-on-my-level avatar Jun 29 '26 04:06 Git-on-my-level

Reviewed the lazy Typesense client refactor on the current head (305463f). The double-checked locking in _get_typesense_client() is correct, the TYPESENSE_PROTOCOL override is preserved, and the new test file covers import-time safety, missing-config validation, first-use construction, protocol override, and 8-thread concurrent initialization. All GitHub checks are green. The search logic itself (filtering, locking, redaction) is unchanged — only client construction timing moves to first use, which actually improves robustness by validating config lazily with a clear RuntimeError. Solid implementation, thanks @tianmind-studio.

Git-on-my-level avatar Jul 03 '26 10:07 Git-on-my-level

Hey @tianmind-studio 👋

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

github-actions[bot] avatar Jul 07 '26 07:07 github-actions[bot]