Repository navigation
fix(backend): unwedge Backend Unit Tests after the customer-Firestore split (#11531) - #11535
Conversation
… credentials
`is_desktop_trial_paywalled` passed `get_customer_firestore_client()` as an
argument, so Python resolved the customer Firestore client before the function
could apply the two guards that need no Firestore at all: the trial paywall is
off by default (`TRIAL_PAYWALL_ENABLED=false`) and mobile platforms are never
gated. Every desktop request therefore initialized credentials to compute an
answer it already had, and an environment without ambient ADC got an exception
out of `/v1/screen-activity/sync` instead of "not paywalled" — CI saw it as
`BlockedNetworkError: Blocked outbound network connection to ('169.254.169.254', 80)`
in `test_desktop_screen_crisp`. Before #11522 these routes did no credential
work here.
Run the cheap guards first; the client is resolved only when a Firestore
decision is actually required.
Verified: with `_build_customer_firestore_client` raising (no credentials),
POST /v1/screen-activity/sync through the real router returns 200
{"synced":1,"last_id":7}; on the parent commit the same request raises.
`bash test.sh` over test_paywall_reconnect_gate.py + test_desktop_screen_crisp.py
-> 34 and 6 passed.
Failure-Class: new
…tore split #11522 added `from database._client import get_customer_firestore_client` to `utils.subscription` and `firestore_client=` / `provision=` routing kwargs on the entitlement lookups. Eight unit files still described the old shape, and the `Backend Unit Tests` lane is path-filtered on `backend/**`, so the desktop-only commits merged after it never re-ran it and main stayed red. - Import-isolation stubs (`memory_import_isolation.make_database_client_stub` and the file-local stub in `test_users_add_sample_transaction`) build a synthetic `database._client` with `get_firestore_client` only, so importing `database.users` raised `ImportError: cannot import name 'get_customer_firestore_client'` at fixture setup. Export it from both. - `test_byok_security` pinned `is_byok_active('byok-user-uid')`; the call now carries the routing kwarg. - `test_neo_desktop_grandfather` monkeypatched the entitlement lookups with single-arg lambdas. The `TypeError` was swallowed by the fail-open `except` in `_is_trial_expired_cached`, so the failure surfaced one step downstream as a missing cache clear. Accept the kwargs. - `test_paywall_reconnect_gate` asserted the exact literal `_is_trial_expired_cached(uid)` and `assert_called_with('uid1')`. Assert the delegation (callee and uid) rather than the caller's routing kwargs, which is what those tests are actually guarding. Verified: `BACKEND_UNIT_TEST_FILE_LIST=<the 9 CI failures> bash test.sh` -> 216 passed, exit 0 (same list was 9/9 red on main at 6083f7d). Failure-Class: none
There was a problem hiding this comment.
2 issues found across 7 files
Confidence score: 5/5
- In
backend/utils/subscription.py(is_trial_paywalledpath), the newly addedTRIAL_PAYWALL_ENABLEDand desktop-token guards duplicate checks already done earlier, which increases drift risk if one copy changes and the other doesn’t—remove the duplicate branch or centralize the guard in one place. - In
backend/tests/unit/test_byok_security.py, the assertion thatenforce_chat_quotaforwardsfirestore_client=Nonetois_byok_activeover-constrains internal routing behavior, so harmless refactors could fail tests without changing behavior—relax this to delegation/behavior-focused assertions instead.
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/subscription.py">
<violation number="1" location="backend/utils/subscription.py:956">
P3: The two guards added here (`TRIAL_PAYWALL_ENABLED` and the `_TRIAL_PAYWALL_DESKTOP_TOKENS` platform check) are exact copies of the guards already at the top of `is_trial_paywalled` (subscription.py:287-289). That coupling means a future change to either condition — e.g. renaming/replacing `_TRIAL_PAYWALL_DESKTOP_TOKENS` or adding a second enable flag — must be mirrored in both functions or the desktop wrapper silently diverges from the gate it wraps. Extract the two checks into a single shared helper (e.g. `_is_desktop_trial_gate_applicable(platform)`) used by both `is_desktop_trial_paywalled` and `is_trial_paywalled`, so the pre-Firestore short-circuit and the gate itself can never drift.</violation>
</file>
<file name="backend/tests/unit/test_byok_security.py">
<violation number="1" location="backend/tests/unit/test_byok_security.py:337">
P3: This assertion documents that `enforce_chat_quota` passes `firestore_client=None` to `is_byok_active`, which pins the caller's routing kwarg — the opposite of the delegation-style assertions the rest of this PR adopts (e.g. `call_args.args == ('uid1',)`). It will fail spuriously if the call site stops passing the kwarg. Assert only the delegated callee and uid, matching the pattern used in test_paywall_reconnect_gate.py.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| initializes credentials, so a disabled paywall or a non-desktop platform must | ||
| neither pay for that nor require ambient ADC to answer "not paywalled". | ||
| """ | ||
| if not TRIAL_PAYWALL_ENABLED: |
There was a problem hiding this comment.
P3: The two guards added here (TRIAL_PAYWALL_ENABLED and the _TRIAL_PAYWALL_DESKTOP_TOKENS platform check) are exact copies of the guards already at the top of is_trial_paywalled (subscription.py:287-289). That coupling means a future change to either condition — e.g. renaming/replacing _TRIAL_PAYWALL_DESKTOP_TOKENS or adding a second enable flag — must be mirrored in both functions or the desktop wrapper silently diverges from the gate it wraps. Extract the two checks into a single shared helper (e.g. _is_desktop_trial_gate_applicable(platform)) used by both is_desktop_trial_paywalled and is_trial_paywalled, so the pre-Firestore short-circuit and the gate itself can never drift.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/subscription.py, line 956:
<comment>The two guards added here (`TRIAL_PAYWALL_ENABLED` and the `_TRIAL_PAYWALL_DESKTOP_TOKENS` platform check) are exact copies of the guards already at the top of `is_trial_paywalled` (subscription.py:287-289). That coupling means a future change to either condition — e.g. renaming/replacing `_TRIAL_PAYWALL_DESKTOP_TOKENS` or adding a second enable flag — must be mirrored in both functions or the desktop wrapper silently diverges from the gate it wraps. Extract the two checks into a single shared helper (e.g. `_is_desktop_trial_gate_applicable(platform)`) used by both `is_desktop_trial_paywalled` and `is_trial_paywalled`, so the pre-Firestore short-circuit and the gate itself can never drift.</comment>
<file context>
@@ -947,7 +947,16 @@ def enforce_desktop_chat_quota(uid: str, platform: Optional[str] = None) -> None
+ initializes credentials, so a disabled paywall or a non-desktop platform must
+ neither pay for that nor require ambient ADC to answer "not paywalled".
+ """
+ if not TRIAL_PAYWALL_ENABLED:
+ return False
+ if not platform or platform.lower() not in _TRIAL_PAYWALL_DESKTOP_TOKENS:
</file context>
|
|
||
| enforce_chat_quota('byok-user-uid') | ||
| mock_users_db.is_byok_active.assert_called_once_with('byok-user-uid') | ||
| mock_users_db.is_byok_active.assert_called_once_with('byok-user-uid', firestore_client=None) |
There was a problem hiding this comment.
P3: This assertion documents that enforce_chat_quota passes firestore_client=None to is_byok_active, which pins the caller's routing kwarg — the opposite of the delegation-style assertions the rest of this PR adopts (e.g. call_args.args == ('uid1',)). It will fail spuriously if the call site stops passing the kwarg. Assert only the delegated callee and uid, matching the pattern used in test_paywall_reconnect_gate.py.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_byok_security.py, line 337:
<comment>This assertion documents that `enforce_chat_quota` passes `firestore_client=None` to `is_byok_active`, which pins the caller's routing kwarg — the opposite of the delegation-style assertions the rest of this PR adopts (e.g. `call_args.args == ('uid1',)`). It will fail spuriously if the call site stops passing the kwarg. Assert only the delegated callee and uid, matching the pattern used in test_paywall_reconnect_gate.py.</comment>
<file context>
@@ -334,7 +334,7 @@ def test_enforce_chat_quota_bypasses_for_byok_with_openai_key(self, mock_users_d
enforce_chat_quota('byok-user-uid')
- mock_users_db.is_byok_active.assert_called_once_with('byok-user-uid')
+ mock_users_db.is_byok_active.assert_called_once_with('byok-user-uid', firestore_client=None)
@patch('utils.byok.get_byok_key', return_value=None)
</file context>
| mock_users_db.is_byok_active.assert_called_once_with('byok-user-uid', firestore_client=None) | |
| mock_users_db.is_byok_active.assert_called_once() | |
| assert mock_users_db.is_byok_active.call_args.args == ('byok-user-uid',) |
…ds (#11529) ## Summary - Follow-up to #11522: thumbs stay visible on a just-finished reply, but the rating PATCH waits until journal sync so a 404 cannot wipe the optimistic rating. - Failed journal turns keep a local-only rating and never PATCH a missing backend row. Clearing thumbs before sync now still PATCHes after the remote id lands (a queued `nil` is not treated as a missing map entry). - Last write wins while sync is in flight; the queue flushes when the journal projection lands a remote id. The dual-client quota stub repair from #11522 landed separately in #11535, so this PR is desktop-only. ## Test plan - [x] `cd desktop/macos && ./scripts/dev-feedback.py --once swift 'ChatMessageRatingPersistenceTests'` — 8 tests passed - [ ] Named-bundle check: send a chat, tap thumbs on the live tail before the backend id appears, confirm the rating sticks after sync ## Product invariants - INV-CHAT-1 - INV-AUTH-1 Failure-Class: none
…s isolation fixtures (#11633) ## What Five backend unit files have been failing on `main` since `6316415534` (merged today, 14:44 UTC) with the same error: ``` ModuleNotFoundError: No module named 'utils.memory.retraction_scope' ``` - `tests/unit/test_batch_upload_storage.py` - `tests/unit/test_conversation_events_bounds.py` - `tests/unit/test_conversation_search_date_validation.py` - `tests/unit/test_conversations_date_range_validation.py` - `tests/unit/test_merge_validation.py` Red lane on `main`: [run 31890773063](https://github.com/BasedHardware/omi/actions/runs/31890773063). ## Why PR #11627 added a new module, `utils/memory/retraction_scope.py`, and imported it from both `utils/conversations/merge_conversations.py:25` and `routers/conversations.py:51`. All five files load their module under test through the `stub_modules` + `load_module_fresh` isolation seam, and each stubs `utils.memory` as a package with an empty `__path__` plus a hand-listed set of submodules (`memory_service`, `memory_system`, `canonical_activation`). An empty `__path__` means any submodule that is *not* on that list cannot resolve at all — so the new import fails at fixture setup rather than falling through to the real module. Nothing in these five files exercises retraction; they cover audio-copy helpers, merge validation, event index bounds, and search/date validation. The stubs simply had not caught up with a new import in the graph they load. ## Fix Register a `utils.memory.retraction_scope` stub in each fixture, in that file's local idiom, exposing only the symbols its importer binds: - the two `merge_conversations` loaders get `canonical_intake_is_fenced`, `historical_source_conversation_ids`, `retraction_can_be_skipped` - the three `routers.conversations` loaders get `retraction_can_be_skipped` Test files only — no production code changes, and no assertion in any of the five was touched. ## On #11531 The issue's original cause (the customer-Firestore split, #11522) was fixed by #11535 and the issue was left open. Verified at `6316415534` that all nine files it named now pass: ``` BACKEND_UNIT_TEST_FILE_LIST=<the 9 files> bash test.sh -> 34 passed in 23.52s ``` The lane was red again for the unrelated cause above. With this change the lane is green, so the issue's condition is resolved. ## Tested ``` # the 5 failing files, before the fix (reproduced locally at 6316415) -> ModuleNotFoundError: No module named 'utils.memory.retraction_scope' in all 5 # after BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-fail5.txt bash test.sh -> 40 + 9 + 9 + 23 + 27 = 108 passed # full backend unit suite bash test.sh -> the 5 files pass. 14 other files fail; the identical 14 fail on unmodified main (stashed, same runner, same machine), so none are attributable to this diff. test_sync_v2.py failed only under full-suite parallel load and passes standalone (168 passed) both before and after. black --line-length 120 --skip-string-normalization --check -> 5 files would be left unchanged scripts/pr-preflight --pr-body-file <this body> -> PR preflight passed: 24 checks in 117.98s (includes backend-module-isolation, backend-import-purity) ``` Local runner is Python 3.12 / pytest 9.1.1 against CI's 3.11 / 8.4.1, which accounts for some of the 14 pre-existing local failures. ## Follow-up (not in this PR) This is the second time in two weeks that a new import into the conversations/memory graph broke hand-listed stub sets (#11531 was the same shape). The durable fix is to derive the stub set rather than hand-list it — e.g. letting a stubbed package auto-provide `AutoMockModule` submodules instead of failing on an empty `__path__`. That is a change to the shared `testing/import_isolation.py` seam with a much wider blast radius than a red-lane repair, so it is deliberately left out here. Auto-generated from issue feedback by the mini issues-improver — tested and merged. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/11633?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Bug
Backend Unit Testshas been red onmainsince0a8d0ffe98(#11522) — 9 unit files fail (run 31753492154). The lane is path-filtered onbackend/**, so the desktop-only commits merged after it (00cc9ed9,6083f7de) never re-ran it and the red state is still live. Filed as #11531. Reproduced locally at6083f7de58with the CI runner: same 9 files.Root cause
#11522 added
from database._client import get_customer_firestore_clienttoutils/subscription.pyplusfirestore_client=/provision=routing kwargs on the entitlement lookups. Three distinct consequences:memory_import_isolation.make_database_client_stuband the file-local stub intest_users_add_sample_transactionbuild a syntheticdatabase._clientwithget_firestore_clientonly, so importingdatabase.users→utils.subscriptionraisesImportError: cannot import name 'get_customer_firestore_client' from 'database._client' (unknown location)at fixture setup (5 files).test_byok_security,test_paywall_reconnect_gate,test_neo_desktop_grandfather(3 files). In the last one the resultingTypeErroris swallowed by the fail-openexceptin_is_trial_expired_cached, so it surfaced one step downstream as a missing cache clear.is_desktop_trial_paywalledresolves the customer client before the guards that make it unnecessary — argument evaluation callsget_customer_firestore_client()first, even thoughTRIAL_PAYWALL_ENABLEDdefaults tofalseand mobile is never gated. Any environment without ambient ADC gets an exception out of/v1/screen-activity/syncinstead of "not paywalled"; CI sawBlockedNetworkError: Blocked outbound network connection to ('169.254.169.254', 80)intest_desktop_screen_crisp. These routes did no credential work here before fix(desktop): align chat tool calls and keep HTTP 402 honest through worker recycle #11522.Fix
is_desktop_trial_paywalledapplies the Firestore-free guards (paywall enabled, desktop platform) before resolving the customer client — production behavior is unchanged when the gate does apply.database._clientstubs exportget_customer_firestore_client.TestDesktopTrialGateClientResolutionfails if the desktop gate resolves the customer client when the paywall is off or the platform is mobile.Verified
BACKEND_UNIT_TEST_FILE_LIST=<the 9 CI failures> bash test.sh→ 216 passed, exit 0. The identical command onmainat6083f7de58fails all 9 files._build_customer_firestore_clientraising):POST /v1/screen-activity/syncthrough the real router returns 200{"synced":1,"last_id":7}; on the parent commit the same request raisesRuntimeErrorout of the admission gate.backend/test.shlocally.Failure class
New class
FC-credentialed-dependency-resolved-before-guard, added in this PR: a caller resolved a credentialed dependency in argument position, ahead of the guards that decide the answer without it. Guard artifact:backend/tests/unit/test_paywall_reconnect_gate.py::TestDesktopTrialGateClientResolution. The test-repair commit declaresnone.Failure-Class: new
🤖 automated by hourly watchdog — tested and merged