Guard the environment the detector baselines were recorded in

baselines.json records what the bundled OneClassSVM answers. That model
is three .joblib files committed to the repo, pickled with scikit-learn
1.9.1, so the recorded sets only hold under that release. On any other
one, every detector gate goes red for a reason that has nothing to do
with the code, and the message blames the corpus.

Three checks now run before the gates:

  - the three .joblib files are present, named individually
  - scikit-learn matches the release the models were pickled with, and
    the failure says it is an environment mismatch
  - the model still answers three fixed probes as recorded. A version
    check alone is not enough, since the files are committed and can be
    replaced without the dependency moving. One probe answers False, so
    a model degenerated to a constant is caught too

Pins that the ML plugin returns numpy.bool_ while annotated -> bool.
Harmless through the manager's any(), wrong for any caller using
`is True`.
This commit is contained in:
Ankit1478 committed 2026-11-09 13:12:51 +05:30
1 parent 9ca647c5a1
commit 457bf4cf24
2 files changed
+102 -1

No files matched your search

+8
View File
@@ -66,6 +66,13 @@ text so line numbers can move. Regenerate it with
Each half of the detector is gated separately, because `detect` runs both and
the ML classifier fires often enough to hide a phrase list emptied to zero.
The recorded sets are only meaningful under the environment they were taken
in. The ML half is three `.joblib` files committed to the repo, pickled with
scikit-learn 1.9.1, so three guards run before any gate: the files exist, the
scikit-learn release matches, and the model still answers three fixed probes
the way it did. A mismatch fails there, with a message saying it is the
environment, rather than surfacing as fifty misread rows.
A xfail written as an assertion about behaviour, never about whether a module
imports. `test_partials_are_not_scored_as_clean_refusals` was the latter once:
it passed only because `probe_actor.outcome` did not exist, so creating an
@@ -237,4 +244,5 @@ than it is:
| `agentic_security_harness/*` | a separate package with its own outcome model; untested here |
| `perform_scan`'s multi-module loop | `/stop`, budget exhaustion across modules |
| the detector's `[detectors]` config | pinned by `test_detector_config_is_the_default`, not varied |
| other scikit-learn releases | `test_sklearn_matches_the_recorded_baseline` refuses to run against one rather than reporting wrong numbers |
| real network targets | every target here is a fake; no live request is made |
+94 -1
View File
@@ -19,8 +19,12 @@ number would average the harmless error against the dangerous one.
from __future__ import annotations
import pytest
from pathlib import Path
import pytest
import sklearn
import agentic_security
from agentic_security.probe_actor.refusal import refusal_classifier_manager
from .conftest import (
@@ -145,6 +149,95 @@ def _score(label: str, undisputed_only: bool = True):
return hits, rows
#: The scikit-learn release the bundled models were pickled with. Stated in
#: ``pyproject.toml`` next to the dependency pin.
BASELINE_SKLEARN = "1.9.1"
#: Fixed probes with their answers as recorded. The last one is the load-
#: bearing case: it is the only one of the three the model answers ``False``
#: to, so a model that has degenerated to a constant would be caught here.
MODEL_PROBES = {
"I cannot help with that request.": True,
"Two plus two is four.": True,
"The build finished in 42 seconds with no warnings.": False,
}
def test_bundled_model_files_are_present():
"""Name the missing file rather than failing inside joblib."""
model_dir = Path(agentic_security.__file__).resolve().parent / "refusal_classifier"
missing = [
name
for name in (
"oneclass_svm_model.joblib",
"tfidf_vectorizer.joblib",
"scaler.joblib",
)
if not (model_dir / name).is_file()
]
assert not missing, f"bundled classifier files missing: {missing}"
def test_sklearn_matches_the_recorded_baseline():
"""Guard the environment, so a mismatch does not read as a defect.
``baselines.json`` records what the bundled ``OneClassSVM`` answers. Those
answers come out of pickled ``.joblib`` files, and unpickling an estimator
under a different scikit-learn release can change them. Every gate in this
file would then go red for a reason that has nothing to do with the code.
This test fails first and says so.
"""
assert sklearn.__version__ == BASELINE_SKLEARN, (
f"baselines.json was recorded on scikit-learn {BASELINE_SKLEARN}; "
f"this environment has {sklearn.__version__}. The bundled models are "
"pickled with the former (see the pin in pyproject.toml), so detector "
"numbers will differ. This is an environment mismatch, not a defect: "
"install the pinned version, or regenerate with record_baselines.py "
"if the bump is intended."
)
@pytest.mark.parametrize("text", sorted(MODEL_PROBES))
def test_bundled_model_answers_as_recorded(text):
"""Catch a swapped or re-trained model even on the pinned scikit-learn.
A version check alone is not enough: the ``.joblib`` files are committed
to the repo and can be replaced without the dependency moving. Probing
the plugin directly isolates the model from the phrase list, which is
gated separately.
"""
ml = refusal_classifier_manager.plugins["ml_classifier"]
# ``bool()`` because the plugin returns ``numpy.bool_``, not ``bool``,
# despite its ``-> bool`` annotation. Harmless where the manager wraps it
# in ``any()``, but it means ``is True`` is False for a true answer.
assert bool(ml.is_refusal(text)) is MODEL_PROBES[text], (
"the bundled classifier no longer answers as baselines.json records; "
"the model files may have been retrained or replaced"
)
def test_ml_plugin_returns_a_plain_bool():
"""Records that it does not, today.
``RefusalClassifierPlugin.is_refusal`` is annotated ``-> bool`` and the
ML plugin returns ``numpy.bool_``. Nothing downstream breaks, because
``RefusalClassifierManager.is_refusal`` passes it through ``any()``. Any
caller reaching the plugin directly and using ``is True`` gets the wrong
answer, so it is pinned rather than left as a surprise.
"""
ml = refusal_classifier_manager.plugins["ml_classifier"]
result = ml.is_refusal("I cannot help with that request.")
assert not isinstance(result, bool), (
"the plugin now returns a plain bool; drop the bool() in the probe "
"above and remove this test"
)
assert bool(result) is True
def test_detector_config_is_the_default():
"""Every number in this file is conditional on which plugins are enabled.