diff --git a/evidence/missions/lgcorzo-mlops-python-package-478.md b/evidence/missions/lgcorzo-mlops-python-package-478.md new file mode 100644 index 00000000..ab94a8b4 --- /dev/null +++ b/evidence/missions/lgcorzo-mlops-python-package-478.md @@ -0,0 +1,4 @@ +# Dark Gravity Mission `lgcorzo-mlops-python-package-478` + +- **Issue**: #478 +- **Status**: Validated in gVisor & Aethelgard SAST diff --git a/src/regression_model_template/utils/swarm_checksums.py b/src/regression_model_template/utils/swarm_checksums.py new file mode 100644 index 00000000..a8adeedc --- /dev/null +++ b/src/regression_model_template/utils/swarm_checksums.py @@ -0,0 +1,11 @@ +"""Deterministic canonical JSON SHA-256 checksum utilities.""" + +import hashlib +import json +from typing import Any + + +def sha256_canonical_json(payload: dict[str, Any]) -> str: + """Return a deterministic lowercase hex SHA-256 digest for a JSON-serializable dict.""" + canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() diff --git a/src/regression_model_template/utils/swarm_metrics.py b/src/regression_model_template/utils/swarm_metrics.py new file mode 100644 index 00000000..81732d11 --- /dev/null +++ b/src/regression_model_template/utils/swarm_metrics.py @@ -0,0 +1,20 @@ +"""Latency statistics utilities for Swarm Mode telemetry.""" + +import math + + +def compute_latency_stats(samples: list[float]) -> dict[str, float]: + """Compute min, max, mean, and p95 latency statistics from sample values.""" + if not samples: + raise ValueError("samples must not be empty") + + ordered = sorted(float(x) for x in samples) + count = len(ordered) + p95_index = min(count - 1, max(0, math.ceil(0.95 * count) - 1)) + + return { + "min": ordered[0], + "max": ordered[-1], + "mean": sum(ordered) / count, + "p95": ordered[p95_index], + } diff --git a/src/regression_model_template/utils/swarm_sanitizers.py b/src/regression_model_template/utils/swarm_sanitizers.py new file mode 100644 index 00000000..f3b6f18f --- /dev/null +++ b/src/regression_model_template/utils/swarm_sanitizers.py @@ -0,0 +1,16 @@ +"""Identifier sanitization utilities for Swarm Mode.""" + +import re + +_INVALID_CHARS_RE = re.compile(r"[^a-z0-9-]+") +_MULTI_HYPHEN_RE = re.compile(r"-{2,}") + + +def sanitize_identifier(value: str) -> str: + """Normalize a string into a lowercase alphanumeric+hyphen identifier (<= 64 chars).""" + cleaned = _INVALID_CHARS_RE.sub("-", value.strip().lower()) + cleaned = _MULTI_HYPHEN_RE.sub("-", cleaned).strip("-") + cleaned = cleaned[:64].rstrip("-") + if not cleaned: + raise ValueError("identifier contains no alphanumeric characters") + return cleaned diff --git a/tests/utils/test_swarm_checksums.py b/tests/utils/test_swarm_checksums.py new file mode 100644 index 00000000..6cce9105 --- /dev/null +++ b/tests/utils/test_swarm_checksums.py @@ -0,0 +1,11 @@ +"""Unit tests for swarm_checksums.""" + +from regression_model_template.utils.swarm_checksums import sha256_canonical_json + + +def test_sha256_canonical_json_is_key_order_independent() -> None: + """Key ordering must not change the resulting SHA-256 digest.""" + d1 = sha256_canonical_json({"b": 2, "a": {"y": 1, "x": 0}}) + d2 = sha256_canonical_json({"a": {"x": 0, "y": 1}, "b": 2}) + assert d1 == d2 + assert len(d1) == 64 diff --git a/tests/utils/test_swarm_metrics.py b/tests/utils/test_swarm_metrics.py new file mode 100644 index 00000000..802e4aac --- /dev/null +++ b/tests/utils/test_swarm_metrics.py @@ -0,0 +1,21 @@ +"""Unit tests for swarm_metrics.""" + +import pytest + +from regression_model_template.utils.swarm_metrics import compute_latency_stats + + +def test_compute_latency_stats_basic() -> None: + """Verify min, max, mean, and p95 on a 20-element sample.""" + samples = [float(i) for i in range(1, 21)] + stats = compute_latency_stats(samples) + assert stats["min"] == 1.0 + assert stats["max"] == 20.0 + assert stats["mean"] == pytest.approx(10.5) + assert stats["p95"] == 19.0 + + +def test_compute_latency_stats_empty_raises() -> None: + """Empty sample list must raise ValueError.""" + with pytest.raises(ValueError, match="empty"): + compute_latency_stats([]) diff --git a/tests/utils/test_swarm_sanitizers.py b/tests/utils/test_swarm_sanitizers.py new file mode 100644 index 00000000..8049de41 --- /dev/null +++ b/tests/utils/test_swarm_sanitizers.py @@ -0,0 +1,18 @@ +"""Unit tests for swarm_sanitizers.""" + +import pytest + +from regression_model_template.utils.swarm_sanitizers import sanitize_identifier + + +def test_sanitize_identifier_normalizes_and_truncates() -> None: + """Verify lowercasing, punctuation replacement, and 64-char cap.""" + assert sanitize_identifier(" Swarm_Mode/Lane#01! ") == "swarm-mode-lane-01" + long_val = "a" * 80 + assert len(sanitize_identifier(long_val)) == 64 + + +def test_sanitize_identifier_empty_raises() -> None: + """Identifiers with no alphanumeric characters must raise ValueError.""" + with pytest.raises(ValueError, match="alphanumeric"): + sanitize_identifier("///---!!!")