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 20 commits into
ClickHouse:mainfrom
hemal9102:fix-live-search-source-starvation
Open

hemal9102 wants to merge 20 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 live multi-provider search timing, quotas, and error isolation on a privacy-sensitive path; behavior is narrower per source but affects which hits users see under timeout.

Overview
Multi-source live search no longer lets the first provider consume the entire top_k window. Each iteration gets a fair share of whatever hits remain (quota via ceiling division over sources still to query), and provider calls use that cap instead of the full remaining budget.

The loop also stops early when the hit budget is exhausted or a dedicated search_deadline (half the overall live-search timeout, leaving the rest for account/membership revalidation at publish time) is reached. Resolve/search for each source runs under asyncio.timeout_at(search_deadline), and per-source failures are swallowed so earlier contributions are still returned.

Tests add a two-source scenario that asserts quota split 2 then 3 for top_k=4, and that hits from the first source still publish when the second provider times out.

Reviewed by Cursor Bugbot for commit 9b17b94. 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 Dec 2, 2026 1:10pm UTC
loom-telemetry Ready Ready Preview Dec 2, 2026 1:10pm 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.

Comment thread tests/unit/test_live_source_search.py Resolved
@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 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.

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.

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

@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.

Comment thread server/knowledge/app/live_search.py Resolved
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.

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

@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 live-search module imports, and its request scope and result interface match the caller. I ran a two-source test on this head. The first hit survived an early provider error, then disappeared when the second provider reached the shared deadline. Give each later source a cutoff that leaves time to revalidate earlier hits. Replace the placeholder with assertions for both quota allocation and the deadline case. Deadline thread · Test thread

@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.

Unit shard 5 tested this head against a base whose saved-page fixture omits the cursor scope digest. Both cases also fail on that base without the live-search change. The same shard passes on main after #1494 adds the digest. PR job · Base job · Merged fix #1494 · Passing job

@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 two-source probe still loses the first hit when the second provider reaches the shared timeout. The added test still has no assertions. Both findings remain on this head. Deadline thread · Test thread

@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 range fixture and structural documentation cap failures both reproduce on clean main. The SIGTERM test also fails on the same main commit with the same missing worker flush. PR range fixture · Main range fixture · PR cap check · Main cap check · Existing repair · PR SIGTERM test · Main SIGTERM test · Existing shutdown repair

@zlareb1

zlareb1 commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

The MCP integration job expects a retry example for a request that supplies its organization. Clean main failed the same assertion without this PR's changes. The merged fix checks bearer and explicit scope separately, and that main run passed. PR job · Failing main job · Merged fix #1634 · Passing main run

@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 tests/unit/test_live_source_search.py Resolved
Comment thread tests/unit/test_live_source_search.py Resolved
Comment thread tests/unit/test_live_source_search.py Resolved
@hemal9102

Copy link
Copy Markdown
Author

@zlareb1 Addressed the review feedback in �d2f0a4a (scoped �syncio.timeout_at(deadline) per-source in live_search.py and added assertions in est_live_search_dynamic_quota_and_fault_tolerance). Ready for re-review when you have a moment!

@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 deadline finding remains on this head. A later source still uses the publication deadline, so reaching its cutoff leaves no time to revalidate and publish earlier hits. The two-source fixture also rejects the second source before its search callback runs. Make the fixture resolve both sources and assert the published results under the shared deadline.

@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.

Unit part 4 reports the same three MCP search constants on this merge and its clean main parent. #1871 moved those limits into settings, and main CI passed after the repair merged. PR job · Main parent job · Merged repair · Passing main CI

@hemal9102

Copy link
Copy Markdown
Author

@zlareb1 Updated in 987fdf2 / 3a9e408: separated search_deadline from the publication deadline so earlier hits have margin to revalidate and publish, fixed knowledge_live_search_timeout_s in the test, and merged main (#1871) for CI.

@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

@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 search cutoff leaves time for revalidation. The new regression still stops before exercising it. The fixture accepts only the personal source and its ID, so workspace never reaches the provider and the first seen_top_k assertion fails. The response field is live.results. Resolve and revalidate both sources in the fixture, then assert the published results when the second source reaches the cutoff. Fixture finding · Response field

@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 tests/unit/test_live_source_search.py Resolved

@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.

Three tests fail on this head. The source-identity regression reproduces the decoy fixture finding. The publication deadline finding also remains open.

Comment thread tests/unit/test_live_source_search.py Outdated
output = await indexed.handle_search(request)

assert seen_top_k == [("original-source", 2), ("second-source", 3)]
assert [h.id for h in output.live.results] == ["hit-1", "hit-2-0", "hit-2-1", "hit-2-2"]

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 — The quota assertions pass, but output.live is None. The fixture's revalidate accepts only its original private-id hit by identity. This test substitutes four hits, so the membership assertion is caught and publication drops the section. Revalidate the test's hits against their own source and check that publication still uses the original authority.

Comment thread server/knowledge/app/live_search.py Outdated
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:

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 — test_live_search_expiry_joins_the_started_native_call now stops before starting the provider, so it no longer tests cancellation and cleanup of in-flight work. Give the test a positive budget and coordinate with the provider's started event so it reaches the timeout with an active call.

@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 dashboard Vitest shard fails on the same tooltip assertions on this PR and on clean main. Radix includes the tooltip ID in aria-describedby even when it repeats the button's name. The repair keeps the accessible name and removes the duplicate description. PR job · Clean main job · Merged repair · Passing main job

@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 publication cutoff finding remains. The search reserves at most 20 ms, and the final account and provider revalidation still share that window. The decoy source fixture finding also remains because the resolver still takes the first matching ID, name, and namespace.

Comment thread tests/unit/test_live_source_search.py Outdated
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."""

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 — The format gate fails on the new test. Run the repository formatter on this file.

@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 latest commit changes formatting in the test. The publication cutoff and source fixture findings remain on this head.

@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 analyzer job reports the same mentor evidence shape mismatch on this head's tested base. The focused test passes on current main with the snapshot update from #1957. The existing digest repair in #1990 addresses the SQL comment that made the literal affect the shape. Failed CI job · Digest repair

@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 first source can now enter the loop after search_deadline, but its resolve still runs inside a timeout set to that expired deadline. The real resolve awaits the source store before the provider starts. Keep the cancellation test on a positive search budget and wait for the provider to start before expiring it. The publication window and source fixture findings also remain.

GitHub reports a merge conflict in server/knowledge/app/live_search.py. Reconcile it with main and restore LF line endings in that file.

@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.

GitHub reports a merge conflict with main in server/knowledge/app/live_search.py. Please resolve it so CI can test the combined tree. The deadline finding remains in the existing review.

Signed-off-by: hemal9102 <157049718+hemal9102@users.noreply.github.com>

@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.

Fix All in Cursor

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

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.

@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 updated fixture exercises the quota and starts the provider before cancellation. The real SourceAuthority still expires at search_deadline, so publication drops earlier hits when a later source uses the search window. Give the authority the publication deadline and bound only the provider search with the earlier deadline. Publication thread

@hemal9102

Copy link
Copy Markdown
Author

All CI checks are now green on 9b17b94 (unit tests, integration suites, isolation gates, and wheels). Ready for review whenever you have a moment—thanks!

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