import sys import numpy as np sys.path.insert(0, "packages/core") from shiftbudget_core.calibration import calibrate, risk_coverage from shiftbudget_core.image_ops import apply_shift, quality_features from shiftbudget_core.patchcore import PatchCoreDetector from shiftbudget_core.policy import Budget, route def test_patch_memory_is_deterministic_and_returns_spatial_heatmap(): rng = np.random.default_rng(4) normal = [rng.integers(0, 255, (64, 64, 3), dtype=np.uint8) for _ in range(3)] detector = PatchCoreDetector(image_size=64, patch_size=8, max_memory=32) metadata = detector.fit(normal) result = detector.predict(normal[0]) assert metadata["descriptor_dimensions"] == 11 assert result.heatmap.shape == (8, 8) assert result.anomaly_score >= 0 def test_shift_is_versioned_and_changes_image(): image = np.full((32, 32, 3), 128, dtype=np.uint8) shifted, params = apply_shift(image, "brightness", 1.0, seed=7) assert params["version"] == "1.0" assert params["seed"] == 7 assert not np.array_equal(image, shifted) assert quality_features(shifted).brightness_mean > quality_features(image).brightness_mean def test_calibration_and_risk_coverage_are_empirical(): calibration = calibrate([0.1, 0.2, 0.2, 0.3, 0.4], 0.2) assert calibration.threshold == 0.4 curve = risk_coverage([0.1, 0.9, 0.2], [0, 1, 0], [0.5, 1.0]) assert curve[0]["coverage"] < curve[1]["coverage"] def test_resource_policy_surfaces_latency_constraint(): decision = route(score=4, threshold=2, uncertainty=1, shift_score=0, brightness=.5, latency_ms=1000, policy="resource_aware_cost_sensitive", budget=Budget(max_latency_ms=100)) assert decision.action == "ABSTAIN" assert decision.constraints_satisfied is False