Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix: validate complete first guard verdict evidence

Attila Laszlo Nagy514b07fffc4b
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
index 8e64415ed..588a7f4e1 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -1657,10 +1657,13 @@ def _guard_verdict_logprobs(event: dict[str, Any]) -> tuple[dict[str, Any], ...]
if not isinstance(meta, dict):
return ()
tokens, top = meta.get("output_token_logprobs"), meta.get("output_top_logprobs")
- if not isinstance(tokens, list) or not isinstance(top, list) or len(top) < len(tokens):
+ if not isinstance(tokens, list) or not isinstance(top, list):
return ()
entries: list[dict[str, Any]] = []
- for token, alternatives in zip(tokens[:_GUARD_VERDICT_SCAN_POSITIONS], top, strict=False):
+ for index, token in enumerate(tokens[:_GUARD_VERDICT_SCAN_POSITIONS]):
+ if index >= len(top):
+ return ()
+ alternatives = top[index]
if not isinstance(alternatives, list):
return ()
parsed: list[dict[str, Any]] = []
@@ -1672,6 +1675,8 @@ def _guard_verdict_logprobs(event: dict[str, Any]) -> tuple[dict[str, Any], ...]
return ()
parsed.append({"token": raw[2], "logprob": value, "bytes": list(raw[2].encode("utf-8"))})
entries.append({**parsed[0], "top_logprobs": parsed[1:]})
+ if parsed[0]["token"].strip().lower() in ("yes", "no"):
+ break
return tuple(entries)
@@ -1679,13 +1684,13 @@ def _p_unsafe_from_entry(entry: Any) -> float | None:
"""``P(unsafe)`` from one OpenAI-shape content token's ``top_logprobs``.
Renormalises ``exp(lp_yes)/(exp(lp_yes)+exp(lp_no))`` over the ``yes``/``no``
- verdict tokens in this single position. ``None`` when neither appears.
+ verdict tokens in this single position. Both probabilities are required.
"""
if not isinstance(entry, dict) or str(entry.get("token") or "").strip().lower() not in ("yes", "no"):
return None
lp_yes: float | None = None
lp_no: float | None = None
- for top in entry.get("top_logprobs") or []:
+ for top in [entry, *(entry.get("top_logprobs") or [])]:
if not isinstance(top, dict):
continue
tok = str(top.get("token") or "").strip().lower()
@@ -1698,11 +1703,11 @@ def _p_unsafe_from_entry(entry: Any) -> float | None:
lp_yes = val if lp_yes is None else max(lp_yes, val)
elif tok == "no":
lp_no = val if lp_no is None else max(lp_no, val)
- if lp_yes is None and lp_no is None:
+ if lp_yes is None or lp_no is None:
return None
- offset = max(value for value in (lp_yes, lp_no) if value is not None)
- ey = math.exp(lp_yes - offset) if lp_yes is not None else 0.0
- en = math.exp(lp_no - offset) if lp_no is not None else 0.0
+ offset = max(lp_yes, lp_no)
+ ey = math.exp(lp_yes - offset)
+ en = math.exp(lp_no - offset)
return ey / (ey + en) if (ey + en) > 0 else None
@@ -1713,8 +1718,8 @@ def _p_unsafe_from_verdict_logprobs(
``chunk_logprobs`` is the OpenAI ``content`` shape this adapter builds —
``({"token", "logprob", "top_logprobs": [{"token", "logprob"}, ...]}, ...)``.
- Scans the first up-to ``scan_positions`` content tokens for the first whose
- ``top_logprobs`` carries a ``yes``/``no`` verdict distribution, then
+ Scans the first up-to ``scan_positions`` content tokens for the first sampled
+ ``yes``/``no`` verdict and validates its distribution, then
renormalises ``exp(lp_yes)/(exp(lp_yes)+exp(lp_no))`` over those two tokens.
Scanning past position 0 keeps a leading whitespace/punctuation/preamble
token from hiding the verdict, matching the eval runner's ``content[:3]``
@@ -1723,9 +1728,8 @@ def _p_unsafe_from_verdict_logprobs(
if not chunk_logprobs:
return None
for entry in chunk_logprobs[:scan_positions]:
- p_unsafe = _p_unsafe_from_entry(entry)
- if p_unsafe is not None:
- return p_unsafe
+ if isinstance(entry, dict) and str(entry.get("token") or "").strip().lower() in ("yes", "no"):
+ return _p_unsafe_from_entry(entry)
return None
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index 2d2c7aaa5..698e780cd 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -2509,18 +2509,18 @@ def test_guard_missing_verdict_distribution_is_typed_error(mock_async_client: Ma
@pytest.mark.parametrize("invalid", [float("nan"), float("inf"), float("-inf"), 0.1, True, "-0.1"])
def test_guard_invalid_verdict_probability_cannot_be_safe(invalid: Any) -> None:
- logprobs = ({"token": "No", "top_logprobs": [_lp("Yes", invalid), _lp("No", -0.1)]},)
+ logprobs = ({"token": "No", "logprob": -0.1, "top_logprobs": [_lp("Yes", invalid), _lp("No", -0.1)]},)
assert _thresholded_verdict(logprobs, {"threshold": 0.5}) is None
@pytest.mark.parametrize("threshold", [float("nan"), float("inf"), -0.1, 1.1, True, "0.5"])
def test_guard_invalid_threshold_cannot_be_safe(threshold: Any) -> None:
- logprobs = ({"token": "Yes", "top_logprobs": [_lp("Yes", -0.5), _lp("No", -0.5)]},)
+ logprobs = ({"token": "Yes", "logprob": -0.5, "top_logprobs": [_lp("Yes", -0.5), _lp("No", -0.5)]},)
assert _thresholded_verdict(logprobs, {"threshold": threshold}) is None
def test_guard_very_small_probabilities_are_normalized_without_underflow() -> None:
- logprobs = ({"token": "Yes", "top_logprobs": [_lp("Yes", -1000), _lp("No", -1001)]},)
+ logprobs = ({"token": "Yes", "logprob": -1000, "top_logprobs": [_lp("Yes", -1000), _lp("No", -1001)]},)
assert _thresholded_verdict(logprobs, {"threshold": 0.5}) == "Yes"
@@ -2576,3 +2576,64 @@ def test_guard_malformed_wire_probability_fails_closed(
assert chunks[-1].error_code == "invalid_guard_verdict"
assert chunks[-1].finish_reason == "error"
assert not any(c.text_delta for c in chunks)
+
+
[email protected]("malformed_tail", ["sampled", "alternative", "missing_top", "malformed_top"])
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_guard_valid_verdict_ignores_malformed_trailing_metadata(
+ mock_async_client: MagicMock, malformed_tail: str
+) -> None:
+ tokens = [_sglang_token("Yes", -0.1), _sglang_token(" because", -0.2)]
+ top: list[Any] = [_guard_top(yes=-0.1, no=-3), _guard_top(filler=" because")]
+ if malformed_tail == "sampled":
+ tokens[1][0] = True
+ elif malformed_tail == "alternative":
+ top[1][0][0] = "-0.1"
+ elif malformed_tail == "missing_top":
+ top.pop()
+ else:
+ top[1] = None
+ lines = [_guard_event("Yes because", tokens, top, terminal=True)]
+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(lines))
+ chunks = _drive_guard(_guard_adapter(), lines, logprobs=True)
+ assert "".join(chunk.text_delta for chunk in chunks) == "Yes"
+ assert chunks[-1].error_code is None
+ assert all(chunk.logprobs is None for chunk in chunks)
+
+
[email protected](("sampled", "opposing"), [("Yes", "No"), ("No", "Yes")])
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_guard_uses_sampled_probability_when_absent_from_top_alternatives(
+ mock_async_client: MagicMock, sampled: str, opposing: str
+) -> None:
+ lines = [_guard_event(sampled, [_sglang_token(sampled, -0.1)], [[_sglang_token(opposing, -3)]], terminal=True)]
+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(lines))
+ chunks = _drive_guard(_guard_adapter(), lines)
+ assert "".join(chunk.text_delta for chunk in chunks) == sampled
+ assert chunks[-1].error_code is None
+
+
[email protected]("sampled", ["Yes", "No"])
[email protected]("later_verdict", [False, True])
+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
+def test_guard_missing_opposing_probability_fails_closed(
+ mock_async_client: MagicMock, sampled: str, later_verdict: bool
+) -> None:
+ tokens = [_sglang_token(sampled, -0.1)]
+ top = [[_sglang_token(sampled, -0.1)]]
+ if later_verdict:
+ tokens.append(_sglang_token("No", -0.1))
+ top.append(_guard_top(yes=-3, no=-0.1))
+ lines = [_guard_event(sampled, tokens, top, terminal=True)]
+ mock_async_client.return_value = _make_client_with_stream(_FakeStreamingResponse(lines))
+ chunks = _drive_guard(_guard_adapter(), lines)
+ assert chunks[-1].error_code == "invalid_guard_verdict"
+ assert not any(chunk.text_delta for chunk in chunks)
+
+
+def test_guard_first_sampled_verdict_requires_complete_evidence() -> None:
+ later_safe = {"token": "No", "logprob": -0.1, "top_logprobs": [_lp("Yes", -3), _lp("No", -0.1)]}
+ incomplete_yes = {"token": "Yes", "logprob": -0.1, "top_logprobs": [_lp("Yes", -0.1)]}
+ assert _p_unsafe_from_verdict_logprobs((incomplete_yes, later_safe)) is None
+ missing_sampled = {"token": "Yes", "top_logprobs": [_lp("Yes", -0.1), _lp("No", -3)]}
+ assert _p_unsafe_from_verdict_logprobs((missing_sampled, later_safe)) is None