Skip to content

fix(backend): defer the client_processing import that breaks unrelated test collection - #12785

Merged
undivisible merged 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/12779-lazy-client-processing-import
Sep 5, 2026
Merged

undivisible merged 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/12779-lazy-client-processing-import

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes the collection failure that has had main's Backend unit suite red across several commits and is blocking unrelated PRs. Tracked in #12779.

The failure

ModuleNotFoundError: No module named 'models.client_processing'
utils/conversations/projection_payload.py:19

ERROR tests/unit/test_batch_upload_storage.py
ERROR tests/unit/test_merge_validation.py

utils/conversations/projection_payload.py imported models.client_processing at module scope. Seven suites under tests/unit replace sys.modules['models'] with a bare stub:

test_sync_silent_failure.py      test_sync_v2.py            test_sync_pcm_decode.py
test_payment_promotion_codes.py  test_sync_opus_decode.py   test_conversation_jit_processing.py
test_sync_cloud_tasks.py

While one of those stubs is installed, collecting any later module that reaches projection_payload fails. The error then lands on a different test file than the one that caused it, which is why it reads as a broken suite rather than as leaked global state.

The fix

Defer the import into strip_client_processing, its only consumer. The name resolves at call time, by which point the stub is torn down.

This is what the module already claimed to be. Its docstring says it lives outside process_conversation precisely so that importing it "must not drag in the coordinator's module graph" — a module-scope import of a models submodule is the same mistake one level down.

Why not fix the polluting tests instead. There are seven today and nothing stops an eighth. Each would need its own teardown audit, and the failure only appears in whole-suite ordering, so a regression would be invisible until CI went red again on someone else's PR. Deferring the import removes the ordering dependency at the single point that has it.

Verification

Every polluter, paired with the two suites that were erroring — all now collect and run:

polluter result
test_sync_silent_failure 112 passed
test_payment_promotion_codes 87 passed
test_sync_cloud_tasks 158 passed
test_sync_v2 236 passed
test_conversation_jit_processing 96 passed
test_sync_opus_decode / test_sync_pcm_decode collect and run

Before this change the same pairings produce 40 collection errors.

Suites covering the changed module are unchanged: test_client_processing_acceptance 27, test_client_processing_trust_boundary 41, test_process_conversation_usage_context 53.

The regression test is mutation-checked. Restoring the module-scope import fails it with the exact production error at the exact line. It installs the same bare models stub the polluting suites use and imports through a fresh module object, so it exercises the real mechanism rather than asserting on source text.

One detail worth keeping: the test also evicts models.client_processing from sys.modules. Without that a cached submodule satisfies the import regardless of the stub's __path__, and the test passes with or without the fix — my first version did exactly that and the mutation check caught it.

Two honest notes

This does not prove CI goes green. Update — CI has now confirmed it. The Backend unit suite on this head is green in 3m29s (run 33961213829), with 1072 backend unit test files selected and zero occurrences of No module named 'models.client_processing' in the log. The same required check is red with that exact error on every other open PR right now. I could not reproduce CI's ordering locally, so I hedged here originally; the lane itself settled it.

It unmasks a second, unrelated pollution. With collection fixed, test_sync_opus_decode / test_sync_pcm_decode running before test_batch_upload_storage leak MagicMocks for utils.other.storage, producing assert 0 == 1 on upload_audio_chunks_batch. Those tests never executed before — they died at collection — so this is pre-existing breakage becoming visible, not a regression from this change. In the alphabetical order CI uses, test_batch_upload_storage sorts before both, so the direction that triggers it should not arise there; I am flagging it rather than claiming it cannot bite. Worth its own issue if it does.

Failure-Class: none

Review in cubic

utils/conversations/projection_payload.py imported models.client_processing at
module scope. Seven suites under tests/unit replace sys.modules['models'] with a
stub, and while one is installed, merely *collecting* a later module that reaches
this one dies with

  ModuleNotFoundError: No module named 'models.client_processing'
  utils/conversations/projection_payload.py:19

That is what has had main's Backend unit suite red across several commits, and it
blocks unrelated PRs: the error surfaces during collection of a different test
file, so it reads as that file being broken rather than as leaked global state.

The module's own docstring already states the intent this violated -- it exists
outside process_conversation precisely so that importing it does not drag in a
larger module graph. A module-scope import of a models submodule is the same
mistake one level down.

Deferring the import into strip_client_processing, its only consumer, removes the
ordering dependency entirely rather than chasing the seven polluters one at a
time. The name resolves at call time, by which point any stub is torn down.

Verified against every polluter -- each of the seven paired with the two suites
that were erroring now collects and runs:

  test_sync_silent_failure          112 passed
  test_payment_promotion_codes       87 passed
  test_sync_cloud_tasks             158 passed (1 unrelated failure, see below)
  test_sync_v2                      236 passed
  test_conversation_jit_processing   96 passed
  test_sync_opus_decode/pcm_decode   collect and run

Module suites unchanged: test_client_processing_acceptance 27,
test_client_processing_trust_boundary 41, test_process_conversation_usage_context 53.

The regression test drives the real mechanism -- it installs the same bare
models stub those suites use and imports through a fresh module object. It is
mutation-checked: restoring the module-scope import fails it with the exact
production error at the exact line. It also evicts models.client_processing from
sys.modules, without which a cached submodule satisfies the import and the test
passes either way.

Failure-Class: none

Co-Authored-By: Claude Opus 5 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@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

  • backend/tests/unit/test_client_processing_acceptance.py hand-rolls sys.modules snapshot/restore instead of using the repository’s memory_import_isolation.py pattern, leaving the regression test with brittle or inconsistent import isolation; adopt the shared utility.
  • backend/utils/conversations/projection_payload.py moves an import inside a function despite the project’s top-level-import rule, creating a maintainability and consistency issue; restore the module-scope import.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/utils/conversations/projection_payload.py">

<violation number="1" location="backend/utils/conversations/projection_payload.py:58">
P2: This adds a function-scoped import, which breaks the AGENTS.md critical rule "All imports at module top level, never inside functions." The module-scope import it replaced complied with that rule, and models/client_processing is lightweight (typing/pydantic only), so deferring it does not serve the module's stated goal of avoiding the coordinator's module graph. The actual fix should be correcting the seven tests that mutate sys.modules at module scope (itself an AGENTS.md violation), not adding a production-code import inside a function to mask the symptom. Leaving the polluting tests unfixed means this collection-time race can resurface for any other module that imports `models` at top level.</violation>
</file>

<file name="backend/tests/unit/test_client_processing_acceptance.py">

<violation number="1" location="backend/tests/unit/test_client_processing_acceptance.py:1158">
P2: This regression test hand-rolls sys.modules snapshot/restore to stub `models` and re-import the target module. The repo explicitly replaced that pattern: `memory_import_isolation.py` (hand-rolled snapshot/restore) is deprecated, and the sanctioned seam is `testing.import_isolation.stub_modules` with `load_module_fresh` (see backend/docs/test_isolation.md and AGENTS.md "Sanctioned seams"). Rewriting the body with the helper is stricter: it also clears parent-package attributes, and evicts/restores any backend-owned modules loaded inside the block so a stub-fed copy never leaks to subsequent files - something the hand-rolled `finally` here does not guarantee (it pops `utils.conversations.projection_payload` but leaves the `utils.conversations` package attribute pointing at the stub-era module until the trailing re-import).</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

# earlier test has stubbed the `models` package in sys.modules -- seven suites in
# tests/unit currently do. The import then resolves at call time, by which point
# the stub is long torn down. See #12779.
from models.client_processing import PROJECTION_FAMILY_FIELDS

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 adds a function-scoped import, which breaks the AGENTS.md critical rule "All imports at module top level, never inside functions." The module-scope import it replaced complied with that rule, and models/client_processing is lightweight (typing/pydantic only), so deferring it does not serve the module's stated goal of avoiding the coordinator's module graph. The actual fix should be correcting the seven tests that mutate sys.modules at module scope (itself an AGENTS.md violation), not adding a production-code import inside a function to mask the symptom. Leaving the polluting tests unfixed means this collection-time race can resurface for any other module that imports models at top level.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/conversations/projection_payload.py, line 58:

<comment>This adds a function-scoped import, which breaks the AGENTS.md critical rule "All imports at module top level, never inside functions." The module-scope import it replaced complied with that rule, and models/client_processing is lightweight (typing/pydantic only), so deferring it does not serve the module's stated goal of avoiding the coordinator's module graph. The actual fix should be correcting the seven tests that mutate sys.modules at module scope (itself an AGENTS.md violation), not adding a production-code import inside a function to mask the symptom. Leaving the polluting tests unfixed means this collection-time race can resurface for any other module that imports `models` at top level.</comment>

<file context>
@@ -51,6 +49,14 @@ def strip_client_processing(payload: dict[str, Any]) -> dict[str, Any]:
+    # earlier test has stubbed the `models` package in sys.modules -- seven suites in
+    # tests/unit currently do. The import then resolves at call time, by which point
+    # the stub is long torn down. See #12779.
+    from models.client_processing import PROJECTION_FAMILY_FIELDS
+
     for field in PROJECTION_FAMILY_FIELDS:
</file context>

import importlib
from types import ModuleType

saved = sys.modules.get('models')

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 regression test hand-rolls sys.modules snapshot/restore to stub models and re-import the target module. The repo explicitly replaced that pattern: memory_import_isolation.py (hand-rolled snapshot/restore) is deprecated, and the sanctioned seam is testing.import_isolation.stub_modules with load_module_fresh (see backend/docs/test_isolation.md and AGENTS.md "Sanctioned seams"). Rewriting the body with the helper is stricter: it also clears parent-package attributes, and evicts/restores any backend-owned modules loaded inside the block so a stub-fed copy never leaks to subsequent files - something the hand-rolled finally here does not guarantee (it pops utils.conversations.projection_payload but leaves the utils.conversations package attribute pointing at the stub-era module until the trailing re-import).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_client_processing_acceptance.py, line 1158:

<comment>This regression test hand-rolls sys.modules snapshot/restore to stub `models` and re-import the target module. The repo explicitly replaced that pattern: `memory_import_isolation.py` (hand-rolled snapshot/restore) is deprecated, and the sanctioned seam is `testing.import_isolation.stub_modules` with `load_module_fresh` (see backend/docs/test_isolation.md and AGENTS.md "Sanctioned seams"). Rewriting the body with the helper is stricter: it also clears parent-package attributes, and evicts/restores any backend-owned modules loaded inside the block so a stub-fed copy never leaks to subsequent files - something the hand-rolled `finally` here does not guarantee (it pops `utils.conversations.projection_payload` but leaves the `utils.conversations` package attribute pointing at the stub-era module until the trailing re-import).</comment>

<file context>
@@ -1134,3 +1134,57 @@ def test_rejected_payload_provenance_is_sanitized_single_line(monkeypatch, stack
+    import importlib
+    from types import ModuleType
+
+    saved = sys.modules.get('models')
+    saved_module = sys.modules.pop('utils.conversations.projection_payload', None)
+    # Also evict the submodule. Leaving it cached makes this test vacuous: a cached
</file context>

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

Verdict: approve

Correct root fix for #12779. Module-scope from models.client_processing import PROJECTION_FAMILY_FIELDS broke collection whenever any suite stubbed sys.modules['models'] with empty __path__. Deferring the import into strip_client_processing matches this module’s import-light contract; the new regression test stubs that exact shape and proves collection/import survive.

Not merging Jules fluff — this unblocks main’s Backend unit suite and related PRs (#12748 etc.).

@undivisible
undivisible merged commit 9410282 into BasedHardware:main Sep 5, 2026
38 checks passed
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Sep 6, 2026
Merged current main, which clears the red Backend unit suite: both failures were
ModuleNotFoundError: No module named 'models.client_processing' in files this PR
does not touch, reproducing at this PR's base commit and fixed on main by BasedHardware#12785.

Also takes the reviewer's second non-blocking note. A page that spends its whole
needed + slack budget mid-hidden-run returns short, and a caller cannot tell that
apart from end-of-data. A bounded scan cannot design that edge away -- it can only
make it observable -- so the loop now logs when it stopped on its own ceiling
rather than on the end of the collection, with the offset, limit, scanned count
and budget needed to tell whether the slack is wrong for that account.

The guard is exact: scanned >= scan_budget AND the page is unfilled. Warning on
every short page would report ordinary end-of-data as a budget failure and make
the signal worthless, so both directions are pinned by test and mutation-checked
-- making the condition unconditional fails the quiet test, and downgrading the
log fails the loud one.

9 tests pass in test_get_memories_scoring_visibility_pagination.py. The parity
contract passes 8/8 on this head; main's version of that file fails 1 of the same
8, which this PR's pin update is what fixes.
kodjima33 pushed a commit that referenced this pull request Sep 6, 2026
* fix(backend): fill scoring memory pages past hidden rows

Failure-Class: new

scoring_desc applied Firestore limit/offset before the Python visibility
filter, so rejected/invalidated rows shortened pages and skipped later
visible memories. Scan with a bounded budget until the visible page fills.

* fix(backend): bound the visible-page slack and update the parity pin

Three review items, all real.

Parity contract (blocking). test_python_memory_query_and_filter_semantics pinned
limit_value == data["limit"] and offset_value == data["offset"] -- that a raw
Firestore limit/offset was applied to the scoring stream. That is the defect
itself: limit/offset applied before user_review / invalid_at were filtered in
Python, so a hidden row inside the raw page stole a visible slot. Keeping the pin
would pin the bug. It now asserts the visible-page contract: no raw offset at
all, and a first read of exactly the documents the page needs.

The old result assertion (["active"]) passed only because the fake recorded
offset_value without applying it. With real visible-offset semantics the
fixture's offset of 4 is past the only visible row, so the correct page is empty.
Visibility filtering is now pinned separately at offset 0, where it is reachable.

Read cost. The budget floored at max(100, ...) and the first batch was a flat
min(100, budget), so every small page streamed 100 full documents on an endpoint
with a documented 504 history (#11831). A page with nothing hidden needs exactly
offset + limit documents, which is what the old raw query streamed, so the budget
now floors there and the first batch reads exactly that.

Truncation at depth. Capping the *total* scan at 2000 meant offset + limit past
the cap could never be reached and the page came back empty, which callers read
as end-of-data -- the same defect at a deeper boundary. Flooring the budget at
the page fixes it.

The slack above the floor is flat rather than proportional. Scaling it with the
page size gave a small page a six-document allowance, so a dense run of hidden
rows still returned an empty page; the new multi-batch test caught that. Read
cost is set by the batch sizing, not by this ceiling, so a flat allowance costs a
clean page nothing.

Tests: a dense block of 150 hidden rows now forces the start_after continuation
that no earlier fixture reached, plus clean-page read cost, deep offset, and
bounded slack. Dropped the ineffective _prepare_memory_for_read patch --
@prepare_for_read binds the original into its closure at decoration time, so
patching the module attribute never changed decryption.

Failure-Class: new

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(backend): keep the registry edit inside what an instance fix may change

The merge resolution rewrote the shared failure-class record: violated_contract
wording, canonical_prevention, scope_hints and evidence_prs, on top of adding
this PR's test. scripts/failure-class rejects that, correctly:

  instance_fix_mutates_registry: an instance-fix PR must not edit failure-class
  definitions except to add or update 'canonical_prevention_artifact' on the
  declared class

The rule is sound. An instance PR quietly rewriting shared contract text is how
a registry stops meaning the same thing to everyone who greps it.

So the record is now main's byte for byte, plus this instance's guard appended to
canonical_prevention_artifact -- the one field an instance fix owns. The wider
edits (wording that names both hidden-row kinds, memories scope_hints, evidence_prs
citing 12712 and 12714) belong in a registry-only lifecycle PR.

Also corrects the declaration from 'new' to the class id: #12712 merged while this
was in review and landed the definition, so this is the second recorded instance of
an existing class, not its birth.

scripts/failure-class validate: OK (declaration=FC-raw-page-limit-before-visibility-filter).

* fix(backend): make a budget-exhausted memories page visible in logs

Merged current main, which clears the red Backend unit suite: both failures were
ModuleNotFoundError: No module named 'models.client_processing' in files this PR
does not touch, reproducing at this PR's base commit and fixed on main by #12785.

Also takes the reviewer's second non-blocking note. A page that spends its whole
needed + slack budget mid-hidden-run returns short, and a caller cannot tell that
apart from end-of-data. A bounded scan cannot design that edge away -- it can only
make it observable -- so the loop now logs when it stopped on its own ceiling
rather than on the end of the collection, with the offset, limit, scanned count
and budget needed to tell whether the slack is wrong for that account.

The guard is exact: scanned >= scan_budget AND the page is unfilled. Warning on
every short page would report ordinary end-of-data as a budget failure and make
the signal worthless, so both directions are pinned by test and mutation-checked
-- making the condition unconditional fails the quiet test, and downgrading the
log fails the loud one.

9 tests pass in test_get_memories_scoring_visibility_pagination.py. The parity
contract passes 8/8 on this head; main's version of that file fails 1 of the same
8, which this PR's pin update is what fixes.

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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.

2 participants