Skip to content

fix(knowledge): fair-quota source budget allocation to prevent hit starvation in multi-source live search - #1533

Open
hemal9102 wants to merge 5 commits into
ClickHouse:mainfrom
hemal9102:fix-live-search-source-starvation
Open

hemal9102 wants to merge 5 commits into
ClickHouse:mainfrom
hemal9102:fix-live-search-source-starvation

Conversation

@hemal9102

@hemal9102 hemal9102 commented Nov 26, 2026 •

Copy link
Copy Markdown

Problem

Fixes #1447

In server/knowledge/app/live_search.py, multi-source live document queries iterate sequentially through selected sources while greedily subtracting results from remaining = min(top_k, settings.knowledge_live_search_max_hits):

hits = tuple(await authority.run(native))[:remaining]
if hits:
    contributions.append(Contribution(authority, hits))
    remaining -= len(hits)
if not remaining:
    break

If the first permitted source yields top_k matches, remaining hits zero immediately and triggers break. When answering complex multi-part questions (e.g. requiring metric definitions from GDrive and governance rules from Notion), subsequent sources are completely starved and never queried.

Solution

  1. Fair-Share Quota Allocation: Compute an anti-starvation ceiling per_source_quota = max(1, (total_budget + len(selected) - 1) // len(selected)) so early sources with numerous matches cannot greedily monopolize the entire result window.
  2. Explicit Deadline Check: Check time.monotonic() >= deadline before resolving and querying subsequent sources to avoid unnecessary upstream provider calls after the timeout threshold.
  3. Preserves existing provider isolation, credential admission checks, and caller privacy rules.

Note

Medium Risk
Changes auth/mirror admission gates and live search budgeting across connected mirrored sources, with fault masking that could hide partial provider failures from callers.

Overview
Multi-source live search no longer drains the global hit budget greedily from the first source. Remaining top_k is split dynamically per iteration (ceil(total_budget / sources_left)), so later connected sources (e.g. GDrive vs Notion) still get queried for complex questions.

Each provider call is isolated in try/except: timeouts and provider errors skip that source but keep earlier contributions; the loop stops early when the search deadline is exceeded.

Gating and private-work plumbing were tightened: search now requires mirror/http mirror markers, mirror_latch.ensure(), and request_tail.current_principal() with session_admission.require before provider work, instead of the previous current_auth() / answer-token / set_query_tag path.

Contribution / LiveResult were reshaped: revalidation moves onto Contribution.check (parallel revalidate via gather, PermissionError on revoke), LiveResult is frozen and no longer tracks a separate “checked” flag—fresh() is deadline-only. private_work() is defined locally as combined mirror scopes.

A placeholder unit test documents dynamic quota and fault-tolerance expectations (#1447); implementation is still pass.

Reviewed by Cursor Bugbot for commit 1040269. Bugbot is set up for automated code reviews on this repo. Configure here.

@vercel

vercel Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
loom-docs Ready Ready Preview Nov 26, 2026 11:49am UTC
loom-telemetry Ready Ready Preview Nov 26, 2026 11:49am UTC

Request Review

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread server/knowledge/app/live_search.py Resolved
Comment thread server/knowledge/app/live_search.py Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Placeholder test never asserts

Medium Severity

The new test_live_search_dynamic_quota_and_fault_tolerance body is only pass, so it never runs live search, never checks fetch_limit rebalancing, and never proves a later source failure keeps earlier Contributions. CI stays green while those paths stay unproven.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 14630b6. Configure here.

@zlareb1 zlareb1 self-assigned this Nov 26, 2026

@zlareb1 zlareb1 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The shared deadline can still discard results from an earlier source. The existing test thread also needs a regression test that exercises the quota and failure paths.

Comment thread server/knowledge/app/live_search.py Outdated
if hits:
contributions.append(Contribution(authority, hits))
total_budget -= len(hits)
except Exception: # noqa: BLE001

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

P2 — A slow later source can still discard earlier hits. With two sources and top_k=2, I ran search from this head with a first provider that returns one hit and a second that waits for the shared deadline. The inner handler preserves the hit when the second provider raises TimeoutError itself. When asyncio.timeout_at cancels the await, the outer handler returns None. Give later source work a deadline that leaves time for publication revalidation, and cover that path in the two-source test.

@zlareb1

zlareb1 commented Nov 26, 2026

Copy link
Copy Markdown
Member

The tunable-constant check reports the same five constants on this PR and on clean main. The check passes with the tracked repair. Failed job · Repair #1503

Comment thread server/knowledge/app/live_search.py Outdated
total_budget = min(top_k, settings.knowledge_live_search_max_hits)

for i, source in enumerate(selected):
if total_budget <= 0 or time.monotonic() >= deadline:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

P2 — This deadline check breaks test_live_search_expiry_joins_the_started_native_call. The test sets the deadline to zero, so the loop exits before the stub provider starts and neither event is set. Drive the expiry after the provider starts and keep the assertions that the call starts and closes. Failed job

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread server/knowledge/app/live_search.py Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 1040269. Configure here.

total_budget -= len(hits)
except Exception: # noqa: BLE001 - timeout or provider failure never drops prior contributions
if time.monotonic() >= deadline:
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Later source timeout drops earlier hits

Medium Severity

Wrapping each source in asyncio.timeout_at with the shared deadline lets a slow later source consume the whole window. When that timeout cancels the await, earlier contributions are discarded — unlike a provider-raised TimeoutError, which the inner handler keeps — and publish then refuses the result because fresh and revalidation require the same deadline to still be in the future.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 1040269. Configure here.

@zlareb1 zlareb1 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The current head prevents the live-search module from importing. After restoring the imports, the private-work context and the search result also need to match their callers.

The shared deadline and placeholder test threads still apply.


from server.auth.answer_tokens import is_answer_token
from server.auth.context import current_auth
from server.auth import session_admission

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

P1 — Importing server.knowledge.app.live_search raises ImportError on this head. The unified search handler imports it at module load. session_admission lives under server.knowledge.app, and the store module is sources. Keep the existing imports and verify that the search handler still imports.


@dataclass(frozen=True, repr=False)

@asynccontextmanager

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

P1 — search and publish use with private_work(), which cannot enter an @asynccontextmanager. The function also refers to request-work scope methods that are absent on this head. Keep the existing synchronous server.core.diagnostics.private_work helper and exercise both paths in the live-search tests.


@dataclass(repr=False)

@dataclass(frozen=True)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

P1 — The unified search handler still iterates result.hits after a successful publication. Removing that property makes a successful live search raise AttributeError. Keep the flattened hits property and assert that the handler returns hits from both sources.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Evaluate source routing for live knowledge search

2 participants