diff --git a/references/source_dispatch.md b/references/source_dispatch.md index 72266c8..2c4146d 100644 --- a/references/source_dispatch.md +++ b/references/source_dispatch.md @@ -55,7 +55,7 @@ **Второй поисковый движок как отдельная ось.** Если в env есть `BRAVE_SEARCH_API_KEY` / `TAVILY_API_KEY` / `EXA_API_KEY` / `FIRECRAWL_API_KEY` (см. `capability_discovery.md`) — независимо от строки матрицы добавь ось `search-engine-2` через `scripts/search_query.py --engine auto --qclass --query "..."`, помимо `web-general`/WebSearch харнесса. Это не замена Primary/Secondary из матрицы, а дополнительная независимая траектория поиска; пересечение с WebSearch пишется в `plan.md` §15 как `overlap_rate`. -**Какой движок берёт `--engine auto`:** первый с ключом из порядка для `qclass` (`ENGINE_ROUTES` в `search_query.py`). Научные и концептуальные классы начинают с exa, свежие (`recent-change`, `sentiment`, `crypto`) с tavily → brave, фактические с tavily → exa. Выбор печатается в stderr, запиши его в §12. Порядок пока гипотеза: стабильно высокий `overlap_rate` на классе значит, что первый движок надо опустить. +**Какой движок берёт `--engine auto`:** первый с ключом из порядка для `qclass` (`ENGINE_ROUTES` в `search_query.py`). Научные и концептуальные классы начинают с exa, свежие (`recent-change`, `sentiment`, `crypto`) с tavily → brave, фактические с tavily → exa. Выбор печатается в stderr, запиши его в §12. Источникам с этой оси ставь в `discovery_path` канал `search-engine-2/<движок>` (печатается там же): по нему роевая постобработка считает отдачу каждого движка, и когда по классу появится статистика, `auto` выбирает движок по приорам, а не по таблице. **Если подвопрос не матчится** ни одну строку — действуй по умолчанию: `web-general` + `academic` + `news-current` минимум. И **сразу же запиши в plan.md секцию 12, что dispatch был ad-hoc** — это сигнал для Phase 6 (adversarial) что покрытие могло быть слабым. diff --git a/references/swarm_postprocess.md b/references/swarm_postprocess.md index dc7b80e..e5bdd92 100644 --- a/references/swarm_postprocess.md +++ b/references/swarm_postprocess.md @@ -13,6 +13,8 @@ python3 scripts/collect_observations.py --research-dir / --run-id |` +хотя бы для одного движка с ключом, выбор идёт Thompson sampling по приорам; движок без +наблюдений тянет из Beta(1, 1) и продолжает исследоваться. Каждый результат в `--json` +несёт поле `channel` (`search-engine-2/<движок>`) для `discovery_path`. Неизвестный или пропущенный `--qclass` даёт порядок класса `qualitative`. Нет ни одного ключа — exit 2 со списком всех переменных. diff --git a/scripts/search_query.py b/scripts/search_query.py index df70063..0eaf894 100644 --- a/scripts/search_query.py +++ b/scripts/search_query.py @@ -24,6 +24,7 @@ import argparse import json +import random import sys from datetime import datetime, timezone from pathlib import Path @@ -33,6 +34,16 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from runner.qclass import normalize_qclass # noqa: E402 +from runner.state import Prior, load_priors, prior_key # noqa: E402 + +# Channel name for the swarm priors: sources found through this script carry it as +# the first field of discovery_path, so collect_observations.py scores each engine +# per qclass with no extra code. +CHANNEL_PREFIX = "search-engine-2/" + + +def engine_channel(engine: str) -> str: + return CHANNEL_PREFIX + engine ENV_VARS = { "brave": "BRAVE_SEARCH_API_KEY", @@ -50,8 +61,8 @@ # gives, and the axis exists to diverge from it. # - firecrawl is last: the normalizer keeps only its description, so the # full-page content that distinguishes it is not used here. -# The order is a starting hypothesis; overlap_rate in plan.md §15 is what should -# move it. +# The order is a starting hypothesis, used until the swarm priors have data for +# the qclass (see resolve_engine). _SEMANTIC = ("exa", "tavily", "brave", "firecrawl") _FRESH = ("tavily", "brave", "exa", "firecrawl") _FACTUAL = ("tavily", "exa", "brave", "firecrawl") @@ -77,15 +88,36 @@ } -def resolve_engine(qclass: str | None, env: dict) -> str: - """First engine of the qclass route with a key set; SystemExit(2) if none.""" - route = ENGINE_ROUTES[normalize_qclass(qclass or "")] - for engine in route: - if _get_key(engine, env): - return engine - names = ", ".join(ENV_VARS[e] for e in route) - print(f"error: no search API key set — set one of {names}", file=sys.stderr) - raise SystemExit(2) +def resolve_engine( + qclass: str | None, + env: dict, + priors: dict[str, Prior] | None = None, + rng: random.Random | None = None, +) -> tuple[str, str]: + """Pick an engine among those with a key set; returns (engine, how it was picked). + + No observation for this qclass yet: the static route decides. Once any keyed + engine has one, Thompson-sample over all keyed engines (as runner/adaptive.py + does for channels): an engine never tried draws from Beta(1, 1), so it still + gets explored instead of the first measured engine winning forever. + SystemExit(2) if no key is set. + """ + qc = normalize_qclass(qclass or "") + route = ENGINE_ROUTES[qc] + keyed = [e for e in route if _get_key(e, env)] + if not keyed: + names = ", ".join(ENV_VARS[e] for e in route) + print(f"error: no search API key set — set one of {names}", file=sys.stderr) + raise SystemExit(2) + cells = {e: (priors or {}).get(prior_key(engine_channel(e), qc)) for e in keyed} + if len(keyed) == 1 or not any(cells.values()): + return keyed[0], "route" + rng = rng or random.Random() + draws = [ + (rng.betavariate(c.alpha, c.beta) if c else rng.betavariate(1.0, 1.0), e) + for e, c in cells.items() + ] + return max(draws)[1], "priors" FIRECRAWL_SNIPPET_MAX_CHARS = 1000 @@ -239,6 +271,7 @@ def normalize(engine: str, payload: dict) -> list[dict]: "url": h["url"], "snippet": h["snippet"], "engine": engine, + "channel": engine_channel(engine), "fetched_at": fetched_at, } ) @@ -284,9 +317,13 @@ def main(argv: list[str] | None = None) -> int: try: engine = args.engine if engine == "auto": - engine = resolve_engine(args.qclass, env) + engine, how = resolve_engine(args.qclass, env, load_priors()) qclass = normalize_qclass(args.qclass or "") - print(f"engine: {engine} (qclass {qclass})", file=sys.stderr) + print( + f"engine: {engine} (qclass {qclass}, by {how}); " + f"discovery_path channel: {engine_channel(engine)}", + file=sys.stderr, + ) hits = run_query(engine, args.query, args.n, env) except SystemExit as exc: return exc.code diff --git a/tests/test_search_query.py b/tests/test_search_query.py index 062256f..79324e4 100644 --- a/tests/test_search_query.py +++ b/tests/test_search_query.py @@ -177,20 +177,20 @@ def test_engine_routes_cover_every_qclass_with_every_engine(): def test_resolve_engine_follows_qclass_route(): env = {k: "x" for k in sq.ENV_VARS.values()} - assert sq.resolve_engine("scientific-claim", env) == "exa" - assert sq.resolve_engine("recent-change", env) == "tavily" + assert sq.resolve_engine("scientific-claim", env)[0] == "exa" + assert sq.resolve_engine("recent-change", env)[0] == "tavily" def test_resolve_engine_skips_engines_without_key(): env = {"BRAVE_SEARCH_API_KEY": "b", "FIRECRAWL_API_KEY": "f"} - assert sq.resolve_engine("scientific-claim", env) == "brave" - assert sq.resolve_engine("pricing", {"FIRECRAWL_API_KEY": "f"}) == "firecrawl" + assert sq.resolve_engine("scientific-claim", env)[0] == "brave" + assert sq.resolve_engine("pricing", {"FIRECRAWL_API_KEY": "f"})[0] == "firecrawl" def test_resolve_engine_unknown_qclass_uses_default_route(): env = {"EXA_API_KEY": "e", "TAVILY_API_KEY": "t"} - assert sq.resolve_engine("nonsense", env) == sq.ENGINE_ROUTES["qualitative"][0] - assert sq.resolve_engine(None, env) == sq.ENGINE_ROUTES["qualitative"][0] + assert sq.resolve_engine("nonsense", env)[0] == sq.ENGINE_ROUTES["qualitative"][0] + assert sq.resolve_engine(None, env)[0] == sq.ENGINE_ROUTES["qualitative"][0] def test_resolve_engine_no_keys_exits_2_naming_all_vars(capsys): @@ -215,8 +215,62 @@ def fake_request(method, timeout=None, **kwargs): for var in ("TAVILY_API_KEY", "FIRECRAWL_API_KEY"): monkeypatch.delenv(var, raising=False) + monkeypatch.setattr(sq, "load_priors", lambda: {}) rc = sq.main(["--engine", "auto", "--qclass", "how-it-works", "--query", "q"]) assert rc == 0 assert captured["url"].startswith("https://api.exa.ai") - assert "engine: exa (qclass how-it-works)" in capsys.readouterr().err + err = capsys.readouterr().err + assert "engine: exa (qclass how-it-works, by route)" in err + assert "search-engine-2/exa" in err + + +def _prior(alpha, beta, n=10): + from runner.state import Prior + + return Prior(alpha=alpha, beta=beta, n=n, last_seen="") + + +def test_resolve_engine_uses_priors_once_a_cell_exists(): + import random + + env = {"EXA_API_KEY": "e", "BRAVE_SEARCH_API_KEY": "b"} + priors = {"search-engine-2/brave|scientific-claim": _prior(50.0, 1.0)} + picks = [ + sq.resolve_engine("scientific-claim", env, priors, random.Random(seed)) + for seed in range(50) + ] + assert all(how == "priors" for _, how in picks) + # brave's cell is strong, exa has none and draws from Beta(1, 1): + # brave wins most draws, exa still gets explored sometimes. + engines = [e for e, _ in picks] + assert engines.count("brave") > 40 and "exa" in engines + + +def test_resolve_engine_ignores_priors_of_other_qclass_and_single_key(): + env = {"EXA_API_KEY": "e", "BRAVE_SEARCH_API_KEY": "b"} + other = {"search-engine-2/brave|pricing": _prior(50.0, 1.0)} + assert sq.resolve_engine("scientific-claim", env, other) == ("exa", "route") + only_exa = {"EXA_API_KEY": "e"} + strong = {"search-engine-2/brave|scientific-claim": _prior(50.0, 1.0)} + assert sq.resolve_engine("scientific-claim", only_exa, strong) == ("exa", "route") + + +def test_hits_carry_the_priors_channel(): + hits = sq.normalize("exa", {"results": [{"title": "T", "url": "https://u", "text": "s"}]}) + assert hits[0]["channel"] == "search-engine-2/exa" + + +def test_engine_channel_is_scored_by_collect_observations(tmp_path): + from scripts import collect_observations as co + + (tmp_path / "sources").mkdir() + (tmp_path / "sources" / "01_x.md").write_text( + "---\nid: s1\ndiscovery_path: search-engine-2/exa|query|en\n---\nbody\n", + encoding="utf-8", + ) + (tmp_path / "claims.csv").write_text("claim_id,sources,dissent\nCL1,s1,-\n", encoding="utf-8") + obs = co.collect(tmp_path, "run1", {"search-engine-2/exa": "scientific-claim"}) + assert [(o.channel, o.qclass, o.reward) for o in obs] == [ + ("search-engine-2/exa", "scientific-claim", 1) + ]