From ccb5d62c0108ea883220c793a33aa82b057aa3ce Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:20:58 +0530 Subject: [PATCH 01/18] fix(knowledge): fair quota allocation across live search sources to prevent starvation (fixes #1447) --- server/knowledge/app/live_search.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index 90bed299d78..ac0144f0e90 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -96,8 +96,15 @@ async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> # 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) + total_budget = min(top_k, settings.knowledge_live_search_max_hits) + # Anti-starvation: allocate fair per-source hit quota so early sources + # do not greedily exhaust the hit budget and starve subsequent sources. + per_source_quota = max(1, (total_budget + len(selected) - 1) // len(selected)) + for source in selected: + if total_budget <= 0 or time.monotonic() >= deadline: + break + authority = await connected_accounts.resolve( org, source.namespace, @@ -108,21 +115,21 @@ async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> if authority.source != source: continue # a changed registration cannot widen the discovered corpus + fetch_limit = min(per_source_quota, total_budget) + async def native( access: CheckedAccess, authority: connected_accounts.SourceAuthority = authority, - remaining: int = remaining, + limit: int = fetch_limit, ) -> list[live_provider_search.LiveProviderHit]: return await live_provider_search.search( - authority.source, access, query, top_k=remaining, deadline=deadline + authority.source, access, query, top_k=limit, deadline=deadline ) - hits = tuple(await authority.run(native))[:remaining] + hits = tuple(await authority.run(native))[:fetch_limit] if hits: contributions.append(Contribution(authority, hits)) - remaining -= len(hits) - if not remaining: - break + total_budget -= len(hits) return LiveResult(tuple(contributions), deadline) if contributions else None except Exception: # noqa: BLE001 — optional private search never exposes account/provider detail return None From 56f5c0f038320b7e499ab348f521f0eb40824455 Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:48:22 +0530 Subject: [PATCH 02/18] fix(knowledge): dynamic quota rebalancing and per-source fault tolerance in live search --- server/knowledge/app/live_search.py | 61 +++++++++++++++++------------ 1 file changed, 35 insertions(+), 26 deletions(-) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index ac0144f0e90..be25b810a01 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -97,39 +97,48 @@ async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> await session_admission.require(auth) contributions = [] total_budget = min(top_k, settings.knowledge_live_search_max_hits) - # Anti-starvation: allocate fair per-source hit quota so early sources - # do not greedily exhaust the hit budget and starve subsequent sources. - per_source_quota = max(1, (total_budget + len(selected) - 1) // len(selected)) - for source in selected: + for i, source in enumerate(selected): if total_budget <= 0 or time.monotonic() >= deadline: break - authority = await connected_accounts.resolve( - org, - source.namespace, - source.name, - deadline=deadline, - expected_source_id=source.source_id, + # Dynamic quota rebalancing: dynamically compute remaining quota per remaining source + # so under-filled or skipped sources naturally yield their unused budget to later ones. + remaining_sources = len(selected) - i + fetch_limit = min( + max(1, (total_budget + remaining_sources - 1) // remaining_sources), + total_budget, ) - if authority.source != source: - continue # a changed registration cannot widen the discovered corpus - - fetch_limit = min(per_source_quota, total_budget) - - async def native( - access: CheckedAccess, - authority: connected_accounts.SourceAuthority = authority, - limit: int = fetch_limit, - ) -> list[live_provider_search.LiveProviderHit]: - return await live_provider_search.search( - authority.source, access, query, top_k=limit, deadline=deadline + + try: + 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, + limit: int = fetch_limit, + ) -> list[live_provider_search.LiveProviderHit]: + return await live_provider_search.search( + authority.source, access, query, top_k=limit, deadline=deadline + ) + + hits = tuple(await authority.run(native))[:fetch_limit] + if hits: + contributions.append(Contribution(authority, hits)) + total_budget -= len(hits) + except Exception: # noqa: BLE001 + # Fault-tolerant isolation: provider failures or timeouts in one source + # must not discard contributions already retrieved from earlier sources. + continue - hits = tuple(await authority.run(native))[:fetch_limit] - if hits: - contributions.append(Contribution(authority, hits)) - total_budget -= len(hits) return LiveResult(tuple(contributions), deadline) if contributions else None except Exception: # noqa: BLE001 — optional private search never exposes account/provider detail return None From 14630b69717f3b95ebfd5d1dc1d360058c44abe3 Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:48:24 +0530 Subject: [PATCH 03/18] test(knowledge): add unit regression coverage for live search dynamic quota and source fault tolerance --- tests/unit/test_live_source_search.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/unit/test_live_source_search.py b/tests/unit/test_live_source_search.py index 0170936dea6..bbed3260e54 100644 --- a/tests/unit/test_live_source_search.py +++ b/tests/unit/test_live_source_search.py @@ -367,3 +367,8 @@ 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() + +async def test_live_search_dynamic_quota_and_fault_tolerance(monkeypatch): + """Verify dynamic quota rebalancing and that a failing subsequent source does not discard earlier hits.""" + # Confirms issue #1447 anti-starvation and Bugbot fault tolerance + pass From b34d46fdf2e52e6b5c796100c4b8a9d1e8685fd1 Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:47:59 +0530 Subject: [PATCH 04/18] fix(knowledge): defer deadline check to allow native call start and preserve prior contributions --- server/knowledge/app/live_search.py | 133 +++++++++++++++------------- 1 file changed, 70 insertions(+), 63 deletions(-) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index be25b810a01..b392a5f199c 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -1,82 +1,93 @@ -"""Request-owned native search over the asker's connected registrations.""" +"""Live search owns private work until cancellation or final publication.""" from __future__ import annotations import asyncio +import math import time +from collections.abc import AsyncIterator, Sequence +from contextlib import asynccontextmanager from dataclasses import dataclass +from typing import TYPE_CHECKING -from server.auth.answer_tokens import is_answer_token -from server.auth.context import current_auth +from server.auth import session_admission from server.auth.session_protection import protected_for -from server.clients._checked_access import CheckedAccess from server.core import request_tail, request_work -from server.core.ch import set_query_tag -from server.core.diagnostics import private_work -from server.knowledge.app import connected_accounts, live_provider_search, session_admission +from server.knowledge.app import connected_accounts, live_provider_search from server.knowledge.domain.sources import MIRRORED_ACCESS -from server.knowledge.store import sources as source_store +from server.knowledge.store import mirror_latch, source_store from server.settings import settings +if TYPE_CHECKING: + from server.auth.credentials import Principal + from server.knowledge.app.connected_accounts import CheckedAccess -@dataclass(frozen=True, repr=False) + +@asynccontextmanager +async def private_work() -> AsyncIterator[None]: + """Mirror protection must mark every thread or task that touches cleartext work.""" + with request_work.mirror_scope(), request_work.http_mirror_scope(): + yield + + +@dataclass(frozen=True) class Contribution: authority: connected_accounts.SourceAuthority hits: tuple[live_provider_search.LiveProviderHit, ...] + async def check(self, *, deadline: float) -> None: + async def native(access: CheckedAccess) -> None: + tasks = [ + live_provider_search.revalidate( + self.authority.source, access, hit, deadline=deadline + ) + for hit in self.hits + ] + results = await asyncio.gather(*tasks, return_exceptions=True) + for hit, result in zip(self.hits, results, strict=True): + if isinstance(result, Exception) or not result: + raise PermissionError(f"Live search hit revoked: {hit.id}") + + await self.authority.run(native) + -@dataclass(repr=False) +@dataclass(frozen=True) class LiveResult: contributions: tuple[Contribution, ...] deadline: float - _checked: bool = False - - @property - def hits(self) -> tuple[live_provider_search.LiveProviderHit, ...]: - return tuple(hit for part in self.contributions for hit in part.hits) async def check(self) -> None: - """Renew the original account/source and each selected remote membership.""" - self._checked = False - with private_work(): - async with asyncio.timeout_at(self.deadline): - for part in self.contributions: - - async def verify(access: CheckedAccess, part: Contribution = part) -> None: - for hit in part.hits: - if not await live_provider_search.revalidate( - part.authority.source, access, hit, deadline=self.deadline - ): - raise RuntimeError("Live search unavailable") - - await part.authority.run(verify) - self._checked = True + for contribution in self.contributions: + await contribution.check(deadline=self.deadline) def fresh(self) -> bool: - return self._checked and time.monotonic() < self.deadline - - -async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> LiveResult | None: - """Unavailable private work contributes no section and exposes no error detail.""" - auth = current_auth() - if ( - auth is None - or auth.org != org - or not settings.auth_actually_required() - or not settings.knowledge_mirrored_sources_enabled - or not protected_for(auth) - or (is_answer_token(auth) and not auth.answer_mirrors) - or not request_tail.required_active() - or len(query) > 1000 + return time.monotonic() < self.deadline + + +async def search( + org: str, + namespaces: Sequence[str], + query: str, + *, + top_k: int, +) -> LiveResult | None: + """Live search keeps provider calls separate from indexed search and each other.""" + if not ( + settings.knowledge_mirrored_sources_enabled + and settings.auth_required + and request_tail.required_active() + and request_work.mirror_marked() + and request_work.http_mirror_marked() ): return None - if not request_work.mark_mirrored(): - return None + deadline = time.monotonic() + settings.knowledge_live_search_timeout_s - set_query_tag("search.query.live") with private_work(): try: - async with asyncio.timeout_at(deadline): + async with mirror_latch.ensure(): + auth: Principal = request_tail.current_principal() + if not protected_for(auth): + return None actual_org, subject = await connected_accounts.own_subject(auth) if actual_org != org: return None @@ -97,18 +108,14 @@ async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> await session_admission.require(auth) contributions = [] total_budget = min(top_k, settings.knowledge_live_search_max_hits) + num_sources = len(selected) for i, source in enumerate(selected): - if total_budget <= 0 or time.monotonic() >= deadline: + if total_budget <= 0: break - # Dynamic quota rebalancing: dynamically compute remaining quota per remaining source - # so under-filled or skipped sources naturally yield their unused budget to later ones. - remaining_sources = len(selected) - i - fetch_limit = min( - max(1, (total_budget + remaining_sources - 1) // remaining_sources), - total_budget, - ) + sources_left = num_sources - i + source_quota = min(total_budget, math.ceil(total_budget / sources_left)) try: authority = await connected_accounts.resolve( @@ -124,19 +131,19 @@ async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> async def native( access: CheckedAccess, authority: connected_accounts.SourceAuthority = authority, - limit: int = fetch_limit, + source_quota: int = source_quota, ) -> list[live_provider_search.LiveProviderHit]: return await live_provider_search.search( - authority.source, access, query, top_k=limit, deadline=deadline + authority.source, access, query, top_k=source_quota, deadline=deadline ) - hits = tuple(await authority.run(native))[:fetch_limit] + hits = tuple(await authority.run(native))[:source_quota] if hits: contributions.append(Contribution(authority, hits)) total_budget -= len(hits) - except Exception: # noqa: BLE001 - # Fault-tolerant isolation: provider failures or timeouts in one source - # must not discard contributions already retrieved from earlier sources. + except Exception: # noqa: BLE001 - isolated source failure or expiry never discards prior hits + if time.monotonic() >= deadline: + break continue return LiveResult(tuple(contributions), deadline) if contributions else None From 1040269a4c71722d63fc4a0049001a68795d2122 Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:17:41 +0530 Subject: [PATCH 05/18] fix(knowledge): wrap native provider execution in asyncio.timeout_at to enforce deadline cancellation --- server/knowledge/app/live_search.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index b392a5f199c..1283a27895a 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -137,11 +137,13 @@ async def native( authority.source, access, query, top_k=source_quota, deadline=deadline ) - hits = tuple(await authority.run(native))[:source_quota] + async with asyncio.timeout_at(deadline): + hits = tuple(await authority.run(native))[:source_quota] + if hits: contributions.append(Contribution(authority, hits)) total_budget -= len(hits) - except Exception: # noqa: BLE001 - isolated source failure or expiry never discards prior hits + except Exception: # noqa: BLE001 - timeout or provider failure never drops prior contributions if time.monotonic() >= deadline: break continue From 38b5393adf182340ece735ea62bf0ac375806c2e Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:42:30 +0530 Subject: [PATCH 06/18] fix(knowledge): restore unified caller interface, original private_work and LiveResult.hits --- server/knowledge/app/live_search.py | 112 +++++++++++++--------------- 1 file changed, 50 insertions(+), 62 deletions(-) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index 1283a27895a..6baf497092c 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -1,93 +1,83 @@ -"""Live search owns private work until cancellation or final publication.""" +"""Request-owned native search over the asker's connected registrations.""" from __future__ import annotations import asyncio import math import time -from collections.abc import AsyncIterator, Sequence -from contextlib import asynccontextmanager from dataclasses import dataclass -from typing import TYPE_CHECKING -from server.auth import session_admission +from server.auth.answer_tokens import is_answer_token +from server.auth.context import current_auth from server.auth.session_protection import protected_for +from server.clients._checked_access import CheckedAccess from server.core import request_tail, request_work -from server.knowledge.app import connected_accounts, live_provider_search +from server.core.ch import set_query_tag +from server.core.diagnostics import private_work +from server.knowledge.app import connected_accounts, live_provider_search, session_admission from server.knowledge.domain.sources import MIRRORED_ACCESS -from server.knowledge.store import mirror_latch, source_store +from server.knowledge.store import sources as source_store from server.settings import settings -if TYPE_CHECKING: - from server.auth.credentials import Principal - from server.knowledge.app.connected_accounts import CheckedAccess - -@asynccontextmanager -async def private_work() -> AsyncIterator[None]: - """Mirror protection must mark every thread or task that touches cleartext work.""" - with request_work.mirror_scope(), request_work.http_mirror_scope(): - yield - - -@dataclass(frozen=True) +@dataclass(frozen=True, repr=False) class Contribution: authority: connected_accounts.SourceAuthority hits: tuple[live_provider_search.LiveProviderHit, ...] - async def check(self, *, deadline: float) -> None: - async def native(access: CheckedAccess) -> None: - tasks = [ - live_provider_search.revalidate( - self.authority.source, access, hit, deadline=deadline - ) - for hit in self.hits - ] - results = await asyncio.gather(*tasks, return_exceptions=True) - for hit, result in zip(self.hits, results, strict=True): - if isinstance(result, Exception) or not result: - raise PermissionError(f"Live search hit revoked: {hit.id}") - - await self.authority.run(native) - -@dataclass(frozen=True) +@dataclass(repr=False) class LiveResult: contributions: tuple[Contribution, ...] deadline: float + _checked: bool = False + + @property + def hits(self) -> tuple[live_provider_search.LiveProviderHit, ...]: + return tuple(hit for part in self.contributions for hit in part.hits) async def check(self) -> None: - for contribution in self.contributions: - await contribution.check(deadline=self.deadline) + """Renew the original account/source and each selected remote membership.""" + self._checked = False + with private_work(): + async with asyncio.timeout_at(self.deadline): + for part in self.contributions: + + async def verify(access: CheckedAccess, part: Contribution = part) -> None: + for hit in part.hits: + if not await live_provider_search.revalidate( + part.authority.source, access, hit, deadline=self.deadline + ): + raise RuntimeError("Live search unavailable") + + await part.authority.run(verify) + self._checked = True def fresh(self) -> bool: - return time.monotonic() < self.deadline - - -async def search( - org: str, - namespaces: Sequence[str], - query: str, - *, - top_k: int, -) -> LiveResult | None: - """Live search keeps provider calls separate from indexed search and each other.""" - if not ( - settings.knowledge_mirrored_sources_enabled - and settings.auth_required - and request_tail.required_active() - and request_work.mirror_marked() - and request_work.http_mirror_marked() + return self._checked and time.monotonic() < self.deadline + + +async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> LiveResult | None: + """Unavailable private work contributes no section and exposes no error detail.""" + auth = current_auth() + if ( + auth is None + or auth.org != org + or not settings.auth_actually_required() + or not settings.knowledge_mirrored_sources_enabled + or not protected_for(auth) + or (is_answer_token(auth) and not auth.answer_mirrors) + or not request_tail.required_active() + or len(query) > 1000 ): return None - + if not request_work.mark_mirrored(): + return None deadline = time.monotonic() + settings.knowledge_live_search_timeout_s + set_query_tag("search.query.live") with private_work(): try: - async with mirror_latch.ensure(): - auth: Principal = request_tail.current_principal() - if not protected_for(auth): - return None + async with asyncio.timeout_at(deadline): actual_org, subject = await connected_accounts.own_subject(auth) if actual_org != org: return None @@ -137,9 +127,7 @@ async def native( authority.source, access, query, top_k=source_quota, deadline=deadline ) - async with asyncio.timeout_at(deadline): - hits = tuple(await authority.run(native))[:source_quota] - + hits = tuple(await authority.run(native))[:source_quota] if hits: contributions.append(Contribution(authority, hits)) total_budget -= len(hits) From 7fa346125b8b62ed66e24f7e20d43a877e96ea8c Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:46:22 +0530 Subject: [PATCH 07/18] style(knowledge): wrap live_provider_search call to satisfy ruff line length limit (E501) --- server/knowledge/app/live_search.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index 6baf497092c..76cbe291d1d 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -124,7 +124,11 @@ async def native( source_quota: int = source_quota, ) -> list[live_provider_search.LiveProviderHit]: return await live_provider_search.search( - authority.source, access, query, top_k=source_quota, deadline=deadline + authority.source, + access, + query, + top_k=source_quota, + deadline=deadline, ) hits = tuple(await authority.run(native))[:source_quota] From aa36fb135d47a5ffb2b3abd97bc0513234fe544b Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:26:39 +0530 Subject: [PATCH 08/18] fix(knowledge): scope asyncio.timeout_at per source so earlier hits survive shared deadline --- server/knowledge/app/live_search.py | 30 +++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index 76cbe291d1d..9810c036632 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -96,18 +96,20 @@ 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 = [] - total_budget = min(top_k, settings.knowledge_live_search_max_hits) - num_sources = len(selected) - for i, source in enumerate(selected): - if total_budget <= 0: - break + contributions = [] + total_budget = min(top_k, settings.knowledge_live_search_max_hits) + num_sources = len(selected) + + for i, source in enumerate(selected): + if total_budget <= 0 or time.monotonic() >= deadline: + break - sources_left = num_sources - i - source_quota = min(total_budget, math.ceil(total_budget / sources_left)) + sources_left = num_sources - i + source_quota = min(total_budget, math.ceil(total_budget / sources_left)) - try: + try: + async with asyncio.timeout_at(deadline): authority = await connected_accounts.resolve( org, source.namespace, @@ -135,12 +137,12 @@ async def native( if hits: contributions.append(Contribution(authority, hits)) total_budget -= len(hits) - except Exception: # noqa: BLE001 - timeout or provider failure never drops prior contributions - if time.monotonic() >= deadline: - break - continue + except Exception: # noqa: BLE001 - timeout or provider failure never drops prior contributions + if time.monotonic() >= deadline: + break + continue - return LiveResult(tuple(contributions), deadline) if contributions else None + return LiveResult(tuple(contributions), deadline) if contributions else None except Exception: # noqa: BLE001 — optional private search never exposes account/provider detail return None From bd2f0a4a9692f6f5345b0f164591997aa27417ed Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:26:44 +0530 Subject: [PATCH 09/18] test(knowledge): assert dynamic quota rebalancing and shared-deadline hit preservation --- tests/unit/test_live_source_search.py | 63 +++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_live_source_search.py b/tests/unit/test_live_source_search.py index bbed3260e54..51920691aac 100644 --- a/tests/unit/test_live_source_search.py +++ b/tests/unit/test_live_source_search.py @@ -368,7 +368,62 @@ async def test_default_filtered_and_page_calls_do_not_start_live_work(native, in assert native.events == [] assert not native.started.is_set() -async def test_live_search_dynamic_quota_and_fault_tolerance(monkeypatch): - """Verify dynamic quota rebalancing and that a failing subsequent source does not discard earlier hits.""" - # Confirms issue #1447 anti-starvation and Bugbot fault tolerance - pass +async def test_live_search_dynamic_quota_and_fault_tolerance(native, indexed, monkeypatch): + """Verify dynamic quota rebalancing and that a timed-out subsequent source does not discard earlier hits.""" + from server.settings import settings + + source_two = SimpleNamespace( + namespace="allowed", + name="workspace", + source_id="second-source", + active=True, + credential_mode="connected", + owner_subject="canonical@example.test", + access=MIRRORED_ACCESS, + kind="notion", + ) + native.sources.append(source_two) + seen_top_k: list[tuple[str, int]] = [] + + async def two_source_search(source, access, query, *, top_k, deadline): + seen_top_k.append((source.source_id, top_k)) + if source.source_id == "original-source": + return [ + live_search.live_provider_search.LiveProviderHit( + "hit-1", "First Hit", "https://drive.google.com/file/d/1", "gdrive", "first" + ) + ] + return [ + live_search.live_provider_search.LiveProviderHit( + f"hit-2-{i}", f"Second {i}", f"https://notion.so/{i}", "notion", "second" + ) + for i in range(top_k) + ] + + 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 seen_top_k == [("original-source", 2), ("second-source", 3)] + assert [h.id for h in output.live.hits] == ["hit-1", "hit-2-0", "hit-2-1", "hit-2-2"] + + # Now verify that if the second source hits the shared deadline, the first hit is preserved. + monkeypatch.setattr(settings, "knowledge_live_search_timeout_seconds", 0.05) + + async def timeout_on_second(source, access, query, *, top_k, deadline): + if source.source_id == "original-source": + return [ + live_search.live_provider_search.LiveProviderHit( + "hit-1", "First Hit", "https://drive.google.com/file/d/1", "gdrive", "first" + ) + ] + await asyncio.sleep(0.2) + return [] + + monkeypatch.setattr(live_search.live_provider_search, "search", timeout_on_second) + async with _request(native.auth): + timeout_output = await indexed.handle_search(request) + + assert timeout_output.live is not None + assert [h.id for h in timeout_output.live.hits] == ["hit-1"] From 987fdf259ba37c489f8ae0ee09f119e1a970c8e4 Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:59:13 +0530 Subject: [PATCH 10/18] fix(knowledge): scope asyncio.timeout_at per source so earlier hits survive shared deadline --- server/knowledge/app/live_search.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index 9810c036632..b29863dd05f 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -100,16 +100,17 @@ async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> contributions = [] total_budget = min(top_k, settings.knowledge_live_search_max_hits) num_sources = len(selected) + search_deadline = deadline - min(0.02, settings.knowledge_live_search_timeout_s * 0.2) for i, source in enumerate(selected): - if total_budget <= 0 or time.monotonic() >= deadline: + if total_budget <= 0 or time.monotonic() >= search_deadline: break sources_left = num_sources - i source_quota = min(total_budget, math.ceil(total_budget / sources_left)) try: - async with asyncio.timeout_at(deadline): + async with asyncio.timeout_at(search_deadline): authority = await connected_accounts.resolve( org, source.namespace, @@ -138,7 +139,7 @@ async def native( contributions.append(Contribution(authority, hits)) total_budget -= len(hits) except Exception: # noqa: BLE001 - timeout or provider failure never drops prior contributions - if time.monotonic() >= deadline: + if time.monotonic() >= search_deadline: break continue From f3a9e4087b4a23f74bd1eb11846b6b2ad2f51ddd Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:59:18 +0530 Subject: [PATCH 11/18] test(knowledge): assert dynamic quota rebalancing and shared-deadline hit preservation --- tests/unit/test_live_source_search.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_live_source_search.py b/tests/unit/test_live_source_search.py index 51920691aac..1742005f427 100644 --- a/tests/unit/test_live_source_search.py +++ b/tests/unit/test_live_source_search.py @@ -408,8 +408,8 @@ async def two_source_search(source, access, query, *, top_k, deadline): assert seen_top_k == [("original-source", 2), ("second-source", 3)] assert [h.id for h in output.live.hits] == ["hit-1", "hit-2-0", "hit-2-1", "hit-2-2"] - # Now verify that if the second source hits the shared deadline, the first hit is preserved. - monkeypatch.setattr(settings, "knowledge_live_search_timeout_seconds", 0.05) + # Now verify that if the second source hits the search cutoff, the first hit is preserved and published. + monkeypatch.setattr(settings, "knowledge_live_search_timeout_s", 0.05) async def timeout_on_second(source, access, query, *, top_k, deadline): if source.source_id == "original-source": From 7c7e2041d0d479b2a7df7b595225868f56830b95 Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:31:35 +0530 Subject: [PATCH 12/18] fix(knowledge): scope asyncio.timeout_at per source so earlier hits survive shared deadline From a905484579b8313b50e15e212eb31039f4ac4a18 Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:31:39 +0530 Subject: [PATCH 13/18] test(knowledge): assert dynamic quota rebalancing and shared-deadline hit preservation --- tests/unit/test_live_source_search.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/tests/unit/test_live_source_search.py b/tests/unit/test_live_source_search.py index 1742005f427..b8a92a2fc04 100644 --- a/tests/unit/test_live_source_search.py +++ b/tests/unit/test_live_source_search.py @@ -110,11 +110,19 @@ 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 + matched = next( + ( + s + for s in state.sources + if (org, s.namespace, s.name) == ("org", namespace, name) + and s.source_id == expected_source_id + ), + None, + ) + assert matched is not None state.resolutions.append((namespace, name, expected_source_id, deadline)) state.deadline = deadline - authority = Authority(source) + authority = Authority(matched) state.authorities.append(authority) return authority @@ -406,7 +414,7 @@ async def two_source_search(source, access, query, *, top_k, deadline): output = await indexed.handle_search(request) assert seen_top_k == [("original-source", 2), ("second-source", 3)] - assert [h.id for h in output.live.hits] == ["hit-1", "hit-2-0", "hit-2-1", "hit-2-2"] + assert [h.id for h in output.live.results] == ["hit-1", "hit-2-0", "hit-2-1", "hit-2-2"] # Now verify that if the second source hits the search cutoff, the first hit is preserved and published. monkeypatch.setattr(settings, "knowledge_live_search_timeout_s", 0.05) @@ -426,4 +434,4 @@ async def timeout_on_second(source, access, query, *, top_k, deadline): timeout_output = await indexed.handle_search(request) assert timeout_output.live is not None - assert [h.id for h in timeout_output.live.hits] == ["hit-1"] + assert [h.id for h in timeout_output.live.results] == ["hit-1"] From 41b1376ab7394813a2e5de3657c19f2474d93ebf Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:23:58 +0530 Subject: [PATCH 14/18] fix(knowledge): scope asyncio.timeout_at per source so earlier hits survive shared deadline From 601dc2ea575315c00b4b541792ec389b6e7069ff Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:24:03 +0530 Subject: [PATCH 15/18] test(knowledge): assert dynamic quota rebalancing and shared-deadline hit preservation --- tests/unit/test_live_source_search.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_live_source_search.py b/tests/unit/test_live_source_search.py index b8a92a2fc04..c0e264bbff1 100644 --- a/tests/unit/test_live_source_search.py +++ b/tests/unit/test_live_source_search.py @@ -141,7 +141,7 @@ 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 selected in state.sources and access is state.access and actual_hit is not None assert deadline == state.deadline return True From 9ab9bf7be2b6ecfe03b35260c7736dd67fb3bce4 Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:53:07 +0530 Subject: [PATCH 16/18] fix(knowledge): scope asyncio.timeout_at per source so earlier hits survive shared deadline From 33f4dd19a68db43e6999bd808a79f44ea808c36e Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:53:10 +0530 Subject: [PATCH 17/18] test(knowledge): assert dynamic quota rebalancing and shared-deadline hit preservation --- tests/unit/test_live_source_search.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/test_live_source_search.py b/tests/unit/test_live_source_search.py index c0e264bbff1..7a197a57e51 100644 --- a/tests/unit/test_live_source_search.py +++ b/tests/unit/test_live_source_search.py @@ -376,6 +376,7 @@ async def test_default_filtered_and_page_calls_do_not_start_live_work(native, in assert native.events == [] assert not native.started.is_set() + async def test_live_search_dynamic_quota_and_fault_tolerance(native, indexed, monkeypatch): """Verify dynamic quota rebalancing and that a timed-out subsequent source does not discard earlier hits.""" from server.settings import settings From 8d4606279924ad6a7c534ecc727f846ef2600215 Mon Sep 17 00:00:00 2001 From: hemal9102 <157049718+hemal9102@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:16:09 +0530 Subject: [PATCH 18/18] fix(knowledge): allow first source attempt before search_deadline check --- server/knowledge/app/live_search.py | 328 ++++++++++++++-------------- 1 file changed, 164 insertions(+), 164 deletions(-) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index b29863dd05f..ad954271c7b 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -1,164 +1,164 @@ -"""Request-owned native search over the asker's connected registrations.""" - -from __future__ import annotations - -import asyncio -import math -import time -from dataclasses import dataclass - -from server.auth.answer_tokens import is_answer_token -from server.auth.context import current_auth -from server.auth.session_protection import protected_for -from server.clients._checked_access import CheckedAccess -from server.core import request_tail, request_work -from server.core.ch import set_query_tag -from server.core.diagnostics import private_work -from server.knowledge.app import connected_accounts, live_provider_search, session_admission -from server.knowledge.domain.sources import MIRRORED_ACCESS -from server.knowledge.store import sources as source_store -from server.settings import settings - - -@dataclass(frozen=True, repr=False) -class Contribution: - authority: connected_accounts.SourceAuthority - hits: tuple[live_provider_search.LiveProviderHit, ...] - - -@dataclass(repr=False) -class LiveResult: - contributions: tuple[Contribution, ...] - deadline: float - _checked: bool = False - - @property - def hits(self) -> tuple[live_provider_search.LiveProviderHit, ...]: - return tuple(hit for part in self.contributions for hit in part.hits) - - async def check(self) -> None: - """Renew the original account/source and each selected remote membership.""" - self._checked = False - with private_work(): - async with asyncio.timeout_at(self.deadline): - for part in self.contributions: - - async def verify(access: CheckedAccess, part: Contribution = part) -> None: - for hit in part.hits: - if not await live_provider_search.revalidate( - part.authority.source, access, hit, deadline=self.deadline - ): - raise RuntimeError("Live search unavailable") - - await part.authority.run(verify) - self._checked = True - - def fresh(self) -> bool: - return self._checked and time.monotonic() < self.deadline - - -async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> LiveResult | None: - """Unavailable private work contributes no section and exposes no error detail.""" - auth = current_auth() - if ( - auth is None - or auth.org != org - or not settings.auth_actually_required() - or not settings.knowledge_mirrored_sources_enabled - or not protected_for(auth) - or (is_answer_token(auth) and not auth.answer_mirrors) - or not request_tail.required_active() - or len(query) > 1000 - ): - return None - if not request_work.mark_mirrored(): - return None - deadline = time.monotonic() + settings.knowledge_live_search_timeout_s - set_query_tag("search.query.live") - with private_work(): - try: - async with asyncio.timeout_at(deadline): - actual_org, subject = await connected_accounts.own_subject(auth) - if actual_org != org: - return None - sources = await source_store.connected_sources(org, subject) - selected = [ - source - for source in sources - if source.namespace in namespaces - and source.active - and source.credential_mode == "connected" - and source.owner_subject == subject - and source.access == MIRRORED_ACCESS - and source.kind in ("gdrive", "notion") - ][: settings.knowledge_live_search_max_sources] - if not selected: - return None - # Real opt-in work activates the same durable protection as mirrored sources. - await session_admission.require(auth) - - contributions = [] - total_budget = min(top_k, settings.knowledge_live_search_max_hits) - num_sources = len(selected) - search_deadline = deadline - min(0.02, settings.knowledge_live_search_timeout_s * 0.2) - - for i, source in enumerate(selected): - if total_budget <= 0 or time.monotonic() >= search_deadline: - break - - sources_left = num_sources - i - source_quota = min(total_budget, math.ceil(total_budget / sources_left)) - - try: - async with asyncio.timeout_at(search_deadline): - 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, - source_quota: int = source_quota, - ) -> list[live_provider_search.LiveProviderHit]: - return await live_provider_search.search( - authority.source, - access, - query, - top_k=source_quota, - deadline=deadline, - ) - - hits = tuple(await authority.run(native))[:source_quota] - if hits: - contributions.append(Contribution(authority, hits)) - total_budget -= len(hits) - except Exception: # noqa: BLE001 - timeout or provider failure never drops prior contributions - if time.monotonic() >= search_deadline: - break - continue - - return LiveResult(tuple(contributions), deadline) if contributions else None - except Exception: # noqa: BLE001 — optional private search never exposes account/provider detail - return None - - -async def publish(result: LiveResult | None) -> LiveResult | None: - """Only selected, current contributions retain a final-response obligation.""" - if result is None: - return None - with private_work(): - try: - await result.check() - if not result.fresh(): - return None - if not request_tail.retain_publication(result, result.check, result.fresh): - return None - return result - except Exception: # noqa: BLE001 — expired or revoked live results leave indexed search intact - return None +"""Request-owned native search over the asker's connected registrations.""" + +from __future__ import annotations + +import asyncio +import math +import time +from dataclasses import dataclass + +from server.auth.answer_tokens import is_answer_token +from server.auth.context import current_auth +from server.auth.session_protection import protected_for +from server.clients._checked_access import CheckedAccess +from server.core import request_tail, request_work +from server.core.ch import set_query_tag +from server.core.diagnostics import private_work +from server.knowledge.app import connected_accounts, live_provider_search, session_admission +from server.knowledge.domain.sources import MIRRORED_ACCESS +from server.knowledge.store import sources as source_store +from server.settings import settings + + +@dataclass(frozen=True, repr=False) +class Contribution: + authority: connected_accounts.SourceAuthority + hits: tuple[live_provider_search.LiveProviderHit, ...] + + +@dataclass(repr=False) +class LiveResult: + contributions: tuple[Contribution, ...] + deadline: float + _checked: bool = False + + @property + def hits(self) -> tuple[live_provider_search.LiveProviderHit, ...]: + return tuple(hit for part in self.contributions for hit in part.hits) + + async def check(self) -> None: + """Renew the original account/source and each selected remote membership.""" + self._checked = False + with private_work(): + async with asyncio.timeout_at(self.deadline): + for part in self.contributions: + + async def verify(access: CheckedAccess, part: Contribution = part) -> None: + for hit in part.hits: + if not await live_provider_search.revalidate( + part.authority.source, access, hit, deadline=self.deadline + ): + raise RuntimeError("Live search unavailable") + + await part.authority.run(verify) + self._checked = True + + def fresh(self) -> bool: + return self._checked and time.monotonic() < self.deadline + + +async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> LiveResult | None: + """Unavailable private work contributes no section and exposes no error detail.""" + auth = current_auth() + if ( + auth is None + or auth.org != org + or not settings.auth_actually_required() + or not settings.knowledge_mirrored_sources_enabled + or not protected_for(auth) + or (is_answer_token(auth) and not auth.answer_mirrors) + or not request_tail.required_active() + or len(query) > 1000 + ): + return None + if not request_work.mark_mirrored(): + return None + deadline = time.monotonic() + settings.knowledge_live_search_timeout_s + set_query_tag("search.query.live") + with private_work(): + try: + async with asyncio.timeout_at(deadline): + actual_org, subject = await connected_accounts.own_subject(auth) + if actual_org != org: + return None + sources = await source_store.connected_sources(org, subject) + selected = [ + source + for source in sources + if source.namespace in namespaces + and source.active + and source.credential_mode == "connected" + and source.owner_subject == subject + and source.access == MIRRORED_ACCESS + and source.kind in ("gdrive", "notion") + ][: settings.knowledge_live_search_max_sources] + if not selected: + return None + # Real opt-in work activates the same durable protection as mirrored sources. + await session_admission.require(auth) + + contributions = [] + total_budget = min(top_k, settings.knowledge_live_search_max_hits) + num_sources = len(selected) + search_deadline = deadline - min(0.02, settings.knowledge_live_search_timeout_s * 0.2) + + for i, source in enumerate(selected): + if total_budget <= 0 or (i > 0 and time.monotonic() >= search_deadline): + break + + sources_left = num_sources - i + source_quota = min(total_budget, math.ceil(total_budget / sources_left)) + + try: + async with asyncio.timeout_at(search_deadline): + 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, + source_quota: int = source_quota, + ) -> list[live_provider_search.LiveProviderHit]: + return await live_provider_search.search( + authority.source, + access, + query, + top_k=source_quota, + deadline=deadline, + ) + + hits = tuple(await authority.run(native))[:source_quota] + if hits: + contributions.append(Contribution(authority, hits)) + total_budget -= len(hits) + except Exception: # noqa: BLE001 - timeout or provider failure never drops prior contributions + if time.monotonic() >= search_deadline: + break + continue + + return LiveResult(tuple(contributions), deadline) if contributions else None + except Exception: # noqa: BLE001 — optional private search never exposes account/provider detail + return None + + +async def publish(result: LiveResult | None) -> LiveResult | None: + """Only selected, current contributions retain a final-response obligation.""" + if result is None: + return None + with private_work(): + try: + await result.check() + if not result.fresh(): + return None + if not request_tail.retain_publication(result, result.check, result.fresh): + return None + return result + except Exception: # noqa: BLE001 — expired or revoked live results leave indexed search intact + return None