diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index bfb6e75fd6c..f2487695129 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -100,35 +100,47 @@ async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> return None # Real opt-in work activates the same durable protection as mirrored sources. await session_admission.require(auth) - contributions = [] - remaining = min(top_k, settings.knowledge_live_search_max_hits) - for source in selected: - authority = await connected_accounts.resolve( - org, - source.namespace, - source.name, - deadline=deadline, - expected_source_id=source.source_id, - ) - if authority.source != source: - continue # a changed registration cannot widen the discovered corpus - - async def native( - access: CheckedAccess, - authority: connected_accounts.SourceAuthority = authority, - remaining: int = remaining, - ) -> list[live_provider_search.LiveProviderHit]: - return await live_provider_search.search( - authority.source, access, query, top_k=remaining, deadline=deadline + # Leave half the remaining request budget for account and membership revalidation. + search_deadline = (time.monotonic() + deadline) / 2 + contributions: list[Contribution] = [] + remaining = min(top_k, settings.knowledge_live_search_max_hits) + for i, source in enumerate(selected): + if remaining <= 0 or time.monotonic() >= search_deadline: + break + sources_left = len(selected) - i + quota = (remaining + sources_left - 1) // sources_left + try: + async with asyncio.timeout_at(search_deadline): + authority = await connected_accounts.resolve( + org, + source.namespace, + source.name, + deadline=search_deadline, + expected_source_id=source.source_id, ) - - hits = tuple(await authority.run(native))[:remaining] - if hits: - contributions.append(Contribution(authority, hits)) - remaining -= len(hits) - if not remaining: - break - return LiveResult(tuple(contributions), deadline) if contributions else None + if authority.source != source: + continue # a changed registration cannot widen the discovered corpus + + async def native( + access: CheckedAccess, + authority: connected_accounts.SourceAuthority = authority, + quota: int = quota, + ) -> list[live_provider_search.LiveProviderHit]: + return await live_provider_search.search( + authority.source, + access, + query, + top_k=quota, + deadline=search_deadline, + ) + + hits = tuple(await authority.run(native))[:quota] + if hits: + contributions.append(Contribution(authority, hits)) + remaining -= len(hits) + except Exception: # noqa: BLE001 - a failed provider cannot discard earlier contributions + continue + return LiveResult(tuple(contributions), deadline) if contributions else None except Exception: # noqa: BLE001 — optional private search never exposes account/provider detail return None diff --git a/tests/unit/test_live_source_search.py b/tests/unit/test_live_source_search.py index fc96c4eabc6..20ff39d78bd 100644 --- a/tests/unit/test_live_source_search.py +++ b/tests/unit/test_live_source_search.py @@ -58,6 +58,8 @@ def native(monkeypatch, request): auth=auth, source=source, sources=[source], + registrations={(source.namespace, source.name, source.source_id): source}, + hits={}, events=[], resolutions=[], authorities=[], @@ -81,6 +83,8 @@ def native(monkeypatch, request): "private excerpt", ) + state.hits[source.source_id] = [hit] + def private(stage): state.events.append(stage) assert request_work.mirror_marked() @@ -116,11 +120,11 @@ async def run(self, callback): async def resolve(org, namespace, name, *, deadline, expected_source_id): private("resolve") - assert (org, namespace, name) == ("org", "allowed", "personal") - assert expected_source_id == source.source_id + assert org == "org" + matched = state.registrations[namespace, name, expected_source_id] state.resolutions.append((namespace, name, expected_source_id, deadline)) state.deadline = deadline - authority = Authority(source) + authority = Authority(matched) state.authorities.append(authority) return authority @@ -139,8 +143,12 @@ async def search(selected, access, query, *, top_k, deadline): async def revalidate(selected, access, actual_hit, *, deadline): private("membership") - assert selected is source and access is state.access and actual_hit is hit - assert deadline == state.deadline + assert ( + selected is state.registrations[selected.namespace, selected.name, selected.source_id] + ) + assert access is state.access + assert any(actual_hit is hit for hit in state.hits[selected.source_id]) + assert deadline > state.deadline return True monkeypatch.setattr(live_search.connected_accounts, "own_subject", own_subject) @@ -184,7 +192,7 @@ async def test_live_search_keeps_only_asker_connected_authorized_sources_and_ori assert len(native.resolutions) == len(result.contributions) == 1 assert result.contributions[0].authority is native.authorities[0] assert all(hit.provider == native.source.kind for hit in result.hits) - assert result.deadline == native.deadline + assert result.deadline > native.deadline assert await live_search.publish(result) is result assert result.fresh() assert native.events[:4] == ["subject", "sources", "latch", "resolve"] @@ -220,9 +228,10 @@ async def test_linear_source_without_a_project_id_does_not_take_a_search_slot( async def test_live_search_expiry_joins_the_started_native_call(native, monkeypatch): native.block = True - monkeypatch.setattr(live_search.settings, "knowledge_live_search_timeout_s", 0) + monkeypatch.setattr(live_search.settings, "knowledge_live_search_timeout_s", 0.4) async with _request(native.auth) as bag: task = asyncio.create_task(live_search.search("org", ["allowed"], "question", top_k=2)) + await asyncio.wait_for(native.started.wait(), 1) assert await task is None assert task.done() assert native.started.is_set() and native.closed.is_set() @@ -403,3 +412,65 @@ async def test_default_filtered_and_page_calls_do_not_start_live_work(native, in assert output.live is None assert native.events == [] assert not native.started.is_set() + + +@pytest.mark.parametrize("second_times_out", [False, True]) +async def test_live_search_rebalances_quota_and_publishes_earlier_hits( + native, indexed, monkeypatch, second_times_out +): + source_two = SimpleNamespace( + **{ + **vars(native.source), + "name": "workspace", + "source_id": "second-source", + "kind": "notion", + } + ) + native.sources.append(source_two) + native.registrations[source_two.namespace, source_two.name, source_two.source_id] = source_two + native.hits[source_two.source_id] = [ + live_search.live_provider_search.LiveProviderHit( + f"hit-2-{i}", f"Second {i}", f"https://notion.so/{i}", "notion", "second" + ) + for i in range(3) + ] + seen_top_k = [] + second_started = asyncio.Event() + second_closed = asyncio.Event() + + async def two_source_search(source, access, query, *, top_k, deadline): + assert access is native.access and query == "question" + assert deadline == native.deadline + seen_top_k.append((source.source_id, top_k)) + if source is source_two: + second_started.set() + try: + if second_times_out: + await asyncio.Event().wait() + finally: + second_closed.set() + return native.hits[source.source_id] + + if second_times_out: + monkeypatch.setattr(live_search.settings, "knowledge_live_search_timeout_s", 0.5) + revalidate = live_search.live_provider_search.revalidate + + async def delayed_revalidate(source, access, hit, *, deadline): + assert second_closed.is_set() + await asyncio.sleep(0.04) + return await revalidate(source, access, hit, deadline=deadline) + + monkeypatch.setattr(live_search.live_provider_search, "revalidate", delayed_revalidate) + + monkeypatch.setattr(live_search.live_provider_search, "search", two_source_search) + request = SearchInput(org="org", namespace="allowed", query="question", top_k=4, live=True) + async with _request(native.auth): + output = await indexed.handle_search(request) + + assert second_started.is_set() and second_closed.is_set() + assert seen_top_k == [("original-source", 2), ("second-source", 3)] + assert output.live is not None + expected = ( + ["private-id"] if second_times_out else ["private-id", "hit-2-0", "hit-2-1", "hit-2-2"] + ) + assert [hit.id for hit in output.live.results] == expected