#!/usr/bin/env python3 """Small, CPU-only tests for the resumable direct compact_v1 builder.""" from __future__ import annotations import json import tempfile import time import unittest from pathlib import Path from unittest import mock import torch from torch_geometric.data import Data import build_compact_v1_direct as direct from compact_graph_dataset import CompactGraphDataset def _synthetic_graph( system_id: str, pose_number: int, *, split_static: bool = False, ) -> Data: n_protein = 2 n_nodes = 4 x = torch.zeros((n_nodes, 82), dtype=torch.float32) x[:, 0] = 1.0 x[:n_protein, 11] = 1.0 x[n_protein:, 31] = 1.0 x[:n_protein, 32] = 1.0 x[n_protein:, 33] = 1.0 x[:, 61:71] = 0.25 x[:, 34:61] = float(pose_number) x[:, 71:82] = float(pose_number) / 10.0 if split_static and pose_number == 2: x[2, 0] = 0.0 x[2, 1] = 1.0 system_offset = 5.0 if system_id == "sys_b" else 0.0 protein_pos = torch.tensor( [[system_offset, 0.0, 0.0], [system_offset + 1.0, 0.0, 0.0]], dtype=torch.float32, ) ligand_pos = torch.tensor( [ [system_offset + 1.5, 0.1 * pose_number, 0.0], [system_offset + 2.0, 0.2 * pose_number, 0.0], ], dtype=torch.float32, ) native_ligand = torch.tensor( [ [system_offset + 1.5, 0.0, 0.0], [system_offset + 2.0, 0.0, 0.0], ], dtype=torch.float32, ) pos = torch.cat((protein_pos, ligand_pos), dim=0) y_grt = torch.cat((protein_pos, native_ligand), dim=0) y_true = torch.linalg.vector_norm(pos - y_grt, dim=1, keepdim=True) edge_index = torch.tensor( [[0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2]], dtype=torch.int64, ) src, dst = edge_index distance = torch.linalg.vector_norm( pos[src].to(torch.float64) - pos[dst].to(torch.float64), dim=1, ) edge_attr = torch.stack( ( (distance / 6.0).to(torch.float32), torch.exp(-distance / 3.0).to(torch.float32), (src < n_protein).to(torch.float32), (dst < n_protein).to(torch.float32), ), dim=1, ) is_protein = torch.zeros((n_nodes, 1), dtype=torch.float32) is_protein[:n_protein] = 1.0 return Data( x=x, edge_index=edge_index, edge_attr=edge_attr, pos=pos, is_protein=is_protein, y_true=y_true, y_pred=pos.clone(), y_grt=y_grt, num_nodes=n_nodes, ) class DirectCompactBuilderTest(unittest.TestCase): def test_exclusive_output_lock_rejects_concurrent_resume(self) -> None: with tempfile.TemporaryDirectory(prefix="direct_compact_lock_") as temp: output = Path(temp) / "compact" with direct._exclusive_build_lock(output): with self.assertRaisesRegex( RuntimeError, "another direct compact build" ): with direct._exclusive_build_lock(output): self.fail("the second lock must not be acquired") def test_corrupt_pose_checkpoint_is_rebuilt(self) -> None: with tempfile.TemporaryDirectory(prefix="direct_compact_corrupt_") as temp: root = Path(temp) for name in ("protein.pdb", "native.pdb", "pose_1.pdb"): (root / name).write_text("test\n", encoding="utf-8") pose = direct.PoseSpec( source_graph_index=0, system_id="sys_a", protein=(root / "protein.pdb"), ligand_native=(root / "native.pdb"), ligand_pred=(root / "pose_1.pdb"), ) system = direct.SystemSpec( ordinal=0, system_id="sys_a", protein=pose.protein, ligand_native=pose.ligand_native, poses=(pose,), ) work_dir = root / "work" work_dir.mkdir() corrupt = direct._pose_graph_path(work_dir, 0) corrupt.write_bytes(b"not a torch checkpoint") calls = [] def graph_builder(**kwargs): calls.append(kwargs["ligand_pred_pdb"]) return _synthetic_graph("sys_a", 1) config = direct.BuildConfig( data_dir=root, output_dir=root / "output", method="protenix", ) graphs = direct.build_pose_graphs( system, work_dir, config, graph_builder=graph_builder, ) self.assertEqual(len(calls), 1) self.assertEqual(len(graphs), 1) rebuilt = torch.load(corrupt, map_location="cpu", weights_only=False) self.assertTrue(torch.equal(rebuilt.x, graphs[0].x)) def test_resume_atomic_publish_and_original_system_index(self) -> None: with tempfile.TemporaryDirectory(prefix="direct_compact_test_") as temp: root = Path(temp) data_dir = root / "docking" output_dir = root / "compact" raw_poses = [] for system_id in ("sys_a", "sys_b"): system_dir = data_dir / system_id system_dir.mkdir(parents=True) protein = system_dir / "protein.pdb" native = system_dir / "ligand_native.pdb" protein.write_text("test\n", encoding="utf-8") native.write_text("test\n", encoding="utf-8") for pose_number in (1, 2): pose = system_dir / f"{system_id}_pose_{pose_number}.pdb" pose.write_text("test\n", encoding="utf-8") raw_poses.append( { "pdb_id": system_id, "protein": str(protein), "ligand_native": str(native), "ligand_pred": str(pose), } ) def graph_builder(**kwargs): pose_path = Path(kwargs["ligand_pred_pdb"]) system_id = pose_path.parent.name pose_number = int(pose_path.stem.rsplit("_", 1)[1]) return _synthetic_graph( system_id, pose_number, split_static=system_id == "sys_b", ) def first_attempt_builder(**kwargs): if Path(kwargs["ligand_pred_pdb"]).parent.name == "sys_b": raise RuntimeError("intentional interruption") return graph_builder(**kwargs) config = direct.BuildConfig( data_dir=data_dir.resolve(), output_dir=output_dir.resolve(), method="protenix", target_shard_mib=1, num_workers=1, ) with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses): with self.assertRaisesRegex(RuntimeError, "intentional interruption"): direct.run(config, graph_builder=first_attempt_builder) progress_path = ( output_dir.with_name(".compact.building") / ".build_state" / "progress.json" ) with progress_path.open("r", encoding="utf-8") as handle: progress = json.load(handle) self.assertEqual(progress["next_system_index"], 1) self.assertEqual(progress["successful_source_systems"], 1) resumed = direct.BuildConfig( **{**config.__dict__, "resume": True} ) manifest = direct.run(resumed, graph_builder=graph_builder) self.assertTrue((output_dir / "manifest.json").is_file()) self.assertFalse(output_dir.with_name(".compact.building").exists()) self.assertFalse((output_dir / ".build_state").exists()) self.assertEqual(manifest["n_graphs"], 4) self.assertEqual(manifest["n_source_systems"], 2) # sys_b is intentionally split into two exact-content storage groups. self.assertEqual(manifest["n_systems"], 3) with (output_dir / "system_index.json").open( "r", encoding="utf-8" ) as handle: system_index = json.load(handle) self.assertEqual( system_index["graph_to_system"], ["sys_a", "sys_a", "sys_b", "sys_b"], ) self.assertEqual(system_index["n_systems"], 2) dataset = CompactGraphDataset(output_dir) self.assertEqual(len(dataset), 4) expected = [ _synthetic_graph("sys_a", 1), _synthetic_graph("sys_a", 2), _synthetic_graph("sys_b", 1, split_static=True), _synthetic_graph("sys_b", 2, split_static=True), ] for actual, reference in zip(dataset, expected): for name in ( "x", "edge_index", "edge_attr", "pos", "is_protein", "y_true", "y_pred", "y_grt", ): self.assertTrue( torch.allclose( getattr(actual, name), getattr(reference, name), rtol=1e-6, atol=1e-6, ), msg=name, ) def test_parallel_system_build_matches_serial_order(self) -> None: """Out-of-order worker completion must not change source graph order.""" with tempfile.TemporaryDirectory(prefix="direct_compact_parallel_") as temp: root = Path(temp) data_dir = root / "docking" raw_poses = [] for system_id in ("sys_a", "sys_b", "sys_c"): system_dir = data_dir / system_id system_dir.mkdir(parents=True) protein = system_dir / "protein.pdb" native = system_dir / "ligand_native.pdb" protein.write_text("test\n", encoding="utf-8") native.write_text("test\n", encoding="utf-8") for pose_number in (1, 2): pose = system_dir / f"{system_id}_pose_{pose_number}.pdb" pose.write_text("test\n", encoding="utf-8") raw_poses.append( { "pdb_id": system_id, "protein": str(protein), "ligand_native": str(native), "ligand_pred": str(pose), } ) def graph_builder(**kwargs): pose_path = Path(kwargs["ligand_pred_pdb"]) system_id = pose_path.parent.name # sys_a is deliberately slower so workers complete out of order. if system_id == "sys_a": time.sleep(0.15) pose_number = int(pose_path.stem.rsplit("_", 1)[1]) return _synthetic_graph(system_id, pose_number) serial_output = root / "serial" parallel_output = root / "parallel" serial_config = direct.BuildConfig( data_dir=data_dir.resolve(), output_dir=serial_output.resolve(), method="protenix", target_shard_mib=1, num_workers=1, ) parallel_config = direct.BuildConfig( data_dir=data_dir.resolve(), output_dir=parallel_output.resolve(), method="protenix", target_shard_mib=1, num_workers=1, system_workers=2, memory_budget_gib=8.0, ) with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses): serial_manifest = direct.run(serial_config, graph_builder=graph_builder) parallel_manifest = direct.run(parallel_config, graph_builder=graph_builder) self.assertEqual(serial_manifest["n_graphs"], parallel_manifest["n_graphs"]) self.assertEqual(serial_manifest["graph_map"], parallel_manifest["graph_map"]) self.assertEqual(serial_manifest["shards"], parallel_manifest["shards"]) with (serial_output / "system_index.json").open("r", encoding="utf-8") as handle: serial_index = json.load(handle) with (parallel_output / "system_index.json").open("r", encoding="utf-8") as handle: parallel_index = json.load(handle) self.assertEqual(serial_index, parallel_index) def test_parallel_ready_checkpoint_resumes_in_source_order(self) -> None: """A later ready system survives interruption before the earlier system.""" with tempfile.TemporaryDirectory(prefix="direct_compact_parallel_resume_") as temp: root = Path(temp) data_dir = root / "docking" output_dir = root / "compact" raw_poses = [] for system_id in ("sys_a", "sys_b"): system_dir = data_dir / system_id system_dir.mkdir(parents=True) protein = system_dir / "protein.pdb" native = system_dir / "ligand_native.pdb" protein.write_text("test\n", encoding="utf-8") native.write_text("test\n", encoding="utf-8") for pose_number in (1, 2): pose = system_dir / f"{system_id}_pose_{pose_number}.pdb" pose.write_text("test\n", encoding="utf-8") raw_poses.append( { "pdb_id": system_id, "protein": str(protein), "ligand_native": str(native), "ligand_pred": str(pose), } ) def graph_builder(**kwargs): pose_path = Path(kwargs["ligand_pred_pdb"]) system_id = pose_path.parent.name pose_number = int(pose_path.stem.rsplit("_", 1)[1]) return _synthetic_graph(system_id, pose_number) def interrupted_builder(**kwargs): pose_path = Path(kwargs["ligand_pred_pdb"]) if pose_path.parent.name == "sys_a": time.sleep(0.35) raise RuntimeError("intentional parallel interruption") return graph_builder(**kwargs) config = direct.BuildConfig( data_dir=data_dir.resolve(), output_dir=output_dir.resolve(), method="protenix", target_shard_mib=1, num_workers=1, system_workers=2, memory_budget_gib=8.0, ) with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses): with self.assertRaisesRegex(RuntimeError, "parallel worker.*sys_a"): direct.run(config, graph_builder=interrupted_builder) stage_dir = output_dir.with_name(".compact.building") progress_path = stage_dir / ".build_state" / "progress.json" with progress_path.open("r", encoding="utf-8") as handle: progress = json.load(handle) self.assertEqual(progress["next_system_index"], 0) self.assertTrue( (stage_dir / ".build_state" / "ready" / "system_00000001.pt").is_file() ) resumed = direct.BuildConfig(**{**config.__dict__, "resume": True}) manifest = direct.run(resumed, graph_builder=graph_builder) self.assertEqual(manifest["n_graphs"], 4) with (output_dir / "system_index.json").open("r", encoding="utf-8") as handle: system_index = json.load(handle) self.assertEqual( system_index["graph_to_system"], ["sys_a", "sys_a", "sys_b", "sys_b"] ) if __name__ == "__main__": unittest.main()