Spaces:
Runtime error
Runtime error
File size: 8,535 Bytes
4c52b20 228ed67 4c52b20 228ed67 4c52b20 228ed67 4c52b20 228ed67 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | """Tests for population-guided mutation selection policy."""
from __future__ import annotations
import asyncio
import json
import os
import random
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
import pytest
from open_range.builder.mutation_policy import (
MutationPolicySettings,
PopulationMutationPolicy,
load_mutation_policy_settings,
)
from open_range.builder.snapshot_store import SnapshotStore
from open_range.protocols import BuildContext, MutationOp
def test_policy_selects_structural_and_security_when_both_available(sample_snapshot_spec):
policy = PopulationMutationPolicy()
structural = [
MutationOp(
mutation_id="add_service_web",
op_type="add_service",
target_selector={"host": "web"},
params={"service": "redis"},
)
]
security = [
MutationOp(
mutation_id="seed_sqli",
op_type="seed_vuln",
target_selector={"host": "web"},
params={"vuln_type": "sqli"},
),
MutationOp(
mutation_id="noise1",
op_type="add_benign_noise",
target_selector={"location": "siem:noise.log"},
params={"location": "siem:noise.log"},
),
]
ops, _score, _breakdown = policy.choose_mutations(
structural_candidates=structural,
security_candidates=security,
snapshot=sample_snapshot_spec,
context=BuildContext(seed=1, tier=1),
rng=random.Random(7),
)
op_types = {op.op_type for op in ops}
assert "add_service" in op_types
assert op_types.intersection({"seed_vuln", "add_benign_noise"})
def test_policy_best_effort_when_only_security_available(sample_snapshot_spec):
policy = PopulationMutationPolicy()
security = [
MutationOp(
mutation_id="seed_sqli",
op_type="seed_vuln",
target_selector={"host": "web"},
params={"vuln_type": "sqli"},
),
MutationOp(
mutation_id="noise1",
op_type="add_benign_noise",
target_selector={"location": "siem:noise.log"},
params={"location": "siem:noise.log"},
),
]
ops, _score, _breakdown = policy.choose_mutations(
structural_candidates=[],
security_candidates=security,
snapshot=sample_snapshot_spec,
context=BuildContext(seed=1, tier=1),
rng=random.Random(11),
)
assert len(ops) == 1
assert ops[0].op_type in {"seed_vuln", "add_benign_noise"}
def test_policy_best_effort_when_only_structural_available(sample_snapshot_spec):
policy = PopulationMutationPolicy()
structural = [
MutationOp(
mutation_id="add_trust_edge_1",
op_type="add_trust_edge",
target_selector={"source": "alice", "target": "bob"},
params={"type": "delegation"},
),
MutationOp(
mutation_id="add_dep_1",
op_type="add_dependency_edge",
target_selector={"source": "web", "target": "db"},
params={},
),
]
ops, _score, _breakdown = policy.choose_mutations(
structural_candidates=structural,
security_candidates=[],
snapshot=sample_snapshot_spec,
context=BuildContext(seed=1, tier=1),
rng=random.Random(21),
)
assert len(ops) == 1
assert ops[0].op_type in {"add_trust_edge", "add_dependency_edge"}
def test_load_policy_settings_from_yaml(tmp_path: Path):
settings_path = tmp_path / "policy.yaml"
settings_path.write_text(
"\n".join(
[
"profile_name: tuned_policy",
"parent:",
" frontier_weight: 0.5",
"mutation:",
" structural_gain_weight: 0.6",
]
),
encoding="utf-8",
)
settings = load_mutation_policy_settings(settings_path)
assert settings.profile_name == "tuned_policy"
assert settings.parent.frontier_weight == 0.5
assert settings.mutation.structural_gain_weight == 0.6
assert settings.structural_gains.add_service == 1.0
def test_parent_scores_expose_weighted_contributions(sample_snapshot_spec):
policy = PopulationMutationPolicy()
snapshot = sample_snapshot_spec.model_copy(deep=True)
snapshot.lineage.root_snapshot_id = "root_a"
entry = SimpleNamespace(snapshot_id="snap_a", snapshot=snapshot)
score = policy.score_parents(
[entry],
context=BuildContext(seed=1, tier=1, weak_areas=["sqli"]),
snapshot_stats={
"snap_a": {
"plays": 2,
"plays_recent": 1,
"red_solve_rate": 0.5,
"blue_detect_rate": 0.25,
}
},
)[0]
assert score.weights["frontier"] == pytest.approx(
policy.settings.parent.frontier_weight
)
assert score.contributions["frontier"] == pytest.approx(
score.signals["frontier"] * score.weights["frontier"],
rel=1e-3,
)
assert score.total == pytest.approx(sum(score.contributions.values()), rel=1e-3)
def test_custom_settings_change_candidate_ranking(sample_snapshot_spec):
settings = MutationPolicySettings(
profile_name="structural_gain_only",
mutation={
"curriculum_weight": 0.0,
"novelty_weight": 0.0,
"structural_gain_weight": 1.0,
"lineage_weight": 0.0,
},
structural_gains={
"add_service": 0.2,
"add_dependency_edge": 0.2,
"add_trust_edge": 0.2,
"add_user": 0.2,
"seed_vuln": 0.1,
"add_benign_noise": 2.5,
"default_gain": 0.0,
},
)
policy = PopulationMutationPolicy(settings=settings)
ranked = policy._rank_candidates(
[
MutationOp(
mutation_id="seed_sqli",
op_type="seed_vuln",
target_selector={"host": "web"},
params={"vuln_type": "sqli"},
),
MutationOp(
mutation_id="noise_1",
op_type="add_benign_noise",
target_selector={"location": "siem:noise.log"},
params={"location": "siem:noise.log"},
),
],
snapshot=sample_snapshot_spec,
context=BuildContext(seed=1, tier=1),
)
assert ranked[0].op.op_type == "add_benign_noise"
assert ranked[0].contributions["structural_gain"] == pytest.approx(
ranked[0].total,
rel=1e-3,
)
def test_calibration_script_compares_default_and_custom_settings(
tmp_path: Path,
sample_snapshot_spec,
):
store_dir = tmp_path / "snapshots"
asyncio.run(SnapshotStore(str(store_dir)).store(sample_snapshot_spec, "snap_demo"))
stats_path = tmp_path / "snapshot_stats.json"
stats_path.write_text(
json.dumps(
{
"snap_demo": {
"plays": 3,
"plays_recent": 1,
"red_solve_rate": 0.5,
"blue_detect_rate": 0.0,
}
}
),
encoding="utf-8",
)
context_path = tmp_path / "context.json"
context_path.write_text(
BuildContext(seed=7, tier=2, weak_areas=["sqli"]).model_dump_json(indent=2),
encoding="utf-8",
)
settings_path = tmp_path / "tuned.json"
settings_path.write_text(
MutationPolicySettings(
profile_name="tuned",
parent={"frontier_weight": 0.5},
).model_dump_json(indent=2),
encoding="utf-8",
)
result = subprocess.run(
[
sys.executable,
"scripts/calibrate_mutation_policy.py",
"--store-dir",
str(store_dir),
"--stats",
str(stats_path),
"--context",
str(context_path),
"--settings",
f"tuned={settings_path}",
],
capture_output=True,
check=False,
cwd=Path(__file__).resolve().parents[1],
env={**os.environ, "PYTHONPATH": "src"},
text=True,
)
assert result.returncode == 0, result.stderr
payload = json.loads(result.stdout)
assert payload["snapshot_count"] == 1
assert [policy["label"] for policy in payload["policies"]] == ["default", "tuned"]
assert payload["policies"][0]["top_parents"][0]["snapshot_id"] == "snap_demo"
|