Skip to content

perf(backend): defer heavy LLM provider imports out of per-file test startup - #23682

Closed
Git-on-my-level wants to merge 1 commit into
mainfrom
lane/sca-1145-flake-backend-shard
Closed

Git-on-my-level wants to merge 1 commit into
mainfrom
lane/sca-1145-flake-backend-shard

Conversation

@Git-on-my-level

Copy link
Copy Markdown
Member

Flake

Backend unit shard N/6 fails with FAIL: backend unit shard N took Xs, over its 720s regression budget with every test passing — a pure wall-time overage on full-suite selections. Verified independent occurrences on 2026-10-26:

Run Shard Wall Where
40255084596 4/6 727s main push
40267543640 5/6 841s PR lane/c5dedupe (#23646)
40271533916 3/6 746s PR lane/langfix (#23651, the dispatched example)

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, via utils/llm.providers, the langchain_google_genai google 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: ChatGoogleGenerativeAI is materialized by a helper at its only two construction sites; module __getattr__ serves external attribute access.
  • backend/utils/llm/clients.py: same treatment for anthropic, ChatAnthropic, and the ChatGoogleGenerativeAI re-export; the gateway_anthropic import (which pulls the Anthropic SDK) resolves through the same hook with its ImportError fallback preserved. from __future__ import annotations plus TYPE_CHECKING imports keep every annotation and the pyright lane unchanged.

mock.patch targets (utils.llm.clients.ChatOpenAI, utils.llm.providers.ChatGoogleGenerativeAI, … in test_omi_qos_tiers.py) keep working: the helpers read the patched global, and __getattr__ materializes the real object before patch replaces it.

Measured effect

Interleaved A/B on the same host (3 rounds × 3 reps, import utils.llm.clients):

  • base (origin/main): median 1.31s, 3167 modules loaded
  • this PR: median 0.90s (−31%), 2014 modules loaded

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.sh file-isolated runner over all 334 test files importing utils.llm (2 workers): exit 0, 0 failed files (first run caught 3 NameError failures 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.

…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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T06:42:56.954902Z 3cb1a78 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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

2 issues found across 2 files

Confidence score: 4/5

  • A cold wildcard import from providers.py omits ChatGoogleGenerativeAI, which can break consumers relying on that legacy export. Add it to the lazy hook’s __all__.
  • A cold wildcard import from clients.py silently 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

Comment on lines +46 to +49
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}')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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>
Suggested change
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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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>

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Folding batch (2026-11-04): this branch's tip was merged into the survivor PR #24477 (feat/cv1-release-safety), which now carries origin/main plus all sixteen folded branches; pushed as 88c7ec5. Both sides' conflict intents were preserved (main's evolved implementations win where a successor of the same intent had already landed). Closing here so the batch lives on one PR. Reopen if something you need is missing from the survivor.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

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:

  • 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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant