diff --git a/CHANGELOG.md b/CHANGELOG.md index 7542320d2..54f739fb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,19 @@ All notable changes to SkillOpt are documented here. This project adheres to search setting. An API key echoed in an error body is redacted before the text reaches `fail_reason`, and the round deadline is checked again after each response. +- **OfficeQA SpecStream search** as an opt-in `env.search_mode=specstream` + provider for `openai_chat`/`qwen_chat`. The default stays `offline` and no + config selects SpecStream automatically. Selecting it needs + `SPECSTREAM_API_KEY` and sends the generated search queries, one `POST` per + query with `speed=fast`, with that key in an `Authorization: Bearer` header + to SpecStream's web search endpoint. The task question is not sent. No key, + credential or account is bundled, a missing key fails the rollout before + the first model call, and service errors fail the rollout with no fallback. + Redirects are not followed, an API key echoed in an error body is redacted, + and one `search_timeout_seconds` deadline, checked again after each + response, covers each round. It uses the core `httpx` dependency, so it + needs no extra. Its scores are not directly comparable to the paper's + Google-backed search setting. - **SkillOpt-Sleep paired A/B evalkit** (`python -m skillopt_sleep.evalkit`): McNemar plus percentile-bootstrap CIs on a fixed task manifest, with task-cluster multi-seed inference and seeded null calibration for exact-test diff --git a/docs/reference/config.md b/docs/reference/config.md index 83de3c6c1..8d0ba2eff 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -225,8 +225,9 @@ corpus and makes no network search call. | `env.search_mode: azure_search` | Use the model-provided Azure search path. | | `env.search_mode: parallel` | Opt in to Parallel's hosted Search MCP. Requires `openai_chat` or `qwen_chat` and the `parallel` extra. | | `env.search_mode: keenable` | Opt in to Keenable's search API. Requires `openai_chat` or `qwen_chat`; no extra and no key needed. | -| `env.search_timeout_seconds` | Whole MCP discovery/search deadline in seconds (default `20`); for `keenable`, the deadline for all queries of one round. | -| `env.search_max_num_results` | Maximum number of Parallel evidence results per round, or Keenable results per query (default `4`). For Keenable a round can therefore carry up to `max_queries_per_turn × search_max_num_results` results: 16 with the defaults, up to about 97k characters of evidence. | +| `env.search_mode: specstream` | Opt in to SpecStream's web search API. Requires `openai_chat` or `qwen_chat` and `SPECSTREAM_API_KEY`; no extra needed. | +| `env.search_timeout_seconds` | Whole MCP discovery/search deadline in seconds (default `20`); for `keenable` and `specstream`, the deadline for all queries of one round. | +| `env.search_max_num_results` | Maximum number of Parallel evidence results per round, or Keenable or SpecStream results per query (default `4`; at most `50` for SpecStream). For Keenable and SpecStream a round can therefore carry up to `max_queries_per_turn × search_max_num_results` results: 16 with the defaults, up to about 97k characters of evidence. | | `env.max_queries_per_turn` / `env.max_tool_turns` | Bound model-requested queries and model rounds. | #### Parallel Search MCP (opt-in) @@ -293,6 +294,44 @@ source-page context is included when that corpus is available. This mode changes the evidence source, so its scores are not directly comparable to, and are not a reproduction of, the paper's Google-backed search setting. +#### SpecStream search (opt-in) + +[SpecStream](https://specstream.ai/docs) web search is never selected +automatically, by default or by `auto`. It is used only when you set +`env.search_mode=specstream` explicitly, for example with +`--cfg-options env.search_mode=specstream`, and it needs `SPECSTREAM_API_KEY`; +selecting the mode without that variable fails the rollout before the first +model call and before any request. It calls a plain HTTPS JSON API through the +core `httpx` dependency, so it needs no extra. SkillOpt bundles no SpecStream +API key, credential or account; if you enable this mode, you use the service +under SpecStream's own terms. + +**Data boundary.** When this mode is selected, each search round sends each +query from the model's generated `` to +`https://api.specstream.ai/v1/web-search`, one HTTPS `POST` per query. A +request carries exactly: + +- a JSON body with the query text as `q`, `env.search_max_num_results` as + `num`, and `"speed": "fast"`; +- your `SPECSTREAM_API_KEY`, in an `Authorization: Bearer` header; +- SkillOpt's `User-Agent` (`SkillOpt/ (+https://github.com/microsoft/SkillOpt)`) + and httpx's standard transport headers. + +SkillOpt does not send the task question, the OfficeQA corpus or any other +credential as such. A generated query is model output, though, so it can +repeat text from the question, from the provided document context or from the +skill. Redirects are not followed, so the key and the queries go only to that +endpoint. Each request is billed to the key's account at the `fast` search +rate listed in SpecStream's documentation. Rate-limit, credit and other +service errors fail the rollout with a search diagnostic that carries the +service's error message, with the key redacted; an explicit provider never +silently falls back to another one. + +SpecStream search does not require a local OfficeQA document corpus; parsed +source-page context is included when that corpus is available. This mode +changes the evidence source, so its scores are not directly comparable to, +and are not a reproduction of, the paper's Google-backed search setting. + ## Credential Environment Variables ### Azure-family backend diff --git a/skillopt/envs/officeqa/rollout.py b/skillopt/envs/officeqa/rollout.py index c3aac5511..a11163370 100644 --- a/skillopt/envs/officeqa/rollout.py +++ b/skillopt/envs/officeqa/rollout.py @@ -8,6 +8,8 @@ from skillopt.envs.officeqa.evaluator import evaluate from skillopt.envs.officeqa.keenable_search import keenable_search +from skillopt.envs.officeqa.specstream_search import API_KEY_ENV as SPECSTREAM_API_KEY_ENV +from skillopt.envs.officeqa.specstream_search import specstream_search from skillopt.envs.officeqa.tool_runtime import ( build_oracle_parsed_pages_context, custom_search, @@ -74,6 +76,7 @@ _AZURE_SEARCH_MODE = "azure_search" _PARALLEL_SEARCH_MODE = "parallel" _KEENABLE_SEARCH_MODE = "keenable" +_SPECSTREAM_SEARCH_MODE = "specstream" def _normalize_search_mode(search_mode: str | None) -> str: normalized = str(search_mode or _DEFAULT_SEARCH_MODE).strip().lower() if normalized in {"custom", _CUSTOM_SEARCH_MODE}: @@ -84,6 +87,8 @@ def _normalize_search_mode(search_mode: str | None) -> str: return _PARALLEL_SEARCH_MODE if normalized == _KEENABLE_SEARCH_MODE: return _KEENABLE_SEARCH_MODE + if normalized == _SPECSTREAM_SEARCH_MODE: + return _SPECSTREAM_SEARCH_MODE return _DEFAULT_SEARCH_MODE def _load_parallel_search(): """Import the Parallel client only when `parallel` mode is actually selected. @@ -119,7 +124,7 @@ def _build_system( "answer inside ....\n\n" + skill_section ).rstrip() - if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE}: + if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE, _SPECSTREAM_SEARCH_MODE}: protocol = ( "You are an expert OfficeQA research assistant. Solve the question using the provided oracle parsed " "OfficeQA page(s) and evidence returned by the controller-managed custom search loop.\n\n" @@ -193,7 +198,7 @@ def _build_user( parts.append("## File Hints\n" + "\n".join(f"- {hint}" for hint in item["source_files"])) if diagnostic_mode and diagnostic_instruction.strip(): parts.append(f"## Training Readout\n{diagnostic_instruction.strip()}") - if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE}: + if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE, _SPECSTREAM_SEARCH_MODE}: parts.append( _build_round_instruction( turn=turn, @@ -384,6 +389,8 @@ def _run_custom_search_process( raise ValueError("custom_search mode requires a non-empty search_api_url") if search_mode == _CUSTOM_SEARCH_MODE and not os.environ.get(search_auth_env, "").strip(): raise ValueError(f"custom_search mode requires auth token env var {search_auth_env}") + if search_mode == _SPECSTREAM_SEARCH_MODE and not os.environ.get(SPECSTREAM_API_KEY_ENV, "").strip(): + raise ValueError(f"specstream mode requires the {SPECSTREAM_API_KEY_ENV} environment variable") if get_target_backend() not in {"openai_chat", "qwen_chat"}: raise ValueError(f"{search_mode} mode is only supported with target_backend='openai_chat' or 'qwen_chat'") system = _build_system( @@ -450,6 +457,11 @@ def _run_custom_search_process( results_text = keenable_search( queries, max_num_results=search_max_num_results, timeout=search_timeout_seconds, ) + elif search_mode == _SPECSTREAM_SEARCH_MODE: + # Same rule as Parallel: a failed explicit provider stays an error. + results_text = specstream_search( + queries, max_num_results=search_max_num_results, timeout=search_timeout_seconds, + ) else: results_text = _execute_custom_search_round( queries, @@ -590,7 +602,7 @@ def process_one( else "Treat it as primary document evidence for answering the question." ), ) - elif normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE}: + elif normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE, _SPECSTREAM_SEARCH_MODE}: try: docs_roots = resolve_docs_roots(data_dirs) except FileNotFoundError: @@ -629,7 +641,7 @@ def process_one( last_response_metadata: dict = {} allowed_files = [os.path.basename(path) for path in candidate_files] try: - if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE}: + if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE, _SPECSTREAM_SEARCH_MODE}: system, user, final_response, final_answer, conversation, fail_reason, last_response_metadata = _run_custom_search_process( item, skill_content, diff --git a/skillopt/envs/officeqa/specstream_search.py b/skillopt/envs/officeqa/specstream_search.py new file mode 100644 index 000000000..577184ca2 --- /dev/null +++ b/skillopt/envs/officeqa/specstream_search.py @@ -0,0 +1,112 @@ +"""SpecStream web search client for the OfficeQA controller's search rounds. + +Reached only through the explicit `search_mode=specstream` selection, and only +with `SPECSTREAM_API_KEY` set. Every call sends each of the model's generated +queries, and nothing else from the task, to SpecStream's web search API. +""" +from __future__ import annotations + +import os +import time +from urllib.parse import urlsplit + +import httpx + +from skillopt import __version__ + +SEARCH_URL = "https://api.specstream.ai/v1/web-search" +API_KEY_ENV = "SPECSTREAM_API_KEY" +USER_AGENT = f"SkillOpt/{__version__} (+https://github.com/microsoft/SkillOpt)" +# `fast` is the lower-cost search tier. +SPEED = "fast" +MAX_RESULTS_LIMIT = 50 + + +def _render(index: int, query: str, sources: list, max_num_results: int) -> str: + blocks = [] + for item in sources: + if len(blocks) >= max_num_results: + break + if not isinstance(item, dict): + raise RuntimeError("SpecStream search returned an invalid source item") + url = item.get("url") + if url is None or url == "": + continue + if not isinstance(url, str) or urlsplit(url).scheme not in {"http", "https"} or not urlsplit(url).netloc: + raise RuntimeError("SpecStream search returned an invalid source URL") + snippet = item.get("snippet") or "" + if not isinstance(snippet, str): + raise RuntimeError("SpecStream search returned an invalid snippet") + if not snippet.strip(): + highlights = item.get("highlights") or [] + if not isinstance(highlights, list): + raise RuntimeError("SpecStream search returned invalid highlights") + snippet = " ".join(text.strip() for text in highlights if isinstance(text, str) and text.strip()) + title = item.get("title") + if not isinstance(title, str) or not title.strip(): + title = url + published = item.get("published") + dated = f"Published: {published.strip()}\n" if isinstance(published, str) and published.strip() else "" + blocks.append(f"[{len(blocks) + 1}] {title.strip()}\nURL: {url}\n{dated}{snippet.strip()[:6000]}") + body = "\n\n".join(blocks) if blocks else "[no search results]" + return f"## Query {index}\nQuery: {query}\n\n{body}" + + +def _error_detail(response: httpx.Response) -> str: + """Prefer the API's `error.message`; fall back to the raw body text.""" + try: + payload = response.json() + except ValueError: + return response.text + error = payload.get("error") if isinstance(payload, dict) else None + message = error.get("message") if isinstance(error, dict) else None + return message if isinstance(message, str) and message.strip() else response.text + + +def specstream_search(queries: list[str], *, max_num_results: int = 4, timeout: float = 20) -> str: + """Search each query within one round deadline and render URL evidence. + + Requires `SPECSTREAM_API_KEY`. Service errors propagate to the controller; + an exceeded deadline always raises the built-in `TimeoutError`. + """ + if not queries or any(not isinstance(query, str) or not query.strip() for query in queries): + raise ValueError("SpecStream search requires non-empty queries") + if timeout <= 0 or not 1 <= max_num_results <= MAX_RESULTS_LIMIT: + raise ValueError(f"SpecStream search needs a positive timeout and 1-{MAX_RESULTS_LIMIT} results") + api_key = os.environ.get(API_KEY_ENV, "").strip() + if not api_key: + raise ValueError(f"specstream mode requires the {API_KEY_ENV} environment variable") + headers = {"User-Agent": USER_AGENT, "Authorization": f"Bearer {api_key}"} + deadline = time.monotonic() + timeout + sections = [] + # Redirects are not followed, so the key and the queries only ever go to SEARCH_URL. + with httpx.Client(headers=headers, follow_redirects=False) as client: + for index, query in enumerate(queries, start=1): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError(f"SpecStream search exceeded its {timeout}s deadline") + try: + response = client.post( + SEARCH_URL, json={"q": query, "num": max_num_results, "speed": SPEED}, timeout=remaining, + ) + except httpx.TimeoutException as exc: + raise TimeoutError(f"SpecStream search exceeded its {timeout}s deadline") from exc + # httpx applies `timeout` per phase, so a slow response can still end + # past the round deadline; check it again once the response is in. + if time.monotonic() > deadline: + raise TimeoutError(f"SpecStream search exceeded its {timeout}s deadline") + if response.status_code != 200: + # The error text reaches fail_reason, results.jsonl and the + # reflection prompt. Redact before cutting, so a key straddling + # the cut can't leak a prefix. + detail = _error_detail(response).replace(api_key, "[redacted]") + raise RuntimeError(f"SpecStream search HTTP {response.status_code}: {detail[:1000]}") + try: + payload = response.json() + except ValueError as exc: + raise RuntimeError("SpecStream search returned invalid JSON") from exc + data = payload.get("data") if isinstance(payload, dict) else None + if not isinstance(data, dict) or not isinstance(data.get("sources"), list): + raise RuntimeError("SpecStream search returned invalid results") + sections.append(_render(index, query, data["sources"], max_num_results)) + return "\n\n".join(sections) diff --git a/tests/test_officeqa_specstream_search.py b/tests/test_officeqa_specstream_search.py new file mode 100644 index 000000000..6495add7b --- /dev/null +++ b/tests/test_officeqa_specstream_search.py @@ -0,0 +1,353 @@ +"""OfficeQA `search_mode=specstream` selection, request data boundary and evidence handling.""" +from __future__ import annotations + +import json +from types import SimpleNamespace +from unittest import mock + +import httpx +import pytest + +from skillopt.envs.officeqa import rollout +from skillopt.envs.officeqa import specstream_search as specstream +from skillopt.envs.officeqa.adapter import OfficeQAAdapter + +KEY = "ss-test-key" +ITEM = {"id": "treasury", "question": "When was the declaration signed?", "ground_truth": "1776"} +PAYLOAD = { + "data": { + "request_id": "req_1", + "query": "declaration treasury history", + "took_ms": 300, + "price_usd": 0.001, + "sources": [ + { + "url": "https://example.org/treasury?year=1776", + "title": "Treasury history", + "snippet": "The declaration was signed in 1776.", + "site": "example.org", + "published": "2026-11-30", + "highlights": [], + "excerpt": None, + } + ], + } +} + + +@pytest.fixture(autouse=True) +def isolated_search_config(monkeypatch): + for name in ("OFFICEQA_CUSTOM_SEARCH_AUTH", "OFFICEQA_SEARCH_API_URL", "PARALLEL_API_KEY", "KEENABLE_API_KEY", "SPECSTREAM_API_KEY"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setattr(rollout, "get_target_backend", lambda: "openai_chat") + + +@pytest.fixture +def api_key(monkeypatch): + monkeypatch.setenv("SPECSTREAM_API_KEY", KEY) + return KEY + + +@pytest.fixture +def transport(monkeypatch): + """Record the HTTP requests the client sends and answer them from `behavior`.""" + requests = [] + behavior = {"payload": PAYLOAD, "status": 200, "timeout": False, "response": None} + original_client = httpx.Client + + def handler(request): + requests.append((request, json.loads(request.content))) + if behavior["response"] is not None: + return behavior["response"] + if behavior["timeout"]: + raise httpx.ReadTimeout("read timed out", request=request) + if behavior["status"] != 200: + return httpx.Response(behavior["status"], json={"error": {"code": "rate_limited", "message": "Too many requests"}}) + return httpx.Response(200, json=behavior["payload"]) + + def client(**kwargs): + return original_client(transport=httpx.MockTransport(handler), **kwargs) + + monkeypatch.setattr(specstream.httpx, "Client", client) + return requests, behavior + + +def scripted_model(monkeypatch, *, rounds=1, queries='["declaration treasury history"]'): + calls = [] + + def chat(**kwargs): + messages = [dict(message) for message in kwargs["messages"]] + calls.append(messages) + if len(calls) <= rounds: + text = f"{queries}" + else: + assert "https://example.org/treasury?year=1776" in messages[-1]["content"] + assert "signed in 1776" in messages[-1]["content"] + text = "1776" + return SimpleNamespace(content=text), {} + + monkeypatch.setattr(rollout, "chat_target_messages", chat) + return calls + + +# ── Selection: SpecStream is never automatic ───────────────────────────────── + +@pytest.mark.parametrize("mode", ["auto", "", None, "web", "specstream_search", "keenable", "parallel"]) +def test_auto_and_other_modes_never_select_specstream(mode): + assert rollout._normalize_search_mode(mode) != rollout._SPECSTREAM_SEARCH_MODE + + +@pytest.mark.parametrize("mode", ["specstream", "SPECSTREAM", " SpecStream "]) +def test_specstream_requires_explicit_selection(mode): + assert rollout._normalize_search_mode(mode) == rollout._SPECSTREAM_SEARCH_MODE + + +@pytest.mark.parametrize("mode", ["auto", "offline"]) +def test_fresh_config_never_calls_specstream(tmp_path, monkeypatch, transport, api_key, mode): + docs = tmp_path / "docs" + docs.mkdir() + # A key is set and the model asks for search; outside explicit specstream mode nothing may reach SpecStream. + responses = iter(['["declaration treasury history"]']) + monkeypatch.setattr( + rollout, "chat_target_messages", + lambda **kwargs: (SimpleNamespace(content=next(responses, "1776")), {}), + ) + rollout.process_one(ITEM, str(tmp_path / "out"), "", search_mode=mode, use_local_tools=False, data_dirs=[str(docs)]) + assert transport[0] == [] + + +# ── Rollout through the search endpoint ────────────────────────────────────── + +@pytest.mark.parametrize("backend", ["openai_chat", "qwen_chat"]) +def test_explicit_specstream_searches_and_consumes_evidence(tmp_path, monkeypatch, transport, api_key, backend): + monkeypatch.setattr(rollout, "get_target_backend", lambda: backend) + calls = scripted_model(monkeypatch, rounds=2) + adapter = OfficeQAAdapter(search_mode="specstream", workers=1, max_tool_turns=3) + rows = adapter.rollout([ITEM], "Read evidence before answering.", str(tmp_path)) + assert rows[0]["predicted_answer"] == "1776" + assert rows[0]["hard"] == 1 + assert len(calls) == 3 + requests, _ = transport + assert len(requests) == 2 + for request, body in requests: + assert request.method == "POST" + assert str(request.url) == specstream.SEARCH_URL + assert request.headers["authorization"] == f"Bearer {KEY}" + assert request.headers["user-agent"] == specstream.USER_AGENT + assert "x-api-key" not in request.headers + # Documented data boundary: only the generated query leaves, never the task question. + assert body == {"q": "declaration treasury history", "num": 4, "speed": "fast"} + assert ITEM["question"] not in request.content.decode() + conversation = json.loads((tmp_path / "predictions" / ITEM["id"] / "conversation.json").read_text()) + assert any(event.get("type") == "tool_call" and "signed in 1776" in event["obs"] for event in conversation) + + +def test_the_data_envelope_is_parsed_into_evidence(transport, api_key): + text = specstream.specstream_search(["treasury"]) + assert text == ( + "## Query 1\nQuery: treasury\n\n" + "[1] Treasury history\nURL: https://example.org/treasury?year=1776\n" + "Published: 2026-11-30\nThe declaration was signed in 1776." + ) + + +def test_sources_outside_the_data_envelope_are_rejected(transport, api_key): + transport[1]["payload"] = PAYLOAD["data"] + with pytest.raises(RuntimeError, match="invalid results"): + specstream.specstream_search(["treasury"]) + + +def test_each_query_is_one_request_with_its_own_evidence_block(transport, api_key): + text = specstream.specstream_search(["treasury", "declaration"], max_num_results=2) + assert [body["q"] for _, body in transport[0]] == ["treasury", "declaration"] + assert all(body["num"] == 2 and body["speed"] == "fast" for _, body in transport[0]) + assert text.index("## Query 1\nQuery: treasury") < text.index("## Query 2\nQuery: declaration") + assert text.count("URL: https://example.org/treasury?year=1776") == 2 + + +def test_results_beyond_the_limit_and_long_snippets_are_cut(transport, api_key): + transport[1]["payload"] = {"data": {"sources": [{"url": f"https://example.org/{n}", "title": f"T{n}", "snippet": "x" * 9000} for n in range(5)]}} + text = specstream.specstream_search(["treasury"], max_num_results=2) + assert "https://example.org/1" in text and "https://example.org/2" not in text + assert "x" * 6000 in text and "x" * 6001 not in text + + +def test_sources_without_a_url_are_skipped(transport, api_key): + transport[1]["payload"] = {"data": {"sources": [ + {"title": "no url", "snippet": "skip me"}, + {"url": "", "title": "empty url", "snippet": "skip me too"}, + {"url": "https://example.org/kept", "title": "Kept", "snippet": "kept"}, + ]}} + text = specstream.specstream_search(["treasury"], max_num_results=1) + assert "skip me" not in text + assert "[1] Kept\nURL: https://example.org/kept\nkept" in text + + +def test_highlights_fill_in_for_an_empty_snippet(transport, api_key): + transport[1]["payload"] = {"data": {"sources": [ + {"url": "https://example.org/h", "title": "H", "snippet": "", "published": None, "highlights": ["Signed in 1776.", "At the Treasury."]}, + ]}} + text = specstream.specstream_search(["treasury"]) + assert "[1] H\nURL: https://example.org/h\nSigned in 1776. At the Treasury." in text + assert "Published:" not in text + + +def test_empty_results_render_a_placeholder(transport, api_key): + transport[1]["payload"] = {"data": {"sources": []}} + assert specstream.specstream_search(["treasury"]).endswith("[no search results]") + + +# ── Required key and other credentials ─────────────────────────────────────── + +def test_the_client_refuses_to_run_without_a_key(transport): + with pytest.raises(ValueError, match="SPECSTREAM_API_KEY"): + specstream.specstream_search(["treasury"]) + assert transport[0] == [] + + +@pytest.mark.parametrize("value", [None, "", " "]) +def test_a_missing_key_fails_before_the_first_model_call(tmp_path, monkeypatch, transport, value): + if value is not None: + monkeypatch.setenv("SPECSTREAM_API_KEY", value) + calls = scripted_model(monkeypatch) + row = rollout.process_one(ITEM, str(tmp_path), "", search_mode="specstream", max_tool_turns=2) + assert "specstream mode requires the SPECSTREAM_API_KEY environment variable" in row["fail_reason"] + assert row["hard"] == 0 + assert calls == [] + assert transport[0] == [] + + +def test_explicit_specstream_ignores_other_search_credentials(tmp_path, monkeypatch, transport, api_key): + monkeypatch.setenv("OFFICEQA_CUSTOM_SEARCH_AUTH", "configured-token") + monkeypatch.setenv("PARALLEL_API_KEY", "must-not-be-sent") + monkeypatch.setenv("KEENABLE_API_KEY", "must-not-be-sent-either") + scripted_model(monkeypatch) + row = rollout.process_one(ITEM, str(tmp_path), "", search_mode="specstream", search_provider="google", max_tool_turns=2) + assert row["hard"] == 1 + request, _ = transport[0][0] + assert str(request.url) == specstream.SEARCH_URL + assert request.headers["authorization"] == f"Bearer {KEY}" + assert "x-api-key" not in request.headers + assert "configured-token" not in str(request.headers) and "must-not-be-sent" not in str(request.headers) + + +# ── Failures: no fallback, bounded time, validated evidence ────────────────── + +@pytest.mark.parametrize("status", [401, 402, 429, 503]) +def test_service_errors_fail_the_task_without_fallback(tmp_path, monkeypatch, transport, api_key, status): + transport[1]["status"] = status + calls = scripted_model(monkeypatch) + with ( + mock.patch.object(rollout, "custom_search", side_effect=AssertionError("no fallback")), + mock.patch.object(rollout, "_load_parallel_search", side_effect=AssertionError("no fallback")), + mock.patch.object(rollout, "keenable_search", side_effect=AssertionError("no fallback")), + ): + row = rollout.process_one(ITEM, str(tmp_path), "", search_mode="specstream", max_tool_turns=2) + assert f"SpecStream search HTTP {status}: Too many requests" in row["fail_reason"] + assert row["hard"] == 0 + assert len(calls) == 1 + + +def test_an_error_without_a_message_falls_back_to_the_body(transport, api_key): + transport[1]["response"] = httpx.Response(502, text="Bad Gateway") + with pytest.raises(RuntimeError, match="SpecStream search HTTP 502: Bad Gateway"): + specstream.specstream_search(["treasury"]) + + +def test_a_transport_timeout_raises_the_builtin_timeout_error(transport, api_key): + transport[1]["timeout"] = True + with pytest.raises(TimeoutError): + specstream.specstream_search(["treasury"]) + + +def test_one_deadline_covers_every_query_of_a_round(monkeypatch, transport, api_key): + clock = iter([0.0, 0.0, 10.0, 25.0]) + monkeypatch.setattr(specstream.time, "monotonic", lambda: next(clock)) + with pytest.raises(TimeoutError): + specstream.specstream_search(["treasury", "declaration"], timeout=20) + assert len(transport[0]) == 1 + + +def test_a_response_that_ends_past_the_deadline_fails_the_round(monkeypatch, transport, api_key): + # One query: checked before the request at t=0, the response lands at t=25. + clock = iter([0.0, 0.0, 25.0]) + monkeypatch.setattr(specstream.time, "monotonic", lambda: next(clock)) + with pytest.raises(TimeoutError): + specstream.specstream_search(["treasury"], timeout=20) + assert len(transport[0]) == 1 + + +@pytest.mark.parametrize( + "payload", + [ + {"data": {"sources": [{"url": "file:///etc/passwd", "snippet": "bad"}]}}, + {"data": {"sources": "malformed"}}, + {"data": {"sources": [{"url": "https://example.org", "snippet": ["not", "text"]}]}}, + {"data": {"sources": ["not a dict"]}}, + {"data": None}, + [], + ], +) +def test_bad_evidence_is_rejected(transport, api_key, payload): + transport[1]["payload"] = payload + with pytest.raises(RuntimeError, match="invalid"): + specstream.specstream_search(["treasury"]) + + +@pytest.mark.parametrize(("queries", "kwargs"), [([], {}), ([" "], {}), (["q"], {"timeout": 0}), (["q"], {"max_num_results": 0}), (["q"], {"max_num_results": 51})]) +def test_invalid_arguments_are_refused_before_any_request(transport, api_key, queries, kwargs): + with pytest.raises(ValueError): + specstream.specstream_search(queries, **kwargs) + assert not transport[0] + + +def test_a_redirect_is_not_followed(transport, api_key): + # Following a 307 would resend the query to another origin, and the bearer key with it on a same-origin target. + transport[1]["response"] = httpx.Response(307, headers={"Location": "https://elsewhere.example/steal"}) + with pytest.raises(RuntimeError, match="SpecStream search HTTP 307"): + specstream.specstream_search(["treasury"]) + assert [str(request.url) for request, _ in transport[0]] == [specstream.SEARCH_URL] + + +def test_a_non_json_body_fails_instead_of_returning_no_results(transport, api_key): + transport[1]["response"] = httpx.Response(200, text="maintenance") + with pytest.raises(RuntimeError, match="invalid JSON"): + specstream.specstream_search(["treasury"]) + + +def test_a_key_echoed_in_an_error_message_is_redacted(tmp_path, monkeypatch, transport, api_key): + transport[1]["response"] = httpx.Response(401, json={"error": {"code": "unauthorized", "message": f"invalid key {KEY} for this workspace"}}) + scripted_model(monkeypatch) + row = rollout.process_one(ITEM, str(tmp_path), "", search_mode="specstream", max_tool_turns=2) + assert "SpecStream search HTTP 401: invalid key [redacted] for this workspace" in row["fail_reason"] + assert KEY not in row["fail_reason"] + assert KEY not in (tmp_path / "predictions" / ITEM["id"] / "conversation.json").read_text() + + +def test_a_key_echoed_in_a_plain_error_body_is_redacted(transport, api_key): + transport[1]["response"] = httpx.Response(401, text=f"bad bearer {KEY}") + with pytest.raises(RuntimeError) as excinfo: + specstream.specstream_search(["treasury"]) + assert "[redacted]" in str(excinfo.value) and KEY not in str(excinfo.value) + + +def test_a_key_straddling_the_error_cut_leaks_no_prefix(transport, api_key): + transport[1]["response"] = httpx.Response(401, text="x" * 995 + KEY) + with pytest.raises(RuntimeError) as excinfo: + specstream.specstream_search(["treasury"]) + assert KEY[:5] not in str(excinfo.value) + + +@pytest.mark.parametrize("backend", ["codex_exec", "copilot_exec", "azure_openai_responses"]) +def test_specstream_refuses_a_non_chat_backend_before_any_request(tmp_path, monkeypatch, transport, api_key, backend): + monkeypatch.setattr(rollout, "get_target_backend", lambda: backend) + scripted_model(monkeypatch) + row = rollout.process_one(ITEM, str(tmp_path), "", search_mode="specstream", max_tool_turns=2) + assert "only supported with target_backend='openai_chat' or 'qwen_chat'" in row["fail_reason"] + assert transport[0] == [] + + +@pytest.mark.parametrize("title", [None, "", " ", 42, ["Treasury"]]) +def test_a_missing_or_non_string_title_falls_back_to_the_url(transport, api_key, title): + transport[1]["payload"] = {"data": {"sources": [{"url": "https://example.org/t", "title": title, "snippet": "s"}]}} + assert "[1] https://example.org/t\nURL: https://example.org/t" in specstream.specstream_search(["treasury"])