|
| 1 | +"""GET /v2/apps/search must read the approved+public app set through the shared Redis cache. |
| 2 | +
|
| 3 | +Prod signature (api.omi.me load-balancer logs, 2026-08-18/19, image c5b0b5d): `?q=<term>` searches |
| 4 | +ran p50 13.4s / p90 30.0s and 24 of 29 requests exceeded 5s, most terminating as 504 at the 30s |
| 5 | +edge — app search was effectively unusable in the mobile Apps tab. `installed_apps=true` requests |
| 6 | +served by the same branch (>30 enabled apps) carried the same tail; the `id in [...]` fast path |
| 7 | +sat at p50 0.15s. |
| 8 | +
|
| 9 | +Root cause: `search_apps_db` streamed `approved==True AND private==False` from Firestore on every |
| 10 | +request. That is 3,247 documents / ~25MB in prod. The marketplace list path |
| 11 | +(`utils.apps.get_approved_available_apps`) already serves exactly those documents from a 10-minute |
| 12 | +Redis cache under `get_public_approved_apps_data`; search was the one reader that bypassed it. |
| 13 | +
|
| 14 | +These tests drive the real route over HTTP with only the Firestore client and the Redis cache |
| 15 | +helpers stubbed, so the router, `search_apps_db` and the cache read all execute. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import os |
| 21 | + |
| 22 | +os.environ.setdefault('OPENAI_API_KEY', 'sk-test-not-real') |
| 23 | +os.environ.setdefault('ENCRYPTION_SECRET', 'omi_ZwB2ZNqB2HHpMK6wStk7sTpavJiPTFg7gXUHnc4tFABPU6pZ2c2DKgehtfgi4RZv') |
| 24 | + |
| 25 | +import pytest # noqa: E402 |
| 26 | +from fastapi import FastAPI # noqa: E402 |
| 27 | +from fastapi.testclient import TestClient # noqa: E402 |
| 28 | + |
| 29 | +from database import apps as apps_db # noqa: E402 |
| 30 | +from routers import apps as apps_mod # noqa: E402 |
| 31 | + |
| 32 | +UID = 'uid-apps-search' |
| 33 | + |
| 34 | + |
| 35 | +def _app_doc(app_id: str, name: str, **overrides): |
| 36 | + doc = { |
| 37 | + 'id': app_id, |
| 38 | + 'name': name, |
| 39 | + 'category': 'productivity', |
| 40 | + 'author': 'Someone', |
| 41 | + 'description': f'{name} description', |
| 42 | + 'image': 'http://img', |
| 43 | + 'capabilities': ['chat'], |
| 44 | + 'approved': True, |
| 45 | + 'private': False, |
| 46 | + 'uid': 'author-uid', |
| 47 | + # Excluded by App.reduce_dict — present on the Firestore document, absent from the cache. |
| 48 | + 'chat_prompt': 'x' * 128, |
| 49 | + 'memory_prompt': 'y' * 128, |
| 50 | + } |
| 51 | + doc.update(overrides) |
| 52 | + return doc |
| 53 | + |
| 54 | + |
| 55 | +class _FakeDoc: |
| 56 | + def __init__(self, data): |
| 57 | + self._data = data |
| 58 | + |
| 59 | + def to_dict(self): |
| 60 | + return dict(self._data) |
| 61 | + |
| 62 | + |
| 63 | +class _FakeQuery: |
| 64 | + def __init__(self, collection, docs): |
| 65 | + self._collection = collection |
| 66 | + self._docs = docs |
| 67 | + |
| 68 | + def stream(self): |
| 69 | + self._collection.streams += 1 |
| 70 | + return [_FakeDoc(d) for d in self._docs] |
| 71 | + |
| 72 | + |
| 73 | +class _FakeCollection: |
| 74 | + """Streams every seeded document; the point of the assertions is *whether* it is streamed.""" |
| 75 | + |
| 76 | + def __init__(self, docs): |
| 77 | + self.docs = docs |
| 78 | + self.streams = 0 |
| 79 | + |
| 80 | + def where(self, filter=None): # noqa: A002 - matches the firestore kwarg |
| 81 | + return _FakeQuery(self, self.docs) |
| 82 | + |
| 83 | + |
| 84 | +class _FakeFirestore: |
| 85 | + def __init__(self, docs): |
| 86 | + self.collection_obj = _FakeCollection(docs) |
| 87 | + |
| 88 | + def collection(self, _name): |
| 89 | + return self.collection_obj |
| 90 | + |
| 91 | + |
| 92 | +@pytest.fixture |
| 93 | +def env(monkeypatch): |
| 94 | + """Real router + real search_apps_db; only Firestore and the Redis cache are stubbed.""" |
| 95 | + docs = [_app_doc('a1', 'Todoist'), _app_doc('a2', 'Grok'), _app_doc('a3', 'Calendar Sync')] |
| 96 | + firestore = _FakeFirestore(docs) |
| 97 | + cache: dict[str, object] = {} |
| 98 | + |
| 99 | + monkeypatch.setattr(apps_db, 'db', firestore) |
| 100 | + # raising=False so the control run against the pre-fix source still executes and fails on the |
| 101 | + # behavioural assertion (a Firestore stream per request) rather than erroring at setup. |
| 102 | + monkeypatch.setattr(apps_db, 'get_generic_cache', lambda key: cache.get(key), raising=False) |
| 103 | + monkeypatch.setattr( |
| 104 | + apps_db, 'set_generic_cache', lambda key, data, ttl=None: cache.__setitem__(key, data), raising=False |
| 105 | + ) |
| 106 | + monkeypatch.setattr(apps_mod, 'get_enabled_apps', lambda uid: set()) |
| 107 | + monkeypatch.setattr(apps_mod, 'get_apps_installs_count', lambda ids: {}) |
| 108 | + monkeypatch.setattr(apps_mod, 'get_apps_reviews', lambda ids: {}) |
| 109 | + |
| 110 | + app = FastAPI() |
| 111 | + app.include_router(apps_mod.router) |
| 112 | + app.dependency_overrides[apps_mod.auth.get_current_user_uid] = lambda: UID |
| 113 | + |
| 114 | + class Env: |
| 115 | + client = TestClient(app) |
| 116 | + |
| 117 | + Env.firestore = firestore |
| 118 | + Env.cache = cache |
| 119 | + Env.docs = docs |
| 120 | + return Env |
| 121 | + |
| 122 | + |
| 123 | +def test_search_populates_the_shared_cache_on_a_cold_read(env): |
| 124 | + response = env.client.get('/v2/apps/search', params={'q': 'todoist', 'limit': 100}) |
| 125 | + |
| 126 | + assert response.status_code == 200 |
| 127 | + assert [a['id'] for a in response.json()['data']] == ['a1'] |
| 128 | + assert env.firestore.collection_obj.streams == 1 |
| 129 | + |
| 130 | + cached = env.cache['get_public_approved_apps_data'] |
| 131 | + assert [a['id'] for a in cached] == ['a1', 'a2', 'a3'] |
| 132 | + # Cached as reduced records, matching the marketplace list path. |
| 133 | + assert 'chat_prompt' not in cached[0] |
| 134 | + assert 'description' in cached[0] |
| 135 | + |
| 136 | + |
| 137 | +def test_warm_cache_serves_search_without_streaming_the_collection(env): |
| 138 | + assert env.client.get('/v2/apps/search', params={'q': 'grok', 'limit': 100}).status_code == 200 |
| 139 | + env.firestore.collection_obj.streams = 0 |
| 140 | + |
| 141 | + response = env.client.get('/v2/apps/search', params={'q': 'grok', 'limit': 100}) |
| 142 | + |
| 143 | + assert response.status_code == 200 |
| 144 | + assert [a['id'] for a in response.json()['data']] == ['a2'] |
| 145 | + # The regression: this is the read that cost 13s+ per request in prod. |
| 146 | + assert env.firestore.collection_obj.streams == 0 |
| 147 | + |
| 148 | + |
| 149 | +def test_default_browse_and_filters_are_served_from_the_cache(env): |
| 150 | + env.client.get('/v2/apps/search', params={'limit': 100}) |
| 151 | + env.firestore.collection_obj.streams = 0 |
| 152 | + |
| 153 | + browse = env.client.get('/v2/apps/search', params={'limit': 100}) |
| 154 | + assert [a['id'] for a in browse.json()['data']] == ['a3', 'a2', 'a1'] # name_asc default |
| 155 | + |
| 156 | + matching = env.client.get('/v2/apps/search', params={'category': 'productivity', 'limit': 100}) |
| 157 | + assert [a['id'] for a in matching.json()['data']] == ['a3', 'a2', 'a1'] |
| 158 | + other = env.client.get('/v2/apps/search', params={'category': 'entertainment', 'limit': 100}) |
| 159 | + assert other.json()['data'] == [] |
| 160 | + |
| 161 | + has_cap = env.client.get('/v2/apps/search', params={'capability': 'chat', 'limit': 100}) |
| 162 | + assert len(has_cap.json()['data']) == 3 |
| 163 | + no_cap = env.client.get('/v2/apps/search', params={'capability': 'persona', 'limit': 100}) |
| 164 | + assert no_cap.json()['data'] == [] |
| 165 | + |
| 166 | + assert env.firestore.collection_obj.streams == 0 |
| 167 | + |
| 168 | + |
| 169 | +def test_my_apps_still_reads_firestore(env): |
| 170 | + """Private/unapproved records are not in the public cache — that branch must keep querying.""" |
| 171 | + env.client.get('/v2/apps/search', params={'limit': 100}) # warm the cache |
| 172 | + env.firestore.collection_obj.streams = 0 |
| 173 | + |
| 174 | + response = env.client.get('/v2/apps/search', params={'my_apps': 'true', 'limit': 100}) |
| 175 | + |
| 176 | + assert response.status_code == 200 |
| 177 | + assert env.firestore.collection_obj.streams == 1 |
| 178 | + |
| 179 | + |
| 180 | +def test_installed_apps_under_the_in_limit_still_reads_firestore(env, monkeypatch): |
| 181 | + monkeypatch.setattr(apps_mod, 'get_enabled_apps', lambda uid: {'a1'}) |
| 182 | + env.client.get('/v2/apps/search', params={'limit': 100}) # warm the cache |
| 183 | + env.firestore.collection_obj.streams = 0 |
| 184 | + |
| 185 | + response = env.client.get('/v2/apps/search', params={'installed_apps': 'true', 'limit': 100}) |
| 186 | + |
| 187 | + assert response.status_code == 200 |
| 188 | + assert env.firestore.collection_obj.streams == 1 |
| 189 | + |
| 190 | + |
| 191 | +def test_installed_apps_over_the_in_limit_uses_the_cache_for_the_public_set(env, monkeypatch): |
| 192 | + """>30 enabled ids: the public set comes from the cache, the user's own apps still from Firestore.""" |
| 193 | + enabled = {'a1', 'a2'} | {f'x{i}' for i in range(30)} |
| 194 | + monkeypatch.setattr(apps_mod, 'get_enabled_apps', lambda uid: enabled) |
| 195 | + env.client.get('/v2/apps/search', params={'limit': 100}) # warm the cache |
| 196 | + env.firestore.collection_obj.streams = 0 |
| 197 | + |
| 198 | + response = env.client.get('/v2/apps/search', params={'installed_apps': 'true', 'limit': 100}) |
| 199 | + |
| 200 | + assert response.status_code == 200 |
| 201 | + assert sorted(a['id'] for a in response.json()['data']) == ['a1', 'a2'] |
| 202 | + # Exactly one stream: the uid-scoped query for the user's own private/unapproved apps. |
| 203 | + assert env.firestore.collection_obj.streams == 1 |
0 commit comments