File size: 10,725 Bytes
27b13d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
import os
import signal
import subprocess
import sys
import tempfile
import time
import unittest
from pathlib import Path
from unittest import mock

import numpy as np

from k2_evalop.analytic_companion import analytic_rows, trapezoid, _write_or_verify_npy
from k2_evalop.common import AuditError, append_jsonl_fsync, file_record, load_json, write_new_json
from k2_evalop.evaluator import pooled_metrics, write_report_markdown
from k2_evalop.hardware import run_idle_probe
from k2_evalop.operator import CampaignLock
from k2_evalop.preflight import _require_identical_receipts
from k2_evalop.sufficient_statistics import integrated_sequence_risk, load_sufficient_statistics
from k2_evalop import supervisor


class LedgerAndStatisticsTests(unittest.TestCase):
    def test_ledger_accepts_multiple_fsynced_appends(self) -> None:
        with tempfile.TemporaryDirectory() as td:
            path = Path(td) / "ledger.jsonl"
            append_jsonl_fsync(path, {"event": "one"})
            append_jsonl_fsync(path, {"event": "two"})
            self.assertEqual([json.loads(line)["event"] for line in path.read_text().splitlines()], ["one", "two"])

    def test_shared_sufficient_stat_loader_and_trapezoid(self) -> None:
        with tempfile.TemporaryDirectory() as td:
            path = Path(td) / "stats.npz"
            n, scalars = 7, 11
            primary = np.arange(n * 16, dtype="<f8").reshape(n, 16)
            early = np.arange(n * 6, dtype="<f8").reshape(n, 6)
            np.savez(path, primary_sse=primary,
                     primary_scalar_count=np.full((n, 16), scalars, dtype="<u4"),
                     early_sse=early,
                     early_scalar_count=np.full((n, 6), scalars, dtype="<u4"))
            loaded = load_sufficient_statistics(path, n_sequence=n, n_scalar=scalars)
            got = integrated_sequence_risk(loaded["primary_sse"], loaded["primary_scalar_count"], n_sequence=n, n_scalar=scalars)
            wanted = (0.5 * primary[:, 0] + primary[:, 1:-1].sum(1) + 0.5 * primary[:, -1]) / 15 / scalars
            np.testing.assert_allclose(got, wanted, rtol=1e-15, atol=0.0)
            self.assertAlmostEqual(trapezoid(np.arange(16, dtype=np.float64)), 7.5)

    def test_nonpositive_full_risk_is_nonadvance_domain_not_exception(self) -> None:
        risks = np.zeros((3, 10_240, 4), dtype=np.float64)
        metrics = pooled_metrics(risks)
        self.assertIsNone(metrics["P_ind"])
        self.assertIsNone(metrics["C_gap"])
        self.assertIn("independent_full_risk_nonpositive", metrics["automatic_non_advance_reasons"])

    def test_analytic_companion_population_identity(self) -> None:
        for rho in (0.1, 0.3):
            row = analytic_rows(rho)
            self.assertGreater(row["g_independent"], 0.0)
            self.assertEqual(row["g_triangular"], 0.0)
            self.assertAlmostEqual(row["C_gap"], 1.0, places=14)

    def test_leaf_symlinks_are_rejected_before_resolution(self) -> None:
        with tempfile.TemporaryDirectory() as td:
            root = Path(td)
            regular = root / "regular.bin"
            regular.write_bytes(b"bytes")
            link = root / "link.bin"
            link.symlink_to(regular)
            with self.assertRaisesRegex(AuditError, "leaf symlink"):
                file_record(link)
            stats = root / "stats.npz"
            np.savez(stats,
                     primary_sse=np.zeros((2, 16), dtype="<f8"),
                     primary_scalar_count=np.full((2, 16), 3, dtype="<u4"),
                     early_sse=np.zeros((2, 6), dtype="<f8"),
                     early_scalar_count=np.full((2, 6), 3, dtype="<u4"))
            stats_link = root / "stats-link.npz"
            stats_link.symlink_to(stats)
            with self.assertRaisesRegex(AuditError, "leaf symlink"):
                load_sufficient_statistics(stats_link, n_sequence=2, n_scalar=3)

    def test_public_cpu_receipt_requires_exact_bytes(self) -> None:
        with tempfile.TemporaryDirectory() as td:
            root = Path(td)
            frozen = root / "frozen.json"
            generated = root / "generated.json"
            frozen.write_bytes(b"same\n")
            generated.write_bytes(b"same\n")
            self.assertEqual(_require_identical_receipts(frozen, generated, "fixture")["sha256"], file_record(frozen)["sha256"])
            generated.write_bytes(b"different\n")
            with self.assertRaisesRegex(AuditError, "public frozen"):
                _require_identical_receipts(frozen, generated, "fixture")

    def test_nonfinite_derived_penalty_is_json_safe_nonadvance(self) -> None:
        risks = np.ones((3, 10_240, 4), dtype=np.float64)
        risks[:, :, 0] = np.nextafter(0.0, 1.0)
        metrics = pooled_metrics(risks)
        self.assertIsNone(metrics["P_ind"])
        self.assertIn("nonfinite_independent_penalty", metrics["automatic_non_advance_reasons"])

    def test_deterministic_cpu_outputs_recover_without_overwrite(self) -> None:
        with tempfile.TemporaryDirectory() as td:
            root = Path(td)
            array = np.arange(12, dtype="<f8").reshape(3, 4)
            first = _write_or_verify_npy(root / "array.npy", array)
            self.assertEqual(_write_or_verify_npy(root / "array.npy", array), first)
            with self.assertRaisesRegex(AuditError, "differs on recovery"):
                _write_or_verify_npy(root / "array.npy", array + 1.0)
            report = root / "k2_report_0000.json"
            write_new_json(report, {
                "status": "NON_ADVANCE", "pooled": {"P_ind": None, "C_gap": None},
                "bootstrap": {"c_gap_lcb95_percentile_2_5": "-Infinity"},
            })
            markdown = write_report_markdown(report)
            before = file_record(markdown)
            self.assertEqual(file_record(write_report_markdown(report)), before)


class IdleAndLockTests(unittest.TestCase):
    def test_two_sample_idle_probe_records_raw_outputs(self) -> None:
        outputs = iter([
            "GPU-test, NVIDIA H200, 0, 686\n", "",
            "GPU-test, NVIDIA H200, 0, 700\n", "",
        ])
        with tempfile.TemporaryDirectory() as td, mock.patch("k2_evalop.hardware._run", side_effect=lambda _argv: next(outputs)):
            path = Path(td) / "idle.json"
            run_idle_probe(path, sleep_fn=lambda seconds: self.assertEqual(seconds, 5.0))
            value = load_json(path)
            self.assertEqual(value["status"], "PASS")
            self.assertEqual(len(value["samples"]), 2)
            self.assertIn("raw_gpu_query_stdout", value["samples"][0])

    def test_idle_probe_rejects_hidden_busy_gpu_without_mutation(self) -> None:
        outputs = iter([
            "GPU-test, NVIDIA H200, 100, 14965\n", "",
            "GPU-test, NVIDIA H200, 100, 14965\n", "",
        ])
        with tempfile.TemporaryDirectory() as td, mock.patch("k2_evalop.hardware._run", side_effect=lambda _argv: next(outputs)):
            path = Path(td) / "idle.json"
            with self.assertRaises(AuditError):
                run_idle_probe(path, sleep_fn=lambda _seconds: None)
            self.assertEqual(load_json(path)["status"], "FAIL")

    def test_campaign_flock_has_one_winner(self) -> None:
        with tempfile.TemporaryDirectory() as td:
            state = Path(td)
            with CampaignLock(state, "first"):
                code = (
                    "from pathlib import Path; from k2_evalop.operator import CampaignLock; "
                    "\ntry:\n CampaignLock(Path(sys.argv[1]),'second').__enter__(); print('BAD')"
                    "\nexcept Exception: print('REJECTED')"
                )
                completed = subprocess.run([sys.executable, "-c", "import sys;" + code, str(state)], text=True, capture_output=True)
                self.assertEqual(completed.stdout.strip(), "REJECTED")


def _fake_idle(path: Path) -> Path:
    write_new_json(path, {"schema_version": 1, "status": "PASS", "receipt": "test"})
    return path


class SupervisorFaultTests(unittest.TestCase):
    def _args(self, root: Path, command: list[str]) -> argparse.Namespace:
        return argparse.Namespace(
            state_root=str(root), phase="test_gpu", lease_id="lease-test",
            controller_pid=os.getpid(), identity_json="{}", command_sha256="0" * 64,
            log_path=str(root / "child.log"), cwd=str(root), budget_seconds=100.0,
            term_margin_seconds=1.0, kill_grace_seconds=0.2, command=command,
        )

    def test_spawn_failure_still_closes_and_charges(self) -> None:
        with tempfile.TemporaryDirectory() as td, mock.patch("k2_evalop.supervisor.run_idle_probe", side_effect=_fake_idle):
            root = Path(td)
            closed = supervisor.supervise(self._args(root, [str(root / "does-not-exist")]))
            value = load_json(closed)
            self.assertEqual(value["status"], "failed")
            self.assertTrue(value["process_group_proven_empty"])
            self.assertFalse(any((root / "leases" / "active").glob("*.json")))
            self.assertEqual(len((root / "ledger.jsonl").read_text().splitlines()), 2)

    def test_log_open_failure_creates_no_active_lease(self) -> None:
        with tempfile.TemporaryDirectory() as td, mock.patch("k2_evalop.supervisor.run_idle_probe", side_effect=_fake_idle):
            root = Path(td)
            (root / "child.log").mkdir()
            with self.assertRaises(OSError):
                supervisor.supervise(self._args(root, [sys.executable, "-c", "pass"]))
            self.assertFalse(any((root / "leases" / "active").glob("*.json")))
            self.assertFalse((root / "ledger.jsonl").exists())

    def test_terminal_ledger_failure_retains_active_evidence(self) -> None:
        with tempfile.TemporaryDirectory() as td, mock.patch("k2_evalop.supervisor.run_idle_probe", side_effect=_fake_idle):
            root = Path(td)
            real = supervisor.append_jsonl_fsync
            calls = 0
            def fail_second(path, value):
                nonlocal calls
                calls += 1
                if calls == 2:
                    raise OSError("injected terminal ledger fault")
                return real(path, value)
            with mock.patch("k2_evalop.supervisor.append_jsonl_fsync", side_effect=fail_second):
                with self.assertRaises(OSError):
                    supervisor.supervise(self._args(root, [sys.executable, "-c", "pass"]))
            self.assertEqual(len(list((root / "leases" / "active").glob("*.json"))), 1)
            self.assertEqual(len(list((root / "leases" / "closed").glob("*.json"))), 1)


if __name__ == "__main__":
    unittest.main()