Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(http): cap decoded judge and generation responses (#1929)

Nurkhan Esenbekedc980d2cb9e
diff --git a/changelog.d/0.76.0/1929.security.md b/changelog.d/0.76.0/1929.security.md
new file mode 100644
index 00000000..afb575a8
--- /dev/null
+++ b/changelog.d/0.76.0/1929.security.md
@@ -0,0 +1,6 @@
+- Bound judge replies to 1 MiB and HTTP generation/Magpie replies to 8 MiB while
+ streaming decoded bytes, including gzip expansion. Oversized replies are
+ refused before JSON parsing, close the response stream, and do not log the
+ response body. Generation/judge errors identify the endpoint setting and cap;
+ Magpie drops the affected sample and continues within its attempt limit
+ (#1819 by @kok-o in #1929).
diff --git a/docs/data.md b/docs/data.md
index 62d910ea..aabeeb03 100644
--- a/docs/data.md
+++ b/docs/data.md
@@ -459,6 +459,15 @@ valid IPv4 address (`10.0.0.256`, `4294967296`) is refused as well.
### Multi-Provider Support
+HTTP generation replies from `openai`, `server`, `ollama`, `vllm` and `anthropic`
+are limited to 8 MiB of decoded content, as are Magpie raw completions. The limit
+is checked while streaming, including gzip expansion, before JSON parsing.
+An oversized generation reply names the limit and the endpoint selector
+(`--api-base`, `--base-url` or `--provider anthropic`); it is refused without
+logging its body. Magpie instead drops the affected instruction/response sample
+and continues collecting rows within its attempt limit, preserving its existing
+per-sample failure behavior; a single oversized reply does not abort the run.
+
```bash
# Generate via local Ollama instance
soup data generate --prompt "..." --provider ollama --model llama3.1
diff --git a/docs/evaluation.md b/docs/evaluation.md
index 8e73b624..1a0d58ae 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -818,6 +818,12 @@ soup eval leaderboard --format csv
soup eval human --input prompts.jsonl --model-a ./model_a --model-b ./model_b
```
+Judge HTTP replies are limited to 1 MiB of decoded content while streaming,
+before JSON parsing, including gzip expansion. An oversized response is an
+unusable reply rather than a transient outage: it is not retried. The error names
+the cap and the endpoint selectors (`--api-base`, `--judge-api-base`, `judge_model`),
+with credentials removed from the judge URL. Existing row-failure policies apply.
+
`soup eval benchmark` saves only requested names with numeric metrics, including a real
`0.0` (not a boolean). Missing or scoreless results are skipped, named and counted;
the saved banner reports the saved count. It exits `0` when at least one result was
diff --git a/src/soup_cli/commands/generate.py b/src/soup_cli/commands/generate.py
index 716b332e..7f6a86f1 100644
--- a/src/soup_cli/commands/generate.py
+++ b/src/soup_cli/commands/generate.py
@@ -703,7 +703,7 @@ def _generate_openai(
)
try:
- import httpx
+ import httpx # noqa: F401 -- retain the optional-dependency diagnostic
except ImportError:
raise ImportError("httpx is required for OpenAI generation. Install: pip install httpx")
@@ -734,7 +734,9 @@ def _generate_openai(
if generation_prompt is None:
generation_prompt = _build_generation_prompt(prompt, count, fmt, seed_examples)
- response = httpx.post(
+ from soup_cli.utils.http_response import GENERATION_RESPONSE_LIMIT_BYTES, post_capped
+
+ response = post_capped(
f"{base_url}/chat/completions",
headers={
"Authorization": f"Bearer {resolved_key}",
@@ -749,11 +751,12 @@ def _generate_openai(
"temperature": temperature,
"max_tokens": 4096,
},
+ max_bytes=GENERATION_RESPONSE_LIMIT_BYTES,
+ endpoint_label="OpenAI --api-base",
timeout=120.0,
)
if response.status_code != 200:
- logger.debug("API error response: %s", response.text)
raise ValueError(
f"API returned {response.status_code}. Check your API key and model name."
)
@@ -852,7 +855,7 @@ def _generate_server(
local inference server via its OpenAI-compatible /v1/chat/completions endpoint.
"""
try:
- import httpx
+ import httpx # noqa: F401 -- retain the optional-dependency diagnostic
except ImportError:
raise ImportError("httpx is required for server generation. Install: pip install httpx")
@@ -892,7 +895,9 @@ def _generate_server(
if generation_prompt is None:
generation_prompt = _build_generation_prompt(prompt, count, fmt, seed_examples)
- response = httpx.post(
+ from soup_cli.utils.http_response import GENERATION_RESPONSE_LIMIT_BYTES, post_capped
+
+ response = post_capped(
f"{base_url}/chat/completions",
headers={"Content-Type": "application/json"},
json={
@@ -904,11 +909,12 @@ def _generate_server(
"temperature": temperature,
"max_tokens": 4096,
},
+ max_bytes=GENERATION_RESPONSE_LIMIT_BYTES,
+ endpoint_label="server --api-base",
timeout=300.0,
)
if response.status_code != 200:
- logger.debug("Server error response: %s", response.text)
raise ValueError(
f"Server returned {response.status_code}. "
"Check that the server is running and the model name is correct."
diff --git a/src/soup_cli/data/providers/anthropic.py b/src/soup_cli/data/providers/anthropic.py
index 4763aa97..b8343548 100644
--- a/src/soup_cli/data/providers/anthropic.py
+++ b/src/soup_cli/data/providers/anthropic.py
@@ -39,7 +39,7 @@ def generate_anthropic(
ImportError: If httpx is not installed.
"""
try:
- import httpx
+ import httpx # noqa: F401 -- retain the optional-dependency diagnostic
except ImportError:
raise ImportError(
"httpx is required for Anthropic generation. Install: pip install httpx"
@@ -51,7 +51,9 @@ def generate_anthropic(
"Anthropic API key not found. Set ANTHROPIC_API_KEY environment variable."
)
- response = httpx.post(
+ from soup_cli.utils.http_response import GENERATION_RESPONSE_LIMIT_BYTES, post_capped
+
+ response = post_capped(
ANTHROPIC_API_URL,
headers={
"x-api-key": api_key,
@@ -67,11 +69,12 @@ def generate_anthropic(
"temperature": temperature,
"max_tokens": 4096,
},
+ max_bytes=GENERATION_RESPONSE_LIMIT_BYTES,
+ endpoint_label="Anthropic --provider anthropic",
timeout=120.0,
)
if response.status_code != 200:
- logger.debug("Anthropic error response: %s", response.text)
raise ValueError(
f"Anthropic API returned {response.status_code}. "
"Check your API key and model name."
diff --git a/src/soup_cli/data/providers/ollama.py b/src/soup_cli/data/providers/ollama.py
index a70a0e08..ff167915 100644
--- a/src/soup_cli/data/providers/ollama.py
+++ b/src/soup_cli/data/providers/ollama.py
@@ -83,7 +83,7 @@ def generate_ollama(
List of generated example dicts.
"""
try:
- import httpx
+ import httpx # noqa: F401 -- retain the optional-dependency diagnostic
except ImportError:
raise ImportError(
"httpx is required for Ollama generation. Install: pip install httpx"
@@ -93,7 +93,9 @@ def generate_ollama(
api_url = f"{base_url}/v1/chat/completions"
- response = httpx.post(
+ from soup_cli.utils.http_response import GENERATION_RESPONSE_LIMIT_BYTES, post_capped
+
+ response = post_capped(
api_url,
headers={"Content-Type": "application/json"},
json={
@@ -105,11 +107,12 @@ def generate_ollama(
"temperature": temperature,
"max_tokens": 4096,
},
+ max_bytes=GENERATION_RESPONSE_LIMIT_BYTES,
+ endpoint_label="ollama --api-base / --base-url",
timeout=300.0,
)
if response.status_code != 200:
- logger.debug("Ollama error response: %s", response.text)
raise ValueError(
f"Ollama returned {response.status_code}. "
"Check that Ollama is running and the model is pulled."
diff --git a/src/soup_cli/data/providers/vllm.py b/src/soup_cli/data/providers/vllm.py
index eb253a3e..f50d8cb8 100644
--- a/src/soup_cli/data/providers/vllm.py
+++ b/src/soup_cli/data/providers/vllm.py
@@ -67,7 +67,7 @@ def generate_vllm(
List of generated example dicts.
"""
try:
- import httpx
+ import httpx # noqa: F401 -- retain the optional-dependency diagnostic
except ImportError:
raise ImportError(
"httpx is required for vLLM generation. Install: pip install httpx"
@@ -80,7 +80,9 @@ def generate_vllm(
if not api_base.endswith("/v1"):
api_base = api_base + "/v1"
- response = httpx.post(
+ from soup_cli.utils.http_response import GENERATION_RESPONSE_LIMIT_BYTES, post_capped
+
+ response = post_capped(
f"{api_base}/chat/completions",
headers={"Content-Type": "application/json"},
json={
@@ -92,11 +94,12 @@ def generate_vllm(
"temperature": temperature,
"max_tokens": 4096,
},
+ max_bytes=GENERATION_RESPONSE_LIMIT_BYTES,
+ endpoint_label="vllm --api-base / --base-url",
timeout=300.0,
)
if response.status_code != 200:
- logger.debug("vLLM error response: %s", response.text)
raise ValueError(
f"vLLM server returned {response.status_code}. "
"Check that the server is running and the model is loaded."
diff --git a/src/soup_cli/eval/judge.py b/src/soup_cli/eval/judge.py
index eec806b5..be535f3e 100644
--- a/src/soup_cli/eval/judge.py
+++ b/src/soup_cli/eval/judge.py
@@ -550,11 +550,23 @@ def _judge_request(url: str, payload: dict, headers: dict, *, timeout: float = 1
"""
import httpx
+ from soup_cli.utils.http_response import (
+ JUDGE_RESPONSE_LIMIT_BYTES,
+ ResponseTooLargeError,
+ post_capped,
+ )
+
failure = ""
for attempt in range(JUDGE_MAX_RETRIES + 1):
retry_after: Optional[str] = None
try:
- resp = httpx.post(url, json=payload, headers=headers, timeout=timeout)
+ resp = post_capped(
+ url, json=payload, headers=headers, timeout=timeout,
+ max_bytes=JUDGE_RESPONSE_LIMIT_BYTES,
+ endpoint_label="judge --api-base / --judge-api-base / judge_model",
+ )
+ except ResponseTooLargeError as exc:
+ raise JudgeUnavailableError(str(exc), url=url) from exc
except httpx.TransportError as exc:
failure = f"{type(exc).__name__}: {exc}"
except httpx.RequestError as exc: # e.g. DecodingError: not transient, no retry
diff --git a/src/soup_cli/utils/http_response.py b/src/soup_cli/utils/http_response.py
new file mode 100644
index 00000000..4712ec29
--- /dev/null
+++ b/src/soup_cli/utils/http_response.py
@@ -0,0 +1,62 @@
+"""Bound decoded HTTP response bodies before JSON parsing or buffering."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ import httpx
+
+JUDGE_RESPONSE_LIMIT_BYTES = 1024 * 1024
+GENERATION_RESPONSE_LIMIT_BYTES = 8 * 1024 * 1024
+_READ_CHUNK_BYTES = 64 * 1024
+
+
+class ResponseTooLargeError(ValueError):
+ """A selected endpoint exceeded its decoded response budget."""
+
+
+def post_capped(
+ url: str, *, max_bytes: int, endpoint_label: str, **kwargs: Any,
+) -> httpx.Response:
+ """POST and return a bounded, decoded response, always closing the stream.
+
+ Callers retain their endpoint validation, request headers and status/retry
+ policies. Error text contains only the caller's setting label and limit,
+ never the URL, credentials, request headers or response body.
+ """
+ import httpx
+
+ if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
+ raise ValueError("max_bytes must be a positive integer")
+
+ def too_large() -> ResponseTooLargeError:
+ return ResponseTooLargeError(
+ f"Response for {endpoint_label} exceeds the {max_bytes} bytes limit"
+ )
+
+ with httpx.stream("POST", url, **kwargs) as response:
+ try:
+ declared_length = int(response.headers.get("Content-Length", ""))
+ except ValueError:
+ declared_length = 0
+ if declared_length > max_bytes:
+ raise too_large()
+
+ chunks: list[bytes] = []
+ size = 0
+ # iter_bytes counts decompressed content, including gzip replies.
+ for chunk in response.iter_bytes(chunk_size=_READ_CHUNK_BYTES):
+ size += len(chunk)
+ if size > max_bytes:
+ raise too_large()
+ chunks.append(chunk)
+
+ headers = response.headers.copy()
+ for name in ("Content-Encoding", "Content-Length", "Transfer-Encoding"):
+ headers.pop(name, None)
+ headers["Content-Length"] = str(size)
+ return httpx.Response(
+ response.status_code, headers=headers, content=b"".join(chunks),
+ request=response.request, extensions=response.extensions,
+ )
diff --git a/src/soup_cli/utils/magpie.py b/src/soup_cli/utils/magpie.py
index 8f8b2666..ca667760 100644
--- a/src/soup_cli/utils/magpie.py
+++ b/src/soup_cli/utils/magpie.py
@@ -335,12 +335,14 @@ def make_magpie_generate_fn(
)
try:
- import httpx
+ import httpx # noqa: F401 -- retain the optional-dependency diagnostic
except ImportError as exc:
raise ImportError(
"httpx is required for live Magpie providers. Run: pip install httpx"
) from exc
+ from soup_cli.utils.http_response import ResponseTooLargeError, post_capped
+
if canonical == "ollama":
from soup_cli.data.providers.ollama import validate_ollama_url
@@ -352,7 +354,7 @@ def make_magpie_generate_fn(
if not isinstance(prompt, str):
return ""
try:
- resp = httpx.post(
+ resp = post_capped(
api_url,
headers={"Content-Type": "application/json"},
json={
@@ -365,17 +367,19 @@ def make_magpie_generate_fn(
"num_predict": max_tokens,
},
},
+ max_bytes=_MAX_RESPONSE_BYTES,
+ endpoint_label="Magpie --base-url",
timeout=timeout_seconds,
)
+ except ResponseTooLargeError:
+ _LOG.debug("ollama magpie response exceeds byte limit; dropping sample")
+ return ""
except Exception as exc: # noqa: BLE001 — httpx error variety
_LOG.debug("ollama magpie HTTP error: %s", exc)
return ""
if resp.status_code != 200:
_LOG.debug("ollama magpie status=%d", resp.status_code)
return ""
- if len(resp.content) > _MAX_RESPONSE_BYTES:
- _LOG.debug("ollama magpie response too large; dropping")
- return ""
try:
text = resp.json()["response"]
except (KeyError, IndexError, TypeError, ValueError) as exc:
@@ -396,7 +400,7 @@ def make_magpie_generate_fn(
if not isinstance(prompt, str):
return ""
try:
- resp = httpx.post(
+ resp = post_capped(
api_url,
headers={"Content-Type": "application/json"},
json={
@@ -405,17 +409,19 @@ def make_magpie_generate_fn(
"temperature": float(temperature),
"max_tokens": max_tokens,
},
+ max_bytes=_MAX_RESPONSE_BYTES,
+ endpoint_label="Magpie --base-url",
timeout=timeout_seconds,
)
+ except ResponseTooLargeError:
+ _LOG.debug("vllm magpie response exceeds byte limit; dropping sample")
+ return ""
except Exception as exc: # noqa: BLE001
_LOG.debug("vllm magpie HTTP error: %s", exc)
return ""
if resp.status_code != 200:
_LOG.debug("vllm magpie status=%d", resp.status_code)
return ""
- if len(resp.content) > _MAX_RESPONSE_BYTES:
- _LOG.debug("vllm magpie response too large; dropping")
- return ""
try:
text = resp.json()["choices"][0]["text"]
except (KeyError, IndexError, TypeError, ValueError) as exc:
diff --git a/tests/test_http_response_limits.py b/tests/test_http_response_limits.py
new file mode 100644
index 00000000..3701dda2
--- /dev/null
+++ b/tests/test_http_response_limits.py
@@ -0,0 +1,386 @@
+"""Decoded response limits exercise httpx streaming, then each production caller."""
+
+from __future__ import annotations
+
+import gzip
+import json
+import logging
+from contextlib import contextmanager
+from typing import Any, Iterator
+
+import httpx
+import pytest
+
+
+class _Body(httpx.SyncByteStream):
+ def __init__(self, chunks: list[bytes]) -> None:
+ self.chunks = chunks
+ self.reads = 0
+ self.closed = False
+
+ def __iter__(self) -> Iterator[bytes]:
+ for chunk in self.chunks:
+ self.reads += 1
+ yield chunk
+
+ def close(self) -> None:
+ self.closed = True
+
+
+def _stream_reply(
+ monkeypatch: pytest.MonkeyPatch,
+ chunks: list[bytes],
+ *,
+ headers: dict[str, str] | None = None,
+ status: int = 200,
+) -> tuple[_Body, list[tuple[str, str, dict[str, Any]]]]:
+ body = _Body(chunks)
+ calls: list[tuple[str, str, dict[str, Any]]] = []
+
+ @contextmanager
+ def stream(method: str, url: str, **kwargs: Any) -> Iterator[httpx.Response]:
+ calls.append((method, url, kwargs))
+ response = httpx.Response(
+ status,
+ headers=headers,
+ stream=body,
+ request=httpx.Request(method, url),
+ )
+ try:
+ yield response
+ finally:
+ response.close()
+
+ monkeypatch.setattr(httpx, "stream", stream)
+ monkeypatch.setattr(httpx, "post", lambda *a, **k: pytest.fail("uncapped httpx.post"))
+ return body, calls
+
+
[email protected]("header", [None, "8", "0", "nonsense", "-1"])
+def test_exact_decoded_boundary_is_buffered(
+ monkeypatch: pytest.MonkeyPatch,
+ header: str | None,
+) -> None:
+ from soup_cli.utils.http_response import post_capped
+
+ headers = {"Retry-After": "2", "Content-Type": "application/json"}
+ if header is not None:
+ headers["Content-Length"] = header
+ body, calls = _stream_reply(monkeypatch, [b'{"a":', b"12}"], headers=headers, status=429)
+ response = post_capped(
+ "https://example.com/api",
+ max_bytes=8,
+ endpoint_label="--api-base",
+ timeout=3.0,
+ )
+
+ assert response.status_code == 429
+ assert response.json() == {"a": 12}
+ assert response.headers["Retry-After"] == "2"
+ assert response.headers["Content-Length"] == "8"
+ assert response.request.url == "https://example.com/api"
+ assert body.closed
+ assert calls == [("POST", "https://example.com/api", {"timeout": 3.0})]
+
+
+def test_content_length_refuses_without_reading_and_closes(monkeypatch: pytest.MonkeyPatch) -> None:
+ from soup_cli.utils.http_response import ResponseTooLargeError, post_capped
+
+ body, _ = _stream_reply(monkeypatch, [b"secret body"], headers={"Content-Length": "9"})
+ with pytest.raises(ResponseTooLargeError, match=r"--api-base.*8 bytes"):
+ post_capped("https://example.com", max_bytes=8, endpoint_label="--api-base")
+ assert body.reads == 0
+ assert body.closed
+
+
+def test_unknown_length_stops_before_remaining_chunks(monkeypatch: pytest.MonkeyPatch) -> None:
+ from soup_cli.utils.http_response import ResponseTooLargeError, post_capped
+
+ body, _ = _stream_reply(monkeypatch, [b"a" * 65536, b"b" * 65536, b"unread"])
+ with pytest.raises(ResponseTooLargeError, match="65536 bytes"):
+ post_capped("https://example.com", max_bytes=65536, endpoint_label="--base-url")
+ assert body.reads == 2
+ assert body.closed
+
+
[email protected]("size", [64, 65], ids=["at-cap", "above-cap"])
+def test_gzip_limit_counts_decoded_bytes(monkeypatch: pytest.MonkeyPatch, size: int) -> None:
+ from soup_cli.utils.http_response import ResponseTooLargeError, post_capped
+
+ payload = b"a" * size
+ compressed = gzip.compress(payload)
+ assert len(compressed) < 64
+ body, _ = _stream_reply(
+ monkeypatch,
+ [compressed],
+ headers={
+ "Content-Encoding": "gzip",
+ "Content-Length": str(len(compressed)),
+ },
+ )
+ if size > 64:
+ with pytest.raises(ResponseTooLargeError, match="64 bytes"):
+ post_capped("https://example.com", max_bytes=64, endpoint_label="--api-base")
+ else:
+ response = post_capped("https://example.com", max_bytes=64, endpoint_label="--api-base")
+ assert response.content == payload
+ assert "Content-Encoding" not in response.headers
+ assert response.headers["Content-Length"] == "64"
+ assert body.closed
+
+
+def test_stream_error_closes(monkeypatch: pytest.MonkeyPatch) -> None:
+ from soup_cli.utils.http_response import post_capped
+
+ class BrokenBody(_Body):
+ def __iter__(self) -> Iterator[bytes]:
+ yield b"first"
+ raise httpx.ReadError("connection ended")
+
+ body = BrokenBody([])
+
+ @contextmanager
+ def stream(*args: Any, **kwargs: Any) -> Iterator[httpx.Response]:
+ response = httpx.Response(200, stream=body)
+ try:
+ yield response
+ finally:
+ response.close()
+
+ monkeypatch.setattr(httpx, "stream", stream)
+ with pytest.raises(httpx.ReadError, match="connection ended"):
+ post_capped("https://example.com", max_bytes=64, endpoint_label="--api-base")
+ assert body.closed
+
+
+TARGETS = [
+ "judge",
+ "ollama",
+ "vllm",
+ "anthropic",
+ "openai",
+ "server",
+ "magpie-ollama",
+ "magpie-vllm",
+]
+
+
+def _call_target(target: str) -> Any:
+ if target == "judge":
+ from soup_cli.eval.judge import JudgeEvaluator
+
+ return JudgeEvaluator(
+ provider="server", model="m", api_base="http://localhost:8000"
+ )._call_llm("p")
+ if target.startswith("magpie-"):
+ from soup_cli.utils.magpie import make_magpie_generate_fn
+
+ return make_magpie_generate_fn(target.removeprefix("magpie-"), model="m")("p")
+ common = dict(prompt="p", count=1, fmt="alpaca", model_name="m", temperature=0.0)
+ if target == "ollama":
+ from soup_cli.data.providers.ollama import generate_ollama
+
+ return generate_ollama(**common, base_url="http://localhost:11434", generation_prompt="p")
+ if target == "vllm":
+ from soup_cli.data.providers.vllm import generate_vllm
+
+ return generate_vllm(**common, base_url="http://localhost:8000", generation_prompt="p")
+ if target == "anthropic":
+ from soup_cli.data.providers.anthropic import generate_anthropic
+
+ return generate_anthropic(**common, generation_prompt="p")
+ from soup_cli.commands.generate import _generate_openai, _generate_server
+
+ if target == "openai":
+ return _generate_openai(**common, api_key="synthetic-key", api_base=None, seed_examples=[])
+ return _generate_server(**common, api_base="http://localhost:8000", seed_examples=[])
+
+
[email protected]("target", TARGETS)
[email protected]("compressed", [False, True], ids=["plain", "gzip"])
+def test_every_target_limits_oversize_before_parsing(
+ monkeypatch: pytest.MonkeyPatch,
+ caplog: pytest.LogCaptureFixture,
+ target: str,
+ compressed: bool,
+) -> None:
+ from soup_cli.eval.judge import JudgeUnavailableError
+ from soup_cli.utils import http_response, magpie
+
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "synthetic-secret-key")
+ monkeypatch.setattr(http_response, "JUDGE_RESPONSE_LIMIT_BYTES", 64)
+ monkeypatch.setattr(http_response, "GENERATION_RESPONSE_LIMIT_BYTES", 64)
+ monkeypatch.setattr(magpie, "_MAX_RESPONSE_BYTES", 64)
+ payload = b"secret-body-" * 20
+ headers = {"Content-Encoding": "gzip"} if compressed else {}
+ body, calls = _stream_reply(
+ monkeypatch, [gzip.compress(payload) if compressed else payload], headers=headers
+ )
+
+ expected_error = (
+ JudgeUnavailableError if target == "judge" else http_response.ResponseTooLargeError
+ )
+ with caplog.at_level(logging.DEBUG):
+ if target.startswith("magpie-"):
+ assert _call_target(target) == ""
+ error_text = ""
+ else:
+ with pytest.raises(expected_error, match=r"64 bytes") as caught:
+ _call_target(target)
+ error_text = str(caught.value)
+ assert (
+ "--api-base" in error_text
+ or "--base-url" in error_text
+ or "--provider anthropic" in error_text
+ )
+ assert "secret-body" not in error_text + caplog.text
+ assert "synthetic-secret-key" not in error_text + caplog.text
+ assert len(calls) == 1 # An oversized judge response is not a transient outage.
+ assert body.closed
+
+
[email protected]("provider", ["ollama", "vllm"])
[email protected]("compressed", [False, True], ids=["plain", "gzip"])
[email protected]("oversized_stage", ["instruction", "response", "all"])
+def test_magpie_drops_oversized_sample_and_respects_attempt_bound(
+ monkeypatch: pytest.MonkeyPatch, tmp_path, caplog: pytest.LogCaptureFixture,
+ provider: str, compressed: bool, oversized_stage: str,
+) -> None:
+ from soup_cli.utils import magpie
+
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(magpie, "_MAX_RESPONSE_BYTES", 64)
+
+ def reply(text: str) -> bytes:
+ payload = {"response": text} if provider == "ollama" else {"choices": [{"text": text}]}
+ return json.dumps(payload).encode()
+
+ oversized = b"secret-body-" * 20
+ payloads = {
+ "instruction": [oversized, reply("q2"), reply("a2")],
+ "response": [reply("q1"), oversized, reply("q2"), reply("a2")],
+ "all": [oversized, oversized],
+ }[oversized_stage]
+ bodies = [_Body([gzip.compress(p) if compressed else p]) for p in payloads]
+ calls: list[dict[str, Any]] = []
+
+ @contextmanager
+ def stream(method: str, url: str, **kwargs: Any) -> Iterator[httpx.Response]:
+ body = bodies[len(calls)]
+ calls.append(kwargs)
+ response = httpx.Response(
+ 200, stream=body, request=httpx.Request(method, url),
+ headers={"Content-Encoding": "gzip"} if compressed else {},
+ )
+ try:
+ yield response
+ finally:
+ response.close()
+
+ monkeypatch.setattr(httpx, "stream", stream)
+ monkeypatch.setattr(httpx, "post", lambda *a, **kw: pytest.fail("uncapped httpx.post"))
+ config = magpie.MagpieConfig("Qwen/Qwen2.5-7B-Instruct", provider, 1, False)
+ with caplog.at_level(logging.DEBUG):
+ result = magpie.run_magpie(config, output_path="rows.jsonl", max_attempts=2)
+ assert result.attempts == 2
+ assert result.rows_kept == (0 if oversized_stage == "all" else 1)
+ assert len(calls) == len(bodies)
+ assert all(body.closed for body in bodies)
+ assert "secret-body" not in caplog.text
+ rows = [json.loads(line) for line in (tmp_path / "rows.jsonl").read_text().splitlines()]
+ assert rows == ([] if oversized_stage == "all" else [{"messages": [
+ {"role": "user", "content": "q2"}, {"role": "assistant", "content": "a2"},
+ ]}])
+
+
[email protected]("target", TARGETS)
+def test_every_target_preserves_valid_reply(monkeypatch: pytest.MonkeyPatch, target: str) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "synthetic-secret-key")
+ generated = '[{"instruction": "q", "output": "a"}]'
+ payload = {
+ "choices": [{"message": {"content": generated}, "text": generated}],
+ "response": generated,
+ "content": [{"type": "text", "text": generated}],
+ }
+ body, calls = _stream_reply(monkeypatch, [json.dumps(payload).encode()])
+ result = _call_target(target)
+ assert result == (
+ generated
+ if target == "judge" or target.startswith("magpie-")
+ else [{"instruction": "q", "output": "a"}]
+ )
+ assert len(calls) == 1
+ assert body.closed
+
+
+def test_limits_and_judge_url_redaction(monkeypatch: pytest.MonkeyPatch) -> None:
+ from soup_cli.eval.judge import JudgeUnavailableError, _judge_request
+ from soup_cli.utils.http_response import (
+ GENERATION_RESPONSE_LIMIT_BYTES,
+ JUDGE_RESPONSE_LIMIT_BYTES,
+ )
+
+ assert JUDGE_RESPONSE_LIMIT_BYTES == 1024 * 1024
+ assert GENERATION_RESPONSE_LIMIT_BYTES == 8 * 1024 * 1024
+ body, calls = _stream_reply(
+ monkeypatch, [], headers={"Content-Length": str(JUDGE_RESPONSE_LIMIT_BYTES + 1)}
+ )
+ with pytest.raises(JudgeUnavailableError) as caught:
+ _judge_request(
+ "https://user:[email protected]/api?api_key=query-secret#fragment", {}, {}
+ )
+ text = str(caught.value)
+ assert "1048576 bytes" in text
+ assert "--api-base" in text
+ assert caught.value.retries_spent is False
+ assert "password" not in text
+ assert "query-secret" not in text
+ assert "fragment" not in text
+ assert body.reads == 0
+ assert body.closed
+ assert len(calls) == 1
+
+
[email protected]("target", ["ollama", "vllm", "anthropic", "openai", "server"])
+def test_provider_error_does_not_log_response_body(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, target: str,
+) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "synthetic-secret-key")
+ body, _ = _stream_reply(monkeypatch, [b"secret-response-body"], status=500)
+ with caplog.at_level(logging.DEBUG), pytest.raises(ValueError, match="500") as caught:
+ _call_target(target)
+ assert "secret-response-body" not in str(caught.value) + caplog.text
+ assert "synthetic-secret-key" not in str(caught.value) + caplog.text
+ assert body.closed
+
+
+def test_judge_retry_preserves_streamed_status_and_headers(monkeypatch: pytest.MonkeyPatch) -> None:
+ from soup_cli.eval import judge
+
+ delays: list[float] = []
+ monkeypatch.setattr(judge, "_sleep", delays.append)
+ bodies = [
+ _Body([b'{"error": "busy"}']),
+ _Body([b'{"choices": [{"message": {"content": "ok"}}]}']),
+ ]
+ attempts: list[str] = []
+
+ @contextmanager
+ def stream(method: str, url: str, **kwargs: Any) -> Iterator[httpx.Response]:
+ index = len(attempts)
+ attempts.append(url)
+ response = httpx.Response(
+ 429 if index == 0 else 200,
+ headers={"Retry-After": "2"}, stream=bodies[index],
+ request=httpx.Request(method, url),
+ )
+ try:
+ yield response
+ finally:
+ response.close()
+
+ monkeypatch.setattr(httpx, "stream", stream)
+ assert judge._judge_request("https://example.com/api", {}, {}) == "ok"
+ assert delays == [2.0]
+ assert len(attempts) == 2
+ assert all(body.closed for body in bodies)
diff --git a/tests/test_http_response_read_ratchet.py b/tests/test_http_response_read_ratchet.py
new file mode 100644
index 00000000..a4ff0f2e
--- /dev/null
+++ b/tests/test_http_response_read_ratchet.py
@@ -0,0 +1,108 @@
+"""Ratchet direct/aliased httpx.post/get calls and review post_capped callers.
+
+The raw-read check covers only httpx.post/get, with explicit legacy exceptions.
+It does not detect reads on arbitrary response objects, httpx.stream or Client
+instances. The sink ledger separately requires endpoint review for post_capped;
+this module does not establish a byte limit for every outbound response.
+"""
+
+from pathlib import Path
+
+import pytest
+
+from tests.test_issue1547_outbound_http_sinks import (
+ DECLARED_SINKS,
+ scan_src_sinks,
+ unlisted_sinks,
+)
+
+LEGACY_REQUESTS = {
+ (
+ "data/providers/ollama.py",
+ "detect_ollama",
+ ): "Local Ollama discovery/version probes; separate discovery contract.",
+ (
+ "utils/data_forge.py",
+ "make_judge_provider_fn._anthropic_judge",
+ ): "Separate forge judge adapter with its own failure contract; fixed Anthropic host.",
+ (
+ "utils/data_forge.py",
+ "make_judge_provider_fn._ollama_judge",
+ ): "Separate forge judge adapter; local endpoint, follow-up streaming migration.",
+ (
+ "utils/data_forge.py",
+ "make_judge_provider_fn._vllm_judge",
+ ): "Separate forge judge adapter; follow-up streaming migration.",
+ (
+ "utils/sglang.py",
+ "generate_with_runtime",
+ ): "In-process local SGLang runtime protocol; separate lifecycle contract.",
+ (
+ "utils/loop_stages.py",
+ "_post_activate",
+ ): "Activation acknowledgment only; response body is not parsed.",
+ (
+ "utils/webhooks.py",
+ "post_webhook",
+ ): "Webhook acknowledgment only; response body is not parsed.",
+}
+
+
+def _unapproved_reads(hits: list[tuple[str, str, int, str]]) -> list[tuple[str, str, int, str]]:
+ return [
+ hit for hit in hits
+ if hit[3] in ("httpx.post", "httpx.get") and hit[:2] not in LEGACY_REQUESTS
+ ]
+
+
+def test_no_new_unbounded_httpx_reads() -> None:
+ hits = scan_src_sinks()
+ reads = {
+ (path, name)
+ for path, name, _, call in hits
+ if call in ("httpx.post", "httpx.get")
+ }
+ assert _unapproved_reads(hits) == []
+ assert reads == set(LEGACY_REQUESTS), (
+ f"Unapproved reads: {sorted(reads - set(LEGACY_REQUESTS))}; "
+ f"stale exceptions: {sorted(set(LEGACY_REQUESTS) - reads)}"
+ )
+ assert all(LEGACY_REQUESTS.values())
+
+
+ "source",
+ [
+ "import httpx\ndef rogue(url):\n return httpx.post(url).json()\n",
+ "from httpx import get as fetch\ndef rogue(url):\n"
+ " response = fetch(url)\n return response.json()\n",
+ ],
+)
+def test_ratchet_detects_new_and_aliased_reads(tmp_path: Path, source: str) -> None:
+ (tmp_path / "rogue.py").write_text(source, encoding="utf-8")
+ hits = _unapproved_reads(scan_src_sinks(tmp_path))
+ assert len(hits) == 1
+ assert hits[0][:2] == ("rogue.py", "rogue")
+ assert hits[0][3] in ("httpx.post", "httpx.get")
+
+
[email protected]("imports, call", [
+ ("from soup_cli.utils.http_response import post_capped", "post_capped"),
+ ("from soup_cli.utils.http_response import post_capped as send", "send"),
+ ("import soup_cli.utils.http_response as transport", "transport.post_capped"),
+ ("from soup_cli.utils import http_response as transport", "transport.post_capped"),
+ ("import soup_cli.utils.http_response", "soup_cli.utils.http_response.post_capped"),
+])
+def test_new_capped_callers_still_require_endpoint_review(
+ tmp_path: Path, imports: str, call: str,
+) -> None:
+ source = f"{imports}\ndef rogue(url):\n return {call}(url).json()\n"
+ (tmp_path / "rogue.py").write_text(source, encoding="utf-8")
+ hits = scan_src_sinks(tmp_path)
+ assert len(hits) == 1
+ assert hits[0][:2] == ("rogue.py", "rogue")
+ assert hits[0][3] == "soup_cli.utils.http_response.post_capped"
+ errors = unlisted_sinks(hits, DECLARED_SINKS)
+ assert len(errors) == 1
+ assert "rogue.py" in errors[0]
+ assert "soup_cli.utils.http_response.post_capped" in errors[0]
diff --git a/tests/test_issue1447_judge_unavailable.py b/tests/test_issue1447_judge_unavailable.py
index e01a33f1..1c36d28b 100644
--- a/tests/test_issue1447_judge_unavailable.py
+++ b/tests/test_issue1447_judge_unavailable.py
@@ -6,7 +6,7 @@ down; ``soup eval judge`` aborted on the first transport error and lost the
scores already collected; nothing was ever retried; and a training eval gate
called an unreachable judge a regression.
-``httpx.post`` is patched throughout, so no judge server is needed, and the
+``post_capped`` is patched throughout, so no judge server is needed, and the
retry pause is captured instead of slept.
"""
@@ -28,6 +28,8 @@ from soup_cli.eval import judge as judge_mod
from soup_cli.eval.judge import JudgeEvaluator, JudgeUnavailableError, pairwise_winrate
from tests.conftest import strip_ansi
+BOUNDED_POST = "soup_cli.utils.http_response.post_capped"
+
JUDGE_BASE = "http://localhost:8000"
REQ = httpx.Request("POST", f"{JUDGE_BASE}/v1/chat/completions")
SCORED = {
@@ -86,7 +88,7 @@ ATTEMPTS = judge_mod.JUDGE_MAX_RETRIES + 1
class TestPairwiseFailureIsNotATie:
def test_dead_judge_raises_instead_of_scoring_half(self, evaluator, no_sleep):
pairs = [("p", "base answer", "tuned answer")] * 5
- with mock.patch("httpx.post", side_effect=_refused) as post:
+ with mock.patch(BOUNDED_POST, side_effect=_refused) as post:
with pytest.raises(JudgeUnavailableError) as excinfo:
pairwise_winrate(pairs, evaluator)
# The message names the judge, and the first pair aborts the run after
@@ -96,18 +98,18 @@ class TestPairwiseFailureIsNotATie:
def test_judge_that_answers_tie_still_scores_half(self, evaluator):
pairs = [("p", "base answer", "tuned answer")] * 3
- with mock.patch("httpx.post", return_value=_content("I cannot decide")):
+ with mock.patch(BOUNDED_POST, return_value=_content("I cannot decide")):
assert pairwise_winrate(pairs, evaluator) == 0.5
def test_judge_that_picks_tuned_scores_one(self, evaluator):
# Base is A and tuned is B in the first order; the swapped order must
# agree, so the fake answers by position.
- def post(url, json, headers, timeout):
+ def post(url, json, headers, timeout, **limits):
body = json["messages"][0]["content"]
winner = "B" if body.index("tuned answer") > body.index("base answer") else "A"
return _content(f'{{"winner": "{winner}"}}')
- with mock.patch("httpx.post", side_effect=post):
+ with mock.patch(BOUNDED_POST, side_effect=post):
assert pairwise_winrate([("p", "base answer", "tuned answer")], evaluator) == 1.0
def test_compare_pair_lets_the_error_propagate(self, evaluator, monkeypatch):
@@ -128,7 +130,7 @@ class TestPairwiseFailureIsNotATie:
judge = make_soup_pairwise_judge(evaluator)
except ImportError:
pytest.skip("installed trl has no BasePairwiseJudge")
- with mock.patch("httpx.post", side_effect=_refused) as post:
+ with mock.patch(BOUNDED_POST, side_effect=_refused) as post:
assert judge.judge(["p"], [["first", "second"]]) == [-1]
# the first order spent its bounded retries; the swapped order was never asked
assert post.call_count == ATTEMPTS
@@ -143,7 +145,7 @@ class TestRetry:
def test_429_then_200_is_scored_after_one_retry(self, evaluator, no_sleep):
replies = iter([_reply(429, {"error": "rate limited"}, {"Retry-After": "3"}),
_reply(200, SCORED)])
- with mock.patch("httpx.post", side_effect=lambda *a, **k: next(replies)) as post:
+ with mock.patch(BOUNDED_POST, side_effect=lambda *a, **k: next(replies)) as post:
score = evaluator.evaluate("q", "a")
assert score.weighted_score == 4.0
assert post.call_count == 2
@@ -156,20 +158,20 @@ class TestRetry:
item = next(replies)
return item(*args, **kwargs) if callable(item) else item
- with mock.patch("httpx.post", side_effect=post) as post_mock:
+ with mock.patch(BOUNDED_POST, side_effect=post) as post_mock:
assert evaluator.evaluate("q", "a").weighted_score == 4.0
assert post_mock.call_count == 2
assert len(no_sleep) == 1
def test_persistent_503_is_bounded_and_raises(self, evaluator, no_sleep):
- with mock.patch("httpx.post", return_value=_reply(503, {"error": "down"})) as post:
+ with mock.patch(BOUNDED_POST, return_value=_reply(503, {"error": "down"})) as post:
with pytest.raises(JudgeUnavailableError, match="503"):
evaluator.evaluate("q", "a")
assert post.call_count == ATTEMPTS
assert len(no_sleep) == judge_mod.JUDGE_MAX_RETRIES
def test_backoff_without_retry_after_grows_and_is_capped(self, evaluator, no_sleep):
- with mock.patch("httpx.post", return_value=_reply(429, {"error": "rate limited"})):
+ with mock.patch(BOUNDED_POST, return_value=_reply(429, {"error": "rate limited"})):
with pytest.raises(JudgeUnavailableError):
evaluator.evaluate("q", "a")
assert no_sleep == sorted(no_sleep)
@@ -177,7 +179,7 @@ class TestRetry:
def test_retry_after_is_capped(self, evaluator, no_sleep):
with mock.patch(
- "httpx.post", return_value=_reply(429, {}, {"Retry-After": "86400"})
+ BOUNDED_POST, return_value=_reply(429, {}, {"Retry-After": "86400"})
):
with pytest.raises(JudgeUnavailableError):
evaluator.evaluate("q", "a")
@@ -185,7 +187,7 @@ class TestRetry:
@pytest.mark.parametrize("status", [400, 401, 403, 404])
def test_client_errors_are_not_retried(self, evaluator, no_sleep, status):
- with mock.patch("httpx.post", return_value=_reply(status, {"error": "no"})) as post:
+ with mock.patch(BOUNDED_POST, return_value=_reply(status, {"error": "no"})) as post:
with pytest.raises(JudgeUnavailableError, match=str(status)):
evaluator.evaluate("q", "a")
assert post.call_count == 1
@@ -203,19 +205,19 @@ class TestRetry:
ids=["empty-choices", "no-content", "null-content", "no-choices-key", "not-a-dict"],
)
def test_malformed_200_reply_is_a_judge_error(self, evaluator, no_sleep, body):
- with mock.patch("httpx.post", return_value=_reply(200, body)) as post:
+ with mock.patch(BOUNDED_POST, return_value=_reply(200, body)) as post:
with pytest.raises(JudgeUnavailableError):
evaluator.evaluate("q", "a")
assert post.call_count == 1
def test_non_json_200_reply_is_a_judge_error(self, evaluator, no_sleep):
reply = httpx.Response(200, text="<html>gateway</html>", request=REQ)
- with mock.patch("httpx.post", return_value=reply):
+ with mock.patch(BOUNDED_POST, return_value=reply):
with pytest.raises(JudgeUnavailableError):
evaluator.evaluate("q", "a")
def test_error_names_the_url_and_the_attempt_count(self, evaluator, no_sleep):
- with mock.patch("httpx.post", side_effect=_refused):
+ with mock.patch(BOUNDED_POST, side_effect=_refused):
with pytest.raises(JudgeUnavailableError) as excinfo:
evaluator.evaluate("q", "a")
message = str(excinfo.value)
@@ -233,7 +235,7 @@ class TestRetry:
@pytest.mark.parametrize("value", ["nan", "NaN", "-5", "-inf", "inf", "1e400", "abc", ""])
def test_hostile_retry_after_never_yields_a_bad_pause(evaluator, no_sleep, value):
- with mock.patch("httpx.post", return_value=_reply(429, {}, {"Retry-After": value})):
+ with mock.patch(BOUNDED_POST, return_value=_reply(429, {}, {"Retry-After": value})):
with pytest.raises(JudgeUnavailableError):
evaluator.evaluate("q", "a")
assert no_sleep
@@ -252,7 +254,7 @@ def test_undecodable_reply_is_a_judge_error_not_a_raw_httpx_error(evaluator, no_
def boom(*args, **kwargs):
raise httpx.DecodingError("bad reply", request=REQ)
- with mock.patch("httpx.post", side_effect=boom) as post:
+ with mock.patch(BOUNDED_POST, side_effect=boom) as post:
with pytest.raises(JudgeUnavailableError, match="DecodingError"):
evaluator.evaluate("q", "a")
assert post.call_count == 1 # not transient: no retry
@@ -268,7 +270,7 @@ def test_undecodable_reply_is_a_judge_error_not_a_raw_httpx_error(evaluator, no_
)
def test_error_text_carries_no_credentials(no_sleep, base, secret):
evaluator = JudgeEvaluator(provider="server", model="judge", api_base=base)
- with mock.patch("httpx.post", side_effect=_refused) as post:
+ with mock.patch(BOUNDED_POST, side_effect=_refused) as post:
with pytest.raises(JudgeUnavailableError) as excinfo:
evaluator.evaluate("q", "a")
assert secret not in str(excinfo.value)
@@ -301,9 +303,9 @@ def _write_rows(path: Path, n: int = 3) -> None:
def _failing_row(prompt_marker: str, failure):
- """A fake ``httpx.post`` that fails only for the row whose prompt has the marker."""
+ """A fake ``post_capped`` that fails only for the row whose prompt has the marker."""
- def post(url, json, headers, timeout):
+ def post(url, json, headers, timeout, **limits):
if prompt_marker in json["messages"][0]["content"]:
if callable(failure):
return failure()
@@ -329,7 +331,7 @@ class TestEvalJudgeCli:
monkeypatch.chdir(tmp_path)
_write_rows(tmp_path / "t.jsonl")
- with mock.patch("httpx.post", side_effect=_failing_row("q1", failure)):
+ with mock.patch(BOUNDED_POST, side_effect=_failing_row("q1", failure)):
result = CliRunner().invoke(
app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],
)
@@ -352,7 +354,7 @@ class TestEvalJudgeCli:
def hostile():
raise httpx.ConnectError("[red]boom[/] \x1b[2J gone", request=REQ)
- with mock.patch("httpx.post", side_effect=_failing_row("q1", hostile)):
+ with mock.patch(BOUNDED_POST, side_effect=_failing_row("q1", hostile)):
result = CliRunner().invoke(
app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],
)
@@ -366,7 +368,7 @@ class TestEvalJudgeCli:
monkeypatch.chdir(tmp_path)
_write_rows(tmp_path / "t.jsonl")
- with mock.patch("httpx.post", side_effect=_refused):
+ with mock.patch(BOUNDED_POST, side_effect=_refused):
result = CliRunner().invoke(
app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],
)
@@ -394,7 +396,7 @@ class TestShipPairwiseCli:
ship_cmd, "_resolve_generators",
lambda *a, **k: (lambda p: "base answer", lambda p: "tuned answer"),
)
- with mock.patch("httpx.post", side_effect=_refused):
+ with mock.patch(BOUNDED_POST, side_effect=_refused):
result = CliRunner().invoke(
ship_cmd.app,
["--base", "m", "--tuned", "t", "--task-eval", "tasks.jsonl",
@@ -425,7 +427,7 @@ class TestEvalGate:
tasks=[GateTask(type="judge", name="quality", threshold=0.7,
prompts="prompts.jsonl", judge_model=f"{JUDGE_BASE}/m")],
)
- with mock.patch("httpx.post", side_effect=_refused):
+ with mock.patch(BOUNDED_POST, side_effect=_refused):
result = run_gate(suite, generate_fn=lambda prompt: "x")
assert result.passed is False
(task,) = result.task_results
diff --git a/tests/test_issue1522_judge_down.py b/tests/test_issue1522_judge_down.py
index a3e8bf23..27477a22 100644
--- a/tests/test_issue1522_judge_down.py
+++ b/tests/test_issue1522_judge_down.py
@@ -5,7 +5,7 @@ retry, but every row retried on its own: 3 s of backoff per row, for the whole
dataset, against a host that never answered once. An evaluator now remembers
that its last requests all went unanswered and stops asking.
-``httpx.post`` is patched throughout, so no judge server is needed, and the
+``post_capped`` is patched throughout, so no judge server is needed, and the
retry pause is captured instead of slept.
"""
@@ -31,6 +31,8 @@ from soup_cli.eval.judge import (
)
from tests.conftest import strip_ansi
+BOUNDED_POST = "soup_cli.utils.http_response.post_capped"
+
JUDGE_BASE = "http://localhost:8000"
REQ = httpx.Request("POST", f"{JUDGE_BASE}/v1/chat/completions")
SCORED = {
@@ -61,7 +63,7 @@ def _refused(*args, **kwargs):
def _script(*steps):
- """A fake ``httpx.post`` that plays ``steps`` in order, then refuses."""
+ """A fake ``post_capped`` that plays ``steps`` in order, then refuses."""
remaining = list(steps)
def post(*args, **kwargs):
@@ -104,7 +106,7 @@ class TestJudgeDownCounter:
# The way every row-by-row caller uses it: a failed row is skipped, and
# the run stops at the first JudgeDownError.
skipped = 0
- with mock.patch("httpx.post", side_effect=_refused) as post:
+ with mock.patch(BOUNDED_POST, side_effect=_refused) as post:
with pytest.raises(JudgeDownError):
for index in range(1000):
try:
@@ -122,7 +124,7 @@ class TestJudgeDownCounter:
evaluator = JudgeEvaluator(
provider="server", model="judge", api_base="https://user:[email protected]"
)
- with mock.patch("httpx.post", side_effect=_refused):
+ with mock.patch(BOUNDED_POST, side_effect=_refused):
errors = _judge_rows(evaluator, JUDGE_DOWN_AFTER)
down = errors[-1]
@@ -135,7 +137,7 @@ class TestJudgeDownCounter:
def test_one_reply_resets_the_count(self, evaluator, no_sleep):
unanswered = [_refused] * ATTEMPTS
steps = [*unanswered, *unanswered, _reply(200, SCORED), *unanswered, *unanswered]
- with mock.patch("httpx.post", side_effect=_script(*steps)) as post:
+ with mock.patch(BOUNDED_POST, side_effect=_script(*steps)) as post:
errors = []
scored = 0
for index in range(5):
@@ -156,7 +158,7 @@ class TestJudgeDownCounter:
ids=["4xx", "unusable-200"],
)
def test_a_judge_that_answers_badly_is_not_down(self, evaluator, no_sleep, answer):
- with mock.patch("httpx.post", return_value=answer) as post:
+ with mock.patch(BOUNDED_POST, return_value=answer) as post:
errors = _judge_rows(evaluator, 10)
assert len(errors) == 10
@@ -167,14 +169,14 @@ class TestJudgeDownCounter:
def test_a_bad_answer_between_outages_resets_the_count(self, evaluator, no_sleep):
unanswered = [_refused] * ATTEMPTS
steps = [*unanswered, *unanswered, _reply(400, {"error": "no"}), *unanswered]
- with mock.patch("httpx.post", side_effect=_script(*steps)):
+ with mock.patch(BOUNDED_POST, side_effect=_script(*steps)):
errors = _judge_rows(evaluator, 4)
assert len(errors) == 4
assert not any(isinstance(exc, JudgeDownError) for exc in errors)
def test_pairwise_and_pointwise_calls_share_the_count(self, evaluator, no_sleep):
- with mock.patch("httpx.post", side_effect=_refused):
+ with mock.patch(BOUNDED_POST, side_effect=_refused):
for _ in range(JUDGE_DOWN_AFTER - 1):
with pytest.raises(JudgeUnavailableError) as excinfo:
evaluator.evaluate("q", "a")
@@ -185,15 +187,15 @@ class TestJudgeDownCounter:
def test_each_evaluator_counts_its_own_judge(self, no_sleep):
dead = JudgeEvaluator(provider="server", model="judge", api_base=JUDGE_BASE)
other = JudgeEvaluator(provider="server", model="judge", api_base="http://localhost:9000")
- with mock.patch("httpx.post", side_effect=_refused):
+ with mock.patch(BOUNDED_POST, side_effect=_refused):
_judge_rows(dead, JUDGE_DOWN_AFTER)
- with mock.patch("httpx.post", return_value=_reply(200, SCORED)):
+ with mock.patch(BOUNDED_POST, return_value=_reply(200, SCORED)):
assert other.evaluate("q", "a").weighted_score == 4.0
def test_a_judge_that_stays_down_is_still_asked(self, evaluator, no_sleep):
# No cooldown: a caller that carries on gets a real request each time,
# so the first reply after an outage is seen.
- with mock.patch("httpx.post", side_effect=_refused) as post:
+ with mock.patch(BOUNDED_POST, side_effect=_refused) as post:
errors = _judge_rows(evaluator, JUDGE_DOWN_AFTER + 2)
assert post.call_count == (JUDGE_DOWN_AFTER + 2) * ATTEMPTS
@@ -220,7 +222,7 @@ def test_a_short_outage_does_not_leave_a_judge_ranked_run_unranked(evaluator, no
# three requests in a row are refused, then the judge answers every request
steps = [*[_refused] * (JUDGE_DOWN_AFTER * ATTEMPTS), *[ok] * 20]
reward = make_judge_reward_func(evaluator)
- with mock.patch("httpx.post", side_effect=_script(*steps)):
+ with mock.patch(BOUNDED_POST, side_effect=_script(*steps)):
scores = reward(["q"] * 10, ["a"] * 10)
assert scores[:3] == [0.0, 0.0, 0.0]
assert scores[3:] == [4.0] * 7, scores
@@ -243,7 +245,7 @@ class TestEvalJudgeCli:
monkeypatch.chdir(tmp_path)
_write_rows(tmp_path / "t.jsonl", 1000)
- with mock.patch("httpx.post", side_effect=_refused) as post:
+ with mock.patch(BOUNDED_POST, side_effect=_refused) as post:
result = CliRunner().invoke(
app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],
)
@@ -265,7 +267,7 @@ class TestEvalJudgeCli:
monkeypatch.chdir(tmp_path)
_write_rows(tmp_path / "t.jsonl", 50)
steps = [_reply(200, SCORED)] * 5
- with mock.patch("httpx.post", side_effect=_script(*steps)):
+ with mock.patch(BOUNDED_POST, side_effect=_script(*steps)):
result = CliRunner().invoke(
app, ["eval", "judge", "--target", "t.jsonl", "--provider", "server"],
)
@@ -292,7 +294,7 @@ class TestPairFilter:
def test_a_dead_judge_stops_the_filter(self, evaluator, no_sleep):
from soup_cli.data.traces.quality import judge_filter_pairs
- with mock.patch("httpx.post", side_effect=_refused) as post:
+ with mock.patch(BOUNDED_POST, side_effect=_refused) as post:
with pytest.raises(JudgeDownError) as excinfo:
judge_filter_pairs(self._pairs(1000), judge=evaluator)
@@ -314,7 +316,7 @@ class TestPairFilter:
# Pair 1 is kept (chosen 5, rejected 1), pairs 2-4 are dropped (a tie
# is below the 0.7 default), then nothing answers.
steps = [scored(5), scored(1)] + [_reply(200, SCORED)] * 6
- with mock.patch("httpx.post", side_effect=_script(*steps)):
+ with mock.patch(BOUNDED_POST, side_effect=_script(*steps)):
with pytest.raises(JudgeDownError) as excinfo:
judge_filter_pairs(self._pairs(10), judge=evaluator)
@@ -324,7 +326,7 @@ class TestPairFilter:
from soup_cli.data.traces.quality import judge_filter_pairs
steps = [*[_refused] * ATTEMPTS, *[_reply(200, SCORED)] * 4]
- with mock.patch("httpx.post", side_effect=_script(*steps)):
+ with mock.patch(BOUNDED_POST, side_effect=_script(*steps)):
kept, report = judge_filter_pairs(self._pairs(3), judge=evaluator)
assert report.errors == 1
@@ -342,7 +344,7 @@ class TestPairFilter:
"outputs": {"output": text},
"feedback": [{"key": "thumbs", "score": score}],
}) + "\n")
- with mock.patch("httpx.post", side_effect=_refused) as post:
+ with mock.patch(BOUNDED_POST, side_effect=_refused) as post:
result = CliRunner().invoke(
app,
["data", "from-traces", "--logs", "traces.jsonl", "--format", "langchain",
@@ -373,7 +375,7 @@ class TestPairwiseWinrate:
_reply(200, {"choices": [{"message": {"content": '{"winner": "B"}'}}]}),
_reply(200, {"choices": [{"message": {"content": '{"winner": "A"}'}}]}),
]
- with mock.patch("httpx.post", side_effect=_script(*steps)):
+ with mock.patch(BOUNDED_POST, side_effect=_script(*steps)):
with pytest.raises(JudgeUnavailableError) as excinfo:
pairwise_winrate(pairs, evaluator)
@@ -391,7 +393,7 @@ class TestPairwiseWinrate:
ship_cmd, "_resolve_generators",
lambda *a, **k: (lambda p: "base answer", lambda p: "tuned answer"),
)
- with mock.patch("httpx.post", side_effect=_refused):
+ with mock.patch(BOUNDED_POST, side_effect=_refused):
result = CliRunner().invoke(
ship_cmd.app,
["--base", "m", "--tuned", "t", "--task-eval", "tasks.jsonl",
@@ -417,7 +419,7 @@ class TestBestOfNCli:
"soup_cli.utils.magpie.make_magpie_generate_fn",
lambda *a, **k: (lambda prompt: "a candidate"),
)
- with mock.patch("httpx.post", side_effect=_refused):
+ with mock.patch(BOUNDED_POST, side_effect=_refused):
result = CliRunner().invoke(
app,
["best-of-n", "--provider", "ollama", "--model", "sampler",
@@ -444,7 +446,7 @@ class TestBestOfNCli:
)
# The first prompt's three candidates are scored, then nothing answers.
steps = [_reply(200, SCORED)] * 3
- with mock.patch("httpx.post", side_effect=_script(*steps)):
+ with mock.patch(BOUNDED_POST, side_effect=_script(*steps)):
result = CliRunner().invoke(
app,
["best-of-n", "--provider", "ollama", "--model", "sampler",
diff --git a/tests/test_issue1547_outbound_http_sinks.py b/tests/test_issue1547_outbound_http_sinks.py
index fa2b56f6..9697e1ff 100644
--- a/tests/test_issue1547_outbound_http_sinks.py
+++ b/tests/test_issue1547_outbound_http_sinks.py
@@ -55,11 +55,15 @@ from pathlib import Path
import pytest
SRC = Path(__file__).resolve().parents[1] / "src" / "soup_cli"
+BOUNDED_HTTP_MODULE = "soup_cli.utils.http_response"
# Inert members of the target HTTP libraries that do not initiate network traffic
# or configure transport pipelines. Any attribute access or from-import not in
# these sets is flagged as an outbound sink reference.
INERT_NAMES: dict[str, frozenset[str]] = {
+ BOUNDED_HTTP_MODULE: frozenset({
+ "ResponseTooLargeError", "GENERATION_RESPONSE_LIMIT_BYTES", "JUDGE_RESPONSE_LIMIT_BYTES",
+ }),
"httpx": frozenset({
"Auth",
"BasicAuth",
@@ -156,7 +160,7 @@ class DeclaredSink:
# - reason: explicit justification for exemptions (fixed host, loopback only, operator env)
DECLARED_SINKS: dict[tuple[str, str], DeclaredSink] = {
("commands/generate.py", "_generate_openai"): DeclaredSink(
- calls=("httpx.post",),
+ calls=("soup_cli.utils.http_response.post_capped",),
gate=("_generate_openai", "refuse_private_ip_literal"),
reason=(
"validates api_base against LOOPBACK_HOSTS (HTTPS required for remote) "
@@ -164,7 +168,7 @@ DECLARED_SINKS: dict[tuple[str, str], DeclaredSink] = {
),
),
("commands/generate.py", "_generate_server"): DeclaredSink(
- calls=("httpx.post",),
+ calls=("soup_cli.utils.http_response.post_capped",),
gate=("_generate_server", "refuse_private_ip_literal"),
reason=(
"validates api_base against LOOPBACK_HOSTS (HTTPS required for remote) "
@@ -172,25 +176,17 @@ DECLARED_SINKS: dict[tuple[str, str], DeclaredSink] = {
),
),
("data/providers/anthropic.py", "generate_anthropic"): DeclaredSink(
- calls=("httpx.post",),
+ calls=("soup_cli.utils.http_response.post_capped",),
gate=None,
reason="fixed host: ANTHROPIC_API_URL is hardcoded to https://api.anthropic.com/v1/messages",
),
- ("data/providers/ollama.py", "detect_ollama"): DeclaredSink(
- calls=("httpx.get", "httpx.get"),
- gate=None,
- reason=(
- "loopback only: callers use default http://localhost:11434; "
- "function accepts base_url parameter"
- ),
- ),
("data/providers/ollama.py", "generate_ollama"): DeclaredSink(
- calls=("httpx.post",),
+ calls=("soup_cli.utils.http_response.post_capped",),
gate=("generate_ollama", "validate_ollama_url"),
reason="validate_ollama_url restricts base_url to localhost/127.0.0.1/::1",
),
("data/providers/vllm.py", "generate_vllm"): DeclaredSink(
- calls=("httpx.post",),
+ calls=("soup_cli.utils.http_response.post_capped",),
gate=("generate_vllm", "validate_vllm_url"),
reason=(
"validate_vllm_url requires HTTPS for remote and calls "
@@ -198,13 +194,42 @@ DECLARED_SINKS: dict[tuple[str, str], DeclaredSink] = {
),
),
("eval/judge.py", "_judge_request"): DeclaredSink(
- calls=("httpx.post",),
+ calls=("soup_cli.utils.http_response.post_capped",),
gate=("validate_judge_api_base", "refuse_private_ip_literal"),
reason=(
"JudgeEvaluator.__init__ enforces policy via validate_judge_api_base, "
"which calls net_guard.refuse_private_ip_literal"
),
),
+ ("utils/magpie.py", "make_magpie_generate_fn._ollama_generate"): DeclaredSink(
+ calls=("soup_cli.utils.http_response.post_capped",),
+ gate=("make_magpie_generate_fn", "validate_ollama_url"),
+ reason="make_magpie_generate_fn enforces validate_ollama_url (loopback only)",
+ ),
+ ("utils/magpie.py", "make_magpie_generate_fn._vllm_generate"): DeclaredSink(
+ calls=("soup_cli.utils.http_response.post_capped",),
+ gate=("make_magpie_generate_fn", "validate_vllm_url"),
+ reason=(
+ "make_magpie_generate_fn enforces validate_vllm_url (calls "
+ "net_guard.refuse_private_ip_literal)"
+ ),
+ ),
+ ("utils/http_response.py", "post_capped"): DeclaredSink(
+ calls=("httpx.stream",),
+ gate=None,
+ reason=(
+ "operator environment: bounded POST transport; callers retain their existing "
+ "endpoint validators, fixed provider hosts and credential policies"
+ ),
+ ),
+ ("data/providers/ollama.py", "detect_ollama"): DeclaredSink(
+ calls=("httpx.get", "httpx.get"),
+ gate=None,
+ reason=(
+ "loopback only: callers use default http://localhost:11434; "
+ "function accepts base_url parameter"
+ ),
+ ),
("ui/app.py", "create_app.chat_send._stream_chat"): DeclaredSink(
calls=("httpx.stream",),
gate=("chat_send", "refuse_private_ip_literal"),
@@ -247,19 +272,6 @@ DECLARED_SINKS: dict[tuple[str, str], DeclaredSink] = {
"validate_webhook_url and restricts target to local/LAN via _endpoint_is_local"
),
),
- ("utils/magpie.py", "make_magpie_generate_fn._ollama_generate"): DeclaredSink(
- calls=("httpx.post",),
- gate=("make_magpie_generate_fn", "validate_ollama_url"),
- reason="make_magpie_generate_fn enforces validate_ollama_url (loopback only)",
- ),
- ("utils/magpie.py", "make_magpie_generate_fn._vllm_generate"): DeclaredSink(
- calls=("httpx.post",),
- gate=("make_magpie_generate_fn", "validate_vllm_url"),
- reason=(
- "make_magpie_generate_fn enforces validate_vllm_url (calls "
- "net_guard.refuse_private_ip_literal)"
- ),
- ),
("utils/sglang.py", "generate_with_runtime"): DeclaredSink(
calls=("httpx.post",),
gate=None,
@@ -290,7 +302,7 @@ def _resolve_call_module(node: ast.AST) -> str | None:
if node.func.attr == "import_module" and node.args:
arg = node.args[0]
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
- if arg.value in ("httpx", "requests", "urllib.request"):
+ if arg.value in ("httpx", "requests", "urllib.request", BOUNDED_HTTP_MODULE):
return arg.value
if arg.value == "urllib":
return "urllib"
@@ -298,7 +310,7 @@ def _resolve_call_module(node: ast.AST) -> str | None:
if node.func.id in ("import_module", "__import__") and node.args:
arg = node.args[0]
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
- if arg.value in ("httpx", "requests", "urllib.request"):
+ if arg.value in ("httpx", "requests", "urllib.request", BOUNDED_HTTP_MODULE):
return arg.value
if arg.value == "urllib":
return "urllib"
@@ -316,9 +328,13 @@ class _ModuleCollector(ast.NodeVisitor):
self.from_bindings: dict[str, tuple[str, str]] = {}
self.star_imports: list[tuple[int, str]] = []
- def visit_Import(self, node: ast.Import) -> None:
+ def visit_Import(self, node: ast.Import) -> None: # noqa: N802 -- ast.NodeVisitor callback
for alias in node.names:
- if alias.name == "httpx" or alias.name.startswith("httpx."):
+ if alias.name == BOUNDED_HTTP_MODULE:
+ self.module_bindings[alias.asname or "soup_cli"] = (
+ BOUNDED_HTTP_MODULE if alias.asname else "soup_cli"
+ )
+ elif alias.name == "httpx" or alias.name.startswith("httpx."):
if alias.asname:
self.module_bindings[alias.asname] = "httpx"
else:
@@ -339,13 +355,25 @@ class _ModuleCollector(ast.NodeVisitor):
self.module_bindings["urllib"] = "urllib"
self.generic_visit(node)
- def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None: # noqa: N802 -- ast.NodeVisitor callback
mod = node.module or ""
root, _, sub = mod.partition(".")
sub = sub.split(".")[0]
if root in PASS_THROUGH and sub in INERT_NAMES[root] and sub not in PASS_THROUGH[root]:
return
- if mod == "httpx" or mod.startswith("httpx."):
+ if mod == BOUNDED_HTTP_MODULE:
+ for alias in node.names:
+ if alias.name == "*":
+ self.star_imports.append((node.lineno, BOUNDED_HTTP_MODULE))
+ elif alias.name not in INERT_NAMES[BOUNDED_HTTP_MODULE]:
+ self.from_bindings[alias.asname or alias.name] = (
+ BOUNDED_HTTP_MODULE, alias.name,
+ )
+ elif mod == "soup_cli.utils":
+ for alias in node.names:
+ if alias.name == "http_response":
+ self.module_bindings[alias.asname or alias.name] = BOUNDED_HTTP_MODULE
+ elif mod == "httpx" or mod.startswith("httpx."):
for alias in node.names:
if alias.name == "*":
self.star_imports.append((node.lineno, "httpx"))
@@ -376,7 +404,7 @@ class _ModuleCollector(ast.NodeVisitor):
self.from_bindings[target] = ("urllib.request", alias.name)
self.generic_visit(node)
- def visit_Assign(self, node: ast.Assign) -> None:
+ def visit_Assign(self, node: ast.Assign) -> None: # noqa: N802 -- ast.NodeVisitor callback
mod = _resolve_call_module(node.value)
if mod:
for target in node.targets:
@@ -401,7 +429,7 @@ class _SinkVisitor(ast.NodeVisitor):
def _is_shadowed(self, name: str) -> bool:
return any(name in shadowed for shadowed in self.shadowed_stack)
- def visit_ClassDef(self, node: ast.ClassDef) -> None:
+ def visit_ClassDef(self, node: ast.ClassDef) -> None: # noqa: N802 -- ast.NodeVisitor callback
# bases, keywords and decorators are evaluated in the enclosing scope
for outer in [*node.decorator_list, *node.bases, *node.keywords]:
self.visit(outer)
@@ -423,7 +451,7 @@ class _SinkVisitor(ast.NodeVisitor):
self.shadowed_stack.pop()
self.scope_stack.pop()
- def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None: # noqa: N802 -- ast.NodeVisitor callback
for decorator in node.decorator_list:
self.visit(decorator)
for default in node.args.defaults + [d for d in node.args.kw_defaults if d is not None]:
@@ -433,7 +461,7 @@ class _SinkVisitor(ast.NodeVisitor):
self.visit(stmt)
self._exit_function()
- def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: # noqa: N802 -- ast.NodeVisitor callback
for decorator in node.decorator_list:
self.visit(decorator)
for default in node.args.defaults + [d for d in node.args.kw_defaults if d is not None]:
@@ -443,7 +471,7 @@ class _SinkVisitor(ast.NodeVisitor):
self.visit(stmt)
self._exit_function()
- def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
+ def visit_AnnAssign(self, node: ast.AnnAssign) -> None: # noqa: N802 -- ast.NodeVisitor callback
self.visit(node.target)
if node.value is not None:
self.visit(node.value)
@@ -458,6 +486,10 @@ class _SinkVisitor(ast.NodeVisitor):
parent = self._resolve_module(node.value)
if parent == "urllib" and node.attr == "request":
return "urllib.request"
+ if parent in ("soup_cli", "soup_cli.utils"):
+ candidate = f"{parent}.{node.attr}"
+ if BOUNDED_HTTP_MODULE.startswith(candidate):
+ return candidate
if parent in ("httpx", "requests") and node.attr in PASS_THROUGH[parent]:
return parent
call_mod = _resolve_call_module(node)
@@ -472,14 +504,14 @@ class _SinkVisitor(ast.NodeVisitor):
return mod, node.attr
return None, None
- def visit_Attribute(self, node: ast.Attribute) -> None:
+ def visit_Attribute(self, node: ast.Attribute) -> None: # noqa: N802 -- ast.NodeVisitor callback
mod, attr = self._resolve_attr(node)
- if mod and mod != "urllib":
+ if mod and mod not in ("urllib", "soup_cli", "soup_cli.utils"):
if attr not in INERT_NAMES.get(mod, frozenset()):
self.sinks.append((self._scope(), node.lineno, f"{mod}.{attr}"))
self.generic_visit(node)
- def visit_Name(self, node: ast.Name) -> None:
+ def visit_Name(self, node: ast.Name) -> None: # noqa: N802 -- ast.NodeVisitor callback
if not isinstance(node.ctx, ast.Load) or self._is_shadowed(node.id):
return
if node.id in self.b.from_bindings:
@@ -490,7 +522,7 @@ class _SinkVisitor(ast.NodeVisitor):
self.sinks.append((self._scope(), node.lineno, f"{mod} (module object)"))
self.generic_visit(node)
- def visit_Call(self, node: ast.Call) -> None:
+ def visit_Call(self, node: ast.Call) -> None: # noqa: N802 -- ast.NodeVisitor callback
is_getattr = (
(isinstance(node.func, ast.Name) and node.func.id == "getattr")
or (
@@ -1316,4 +1348,3 @@ def test_class_decorators_and_keywords_are_read_in_the_enclosing_scope() -> None
assert decorated == [("<module>", 2, "httpx.post")]
keyword = find_outbound_sinks("import httpx\nclass C(metaclass=httpx.Client):\n pass\n")
assert keyword == [("<module>", 2, "httpx.Client")]
-
diff --git a/tests/test_judge_key_scoping.py b/tests/test_judge_key_scoping.py
index 036fee69..8910f0f4 100644
--- a/tests/test_judge_key_scoping.py
+++ b/tests/test_judge_key_scoping.py
@@ -6,6 +6,8 @@ from unittest import mock
import pytest
+BOUNDED_POST = "soup_cli.utils.http_response.post_capped"
+
@pytest.fixture(autouse=True)
def _key(monkeypatch):
@@ -18,7 +20,7 @@ def _auth_header_for(url: str):
provider, model, base = _parse_judge_url(url)
evaluator = JudgeEvaluator(provider=provider, model=model, api_base=base)
- with mock.patch("httpx.post") as post:
+ with mock.patch(BOUNDED_POST) as post:
post.return_value.status_code = 200
post.return_value.json.return_value = {
"choices": [{"message": {"content": '{"winner": "A"}'}}]
diff --git a/tests/test_server_generate.py b/tests/test_server_generate.py
index 4d3276f2..c32eeefb 100644
--- a/tests/test_server_generate.py
+++ b/tests/test_server_generate.py
@@ -5,6 +5,8 @@ from unittest.mock import patch as mock_patch
import pytest
+BOUNDED_POST = "soup_cli.utils.http_response.post_capped"
+
# ─── Provider Validation Tests ───────────────────────────────────────────
@@ -70,7 +72,7 @@ class TestGenerateServer:
]
}
- with mock_patch("httpx.post", return_value=mock_response) as mock_post:
+ with mock_patch(BOUNDED_POST, return_value=mock_response) as mock_post:
_generate_server(
prompt="Generate test data",
count=1,
@@ -98,7 +100,7 @@ class TestGenerateServer:
]
}
- with mock_patch("httpx.post", return_value=mock_response) as mock_post:
+ with mock_patch(BOUNDED_POST, return_value=mock_response) as mock_post:
_generate_server(
prompt="test",
count=1,
@@ -124,7 +126,7 @@ class TestGenerateServer:
]
}
- with mock_patch("httpx.post", return_value=mock_response) as mock_post:
+ with mock_patch(BOUNDED_POST, return_value=mock_response) as mock_post:
_generate_server(
prompt="test",
count=1,
@@ -150,7 +152,7 @@ class TestGenerateServer:
]
}
- with mock_patch("httpx.post", return_value=mock_response) as mock_post:
+ with mock_patch(BOUNDED_POST, return_value=mock_response) as mock_post:
_generate_server(
prompt="test",
count=1,
@@ -172,7 +174,7 @@ class TestGenerateServer:
mock_response.status_code = 500
mock_response.text = "Internal Server Error"
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
with pytest.raises(ValueError, match="Server returned 500"):
_generate_server(
prompt="test",
@@ -203,7 +205,7 @@ class TestGenerateServer:
]
}
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
result = _generate_server(
prompt="test",
count=1,
@@ -227,7 +229,7 @@ class TestGenerateServer:
"choices": [{"message": {"content": "[]"}}]
}
- with mock_patch("httpx.post", return_value=mock_response) as mock_post:
+ with mock_patch(BOUNDED_POST, return_value=mock_response) as mock_post:
_generate_server(
prompt="test",
count=1,
@@ -475,7 +477,7 @@ class TestServerSSRFValidation:
"choices": [{"message": {"content": "[]"}}]
}
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
result = _generate_server(
prompt="test", count=1, fmt="alpaca",
model_name="m", api_base="http://127.0.0.1:8000",
diff --git a/tests/test_synth_data_pro.py b/tests/test_synth_data_pro.py
index 9975ba90..7a2a9c5b 100644
--- a/tests/test_synth_data_pro.py
+++ b/tests/test_synth_data_pro.py
@@ -12,6 +12,8 @@ from unittest.mock import patch as mock_patch
import pytest
+BOUNDED_POST = "soup_cli.utils.http_response.post_capped"
+
def _strip_ansi(text: str) -> str:
"""Remove ANSI escape codes from Rich-formatted output."""
@@ -174,7 +176,7 @@ class TestOllamaProvider:
]
}
- with mock_patch("httpx.post", return_value=mock_response) as mock_post:
+ with mock_patch(BOUNDED_POST, return_value=mock_response) as mock_post:
result = generate_ollama(
prompt="test", count=1, fmt="alpaca",
model_name="llama3.1",
@@ -197,7 +199,7 @@ class TestOllamaProvider:
mock_response.status_code = 404
mock_response.text = "model not found"
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
with pytest.raises(ValueError, match="Ollama returned 404"):
generate_ollama(
prompt="test", count=1, fmt="alpaca",
@@ -270,7 +272,7 @@ class TestAnthropicProvider:
}
with mock_patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}):
- with mock_patch("httpx.post", return_value=mock_response) as mock_post:
+ with mock_patch(BOUNDED_POST, return_value=mock_response) as mock_post:
result = generate_anthropic(
prompt="test", count=1, fmt="alpaca",
model_name="claude-3-haiku-20240307",
@@ -311,7 +313,7 @@ class TestAnthropicProvider:
mock_response.text = "Unauthorized"
with mock_patch.dict(os.environ, {"ANTHROPIC_API_KEY": "bad-key"}):
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
with pytest.raises(ValueError, match="401"):
generate_anthropic(
prompt="test", count=1, fmt="alpaca",
@@ -344,7 +346,7 @@ class TestAnthropicProvider:
}
with mock_patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}):
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
result = generate_anthropic(
prompt="test", count=2, fmt="alpaca",
model_name="claude-3-haiku-20240307",
@@ -373,7 +375,7 @@ class TestVLLMProvider:
]
}
- with mock_patch("httpx.post", return_value=mock_response) as mock_post:
+ with mock_patch(BOUNDED_POST, return_value=mock_response) as mock_post:
result = generate_vllm(
prompt="test", count=1, fmt="alpaca",
model_name="meta-llama/Llama-3.1-8B-Instruct",
@@ -398,7 +400,7 @@ class TestVLLMProvider:
"choices": [{"message": {"content": "[]"}}]
}
- with mock_patch("httpx.post", return_value=mock_response) as mock_post:
+ with mock_patch(BOUNDED_POST, return_value=mock_response) as mock_post:
generate_vllm(
prompt="test", count=1, fmt="alpaca",
model_name="m", base_url="http://localhost:8000",
@@ -416,7 +418,7 @@ class TestVLLMProvider:
mock_response.status_code = 500
mock_response.text = "Internal Server Error"
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
with pytest.raises(ValueError, match="vLLM server returned 500"):
generate_vllm(
prompt="test", count=1, fmt="alpaca",
@@ -504,7 +506,7 @@ class TestProviderMalformedResponse:
mock_response.json.return_value = {"unexpected": "format"}
with mock_patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-ant-test"}):
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
with pytest.raises(ValueError, match="Unexpected"):
generate_anthropic(
prompt="test", count=1, fmt="alpaca",
@@ -521,7 +523,7 @@ class TestProviderMalformedResponse:
mock_response.status_code = 200
mock_response.json.return_value = {"unexpected": "format"}
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
with pytest.raises(ValueError, match="Unexpected"):
generate_vllm(
prompt="test", count=1, fmt="alpaca",
@@ -539,7 +541,7 @@ class TestProviderMalformedResponse:
mock_response.status_code = 200
mock_response.json.return_value = {"unexpected": "format"}
- with mock_patch("httpx.post", return_value=mock_response):
+ with mock_patch(BOUNDED_POST, return_value=mock_response):
with pytest.raises(ValueError, match="Unexpected"):
generate_ollama(
prompt="test", count=1, fmt="alpaca",
diff --git a/tests/test_v0716.py b/tests/test_v0716.py
index 91af534c..33d07c13 100644
--- a/tests/test_v0716.py
+++ b/tests/test_v0716.py
@@ -754,9 +754,9 @@ class TestMakeMagpieGenerateFn:
def json(self):
return {"response": "What is 2+2?"}
- import httpx
+ from soup_cli.utils import http_response
- monkeypatch.setattr(httpx, "post", lambda *a, **k: FakeResp())
+ monkeypatch.setattr(http_response, "post_capped", lambda *a, **k: FakeResp())
gen = magpie.make_magpie_generate_fn("ollama", model="qwen2.5:0.5b")
assert gen("<|im_start|>user\n") == "What is 2+2?"
@@ -770,9 +770,9 @@ class TestMakeMagpieGenerateFn:
def json(self):
return {"choices": [{"text": "hello"}]}
- import httpx
+ from soup_cli.utils import http_response
- monkeypatch.setattr(httpx, "post", lambda *a, **k: FakeResp())
+ monkeypatch.setattr(http_response, "post_capped", lambda *a, **k: FakeResp())
gen = magpie.make_magpie_generate_fn("vllm", model="m")
assert gen("prefix") == "hello"
@@ -1573,9 +1573,9 @@ class TestMagpieReviewFixes:
def json(self):
return {}
- import httpx
+ from soup_cli.utils import http_response
- monkeypatch.setattr(httpx, "post", lambda *a, **k: FakeResp())
+ monkeypatch.setattr(http_response, "post_capped", lambda *a, **k: FakeResp())
gen = magpie.make_magpie_generate_fn("ollama", model="m")
assert gen("prefix") == ""
@@ -1591,9 +1591,9 @@ class TestMagpieReviewFixes:
def json(self):
return {} # missing "response" key
- import httpx
+ from soup_cli.utils import http_response
- monkeypatch.setattr(httpx, "post", lambda *a, **k: FakeResp())
+ monkeypatch.setattr(http_response, "post_capped", lambda *a, **k: FakeResp())
gen = magpie.make_magpie_generate_fn("ollama", model="m")
assert gen("prefix") == ""