Defer Typesense client setup for conversation search
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.pygit diff --check origin/main..HEAD
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-leveltypesense.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_KEYraises 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.Clientinstances (minor, benign in CPython due to the GIL, but worth hardening). The existing broadexcept Exceptioncatch also repackages the configRuntimeErroras a genericException, 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)
-
backend/utils/conversations/search.py, line 87-88 (link)Config
RuntimeErroris repackaged as a genericExceptionWhen
_get_required_env_varraisesRuntimeError(missing env vars), the outerexcept Exceptioncatch-all wraps it into a plainException("Failed to search conversations: ..."). This changes the exception type, so callers cannot useexcept RuntimeErrorto distinguish a misconfiguration from a network/search error. The tests pass becausepytest.raisesmatches the substring, but any production error-handling code that inspects exception type will treat a missingTYPESENSE_API_KEYidentically to a Typesense timeout. Letting theRuntimeErrorpropagate 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
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.
Updated this branch for the June 26 CHANGES_REQUESTED review.
What changed:
- Rebased on current
main(5de6546f62456f3160fd9957a71380945e369680). - Updated all 5
TestSearchRedactionsites intests/unit/test_lock_bypass_fixes.pythat previously patched the removedutils.conversations.search.clientsymbol. - 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 realsearch_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 passedpython -m py_compile utils/conversations/search.py tests/unit/test_conversation_search_typesense_config.py tests/unit/test_lock_bypass_fixes.pypython -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.
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
TestSearchRedactionpatch sites now usepatch.object(search_module, '_get_typesense_client', ...)instead of the removedclientsymbol — good. - The
RuntimeErrorfor missing config is raised before thetry/exceptinsearch_conversations, so it propagates unwrapped with a clear message (verified againsttest_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.
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.
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! 💜