Skip to content

[codex] Defer Typesense client setup for conversation search - #7662

Closed
tianmind-studio wants to merge 8 commits into
BasedHardware:mainfrom
tianmind-studio:codex/lazy-typesense-client
Closed

tianmind-studio wants to merge 8 commits into
BasedHardware:mainfrom
tianmind-studio:codex/lazy-typesense-client

Conversation

@tianmind-studio

@tianmind-studio tianmind-studio commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Rebased the lazy Typesense client work onto current main (45fe68b82f).
  • Keeps conversation search import-safe by constructing the Typesense client on first use behind a lock.
  • Preserves current main's transient Typesense error handling while keeping TYPESENSE_PROTOCOL override support.
  • Exposes get_typesense_client() so the canonical atom keyword index can share the same lazy singleton instead of importing the removed eager client symbol.
  • Updates the conversation search, hybrid-search, and lock-bypass tests to patch the lazy accessor path.

Product invariants affected

  • INV-MEM-1: backend/utils/memory/atom_keyword_index.py still gates canonical long-term atom keyword indexing through existing canonical/data-protection checks; this PR only changes how the shared Typesense client is acquired after lazy initialization.

Why

utils.conversations.search previously built a Typesense client at import time, so importing conversation search required TYPESENSE_HOST, TYPESENSE_HOST_PORT, and TYPESENSE_API_KEY even in test paths that never searched. The refresh also fixes the backend typecheck regression where utils.memory.atom_keyword_index still imported the old eager client symbol.

Validation

  • python -m py_compile utils\conversations\search.py utils\memory\atom_keyword_index.py tests\unit\test_conversation_search_typesense_config.py
  • python -m black --check utils\conversations\search.py utils\memory\atom_keyword_index.py tests\unit\test_conversation_search_typesense_config.py tests\unit\test_conversation_hybrid_search.py tests\unit\test_lock_bypass_fixes.py
  • python -m pytest tests\unit\test_conversation_search_typesense_config.py tests\unit\test_ws_m_atom_keyword_index.py -q --tb=short -> 27 passed
  • python -m pytest tests\unit\test_conversation_hybrid_search.py tests\unit\test_lock_bypass_fixes.py -q --tb=short -> 75 passed
  • python -m pyright -p pyrightconfig.json utils\conversations\search.py utils\memory\atom_keyword_index.py --pythonpath D:\codex-omi-work\.venvs\omi-backend-311\Scripts\python.exe -> 0 errors, 1 existing warning
  • git diff --check

@greptile-apps

greptile-apps Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

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}"
Loading

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

Comment thread backend/utils/conversations/search.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.

Lazy Typesense client init — backend refactor with tests, approve only per backend policy.

@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch from b3a0c51 to a02fc14 Compare June 8, 2026 13:45

Copy link
Copy Markdown
Contributor Author

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.

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

re-approved on new sha: backend bug fix (lazy Typesense client init + concurrency lock) — approve only

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

Re-approved on new sha: lazy Typesense init — has merge conflicts, please rebase

@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch from 3bd28ca to 361a79c Compare June 12, 2026 07:13

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

Lazy Typesense init w/ tests — re-approved on new sha

@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch 4 times, most recently from d266b5b to b767d69 Compare June 17, 2026 08:23

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

Lazy Typesense init — approve only (re-approve)

@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch from b767d69 to 2312c5c Compare June 23, 2026 07:09

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

Re-approved on new commits; approve-only per area policy. (auto-review)

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Clean, well-tested improvement. Lazy-initializing the Typesense client with double-checked locking is the right call — it removes an unnecessary import-time dependency on TYPESENSE_* env vars while preserving clear RuntimeError validation on first use. The concurrency test confirming a single shared client across 8 threads is a nice touch, and the Greptile thread-safety feedback was addressed correctly. Both CI checks pass. Thanks @tianmind-studio!

@Git-on-my-level Git-on-my-level added the backend Backend Task (python) label Jun 26, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @tianmind-studio — the lazy-init refactor itself is clean and well-tested. The double-checked locking pattern is correct, and the concurrency test confirming a single shared client across 8 threads is a nice touch.

One gap before this can land: this PR removes the module-level client symbol, but 5 tests in tests/unit/test_lock_bypass_fixes.py (the TestSearchRedaction class) still patch it:

with patch('utils.conversations.search.client', mock_client):

Since client no longer exists, patch() raises AttributeError at test time. This isn't caught by the hermetic E2E CI check (which runs testing/e2e/), but backend/test.sh runs test_lock_bypass_fixes.py on line 128 and would fail there.

The fix is straightforward — update those 5 patch sites to target the new lazy-init API, e.g.:

with patch('utils.conversations.search._get_typesense_client', return_value=mock_client):
    from utils.conversations.search import search_conversations
    result = search_conversations(uid='test-uid', query='test')

Once that's updated, this is good to go. Happy to re-review quickly after the fix.

@Git-on-my-level Git-on-my-level added the needs-tests PR introduces logic that should be covered by tests label Jun 26, 2026
@Git-on-my-level
Git-on-my-level dismissed their stale review June 27, 2026 00:02

Automated approval dismissed: this PR falls into a category that should receive human maintainer/product/security judgment rather than formal auto-approval. No changes are being requested by this dismissal; prior automated feedback should be treated as an implementation review/positive signal only.

@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch from 2312c5c to 5dfa90a Compare June 29, 2026 02:27
@tianmind-studio tianmind-studio changed the title Defer Typesense client setup for conversation search [codex] Defer Typesense client setup for conversation search Jun 29, 2026

Copy link
Copy Markdown
Contributor Author

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
tianmind-studio force-pushed the codex/lazy-typesense-client branch from 5dfa90a to 78a144b Compare June 29, 2026 02:58
@Git-on-my-level

Copy link
Copy Markdown
Member

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.

@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch from 78a144b to a2decaa Compare June 29, 2026 07:07

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @tianmind-studio — I re-reviewed the latest head (a2decaa41f7b504b928731795f098c0d7e9c7e12). The previous requested test-update gap is addressed.

What I checked:

  • utils.conversations.search._get_typesense_client() now uses lock-guarded lazy initialization, so importing the module no longer requires TYPESENSE_* config.
  • Missing Typesense config is validated on first actual search and the RuntimeError remains unwrapped because the client setup happens before the broad search try/except.
  • The five TestSearchRedaction patch sites now target _get_typesense_client, so they still exercise the real search_conversations() path without relying on the removed module-level client symbol.
  • Added coverage exercises import-time safety, missing config, first-use construction, and concurrent first-use singleton behavior.

Verification I ran locally from backend/ on this head:

  • PYTHONPATH=. pytest tests/unit/test_conversation_search_typesense_config.py tests/unit/test_lock_bypass_fixes.py::TestSearchRedaction -q --tb=short → 9 passed
  • PYTHONPATH=. python3 -m py_compile utils/conversations/search.py tests/unit/test_conversation_search_typesense_config.py tests/unit/test_lock_bypass_fixes.py → passed
  • Searched for remaining utils.conversations.search.client patch/import references → none found

One operational note for maintainers: this intentionally moves missing TYPESENSE_* failures from startup/import time to first search use. That seems like the right tradeoff for router import safety, but it is worth keeping in mind for monitoring.

I’m removing the needs-tests label because the added/updated tests cover the prior gap. Not formally approving here because this PR was still carrying a blocking human-review label in the review context, but from a backend implementation/testing perspective this looks ready for maintainer final review.

@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch from a2decaa to dd8d8ca Compare July 3, 2026 06:43

@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 5 files

Confidence score: 5/5

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

Re-trigger cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

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.

@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch from 305463f to 71a3402 Compare July 3, 2026 11:27

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @tianmind-studio — I re-reviewed the current head (71a3402). This remains a small, self-contained backend refactor: the Typesense client is initialized lazily with a lock, missing config now fails clearly on first real search rather than import, and the protocol override is preserved.

I verified the targeted backend coverage locally with a stripped environment: \ -> 26 passed, plus py_compile on the touched Python files passed. GitHub checks are also green and the PR is mergeable.

No agent-behavior or instruction changes are involved. Good to go from my review.

@github-actions

github-actions Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

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

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the rebase and the well-structured lazy-init refactor — the double-checked locking and the env-var validation on first use are good.

There's one blocker that's breaking the Backend unit suite right now: the module-level client symbol is removed from backend/utils/conversations/search.py, but another module still imports it.

backend/utils/memory/atom_keyword_index.py:

def _typesense_client() -> Any:
    from utils.conversations.search import client  # <-- ImportError now
    return client

This is the pyright error: "client" is unknown import symbol that fails the check, and it would also be a runtime ImportError whenever keyword_search_memory_ids() is exercised. It looks like it was missed because the search-result tests were updated but this keyword-index consumer wasn't.

Suggested fix — make atom_keyword_index._typesense_client() go through the new factory:

def _typesense_client() -> Any:
    from utils.conversations.search import _get_typesense_client
    return _get_typesense_client()

(or return _get_typesense_client() if you prefer keeping it lazy). Worth a quick grep for any other from utils.conversations.search import client / search.client references too.

Requesting changes until the build is green. Separately, there's a generic github-actions[bot] "not merging" comment above that doesn't match the review history here — flagging for a maintainer since this PR is still open and previously approved.

@Git-on-my-level Git-on-my-level added the needs-maintainer-review Needs a human maintainer to sign off before merge label Jul 7, 2026
@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch from 375e7a1 to 31a58cd Compare July 10, 2026 05:11
@github-actions

Copy link
Copy Markdown
Contributor

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 product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

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!

@tianmind-studio
tianmind-studio force-pushed the codex/lazy-typesense-client branch from 0ce00bf to b9eb80c Compare July 10, 2026 05:19
@Git-on-my-level Git-on-my-level added the needs-tests PR introduces logic that should be covered by tests label Jul 10, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @tianmind-studio — the latest fix correctly updates atom_keyword_index.py to use the new shared lazy accessor, and the targeted tests you listed are green.

I found one remaining blocker before this can land: another existing backend unit test file still patches the removed module-level client symbol:

backend/tests/unit/test_search_conversations_typesense_timeout_failsoft.py

Running it on the current head fails all 3 tests with AttributeError because utils.conversations.search.client no longer exists:

PYTHONPATH=. python3 -m pytest tests/unit/test_search_conversations_typesense_timeout_failsoft.py -q --tb=short
# 3 failed: patch('utils.conversations.search.client') does not have the attribute 'client'

Please update those tests to patch the lazy accessor path (for example patch('utils.conversations.search._get_typesense_client', return_value=mock_client)), similar to the lock-bypass and hybrid-search test updates already in this PR. After that, please rerun at least:

PYTHONPATH=. python3 -m pytest \
  tests/unit/test_conversation_search_typesense_config.py \
  tests/unit/test_search_conversations_typesense_timeout_failsoft.py \
  tests/unit/test_lock_bypass_fixes.py::TestSearchRedaction \
  tests/unit/test_conversation_hybrid_search.py \
  -q --tb=short

Separate non-blocking note for maintainers: missing TYPESENSE_* config is still raised during first search use rather than import, but because _get_typesense_client() is called inside search_conversations()'s broad try/except, the public exception type is currently wrapped as a generic Exception with the original RuntimeError as __cause__. That may be acceptable, but it is worth being explicit about if callers rely on exception type.

Copy link
Copy Markdown
Contributor Author

Closing this PR to respect the project decision above and keep the contributor queue tidy. Thanks for the reviews; I will carry the feedback into smaller, issue-backed Windows contributions.

@github-actions

Copy link
Copy Markdown
Contributor

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 product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants