Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions evidence/missions/lgcorzo-mlops-python-package-478.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Dark Gravity Mission `lgcorzo-mlops-python-package-478`

- **Issue**: #478
- **Status**: Validated in gVisor & Aethelgard SAST
11 changes: 11 additions & 0 deletions src/regression_model_template/utils/swarm_checksums.py
Original file line number Diff line number Diff line change
@@ -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()
20 changes: 20 additions & 0 deletions src/regression_model_template/utils/swarm_metrics.py
Original file line number Diff line number Diff line change
@@ -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],
}
16 changes: 16 additions & 0 deletions src/regression_model_template/utils/swarm_sanitizers.py
Original file line number Diff line number Diff line change
@@ -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
11 changes: 11 additions & 0 deletions tests/utils/test_swarm_checksums.py
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions tests/utils/test_swarm_metrics.py
Original file line number Diff line number Diff line change
@@ -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([])
18 changes: 18 additions & 0 deletions tests/utils/test_swarm_sanitizers.py
Original file line number Diff line number Diff line change
@@ -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("///---!!!")
Loading