Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
ccb5d62
fix(knowledge): fair quota allocation across live search sources to p…
hemal9102 Nov 26, 2026
56f5c0f
fix(knowledge): dynamic quota rebalancing and per-source fault tolera…
hemal9102 Nov 26, 2026
14630b6
test(knowledge): add unit regression coverage for live search dynamic…
hemal9102 Nov 26, 2026
b34d46f
fix(knowledge): defer deadline check to allow native call start and p…
hemal9102 Nov 26, 2026
1040269
fix(knowledge): wrap native provider execution in asyncio.timeout_at …
hemal9102 Nov 26, 2026
38b5393
fix(knowledge): restore unified caller interface, original private_wo…
hemal9102 Nov 27, 2026
7fa3461
style(knowledge): wrap live_provider_search call to satisfy ruff line…
hemal9102 Nov 27, 2026
aa36fb1
fix(knowledge): scope asyncio.timeout_at per source so earlier hits s…
hemal9102 Dec 1, 2026
bd2f0a4
test(knowledge): assert dynamic quota rebalancing and shared-deadline…
hemal9102 Dec 1, 2026
987fdf2
fix(knowledge): scope asyncio.timeout_at per source so earlier hits s…
hemal9102 Dec 1, 2026
f3a9e40
test(knowledge): assert dynamic quota rebalancing and shared-deadline…
hemal9102 Dec 1, 2026
2c55682
Merge branch 'main' into fix-live-search-source-starvation
hemal9102 Dec 1, 2026
7c7e204
fix(knowledge): scope asyncio.timeout_at per source so earlier hits s…
hemal9102 Dec 1, 2026
a905484
test(knowledge): assert dynamic quota rebalancing and shared-deadline…
hemal9102 Dec 1, 2026
41b1376
fix(knowledge): scope asyncio.timeout_at per source so earlier hits s…
hemal9102 Dec 1, 2026
601dc2e
test(knowledge): assert dynamic quota rebalancing and shared-deadline…
hemal9102 Dec 1, 2026
9ab9bf7
fix(knowledge): scope asyncio.timeout_at per source so earlier hits s…
hemal9102 Dec 2, 2026
33f4dd1
test(knowledge): assert dynamic quota rebalancing and shared-deadline…
hemal9102 Dec 2, 2026
8d46062
fix(knowledge): allow first source attempt before search_deadline check
hemal9102 Dec 2, 2026
9b17b94
fix(knowledge): preserve live hits when a later source times out
hemal9102 Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 40 additions & 28 deletions server/knowledge/app/live_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Search deadline starves publication

High Severity

Passing search_deadline into connected_accounts.resolve stamps that midpoint onto SourceAuthority and CheckedAccess. publish revalidates through authority.run, which times out and validates against the same midpoint, so hits found before a slow later source or a longer indexed fan-out are dropped.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 9b17b94. Configure here.

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

Expand Down
85 changes: 78 additions & 7 deletions tests/unit/test_live_source_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=[],
Expand All @@ -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()
Expand Down Expand Up @@ -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)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
state.authorities.append(authority)
return authority

Expand All @@ -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)
Expand Down Expand Up @@ -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"]
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Loading