Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/4/test_campaign.py +73 -0
- paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/5/test_runtime.py +237 -0
- paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/6/test_runtime_recovery.py +129 -0
- paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/7/test_support_input_isolation.py +289 -0
paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/4/test_campaign.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib.util
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys
|
| 4 |
+
import unittest
|
| 5 |
+
|
| 6 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 7 |
+
sys.path.insert(0, str(ROOT / "tools"))
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CampaignTests(unittest.TestCase):
|
| 11 |
+
def module(self):
|
| 12 |
+
path = ROOT / "tools/campaign.py"
|
| 13 |
+
self.assertTrue(path.exists(), "campaign is not implemented")
|
| 14 |
+
spec = importlib.util.spec_from_file_location("strict_campaign", path)
|
| 15 |
+
mod = importlib.util.module_from_spec(spec)
|
| 16 |
+
spec.loader.exec_module(mod)
|
| 17 |
+
return mod
|
| 18 |
+
|
| 19 |
+
def test_training_command_enforces_fixed_steps_and_exact_support(self):
|
| 20 |
+
mod = self.module()
|
| 21 |
+
support = ROOT / "protocol/splits/immicro/healthy/fold0/n5/support.json"
|
| 22 |
+
argv = mod.train_command(support)
|
| 23 |
+
self.assertEqual(argv[argv.index("--fixed-steps") + 1], "3000")
|
| 24 |
+
self.assertEqual(argv[argv.index("--support-manifest") + 1], str(support))
|
| 25 |
+
self.assertNotIn("--train-donors-file", argv)
|
| 26 |
+
self.assertNotIn("--train-n", argv)
|
| 27 |
+
self.assertEqual(argv[argv.index("--lora-rank") + 1], "16")
|
| 28 |
+
|
| 29 |
+
def test_no_figure6_units_can_enter_campaign(self):
|
| 30 |
+
mod = self.module()
|
| 31 |
+
units = mod.discover_units()
|
| 32 |
+
self.assertEqual(len(units), 40)
|
| 33 |
+
self.assertTrue(all("bulkonly" not in str(p) for p in units))
|
| 34 |
+
self.assertEqual({mod.read_support(p)["cohort"] for p in units}, set(mod.COHORTS))
|
| 35 |
+
|
| 36 |
+
def test_only_whole_campaign_can_finalize(self):
|
| 37 |
+
mod = self.module()
|
| 38 |
+
units = mod.discover_units()
|
| 39 |
+
self.assertTrue(mod.is_full_campaign("all", units))
|
| 40 |
+
self.assertFalse(mod.is_full_campaign("all", units[:1]))
|
| 41 |
+
self.assertFalse(mod.is_full_campaign("score", units))
|
| 42 |
+
self.assertFalse(mod.is_full_campaign("compute", units))
|
| 43 |
+
|
| 44 |
+
def test_disjoint_host_selection_preserves_canonical_order(self):
|
| 45 |
+
mod = self.module()
|
| 46 |
+
units = mod.discover_units()
|
| 47 |
+
names = [mod.name(p) for p in units if "fold2" in str(p)]
|
| 48 |
+
selected = mod.select_units(units, names=list(reversed(names)))
|
| 49 |
+
self.assertEqual([mod.name(p) for p in selected], names)
|
| 50 |
+
self.assertFalse(mod.is_full_campaign("all", selected))
|
| 51 |
+
|
| 52 |
+
def test_invalid_partition_names_fail_before_execution(self):
|
| 53 |
+
mod = self.module()
|
| 54 |
+
units = mod.discover_units()
|
| 55 |
+
known = mod.name(units[0])
|
| 56 |
+
for names in ([], [known, known], ["unknown-unit"]):
|
| 57 |
+
with self.assertRaises(ValueError):
|
| 58 |
+
mod.select_units(units, names=names)
|
| 59 |
+
with self.assertRaises(ValueError):
|
| 60 |
+
mod.select_units(units, names=[known], only=known)
|
| 61 |
+
|
| 62 |
+
def test_scssemi_commands_do_not_reuse_larger_reference(self):
|
| 63 |
+
mod = self.module()
|
| 64 |
+
path = ROOT / "protocol/splits/immicro/healthy/fold0/n5/support.json"
|
| 65 |
+
argv = mod.scsemi_command(path, "prepare")
|
| 66 |
+
self.assertIn("--support-manifest", argv)
|
| 67 |
+
self.assertIn("--lean-hvset", argv)
|
| 68 |
+
self.assertNotIn("--reuse-from", argv)
|
| 69 |
+
self.assertIn("run_scsemi_strict.py", " ".join(argv))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
unittest.main()
|
paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/5/test_runtime.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Safety and resume invariants for the scientific campaign runner."""
|
| 2 |
+
import importlib.util
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import socket
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
from unittest.mock import patch
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import tempfile
|
| 11 |
+
import unittest
|
| 12 |
+
|
| 13 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class RuntimeTests(unittest.TestCase):
|
| 17 |
+
def load(self):
|
| 18 |
+
self.assertTrue((ROOT / "tools/runtime.py").is_file(), "campaign runtime is not implemented")
|
| 19 |
+
spec = importlib.util.spec_from_file_location("campaign_runtime", ROOT / "tools/runtime.py")
|
| 20 |
+
self.assertIsNotNone(spec, "runtime implementation missing")
|
| 21 |
+
mod = importlib.util.module_from_spec(spec)
|
| 22 |
+
spec.loader.exec_module(mod)
|
| 23 |
+
return mod
|
| 24 |
+
|
| 25 |
+
def test_changed_scientific_input_cannot_reuse_completed_operation(self):
|
| 26 |
+
mod = self.load()
|
| 27 |
+
with tempfile.TemporaryDirectory() as td:
|
| 28 |
+
root = Path(td)
|
| 29 |
+
inp, output = root / "support.json", root / "output.csv"
|
| 30 |
+
inp.write_text('{"train_sample_ids":["a"]}')
|
| 31 |
+
output.write_text("value\n1\n")
|
| 32 |
+
runtime = mod.Runtime(root)
|
| 33 |
+
signature = runtime.signature(["tool", "--support", str(inp)], [inp])
|
| 34 |
+
runtime.record_completed("score", signature, [output], 0.1)
|
| 35 |
+
inp.write_text('{"train_sample_ids":["b"]}')
|
| 36 |
+
changed = runtime.signature(["tool", "--support", str(inp)], [inp])
|
| 37 |
+
with self.assertRaises(mod.ReceiptError):
|
| 38 |
+
runtime.can_skip("score", changed, [output])
|
| 39 |
+
|
| 40 |
+
def test_modified_output_is_not_silently_accepted(self):
|
| 41 |
+
mod = self.load()
|
| 42 |
+
with tempfile.TemporaryDirectory() as td:
|
| 43 |
+
root = Path(td)
|
| 44 |
+
output = root / "output.csv"
|
| 45 |
+
output.write_text("value\n1\n")
|
| 46 |
+
runtime = mod.Runtime(root)
|
| 47 |
+
sig = runtime.signature(["tool"], [])
|
| 48 |
+
runtime.record_completed("score", sig, [output], 0.1)
|
| 49 |
+
self.assertTrue(runtime.can_skip("score", sig, [output]))
|
| 50 |
+
output.write_text("value\n999\n")
|
| 51 |
+
with self.assertRaises(mod.ReceiptError):
|
| 52 |
+
runtime.can_skip("score", sig, [output])
|
| 53 |
+
|
| 54 |
+
def test_unreceipted_existing_output_is_preserved_and_rejected(self):
|
| 55 |
+
mod = self.load()
|
| 56 |
+
with tempfile.TemporaryDirectory() as td:
|
| 57 |
+
root = Path(td)
|
| 58 |
+
output = root / "output.npz"
|
| 59 |
+
output.write_bytes(b"partial output must survive")
|
| 60 |
+
runtime = mod.Runtime(root)
|
| 61 |
+
with self.assertRaises(mod.ReceiptError):
|
| 62 |
+
runtime.can_skip("sample", runtime.signature(["tool"], []), [output])
|
| 63 |
+
self.assertEqual(output.read_bytes(), b"partial output must survive")
|
| 64 |
+
|
| 65 |
+
def test_same_size_and_timestamp_do_not_hide_replaced_scientific_output(self):
|
| 66 |
+
mod = self.load()
|
| 67 |
+
with tempfile.TemporaryDirectory() as td:
|
| 68 |
+
root = Path(td)
|
| 69 |
+
output = root / "output.csv"
|
| 70 |
+
output.write_bytes(b"value\n1\n")
|
| 71 |
+
runtime = mod.Runtime(root)
|
| 72 |
+
signature = runtime.signature(["score"], [])
|
| 73 |
+
runtime.record_completed("score", signature, [output], .1)
|
| 74 |
+
before = output.stat()
|
| 75 |
+
output.write_bytes(b"value\n9\n")
|
| 76 |
+
os.utime(output, ns=(before.st_atime_ns, before.st_mtime_ns))
|
| 77 |
+
with self.assertRaises(mod.ReceiptError):
|
| 78 |
+
runtime.can_skip("score", signature, [output])
|
| 79 |
+
|
| 80 |
+
def test_failed_action_requires_review_before_retry(self):
|
| 81 |
+
mod = self.load()
|
| 82 |
+
with tempfile.TemporaryDirectory() as td:
|
| 83 |
+
root = Path(td)
|
| 84 |
+
runtime = mod.Runtime(root)
|
| 85 |
+
runtime.write_receipt("sample", {"state": "failed", "exit_code": 1})
|
| 86 |
+
with self.assertRaises(mod.ReceiptError):
|
| 87 |
+
runtime.can_skip("sample", "new", [])
|
| 88 |
+
|
| 89 |
+
def test_preview_replacement_requires_verified_preserved_copy(self):
|
| 90 |
+
mod = self.load()
|
| 91 |
+
with tempfile.TemporaryDirectory() as td:
|
| 92 |
+
root = Path(td)
|
| 93 |
+
current = root / "reports/readiness.json"
|
| 94 |
+
current.parent.mkdir()
|
| 95 |
+
current.write_text('{"status":"pending"}')
|
| 96 |
+
backup = root / "preview.json"
|
| 97 |
+
backup.write_bytes(current.read_bytes())
|
| 98 |
+
runtime = mod.Runtime(root)
|
| 99 |
+
proof = {str(current): {"backup": str(backup), "sha256": mod.sha256(current)}}
|
| 100 |
+
self.assertFalse(runtime.can_skip("render", "new", [current], previous_outputs=proof))
|
| 101 |
+
backup.write_text("changed")
|
| 102 |
+
with self.assertRaises(mod.ReceiptError):
|
| 103 |
+
runtime.can_skip("render", "new", [current], previous_outputs=proof)
|
| 104 |
+
|
| 105 |
+
def test_cuda_and_cpu_commands_are_contained(self):
|
| 106 |
+
mod = self.load()
|
| 107 |
+
with tempfile.TemporaryDirectory() as td:
|
| 108 |
+
runtime = mod.Runtime(Path(td))
|
| 109 |
+
gpu = runtime.wrapped_command("train", ["python", "train.py"], "gpu", 16, 4)
|
| 110 |
+
cpu = runtime.wrapped_command("score", ["python", "score.py"], "cpu", 16, 4)
|
| 111 |
+
self.assertEqual(Path(gpu[0]).name, "ml-run")
|
| 112 |
+
self.assertIn("CUDA_VISIBLE_DEVICES=0", gpu)
|
| 113 |
+
self.assertIn("MemorySwapMax=0", cpu)
|
| 114 |
+
self.assertIn("OOMPolicy=kill", cpu)
|
| 115 |
+
self.assertIn("CUDA_VISIBLE_DEVICES=", cpu)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def execution_map(self, root):
|
| 119 |
+
launcher, guard = root / "ml-run", root / "ml-memory-guard"
|
| 120 |
+
for executable in (launcher, guard):
|
| 121 |
+
executable.write_text("#!/bin/sh\nexit 0\n")
|
| 122 |
+
executable.chmod(0o700)
|
| 123 |
+
config = {"host": "server_2", "executables": {"/canonical/python": sys.executable},
|
| 124 |
+
"ml_run": str(launcher), "guard_check": str(guard), "path": "/usr/bin:/bin"}
|
| 125 |
+
config_path = root / "execution.json"
|
| 126 |
+
config_path.write_text(json.dumps(config))
|
| 127 |
+
return config_path, config
|
| 128 |
+
|
| 129 |
+
def test_native_mapping_changes_only_executed_program_not_scientific_signature(self):
|
| 130 |
+
mod = self.load()
|
| 131 |
+
with tempfile.TemporaryDirectory() as td:
|
| 132 |
+
root = Path(td)
|
| 133 |
+
config_path, config = self.execution_map(root)
|
| 134 |
+
argv = ["/canonical/python", "tool.py", "--source", "/canonical/python"]
|
| 135 |
+
with patch.dict(os.environ, {"PBISC_STRICT_EXECUTION_MAP": ""}):
|
| 136 |
+
original = mod.Runtime(root).signature(argv, [])
|
| 137 |
+
with patch.dict(os.environ, {"PBISC_STRICT_EXECUTION_MAP": str(config_path)}):
|
| 138 |
+
runtime = mod.Runtime(root)
|
| 139 |
+
command = runtime.wrapped_command("train", argv, "gpu", 16, 1)
|
| 140 |
+
self.assertEqual(runtime.signature(argv, []), original)
|
| 141 |
+
self.assertEqual(command[0], config["ml_run"])
|
| 142 |
+
self.assertEqual(command[-4:], [sys.executable, *argv[1:]])
|
| 143 |
+
self.assertIn("CUDA_VISIBLE_DEVICES=0", command)
|
| 144 |
+
self.assertIn("PATH=/usr/bin:/bin", command)
|
| 145 |
+
self.assertEqual(argv[0], "/canonical/python")
|
| 146 |
+
cpu = runtime.wrapped_command("score", argv, "cpu", 16, 1)
|
| 147 |
+
self.assertIn("MemorySwapMax=0", cpu)
|
| 148 |
+
self.assertIn("OOMPolicy=kill", cpu)
|
| 149 |
+
self.assertIn("CUDA_VISIBLE_DEVICES=", cpu)
|
| 150 |
+
self.assertEqual(cpu[-4:], [sys.executable, *argv[1:]])
|
| 151 |
+
|
| 152 |
+
def test_invalid_execution_paths_fail_before_any_command(self):
|
| 153 |
+
mod = self.load()
|
| 154 |
+
with tempfile.TemporaryDirectory() as td:
|
| 155 |
+
root = Path(td)
|
| 156 |
+
config_path, config = self.execution_map(root)
|
| 157 |
+
invalid_configs = [
|
| 158 |
+
{**config, "executables": {"relative/python": sys.executable}},
|
| 159 |
+
{**config, "executables": {"/canonical/python": "python -c code"}},
|
| 160 |
+
{**config, "executables": {"/canonical/python": "/missing/native/python"}},
|
| 161 |
+
{**config, "ml_run": "ml-run"},
|
| 162 |
+
{**config, "guard_check": "/bin/true --check"},
|
| 163 |
+
{**config, "path": "/usr/bin:relative"},
|
| 164 |
+
{**config, "host": ""},
|
| 165 |
+
]
|
| 166 |
+
with patch.dict(os.environ, {"PBISC_STRICT_EXECUTION_MAP": str(config_path)}):
|
| 167 |
+
for invalid in invalid_configs:
|
| 168 |
+
with self.subTest(config=invalid):
|
| 169 |
+
config_path.write_text(json.dumps(invalid))
|
| 170 |
+
with self.assertRaises(ValueError):
|
| 171 |
+
mod.Runtime(root)
|
| 172 |
+
|
| 173 |
+
def test_mapping_provenance_persists_in_running_and_completed_receipts(self):
|
| 174 |
+
mod = self.load()
|
| 175 |
+
with tempfile.TemporaryDirectory() as td:
|
| 176 |
+
root = Path(td)
|
| 177 |
+
config_path, config = self.execution_map(root)
|
| 178 |
+
output = root / "result.txt"
|
| 179 |
+
with patch.dict(os.environ, {"PBISC_STRICT_EXECUTION_MAP": str(config_path)}):
|
| 180 |
+
runtime = mod.Runtime(root)
|
| 181 |
+
seen = []
|
| 182 |
+
def run(command, **kwargs):
|
| 183 |
+
seen.append(json.loads(runtime.receipt_path("score").read_text()))
|
| 184 |
+
output.write_text("completed CPU fixture\n")
|
| 185 |
+
return subprocess.CompletedProcess(command, 0)
|
| 186 |
+
with patch.object(runtime, "preflight"), patch.object(mod.subprocess, "run", side_effect=run):
|
| 187 |
+
self.assertTrue(runtime.execute("score", ["/canonical/python", "tool.py"], outputs=[output]))
|
| 188 |
+
completed = json.loads(runtime.receipt_path("score").read_text())
|
| 189 |
+
for receipt in [seen[0], completed]:
|
| 190 |
+
execution = receipt["execution"]
|
| 191 |
+
self.assertEqual(execution["host"], socket.gethostname())
|
| 192 |
+
self.assertEqual(execution["map_host"], "server_2")
|
| 193 |
+
self.assertEqual(execution["map_sha256"], mod.sha256(config_path))
|
| 194 |
+
self.assertEqual(execution["argv"], [sys.executable, "tool.py"])
|
| 195 |
+
self.assertEqual(execution["command"][-2:], [sys.executable, "tool.py"])
|
| 196 |
+
self.assertEqual(receipt["argv"], ["/canonical/python", "tool.py"])
|
| 197 |
+
self.assertEqual(seen[0]["state"], "running")
|
| 198 |
+
self.assertEqual(completed["state"], "completed")
|
| 199 |
+
|
| 200 |
+
def test_mapped_guard_preflight_retains_all_host_safety_checks(self):
|
| 201 |
+
mod = self.load()
|
| 202 |
+
with tempfile.TemporaryDirectory() as td:
|
| 203 |
+
root = Path(td)
|
| 204 |
+
config_path, config = self.execution_map(root)
|
| 205 |
+
with patch.dict(os.environ, {"PBISC_STRICT_EXECUTION_MAP": str(config_path)}):
|
| 206 |
+
runtime = mod.Runtime(root)
|
| 207 |
+
observed = []
|
| 208 |
+
def run(command, **kwargs):
|
| 209 |
+
observed.append(command)
|
| 210 |
+
return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
|
| 211 |
+
with patch.object(mod.subprocess, "run", side_effect=run), \
|
| 212 |
+
patch.object(mod.shutil, "disk_usage", return_value=type("Disk", (), {"free": 128 * 2**30})()), \
|
| 213 |
+
patch.object(Path, "read_text", return_value="MemAvailable: 100663296 kB\n"):
|
| 214 |
+
runtime.preflight("gpu", 16)
|
| 215 |
+
self.assertIn([config["guard_check"], "--check"], observed)
|
| 216 |
+
self.assertIn(["systemctl", "--user", "is-active", "ml-memory-guard.service"], observed)
|
| 217 |
+
self.assertIn(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader"], observed)
|
| 218 |
+
self.assertIn(["flock", "--nonblock", "/run/user/1000/ml-gpu0.lock", "true"], observed)
|
| 219 |
+
|
| 220 |
+
def test_new_receipts_include_actual_host_without_requiring_it_in_old_receipts(self):
|
| 221 |
+
mod = self.load()
|
| 222 |
+
with tempfile.TemporaryDirectory() as td:
|
| 223 |
+
root = Path(td)
|
| 224 |
+
runtime = mod.Runtime(root)
|
| 225 |
+
output = root / "out"
|
| 226 |
+
output.write_text("valid")
|
| 227 |
+
runtime.record_completed("score", "unchanged", [output], .1)
|
| 228 |
+
record = json.loads(runtime.receipt_path("score").read_text())
|
| 229 |
+
self.assertEqual(record["execution"]["host"], socket.gethostname())
|
| 230 |
+
self.assertIsNone(record["execution"]["map_sha256"])
|
| 231 |
+
del record["execution"]
|
| 232 |
+
runtime.write_receipt("score", record)
|
| 233 |
+
self.assertTrue(runtime.can_skip("score", "unchanged", [output]))
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
if __name__ == "__main__":
|
| 237 |
+
unittest.main()
|
paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/6/test_runtime_recovery.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Source reuse requires exact historical provenance and intact replay evidence."""
|
| 2 |
+
import importlib.util
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import tempfile
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_runtime():
|
| 12 |
+
spec = importlib.util.spec_from_file_location('runtime_recovery', ROOT / 'tools/runtime.py')
|
| 13 |
+
mod = importlib.util.module_from_spec(spec)
|
| 14 |
+
spec.loader.exec_module(mod)
|
| 15 |
+
return mod
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RecoveryTests(unittest.TestCase):
|
| 19 |
+
def setUp(self):
|
| 20 |
+
self.tmp = tempfile.TemporaryDirectory()
|
| 21 |
+
self.addCleanup(self.tmp.cleanup)
|
| 22 |
+
self.root = Path(self.tmp.name)
|
| 23 |
+
self.mod = load_runtime()
|
| 24 |
+
self.runtime = self.mod.Runtime(self.root)
|
| 25 |
+
self.source = self.root / 'source.py'
|
| 26 |
+
self.source.write_text('old source')
|
| 27 |
+
self.output = self.root / 'score.csv'
|
| 28 |
+
self.output.write_text('value\n1\n')
|
| 29 |
+
self.old = self.runtime.signature(['/canonical/python', str(self.source)], [self.source])
|
| 30 |
+
self.runtime.record_completed('score', self.old, [self.output], .1)
|
| 31 |
+
self.original = self.runtime.receipt_path('score').read_bytes()
|
| 32 |
+
self.saved = self.root / 'recoveries/original_score.json'
|
| 33 |
+
self.saved.parent.mkdir()
|
| 34 |
+
self.saved.write_bytes(self.original)
|
| 35 |
+
self.source.write_text('isolated source')
|
| 36 |
+
self.new = self.runtime.signature(['/canonical/python', str(self.source)], [self.source])
|
| 37 |
+
self.evidence = self.root / 'recoveries/replay.json'
|
| 38 |
+
self.evidence.write_text('{"source_reproduced":true,"replay":"equal"}')
|
| 39 |
+
self.manifest = self.root / 'recoveries/SOURCE_REUSE.json'
|
| 40 |
+
self.transition = {
|
| 41 |
+
'operation': 'score', 'old_signature': self.old, 'new_signature': self.new,
|
| 42 |
+
'original_receipt': {'path': str(self.saved), 'sha256': self.mod.sha256(self.saved)},
|
| 43 |
+
'evidence': [{'name': 'source-reproduction-and-replay', 'path': str(self.evidence),
|
| 44 |
+
'sha256': self.mod.sha256(self.evidence)}],
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
def attest(self):
|
| 48 |
+
self.manifest.write_text(json.dumps({'schema': 'pbisc.strictpairs.source-reuse.v1',
|
| 49 |
+
'transitions': [self.transition]}))
|
| 50 |
+
|
| 51 |
+
def test_exact_attestation_allows_reuse_without_rewriting_receipts(self):
|
| 52 |
+
self.attest()
|
| 53 |
+
self.assertTrue(self.runtime.can_skip('score', self.new, [self.output]))
|
| 54 |
+
self.assertEqual(self.runtime.receipt_path('score').read_bytes(), self.original)
|
| 55 |
+
self.assertEqual(self.saved.read_bytes(), self.original)
|
| 56 |
+
|
| 57 |
+
def test_same_signature_uses_normal_path_without_a_recovery_manifest(self):
|
| 58 |
+
self.manifest.write_text('malformed unrelated recovery manifest')
|
| 59 |
+
self.assertTrue(self.runtime.can_skip('score', self.old, [self.output]))
|
| 60 |
+
|
| 61 |
+
def test_unapproved_changed_signature_is_rejected(self):
|
| 62 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 63 |
+
self.runtime.can_skip('score', self.new, [self.output])
|
| 64 |
+
|
| 65 |
+
def test_attestation_cannot_authorize_future_input_changes(self):
|
| 66 |
+
self.attest()
|
| 67 |
+
self.source.write_text('different scientific data')
|
| 68 |
+
changed = self.runtime.signature(['/canonical/python', str(self.source)], [self.source])
|
| 69 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 70 |
+
self.runtime.can_skip('score', changed, [self.output])
|
| 71 |
+
|
| 72 |
+
def test_wrong_operation_or_signature_cannot_match(self):
|
| 73 |
+
for field, value in [('operation', 'train'), ('old_signature', 'a' * 64),
|
| 74 |
+
('new_signature', 'b' * 64)]:
|
| 75 |
+
with self.subTest(field=field):
|
| 76 |
+
original = self.transition[field]
|
| 77 |
+
self.transition[field] = value
|
| 78 |
+
self.attest()
|
| 79 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 80 |
+
self.runtime.can_skip('score', self.new, [self.output])
|
| 81 |
+
self.transition[field] = original
|
| 82 |
+
|
| 83 |
+
def test_missing_or_changed_named_evidence_is_rejected(self):
|
| 84 |
+
self.attest()
|
| 85 |
+
self.evidence.write_text('changed replay')
|
| 86 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 87 |
+
self.runtime.can_skip('score', self.new, [self.output])
|
| 88 |
+
self.evidence.unlink()
|
| 89 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 90 |
+
self.runtime.can_skip('score', self.new, [self.output])
|
| 91 |
+
|
| 92 |
+
def test_no_evidence_is_not_an_approval(self):
|
| 93 |
+
self.transition['evidence'] = []
|
| 94 |
+
self.attest()
|
| 95 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 96 |
+
self.runtime.can_skip('score', self.new, [self.output])
|
| 97 |
+
|
| 98 |
+
def test_changed_original_receipt_is_rejected(self):
|
| 99 |
+
self.attest()
|
| 100 |
+
self.saved.write_text('{}')
|
| 101 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 102 |
+
self.runtime.can_skip('score', self.new, [self.output])
|
| 103 |
+
|
| 104 |
+
def test_live_receipt_must_match_preserved_original_bytes(self):
|
| 105 |
+
self.attest()
|
| 106 |
+
record = json.loads(self.original)
|
| 107 |
+
record['seconds'] = 99
|
| 108 |
+
self.runtime.write_receipt('score', record)
|
| 109 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 110 |
+
self.runtime.can_skip('score', self.new, [self.output])
|
| 111 |
+
|
| 112 |
+
def test_attestation_never_waives_output_contract_or_hash_checks(self):
|
| 113 |
+
self.attest()
|
| 114 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 115 |
+
self.runtime.can_skip('score', self.new, [])
|
| 116 |
+
self.output.write_text('value\n999\n')
|
| 117 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 118 |
+
self.runtime.can_skip('score', self.new, [self.output])
|
| 119 |
+
|
| 120 |
+
def test_invalid_manifest_is_fail_closed(self):
|
| 121 |
+
for content in ['{', '[]', '{"schema":"wrong","transitions":[]}']:
|
| 122 |
+
with self.subTest(content=content):
|
| 123 |
+
self.manifest.write_text(content)
|
| 124 |
+
with self.assertRaises(self.mod.ReceiptError):
|
| 125 |
+
self.runtime.can_skip('score', self.new, [self.output])
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
if __name__ == '__main__':
|
| 129 |
+
unittest.main()
|
paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/7/test_support_input_isolation.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small CPU fixtures: excluded expression is poison, selected values are exact."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sys
|
| 8 |
+
from types import SimpleNamespace
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pandas as pd
|
| 12 |
+
import pytest
|
| 13 |
+
import scipy.sparse as sp
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 16 |
+
OLD = ROOT.parent / "paired_finetune_intradataset_20260927"
|
| 17 |
+
sys.path.insert(0, str(ROOT / "tools"))
|
| 18 |
+
import support_input_isolation as isolation
|
| 19 |
+
import support_manifest as manifests
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def module_from_path(name: str, path: Path):
|
| 23 |
+
spec = importlib.util.spec_from_file_location(name, path)
|
| 24 |
+
module = importlib.util.module_from_spec(spec)
|
| 25 |
+
spec.loader.exec_module(module)
|
| 26 |
+
return module
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@pytest.fixture
|
| 30 |
+
def cohort(tmp_path, monkeypatch):
|
| 31 |
+
m8 = tmp_path / "model8"
|
| 32 |
+
plan = m8 / "plans" / ROOT.name
|
| 33 |
+
old = m8 / "plans" / OLD.name
|
| 34 |
+
dataset = old / "data/immicro"
|
| 35 |
+
dataset.mkdir(parents=True)
|
| 36 |
+
folds = pd.DataFrame({"sample_id": ["s0", "s1", "s2", "s3"],
|
| 37 |
+
"donor_id": ["d0", "d1", "d2", "d3"],
|
| 38 |
+
"group": ["healthy"] * 4, "fold": [0, 1, 0, 2],
|
| 39 |
+
"inner_val_f0": [False] * 4})
|
| 40 |
+
folds.to_csv(dataset / "folds.csv", index=False)
|
| 41 |
+
samples = folds.assign(n_cells=[2, 3, 1, 2])
|
| 42 |
+
samples.to_csv(dataset / "samples.csv", index=False)
|
| 43 |
+
panel = np.asarray([f"g{i}" for i in range(1001)])
|
| 44 |
+
genes = np.asarray([f"g{i}" for i in range(20097)])
|
| 45 |
+
row_sample = np.asarray([0, 0, 1, 1, 1, 2, 3, 3], dtype=np.int64)
|
| 46 |
+
dense = np.zeros((len(row_sample), len(panel)), dtype=np.float32)
|
| 47 |
+
dense[:, 0] = np.arange(1, len(row_sample) + 1)
|
| 48 |
+
dense[:, 3] = 2 * dense[:, 0]
|
| 49 |
+
csr = sp.csr_matrix(dense)
|
| 50 |
+
arrays = {"data": csr.data.copy(), "indices": csr.indices.copy(), "indptr": csr.indptr,
|
| 51 |
+
"row_sample": row_sample, "shape": np.asarray(csr.shape),
|
| 52 |
+
"panel_gene_ids": panel, "panel_measured": np.ones((4, len(panel)), bool)}
|
| 53 |
+
clean = dataset / "clean.npz"
|
| 54 |
+
np.savez_compressed(clean, **arrays)
|
| 55 |
+
for cell in np.flatnonzero(~np.isin(row_sample, [1, 3])):
|
| 56 |
+
section = slice(csr.indptr[cell], csr.indptr[cell + 1])
|
| 57 |
+
arrays["data"][section] = np.nan
|
| 58 |
+
arrays["indices"][section] = -999
|
| 59 |
+
source = dataset / "cells_panel6k.npz"
|
| 60 |
+
np.savez_compressed(source, **arrays)
|
| 61 |
+
bulk = np.arange(4 * len(genes), dtype=np.float32).reshape(4, -1) + 1
|
| 62 |
+
bulk_valid = np.ones(bulk.shape, dtype=bool)
|
| 63 |
+
bulk_valid[0, -1] = False
|
| 64 |
+
bulk[0, -1] = np.nan
|
| 65 |
+
np.savez_compressed(dataset / "features.npz", sample_ids=folds.sample_id.to_numpy(str),
|
| 66 |
+
donor_ids=folds.donor_id.to_numpy(str), groups=folds.group.to_numpy(str),
|
| 67 |
+
qc_cell_counts=samples.n_cells.to_numpy(), gene_ids=genes,
|
| 68 |
+
bulk_valid=bulk_valid, sc_valid=np.ones_like(bulk_valid), bulk_raw=bulk,
|
| 69 |
+
identity_pass=np.ones(4, bool),
|
| 70 |
+
pseudo_raw_sum=np.asarray(["must never load"], dtype=object))
|
| 71 |
+
support = manifests.build_healthy(folds, 0, 2, seed=3)
|
| 72 |
+
support_path = plan / "protocol/splits/immicro/healthy/fold0/n2/support.json"
|
| 73 |
+
support_path.parent.mkdir(parents=True)
|
| 74 |
+
manifests.write_manifest(support_path, support)
|
| 75 |
+
condition = plan / "data/immicro/healthy/fold0/n2/test_raw.npz"
|
| 76 |
+
condition.parent.mkdir(parents=True)
|
| 77 |
+
np.savez_compressed(condition, sample_ids=np.asarray(support["test_sample_ids"]))
|
| 78 |
+
symbols = m8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv"
|
| 79 |
+
symbols.parent.mkdir(parents=True)
|
| 80 |
+
pd.DataFrame({"gene_id": panel, "gene_symbol": panel}).to_csv(symbols, index=False)
|
| 81 |
+
monkeypatch.setattr(isolation, "PLAN", plan)
|
| 82 |
+
monkeypatch.setattr(isolation, "OLD", old)
|
| 83 |
+
monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "")
|
| 84 |
+
return SimpleNamespace(plan=plan, old=old, dataset=dataset, support=support,
|
| 85 |
+
support_path=support_path, source=source, clean=clean,
|
| 86 |
+
dense=dense, arrays=arrays, folds=folds, panel=panel,
|
| 87 |
+
row_sample=row_sample, bulk=bulk)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def forbid_full_expression(monkeypatch, source: Path):
|
| 91 |
+
"""Catch np.load expression access, while permitting streamed source ranges."""
|
| 92 |
+
original = np.lib.npyio.NpzFile.__getitem__
|
| 93 |
+
accessed = []
|
| 94 |
+
|
| 95 |
+
def guarded(archive, key):
|
| 96 |
+
name = Path(archive.zip.filename)
|
| 97 |
+
accessed.append((name, key))
|
| 98 |
+
if name == source and key in {"data", "indices"}:
|
| 99 |
+
pytest.fail(f"full source expression member accessed: {key}")
|
| 100 |
+
if key in {"pseudo_raw_sum", "pseudo", "sc_raw_sum"}:
|
| 101 |
+
pytest.fail(f"single-cell aggregate accessed: {key}")
|
| 102 |
+
return original(archive, key)
|
| 103 |
+
|
| 104 |
+
monkeypatch.setattr(np.lib.npyio.NpzFile, "__getitem__", guarded)
|
| 105 |
+
return accessed
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_isolation_discards_poison_and_preserves_original_cell_rows(cohort, monkeypatch):
|
| 109 |
+
forbid_full_expression(monkeypatch, cohort.source)
|
| 110 |
+
got, audit = isolation.isolated_arrays(cohort.source, np.asarray([3, 1]))
|
| 111 |
+
clean, _ = isolation.isolated_arrays(cohort.clean, np.asarray([1, 3]))
|
| 112 |
+
for key in got:
|
| 113 |
+
np.testing.assert_array_equal(got[key], clean[key])
|
| 114 |
+
selected = np.isin(cohort.row_sample, [1, 3])
|
| 115 |
+
expected = cohort.dense.copy()
|
| 116 |
+
expected[~selected] = 0
|
| 117 |
+
matrix = sp.csr_matrix((got["data"], got["indices"], got["indptr"]), shape=got["shape"])
|
| 118 |
+
np.testing.assert_array_equal(matrix.toarray(), expected)
|
| 119 |
+
np.testing.assert_array_equal(got["row_sample"], cohort.row_sample)
|
| 120 |
+
assert np.all(np.diff(got["indptr"])[~selected] == 0)
|
| 121 |
+
assert audit["selected_sample_rows"] == [1, 3]
|
| 122 |
+
assert audit["selected_cells"] == 5
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@pytest.mark.parametrize("rows", [[], [-1], [0.9], ["1"], [[1]], [9]])
|
| 126 |
+
def test_rejects_invalid_support_rows_without_coercion(cohort, rows):
|
| 127 |
+
with pytest.raises(ValueError):
|
| 128 |
+
isolation.isolated_arrays(cohort.source, np.asarray(rows))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@pytest.mark.parametrize("key,value", [
|
| 132 |
+
("row_sample", np.asarray([0., 0., 1., 1., 1., 2., 3., 3.])),
|
| 133 |
+
("shape", np.asarray([8, 1001, 1])),
|
| 134 |
+
("indices", np.full(16, -1, dtype=np.int64)),
|
| 135 |
+
("data", np.asarray(["bad"] * 16)),
|
| 136 |
+
("data", np.ones(15)),
|
| 137 |
+
])
|
| 138 |
+
def test_rejects_malformed_csr_members(cohort, key, value, tmp_path):
|
| 139 |
+
arrays = dict(cohort.arrays)
|
| 140 |
+
arrays[key] = value
|
| 141 |
+
path = tmp_path / "malformed.npz"
|
| 142 |
+
np.savez_compressed(path, **arrays)
|
| 143 |
+
with pytest.raises(ValueError):
|
| 144 |
+
isolation.isolated_arrays(path, np.asarray([1, 3]))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_stream_ranges_boundaries_and_validation(tmp_path):
|
| 148 |
+
path = tmp_path / "ranges.npz"
|
| 149 |
+
values = np.arange(20, dtype="<i4")
|
| 150 |
+
np.savez_compressed(path, data=values)
|
| 151 |
+
np.testing.assert_array_equal(isolation.read_ranges(path, "data", [(1, 3), (10, 14), (20, 20)]),
|
| 152 |
+
np.r_[values[1:3], values[10:14]])
|
| 153 |
+
assert isolation.read_ranges(path, "data", []).size == 0
|
| 154 |
+
for ranges in [[(3, 4), (2, 3)], [(-1, 1)], [(19, 21)], [(0.5, 1)]]:
|
| 155 |
+
with pytest.raises(ValueError):
|
| 156 |
+
isolation.read_ranges(path, "data", ranges)
|
| 157 |
+
with pytest.raises(ValueError, match="length"):
|
| 158 |
+
isolation.read_ranges(path, "data", [(1, 3)], expected_length=21)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_materialize_receipt_is_immutable_and_replay_has_limited_scope(cohort, monkeypatch):
|
| 162 |
+
forbid_full_expression(monkeypatch, cohort.source)
|
| 163 |
+
path, receipt = isolation.materialize(cohort.support_path, dataset_dir=cohort.dataset)
|
| 164 |
+
before = path.stat().st_mtime_ns
|
| 165 |
+
assert isolation.materialize(cohort.support_path) == (path, receipt)
|
| 166 |
+
assert path.stat().st_mtime_ns == before
|
| 167 |
+
result = isolation.validate_replay(cohort.support_path)
|
| 168 |
+
assert result["all_selected_values_exact"] and result["training_draws_exact"]
|
| 169 |
+
assert "no training" in result["validation_scope"]
|
| 170 |
+
assert "does not change historical access claims" in result["legacy_access_limitation"]
|
| 171 |
+
assert receipt["target_sc_aggregate_keys_accessed"] == []
|
| 172 |
+
with pytest.raises(ValueError, match="dataset directory"):
|
| 173 |
+
isolation.materialize(cohort.support_path, dataset_dir=cohort.dataset.parent)
|
| 174 |
+
changed = dict(receipt, builder_sha256="stale")
|
| 175 |
+
(path.parent / "ISOLATION.json").write_text(json.dumps(changed))
|
| 176 |
+
with pytest.raises(ValueError, match="immutable"):
|
| 177 |
+
isolation.materialize(cohort.support_path)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def test_bulk_loader_does_not_open_pseudobulk_and_matches_legacy_nan_conversion(cohort, monkeypatch):
|
| 181 |
+
accessed = forbid_full_expression(monkeypatch, cohort.source)
|
| 182 |
+
d = isolation.bulk_only_load(cohort.dataset)
|
| 183 |
+
expected = np.where(np.isnan(cohort.bulk), 0, cohort.bulk).astype(np.float64)
|
| 184 |
+
np.testing.assert_array_equal(d["bulk"], expected)
|
| 185 |
+
assert d["bulk"].dtype == np.float64
|
| 186 |
+
assert "pseudo" not in d
|
| 187 |
+
assert not d["use"].any() # Same 200-cell metadata eligibility floor as legacy loader.
|
| 188 |
+
assert all(key != "pseudo_raw_sum" for _, key in accessed)
|
| 189 |
+
(cohort.dataset / "samples.csv").unlink()
|
| 190 |
+
fallback = isolation.bulk_only_load(cohort.dataset)
|
| 191 |
+
np.testing.assert_array_equal(fallback["sample_ids"], d["sample_ids"])
|
| 192 |
+
assert not (cohort.dataset / "samples.csv").exists()
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def test_actual_trainer_seeded_draws_and_selected_dense_values_are_identical(cohort):
|
| 196 |
+
pytest.importorskip("torch")
|
| 197 |
+
trainer = module_from_path("isolation_test_trainer_draws", OLD / "tools/ft_sdd.py")
|
| 198 |
+
path, _ = isolation.materialize(cohort.support_path)
|
| 199 |
+
old = trainer.Cells(cohort.clean, cohort.panel)
|
| 200 |
+
strict = trainer.Cells(path, cohort.panel)
|
| 201 |
+
rng_old, rng_strict = np.random.default_rng(20260927), np.random.default_rng(20260927)
|
| 202 |
+
for _ in range(3000):
|
| 203 |
+
rows_a, cells_a = trainer.draw_batch(old, np.asarray([1, 3]), 256, rng_old)
|
| 204 |
+
rows_b, cells_b = trainer.draw_batch(strict, np.asarray([1, 3]), 256, rng_strict)
|
| 205 |
+
np.testing.assert_array_equal(rows_a, rows_b)
|
| 206 |
+
np.testing.assert_array_equal(cells_a, cells_b)
|
| 207 |
+
np.testing.assert_array_equal(strict.dense(cells_b), cohort.dense[cells_b])
|
| 208 |
+
np.testing.assert_array_equal(old.dense(cells_a), strict.dense(cells_b))
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@pytest.mark.parametrize("strict", [False, True])
|
| 212 |
+
def test_trainer_main_routes_only_opt_in_to_isolated_cells(cohort, monkeypatch, strict):
|
| 213 |
+
pytest.importorskip("torch")
|
| 214 |
+
trainer = module_from_path(f"isolation_test_trainer_main_{strict}", OLD / "tools/ft_sdd.py")
|
| 215 |
+
checkpoint = cohort.plan / "fake-checkpoint.pt"
|
| 216 |
+
checkpoint.write_bytes(b"metadata-only test checkpoint")
|
| 217 |
+
condition = cohort.plan / "fake-condition.npz"
|
| 218 |
+
np.savez(condition, sample_ids=cohort.folds.sample_id.to_numpy(str))
|
| 219 |
+
monkeypatch.setattr(trainer.SS, "restore_standalone", lambda *args, **kw:
|
| 220 |
+
SimpleNamespace(diffusion=object(), scaler=object(), gene_ids=cohort.panel))
|
| 221 |
+
monkeypatch.setattr(trainer.SS, "load_conditions", lambda *args, **kw:
|
| 222 |
+
SimpleNamespace(sample_ids=cohort.folds.sample_id.to_numpy(str)))
|
| 223 |
+
captured = []
|
| 224 |
+
|
| 225 |
+
class ReachedCellLoader(Exception):
|
| 226 |
+
pass
|
| 227 |
+
|
| 228 |
+
cells_class = trainer.Cells
|
| 229 |
+
|
| 230 |
+
def capture(path, panel):
|
| 231 |
+
captured.append((path, cells_class(path, panel)))
|
| 232 |
+
raise ReachedCellLoader
|
| 233 |
+
|
| 234 |
+
monkeypatch.setattr(trainer, "Cells", capture)
|
| 235 |
+
argv = ["--checkpoint", str(checkpoint), "--checkpoint-sha", trainer.sha256_file(checkpoint),
|
| 236 |
+
"--dataset-dir", str(cohort.dataset), "--condition-npz", str(condition), "--fold", "0",
|
| 237 |
+
"--mode", "lora", "--lr", "0.0001", "--device", "cpu", "--min-system-gib", "0",
|
| 238 |
+
"--out-dir", str(cohort.plan / "trainer-output")]
|
| 239 |
+
if strict:
|
| 240 |
+
argv += ["--support-manifest", str(cohort.support_path), "--fixed-steps", "3000"]
|
| 241 |
+
forbid_full_expression(monkeypatch, cohort.source)
|
| 242 |
+
with pytest.raises(ReachedCellLoader):
|
| 243 |
+
trainer.main(argv)
|
| 244 |
+
assert len(captured) == 1
|
| 245 |
+
if strict:
|
| 246 |
+
assert captured[0][0].name == "cells_support_only.npz"
|
| 247 |
+
assert np.isfinite(captured[0][1].data).all()
|
| 248 |
+
else:
|
| 249 |
+
assert captured[0][0] == cohort.source
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def test_scsemi_preparation_uses_support_only_expression_and_no_pseudo(cohort, monkeypatch):
|
| 253 |
+
ad = pytest.importorskip("anndata")
|
| 254 |
+
prep = module_from_path("isolation_test_scsemi", OLD / "scsemi/tools/prepare_draw_inputs.py")
|
| 255 |
+
monkeypatch.setattr(prep, "TASK", cohort.old)
|
| 256 |
+
monkeypatch.setattr(prep.PD, "load", lambda *_: pytest.fail("strict called legacy pseudo loader"))
|
| 257 |
+
forbid_full_expression(monkeypatch, cohort.source)
|
| 258 |
+
work = cohort.plan / "scsemi-fixture"
|
| 259 |
+
assert prep.main(["--dataset", "immicro", "--support-manifest", str(cohort.support_path),
|
| 260 |
+
"--work", str(work)]) == 0
|
| 261 |
+
man = json.loads((work / "inputs/inputs_manifest.json").read_text())
|
| 262 |
+
out = ad.read_h5ad(work / "inputs/rep_sc.h5ad")
|
| 263 |
+
expected_cells = np.concatenate([np.flatnonzero(cohort.row_sample == int(s[1:]))
|
| 264 |
+
for s in cohort.support["train_sample_ids"]])
|
| 265 |
+
np.testing.assert_array_equal(out.obs.source_cell_row.to_numpy(), expected_cells)
|
| 266 |
+
np.testing.assert_array_equal(out.X.toarray(), cohort.dense[expected_cells])
|
| 267 |
+
assert out.obs.sample_ids.unique().tolist() == cohort.support["train_sample_ids"]
|
| 268 |
+
assert man["depth"]["value"] == float(np.median(cohort.dense[expected_cells].sum(1)))
|
| 269 |
+
assert man["support_expression_isolation"]["audit"]["selected_cells"] == 5
|
| 270 |
+
assert man["support_expression_isolation"]["target_sc_aggregate_keys_accessed"] == []
|
| 271 |
+
assert "cells_support_only.npz" in man["sources"]
|
| 272 |
+
assert man["targets"] == cohort.support["test_sample_ids"]
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def test_scsemi_without_manifest_keeps_legacy_loader(cohort, monkeypatch):
|
| 276 |
+
prep = module_from_path("isolation_test_scsemi_legacy", OLD / "scsemi/tools/prepare_draw_inputs.py")
|
| 277 |
+
monkeypatch.setattr(prep, "TASK", cohort.old)
|
| 278 |
+
|
| 279 |
+
class LegacyLoaderReached(Exception):
|
| 280 |
+
pass
|
| 281 |
+
|
| 282 |
+
def legacy_loader(path):
|
| 283 |
+
assert path == cohort.dataset
|
| 284 |
+
raise LegacyLoaderReached
|
| 285 |
+
|
| 286 |
+
monkeypatch.setattr(prep.PD, "load", legacy_loader)
|
| 287 |
+
monkeypatch.setattr(isolation, "bulk_only_load", lambda *_: pytest.fail("legacy used strict loader"))
|
| 288 |
+
with pytest.raises(LegacyLoaderReached):
|
| 289 |
+
prep.main(["--dataset", "immicro", "--draw", "0", "--check-only", "--work", str(cohort.plan / "legacy")])
|