Merge pull request #686 from elder-plinius/fix/679-coverage-and-mutation-timeout

test(release): restore touched-module coverage and raise the Quality depth timeout to 60 min
This commit is contained in:
Joseph Magly authored and GitHub committed 2026-11-25 18:02:52 -05:00
commit dd313618ee
6 files changed
+237 -2

No files matched your search

+1 -1
View File
@@ -1261,7 +1261,7 @@ jobs:
name: Quality depth
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
timeout-minutes: 45
timeout-minutes: 60
env:
CUDA_VISIBLE_DEVICES: ""
HF_DATASETS_OFFLINE: "1"
+5
View File
@@ -80,6 +80,11 @@ confidence-interval, and canonical substring-protocol behavior.
### Fixed
- Release gates (#679): focused tests restore touched-module line and branch
coverage for `evaluation/evaluator.py`, `recipes/search.py`,
`recipes/search_cli.py` and `study_presets.py` above their comparison base,
and the Quality depth job timeout rises from 45 to 60 minutes so the
selective mutation run can finish (the 85% mutation floor is unchanged).
- Release gates (#679): an interrupted failed-run cleanup no longer keeps results on
the accelerator through the interrupt's traceback. The tensor transfer converted
container items in comprehensions/generators, whose frames keep their closure (the
+169
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import math
import sys
from types import SimpleNamespace
from unittest.mock import MagicMock, Mock
@@ -682,3 +683,171 @@ def test_padding_offset_position_models_keep_their_own_positions(padding_side):
expected = torch.arange(len(real)) + padding_idx + 1
assert real.tolist() == expected.tolist()
assert (positions[row][~mask[row]] == padding_idx).all()
# ── #679: touched-module coverage for the #675 evaluator changes ─────────────
_LEFT_PADDED = {
"input_ids": torch.tensor([[0, 0, 5, 6], [3, 4, 5, 6]]),
"attention_mask": torch.tensor([[0, 0, 1, 1], [1, 1, 1, 1]]),
}
class _PositionRecordingModel(nn.Module):
"""A model whose ``forward`` names ``position_ids`` and records what it got."""
def __init__(self, embedding: nn.Module):
super().__init__()
self.embeddings = embedding
self.plain = nn.Embedding(8, 2) # padding_idx is None: not a padding-offset sign
self.received: list[torch.Tensor | None] = []
def forward(self, *, input_ids, attention_mask, position_ids=None):
del input_ids, attention_mask
self.received.append(position_ids)
return SimpleNamespace(loss=torch.tensor(0.0))
class _OwnPositionsEmbedding(nn.Embedding):
"""RoBERTa-style: the embedding class itself builds positions from input_ids."""
@staticmethod
def create_position_ids_from_input_ids(input_ids, padding_idx):
return input_ids.ne(padding_idx).long().cumsum(-1) + padding_idx
class _PaddedEmbedding(nn.Embedding):
"""Has a ``padding_idx`` but nothing that builds positions from input_ids."""
def _left_padded_call(model):
from obliteratus.evaluation.evaluator import _forward, _position_ids_support
support = _position_ids_support(model)
_forward(model, dict(_LEFT_PADDED), support)
return support
def test_padding_offset_embedding_class_keeps_the_models_own_positions():
"""#675 B1: an embedding class that numbers positions itself gets no 0-based ones."""
model = _PositionRecordingModel(_OwnPositionsEmbedding(8, 2, padding_idx=0))
assert _left_padded_call(model) == "none"
assert model.received == [None]
def test_padding_offset_embedding_module_keeps_the_models_own_positions(monkeypatch):
"""#675 B1: so does an embedding whose defining module provides the position helper."""
import types
modeling = types.ModuleType("fake_modeling_roberta_like")
modeling.create_position_ids_from_input_ids = lambda input_ids, padding_idx: input_ids
monkeypatch.setitem(sys.modules, modeling.__name__, modeling)
embedding_type = type("Embeddings", (nn.Embedding,), {"__module__": modeling.__name__})
model = _PositionRecordingModel(embedding_type(8, 2, padding_idx=0))
assert _left_padded_call(model) == "none"
assert model.received == [None]
def test_padding_index_alone_does_not_suppress_left_padding_positions():
"""#675 B1: a plain ``padding_idx`` is not enough; absolute-position models still get positions."""
model = _PositionRecordingModel(_PaddedEmbedding(8, 2, padding_idx=0))
assert _left_padded_call(model) == "named"
(positions,) = model.received
assert positions.tolist() == [[0, 0, 0, 1], [0, 1, 2, 3]]
def test_position_support_of_non_module_and_uninspectable_models():
"""A non-Module wrapper is classified by its signature; an uninspectable one gets none."""
from obliteratus.evaluation.evaluator import _position_ids_support
class CallableWrapper:
def forward(self, **kwargs):
return kwargs
def forward(**kwargs):
return kwargs
forward.__signature__ = "not a Signature" # inspect.signature raises TypeError
uninspectable = SimpleNamespace(forward=forward)
assert _position_ids_support(CallableWrapper()) == "kwargs"
assert _position_ids_support(uninspectable) == "none"
class _SlottedKwargsModel:
"""A non-Module, non-weak-referenceable callable that rejects ``position_ids``."""
__slots__ = ("attempts",)
device = torch.device("cpu")
def __init__(self):
self.attempts: list[bool] = []
def parameters(self):
return iter(())
def forward(self, **kwargs):
self.attempts.append("position_ids" in kwargs)
if "position_ids" in kwargs:
raise TypeError(_CPYTHON_REJECTION)
return SimpleNamespace(loss=torch.tensor(math.log(2.0)))
__call__ = forward
def test_unweakrefable_model_falls_back_and_warns_every_time(caplog):
"""#675 B3: a model the warn-once set cannot hold still falls back, and is never silent."""
model = _SlottedKwargsModel()
with caplog.at_level("WARNING", logger="obliteratus.evaluation.evaluator"):
first = _two_left_padded_batches(model).evaluate() # no eval()/train(): not a Module
second = _two_left_padded_batches(model).evaluate()
assert first["perplexity"] == pytest.approx(2.0) == second["perplexity"]
assert model.attempts == [True, False, False, True, False, False]
warnings = [r for r in caplog.records if r.levelname == "WARNING"]
assert len(warnings) == 2
def test_unsupported_task_is_rejected_before_touching_the_model():
model = Mock()
handle = SimpleNamespace(model=model, tokenizer=Mock(), task="seq2seq")
with pytest.raises(ValueError, match="Unsupported task: seq2seq"):
Evaluator(handle=handle, dataset=_MapDataset(["a"])).evaluate()
model.eval.assert_not_called()
class _FirstTokenClassifier(nn.Module):
"""Predicts the label carried by each row's first token (``input_ids[:, 0] % 2``)."""
def __init__(self):
super().__init__()
self.anchor = nn.Parameter(torch.zeros(()))
def forward(self, *, input_ids, attention_mask):
del attention_mask
return SimpleNamespace(logits=nn.functional.one_hot(input_ids[:, 0] % 2, 2).float())
@pytest.mark.parametrize("metrics", [["accuracy"], ["f1"]])
def test_classification_reports_only_requested_metrics_over_max_samples(metrics):
from datasets import Dataset
from obliteratus.evaluation.metrics import accuracy, f1_score_metric
dataset = Dataset.from_dict({"text": ["a", "b", "c", "d"], "label": [1, 0, 0, 1]})
# Predictions 1, 0, 1 for the first three rows; the fourth must never be read.
tokenizer = _ScriptedTokenizer([_encoding([[1], [2]], [[1], [1]]), _encoding([[3]], [[1]])])
handle = SimpleNamespace(model=_FirstTokenClassifier(), tokenizer=tokenizer, task="classification")
result = Evaluator(
handle=handle, dataset=dataset, metrics=metrics, batch_size=2, max_samples=3,
).evaluate()
assert tokenizer.calls == [["a", "b"], ["c"]]
expected = {"accuracy": accuracy, "f1": f1_score_metric}
assert result == {name: expected[name]([1, 0, 1], [1, 0, 0]) for name in metrics}
+1 -1
View File
@@ -76,7 +76,7 @@ def test_mutation_campaign_uses_fork_safe_native_runtime_policy():
"OPENBLAS_NUM_THREADS": "1",
"VECLIB_MAXIMUM_THREADS": "1",
}
assert quality_job["timeout-minutes"] == 45
assert quality_job["timeout-minutes"] == 60
assert "scripts/check_mutation_targets.py prepare" in mutation_run
assert "scripts/prepare_mutation_coverage.py prepare-coverage --max-children 8" in mutation_run
assert "scripts/prepare_mutation_coverage.py prepare-stats --max-children 8" in mutation_run
+54
View File
@@ -1447,6 +1447,34 @@ def test_diagnostic_flush_failure_never_prints_the_line_twice(monkeypatch):
assert "".join(stream.written).count("could not record the marker") == 1, stream.written
def test_diagnostic_drops_the_line_when_the_escaped_retry_also_fails(monkeypatch):
"""#679: one escaped retry after an encoding failure; if that fails too, drop the line."""
from obliteratus.recipes import search
class EncodeThenClosed:
def __init__(self):
self.attempts = []
self.flushed = False
def write(self, text):
self.attempts.append(text)
if len(self.attempts) == 1:
raise UnicodeEncodeError("ascii", text, 0, 1, "simulated")
raise ValueError("I/O operation on closed file.")
def flush(self):
self.flushed = True
stream = EncodeThenClosed()
monkeypatch.setattr(sys, "stderr", stream)
search._diagnostic("waiting for out-ü/.process-cleanup.lock") # must not raise
assert stream.attempts == [
"waiting for out-ü/.process-cleanup.lock\n",
"waiting for out-\\xfc/.process-cleanup.lock\n", # retried once, escaped
]
assert not stream.flushed
def test_marker_release_failure_after_a_durable_write_says_it_was_recorded(tmp_path, monkeypatch, capsys):
from obliteratus.recipes import search
@@ -1685,6 +1713,32 @@ def test_recipe_cli_exits_four_on_process_cleanup_failure(setup_grid, monkeypatc
assert "could not stop a process group" in capsys.readouterr().out
def test_recipe_cli_exits_one_when_no_candidate_satisfies_the_rule(setup_grid, monkeypatch, capsys):
"""#679: a completed search without a winner is exit 1, distinct from errors (2) and cleanup (4)."""
from obliteratus.cli import main
from obliteratus.recipes import search
_, path, _, _, _ = setup_grid
monkeypatch.setattr(search, "run_search", lambda grid: {"winner": None})
with pytest.raises(SystemExit) as error:
main(["recipe", "search", str(path)])
assert error.value.code == 1
out = capsys.readouterr().out
assert "No candidate satisfied the preregistered rule" in out
assert "Proposed candidate" not in out
def test_cleanup_details_show_non_sequence_notes_as_one_line():
"""#679: a malformed ``__notes__`` is reported once by repr, never iterated or dropped."""
from obliteratus.recipes import search
from obliteratus.recipes.search_cli import _cleanup_details
failure = search.ProcessCleanupFailed("candidate alpha: a process group may still be running")
failure.__notes__ = "could not write candidates/alpha.json"
assert _cleanup_details(failure) == ["recipe: note: 'could not write candidates/alpha.json'"]
def test_grid_schema_validation_and_canonical_lock(setup_grid):
from obliteratus.recipes.search import run_search
+7
View File
@@ -164,3 +164,10 @@ class TestPresetRegistryIsReadOnly:
assert dict(STUDY_PRESETS.items()) == {p.key: p for p in list_study_presets()}
assert STUDY_PRESETS.get("missing") is None
assert sorted(STUDY_PRESETS) == sorted(p.key for p in list_presets())
def test_registry_repr_names_the_presets_without_exposing_a_dict(self):
"""#679: the read-only view reports its keys, not a mutable dict or a preset copy."""
text = repr(STUDY_PRESETS)
assert text == f"STUDY_PRESETS({sorted(p.key for p in list_study_presets())!r})"
assert not isinstance(STUDY_PRESETS, dict)