Skip to content

Search overview endpoint on the quick model (E6.3) - #704

Merged
neuromechanist merged 14 commits into
developfrom
feature/issue-702-search-overview
Nov 11, 2026
Merged

neuromechanist merged 14 commits into
developfrom
feature/issue-702-search-overview

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

POST /{community_id}/overview for the Discover panel of board D2 (nemarOrg/website#518), plan E6.3.
The caller sends a query, its filters and up to 10 search results; the community's quick model writes a summary of at most about 100 words as segments ({text} or {dataset_id}), up to 3 picks, cited_ids, shown, cached, model and generated_at.

  • Route and model: in create_community_router beside /ask. 404 when the community has no quick_model (no new config key), 502 when no sentence survives. _route_request(..., tier="quick"), _check_model_cost, then a new _build_chat_model helper that create_community_assistant now also uses (extracted from its inline provider block, behavior unchanged). The model runs at reasoning_effort="low" with max_tokens=1500, retried once through the now-public invoke_with_retry (the summarizer's _invoke_summarizer, same classification).
  • Citations: only ids in the request's results appear. The model writes [[id]] markers and a JSON picks list; the server parses it, drops any sentence holding a marker or a bare id-shaped token (\b[a-z]{2}\d{6}\b) outside the given ids, and any pick of one. Result text goes to the prompt as JSON inside <data> tags with < and > escaped, and never widens the allowed ids.
  • Cache: in memory, 24 hours, 500 entries per community (oldest evicted), keyed on the normalized query (NFKC, case fold, collapsed spaces), the canonical filters and a SHA-256 of the results payload. Injectable clock. Identical concurrent requests share one in-flight call; failures are never cached; authorization runs before the cache is read.
  • Budget: the request row is set as /ask's is (tier quick, model, key source, tokens, cost) and overview is in _COMMUNITY_SUFFIXES, so check_budget counts it. A cache hit or a joined call logs zero tokens and zero cost; a call that produced no answer is still paid for.
  • Worker: ROUTE_PATTERNS.communityOverview and handleOverview (rate limit only, no Turnstile, like feedback), tested in test-routing.js. The worker is deployed by hand (wrangler deploy, see workers/osa-worker/README.md): a maintainer must deploy it before the website can call the endpoint through it.
  • Docs: .context/api-structure.md section 5, docs/search-overview.md, CHANGELOG.md.

Also changed: tests/test_api/test_security.py lists /overview among the routes allowed to use verify_api_key (it spends the caller's credential on a model, like /ask).

Closes #702

Commands run

  • uv sync --extra dev
  • uv run pytest tests/test_api/test_search_overview.py tests/test_api/test_overview_unit.py -v: 51 + 87 passed
  • uv run pytest tests/test_api tests/test_metrics -q (also tests/test_agents): all passed after rebasing onto develop (2325 with test_agents)
  • Full suite before the rebase: 6141 passed, 92 skipped; one failure, tests/test_tools/test_hed_suggest.py::test_real_program_suggests_a_schema_tag, a real-network HED schema test unrelated to this change (every other test in tests/test_tools passes)
  • uv run pytest tests/test_integration/test_search_overview_llm.py -m llm -v: skipped, there is no ANTHROPIC_API_KEY in this environment (the skipif reason says so). The prompt and the JSON/marker contract have therefore not been run against the real model yet; the post-merge dev check below does that.
  • uv run ruff check . && uv run ruff format --check .: clean
  • bun workers/osa-worker/test-routing.js (192 passed), bun workers/osa-worker/test-mounted-hosts.js (37 passed), node --check workers/osa-worker/index.js
  • curl -s 'https://api-test.nemar.org/datasets?limit=6': the source of tests/fixtures/overview_results.json (the six xx0999NN rows)
  • The dev check (wait for https://api.osc.earth/osa-dev/health to carry the merged version, POST twice to https://api.osc.earth/osa-dev/nemar/overview with Origin https://test.nemar.org and a staging xx0999NN result set, check cited ids and cached: true on the second call, read the request_log row with docker exec osa-dev python3): after merge, output to be pasted in Search overview endpoint on the quick model #702

Notes for review

  • The tests drive the real ASGI app (metrics middleware, the router, real authorization and routing, real cache, prompt, parser, filter, request_log and check_budget); the only stand-in is a ScriptedChatModel. Deleting overview from _COMMUNITY_SUFFIXES makes five budget tests fail.
  • A request that shares another's in-flight call reports cached: true and logs no cost.

Extract _build_chat_model from create_community_assistant and make the
summarizer's one-retry call a public invoke_with_retry, for the overview
endpoint to reuse. No behavior change; tests/test_api and
tests/test_agents/test_model_routing.py pass.
src/api/overview.py holds the request and response models, query
normalization, the cache key, the bounded 24 h cache with one call in
flight per key, the prompt, the parser and the citation filter, with no
FastAPI import. Unit tests cover the pure parts (87 passing).
Route in create_community_router, beside /ask: 404 without a quick_model,
quick tier routing and cost check, low effort and a small token budget,
one retry, a request_log row with the tier and cost (overview added to the
middleware's community suffixes), 502 when no sentence survives. Tests
drive the real ASGI app with a scripted model (51 passing); the real-model
test is skipped without ANTHROPIC_API_KEY.
communityOverview matcher and handleOverview, handled like feedback (no Turnstile). test-routing.js covers the route on every host, POST only, the forwarded body and Origin, and a Turnstile secret not being asked for. Tested: bun test-routing.js (192) and test-mounted-hosts.js (37) pass. The worker is deployed by hand.
…hangelog)

Request, response, errors, cache and budget behavior. Docs-only; tests/test_frontend/test_embed_snippet_hygiene.py passes.
answer_from_reply raises OverviewUnanswered when the surviving summary has no
dataset segment, so a refusal, an off-format reply or planted text is a 502 and
uncached. Sentences with a link are dropped, a long first sentence is kept
instead of leaving nothing, stray single brackets are removed, and
build_messages returns list[BaseMessage] (ty clean). Unit tests added; tested.
The call outlives a cancelled request, so it books its own cost on a 499 row
when the request that started it is gone. A failure that is not the provider's
is a 500 logged with its traceback; classified provider failures stay 502.
Route tests for refusals, off-format and planted replies, the cancelled-owner
spend, and the 500; the concurrency tests wait on arrivals with a 5 s timeout
instead of a fixed sleep. Tested.
…chat counter

100 an hour in production, 500 in development, key rl:overview:hour; the
per-minute limiter still applies. Shares a helper with the resume-chain
counter. README documents the budget and the Origin trust model. Tested with
workers/osa-worker/test-routing.js.
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Worker Deployment Required

Worker changes detected. After merging to main or develop, the workflow will automatically deploy the worker.

Manual deployment (if needed):

cd workers/osa-worker
wrangler deploy --env dev  # for develop branch
wrangler deploy            # for main branch

@neuromechanist

Copy link
Copy Markdown
Member Author

Review round 1: outcome for each finding (fix commits a2fdb0c, 7691879, d6f8818, e228f55 on this branch).

  • A reply that cites nothing is returned 200 and cached (important): fixed. answer_from_reply now raises OverviewUnanswered when the surviving summary has no result id, so a refusal, a JSON object with no summary, and a citation-free sentence are a 502 and uncached. Sentences holding a link (http://, https://, www.) are dropped as well (also in pick reasons). Unit tests (test_overview_unit.py) and route tests (TestACitationFreeReplyIsNotAnOverview) cover the refusal, the object with no summary, the planted link, a citation-free reply, and a link planted through a result's description.
  • /overview draws on the /chat hourly budget (important): fixed (own counter). The worker now gives /overview its own per-IP hourly budget (OVERVIEW_LIMIT_PER_HOUR, 100 in production, 500 in development, key rl:overview:hour:), exempt from the 20/hour /chat counter; the per-minute limiter still applies. It shares one helper with the resume-chain counter. test-routing.js now asserts a spent /chat hour does not block the overview, the overview does not add to the /chat count, and a spent overview hour is a 429 that leaves /chat alone. The worker README and docs/search-overview.md state the budget and the trust model (no Turnstile, Origin enforced by browsers only, so per-IP limits and the community budget are the only edge protection); .context/api-structure.md likewise.
  • Spend can go unlogged when the owning request is cancelled (suggestion): fixed. The call books its own cost on a 499 row (once, _OverviewSpend) when the request that started it is cancelled, whether the call is still running or has already finished; the normal path is unchanged. A route test cancels the owner while a joiner waits and asserts exactly one costed row (499, community, tier, tokens), the joiner's 200, and that the result was still cached. I checked the test fails with the booking disabled.
  • Generic except Exception hides bugs as a 502 (suggestion): fixed. A failure classify_model_error does not read as the provider's is now a 500, logged with exc_info; classified provider failures stay 502 with the existing log line. Test: a RuntimeError is a 500 with a traceback in the log record and nothing cached; the "does not clear" test now uses a provider 400.
  • build_messages annotation and the Segment alias (suggestion): fixed. build_messages returns list[BaseMessage] and OverviewResponse.summary is list[Segment]; ty check src/api/overview.py passes.
  • First sentence over the cap is a billed 502; bare-id filter is NEMAR-shaped; stray brackets (suggestion): fixed, with one part documented rather than changed. The first sentence is kept when it is over the cap alone (later ones are still dropped), stray single brackets are removed from text (See [[[xx099901]]] ok is clean). The bare-token pattern stays NEMAR-shaped by design (the route has no per-community setting yet, and [[...]] markers are checked for every community); api-structure.md and the docs page now say so.
  • Concurrency tests poll without a timeout and sleep a fixed time (suggestion): fixed. The tests wait with asyncio.timeout(5) on a condition: the model entered once and N requests have arrived at the cache (a counting wrapper around OverviewCache.get_or_compute that delegates to the real one), so no fixed sleep remains. The two gaps the finding names (citation-free answer, owner-cancelled spend) are the tests above.

Verification: uv run pytest tests/test_api tests/test_metrics tests/test_frontend (2186 passed), bun workers/osa-worker/test-routing.js (197 passed) and test-mounted-hosts.js (37 passed), uv run ruff check . && uv run ruff format --check . clean.

@neuromechanist

Copy link
Copy Markdown
Member Author

Review round 2 outcomes (fix commits c142363, 55ecb05, fb14145, f159061 on this branch).

  • Budget is not a ceiling (important): fixed. Reworded in workers/osa-worker/index.js, workers/osa-worker/README.md, docs/search-overview.md, .context/api-structure.md and the CHANGELOG entry: the community budget is monitored by the scheduler and opens an alert issue, it does not refuse requests, so the worker's per-IP limits are the only enforced control. No gate added in the route.
  • _URL_LIKE too narrow (suggestion): fixed. The filter now also drops javascript:, data:, vbscript: and mailto: schemes and bare hosts on .com/.org/.net/.io/.edu/.gov/.dev/.app/.info/.xyz; the docstring and docs/search-overview.md state it is a filter, not a guarantee, and that the website must render text segments as plain text without autolinking. Test cases added for evil.com/x and link(javascript:alert(1)).
  • _words second implementation (suggestion): fixed. tests/test_integration/test_search_overview_llm.py uses src.api.overview._plain_words. The test needs ANTHROPIC_API_KEY, so it was collected, not run.
  • CHANGELOG entry too long (suggestion): fixed. Split into sentence-per-line lines, review narration dropped, final behaviour stated once.

Tests: tests/test_api/test_overview_unit.py and tests/test_api/test_search_overview.py (152 passed), bun workers/osa-worker/test-routing.js (197 passed), uv run ruff check . and ruff format --check . clean.

@neuromechanist
neuromechanist merged commit 744e695 into develop Nov 11, 2026
10 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-702-search-overview branch November 11, 2026 09:06
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.

1 participant