Repository navigation
perf(backend): defer heavy LLM provider imports out of per-file test startup - #23682
Git-on-my-level wants to merge 1 commit into
Conversation
…startup Backend unit shards run one pytest process per test file, and every file that reaches utils/llm/clients paid for the Anthropic SDK, the langchain-anthropic binding, and (via utils/llm/providers) the google gRPC stack at import time, even though those clients are only constructed on use. With ~1/3 of the 2314-file suite importing this chain, full-suite shards carried ~763 redundant provider imports, which is part of why shard walls now drift past the 720s regression budget (flaky overages of 727s, 746s, and 841s on 2026-10-26 with every test passing). Resolve the bindings on first use instead: construction sites go through materialization helpers, module __getattr__ keeps from-imports and mock.patch targets working, and TYPE_CHECKING imports keep the pyright lane unchanged (0 errors). Interleaved A/B on the same host: importing utils.llm.clients drops from a median 1.31s to 0.90s (-31%) and 3167 to 2014 loaded modules per affected process; at runner speed that removes roughly 20s of wall from a full-suite shard, permanently, and shrinks the slow tail that trips the budget.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3cb1a78432
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| def _anthropic_module(): | ||
| module = globals().get('anthropic') | ||
| if module is None: | ||
| import anthropic as _anthropic_sdk |
There was a problem hiding this comment.
Keep provider imports at module scope
The new function-local provider imports violate the explicit backend import rule in backend/AGENTS.md: all imports must be at module top level, never inside functions. The same violation occurs in the other materialization helpers in clients.py and providers.py. The guide permits lazy SDK client construction, but does not exempt provider imports from this restriction; keep the imports at module scope and pursue the startup optimization within that constraint.
AGENTS.md reference: backend/AGENTS.md:L165-L165
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
2 issues found across 2 files
Confidence score: 4/5
- A cold wildcard import from
providers.pyomitsChatGoogleGenerativeAI, which can break consumers relying on that legacy export. Add it to the lazy hook’s__all__. - A cold wildcard import from
clients.pysilently omits four legacy provider names. Include them in a complete__all__alongside the existing public exports.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/utils/llm/providers.py">
<violation number="1" location="backend/utils/llm/providers.py:46">
P2: This lazy hook does not preserve wildcard re-exports: a cold `from utils.llm.providers import *` omits `ChatGoogleGenerativeAI`. Expose an explicit `__all__` through the lazy hook so wildcard consumers retain the legacy symbol.</violation>
</file>
<file name="backend/utils/llm/clients.py">
<violation number="1" location="backend/utils/llm/clients.py:109">
P2: This lazy re-export breaks wildcard imports: `from utils.llm.clients import *` silently omits the four legacy provider names on a fresh import. Add a complete `__all__` that includes the existing public exports and these dynamically resolved names, or preserve them through another wildcard-compatible export mechanism.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| def __getattr__(name: str) -> object: | ||
| if name == 'ChatGoogleGenerativeAI': | ||
| return _chat_google_generative_ai_cls() | ||
| raise AttributeError(f'module {__name__!r} has no attribute {name!r}') |
There was a problem hiding this comment.
P2: This lazy hook does not preserve wildcard re-exports: a cold from utils.llm.providers import * omits ChatGoogleGenerativeAI. Expose an explicit __all__ through the lazy hook so wildcard consumers retain the legacy symbol.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/llm/providers.py, line 46:
<comment>This lazy hook does not preserve wildcard re-exports: a cold `from utils.llm.providers import *` omits `ChatGoogleGenerativeAI`. Expose an explicit `__all__` through the lazy hook so wildcard consumers retain the legacy symbol.</comment>
<file context>
@@ -10,19 +10,45 @@
+ return cls
+
+
+def __getattr__(name: str) -> object:
+ if name == 'ChatGoogleGenerativeAI':
+ return _chat_google_generative_ai_cls()
</file context>
| def __getattr__(name: str) -> object: | |
| if name == 'ChatGoogleGenerativeAI': | |
| return _chat_google_generative_ai_cls() | |
| raise AttributeError(f'module {__name__!r} has no attribute {name!r}') | |
| def __getattr__(name: str) -> object: | |
| if name == '__all__': | |
| return [key for key in globals() if not key.startswith('_')] + ['ChatGoogleGenerativeAI'] | |
| if name == 'ChatGoogleGenerativeAI': | |
| return _chat_google_generative_ai_cls() | |
| raise AttributeError(f'module {__name__!r} has no attribute {name!r}') |
| return cls | ||
|
|
||
|
|
||
| def __getattr__(name: str) -> object: |
There was a problem hiding this comment.
P2: This lazy re-export breaks wildcard imports: from utils.llm.clients import * silently omits the four legacy provider names on a fresh import. Add a complete __all__ that includes the existing public exports and these dynamically resolved names, or preserve them through another wildcard-compatible export mechanism.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/llm/clients.py, line 109:
<comment>This lazy re-export breaks wildcard imports: `from utils.llm.clients import *` silently omits the four legacy provider names on a fresh import. Add a complete `__all__` that includes the existing public exports and these dynamically resolved names, or preserve them through another wildcard-compatible export mechanism.</comment>
<file context>
@@ -58,14 +64,60 @@ class BaseCallbackHandler:
+ return cls
+
+
+def __getattr__(name: str) -> object:
+ if name == 'anthropic':
+ return _anthropic_module()
</file context>
|
Folding batch (2026-11-04): this branch's tip was merged into the survivor PR #24477 ( |
|
Hey @Git-on-my-level 👋 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:
Before your next PR, please skim:
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! |
Flake
Backend unit shard N/6fails withFAIL: backend unit shard N took Xs, over its 720s regression budgetwith every test passing — a pure wall-time overage on full-suite selections. Verified independent occurrences on 2026-10-26:Green main shards the same day ran the same 386-file selection in 484s — the budget sits inside the right tail of the shard-wall distribution, which keeps drifting up as the suite grows (1727 files at the six-shard rebalance → 2313 today).
Root cause: per-file provider imports
The runner keeps one pytest process per test file (documented: process startup dominates). Every file that reaches
utils/llm/clients— ~33% of the suite, measured on a 120-file random sample — paid for the Anthropic SDK (anthropic,langchain_anthropic) and, viautils/llm.providers, thelangchain_google_genaigoogle gRPC stack at import time, even though those clients are only ever constructed on use. That is ~763 redundant provider-import chains per full-suite run, ~127 per shard, and it grows with every new test file.Change
Resolve the bindings on first use instead of at import, in the two modules that own them:
backend/utils/llm/providers.py:ChatGoogleGenerativeAIis materialized by a helper at its only two construction sites; module__getattr__serves external attribute access.backend/utils/llm/clients.py: same treatment foranthropic,ChatAnthropic, and theChatGoogleGenerativeAIre-export; thegateway_anthropicimport (which pulls the Anthropic SDK) resolves through the same hook with itsImportErrorfallback preserved.from __future__ import annotationsplusTYPE_CHECKINGimports keep every annotation and the pyright lane unchanged.mock.patchtargets (utils.llm.clients.ChatOpenAI,utils.llm.providers.ChatGoogleGenerativeAI, … intest_omi_qos_tiers.py) keep working: the helpers read the patched global, and__getattr__materializes the real object beforepatchreplaces it.Measured effect
Interleaved A/B on the same host (3 rounds × 3 reps,
import utils.llm.clients):At CI runner speed (~1.6–2× slower imports than the local host) that removes ≈0.65–0.8s from each of ~127 affected sessions per full-suite shard — roughly 20s of shard wall, permanently, and proportionally more as the suite grows. No test is skipped, relaxed, or deleted; behavior and all re-export/patch surfaces are unchanged.
Verification
test.shfile-isolated runner over all 334 test files importingutils.llm(2 workers): exit 0, 0 failed files (first run caught 3NameErrorfailures from bare in-body references; fixed by routing constructions through the materialization helpers).pytest tests/unit/test_omi_qos_tiers.py tests/unit/test_embeddings_gateway.py tests/unit/test_shaped_agent.py tests/unit/test_byok_security_enrollment.py tests/unit/test_gateway_anthropic_client.py tests/unit/test_conversation_structure_byok_quota.py: 249 passed.scripts/typecheck.sh(pyright): 0 errors (51844 warnings, identical to the untouched baseline).scripts/backend-python-format --check: clean; pre-commit hook passed on commit.Relation to the budget recalibration
This is the backend-side root-cause cut; it does not by itself re-pin the budget. The measured-evidence budget raise to 900s is already open for review in #23473 (green, clean) — this PR and that one are complementary: fewer wasted imports per shard here, calibrated ceiling there.