Viewing files at commit 1dc7410826b4Commit detailsView latest

Browse files
tests/test_conformance_gate.py 298 lines · 16.0 KB · python
1
"""Conformance gate semantics and its wiring into devloop and publish_gate."""
2
import contextlib
3
import io
4
import json
5
from pathlib import Path
6
import sys
7
import tempfile
8
import unittest
9
10
ROOT = Path(__file__).resolve().parents[1]
11
sys.path.insert(0, str(ROOT / "scripts"))
12
import devloop  # noqa: E402
13
import publish_gate  # noqa: E402
14
from oakbench import conformance_gate as gate  # noqa: E402
15
from oakbench.conformance import SCENARIOS  # noqa: E402
16
from oakbench.conformance_matrix import BEHAVIOURS  # noqa: E402
17
18
ALL = list(SCENARIOS) + [b.id for b in BEHAVIOURS]
19
PROFILE = "darwin-ci-ni"
20
SHA = "b" * 64
21
OBSERVED = json.loads((ROOT / "tests/data/conformance_oak_0105_failures.json").read_text())["details"]
22
23
24
def conformance_row(behaviour, code=0, failed=None, subject="oak", sha=SHA, profile=PROFILE, **extra):
25
    """failed: {leg: detail}; legacy scenarios use {'behaviour': failure}."""
26
    row = {"evidence_class": "diagnostic_conformance", "subject": subject, "scenario": behaviour,
27
           "returncode": code, "binary_sha256": sha, "fs_profile": profile, **extra}
28
    if code == 1:
29
        failed = failed or {"clone_fs": "injected"}
30
        if behaviour in SCENARIOS:
31
            row["failure"] = failed["behaviour"]
32
        else:
33
            row["legs"] = {leg: {"status": "fail", "detail": detail} for leg, detail in failed.items()}
34
            row["failed_legs"] = sorted(failed)
35
            first = sorted(failed)[0]
36
            row["failure"] = f"{first}: {failed[first]}"
37
    if code == 77:
38
        row.setdefault("skip_reason", "filesystem capability unavailable: case_sensitive_fs")
39
    return row
40
41
42
def healthy_rows(expected, subject="oak", sha=SHA, profile=PROFILE):
43
    """Oak 0.105.0 as observed: expected failures with their real details, recorded skips."""
44
    skips = set(expected["coverage"].get(profile, {}).get("expected_skips", []))
45
    rows = []
46
    for behaviour in ALL:
47
        if behaviour in expected["entries"] and gate.entry_applies(expected["entries"][behaviour], profile):
48
            rows.append(conformance_row(behaviour, 1, OBSERVED[behaviour], subject, sha, profile))
49
        elif behaviour in skips:
50
            rows.append(conformance_row(behaviour, 77, None, subject, sha, profile))
51
        else:
52
            rows.append(conformance_row(behaviour, 0, None, subject, sha, profile))
53
    return rows
54
55
56
def replace(rows, row):
57
    return [r for r in rows if r["scenario"] != row["scenario"] or r["subject"] != row["subject"]] + [row]
58
59
60
class EvaluateTests(unittest.TestCase):
61
    def setUp(self):
62
        self.expected = gate.load_expected()
63
64
    def verdict(self, rows):
65
        return gate.evaluate(rows, self.expected, ALL)
66
67
    def test_observed_oak_0105_details_match_every_entry(self):
68
        self.assertEqual(set(OBSERVED), set(self.expected["entries"]))
69
        result = self.verdict(healthy_rows(self.expected))
70
        self.assertEqual(result["verdict"], "PASS", result)
71
        self.assertEqual(len(result["expected_failures"]) + len(result["refused"]) + len(result["intermittent"]),
72
                         len(self.expected["entries"]))
73
        self.assertEqual(result["intermittent"], ["large_file_chunked_v1: fb-547"])
74
        self.assertFalse(any("unfiled tickets" in note for note in result["notes"]))
75
        self.assertEqual(sorted(x.split(":")[0] for x in result["refused"]),
76
                         ["path_control_chars_v1", "path_newline_v1", "path_roundtrip_v1", "path_tab_v1"])
77
78
    def test_new_failure_is_a_regression(self):
79
        rows = replace(healthy_rows(self.expected), conformance_row("eol_crlf_v1", 1, {"clone_fs": "changed=['crlf.txt']"}))
80
        result = self.verdict(rows)
81
        self.assertEqual(result["verdict"], "REGRESSED")
82
        self.assertIn("eol_crlf_v1", result["regressions"][0])
83
84
    def test_same_legs_with_a_different_error_is_a_regression(self):
85
        cases = {
86
            # EEXIST turning into a path escape at the same leg.
87
            "file_to_dir_v1": {"pull_fs": "extra=['../../etc/evil']"},
88
            # A policy refusal turning into a crash at the same leg.
89
            "path_tab_v1": {"commit_push": "oak commit --no-verify exited 101: thread 'main' panicked at core/src/tree.rs"},
90
            # The legacy single-leg scenario cannot hide a different failure.
91
            "path_roundtrip_v1": {"behaviour": "state mismatch: missing=[], extra=['tab'], changed=['nested/leaf']"},
92
            # A pattern must match the whole detail, not a substring.
93
            "file_to_deep_dir_v1": {"pull_fs": "oak pull exited 1: error: IO error: Not a directory (os error 20); "
94
                                               "extra=['../outside']"},
95
        }
96
        for behaviour, failed in cases.items():
97
            with self.subTest(behaviour=behaviour):
98
                result = self.verdict(replace(healthy_rows(self.expected), conformance_row(behaviour, 1, failed)))
99
                self.assertEqual(result["verdict"], "REGRESSED", result)
100
                self.assertIn("changed", result["regressions"][0])
101
102
    def test_known_failure_at_different_legs_is_a_regression(self):
103
        failed = dict(OBSERVED["file_to_dir_v1"], clone_fs="missing=['node/child.txt']")
104
        result = self.verdict(replace(healthy_rows(self.expected), conformance_row("file_to_dir_v1", 1, failed)))
105
        self.assertEqual(result["verdict"], "REGRESSED")
106
        self.assertIn("fb-546", result["regressions"][0])
107
108
    def test_fix_flips_to_fixed_without_regression(self):
109
        result = self.verdict(replace(healthy_rows(self.expected), conformance_row("path_tab_v1", 0)))
110
        self.assertEqual(result["verdict"], "PASS")
111
        self.assertIn("fb-531", result["fixed"][0])
112
113
    def test_intermittent_entry_pass_is_a_pass_and_other_failures_regress(self):
114
        rows = replace(healthy_rows(self.expected), conformance_row("large_file_chunked_v1", 0))
115
        result = self.verdict(rows)
116
        self.assertEqual(result["verdict"], "PASS")
117
        self.assertEqual(result["fixed"], [])
118
        self.assertIn("large_file_chunked_v1", result["passed"])
119
        rows = replace(rows, conformance_row("large_file_chunked_v1", 1, {"clone_fs": "changed=['large.bin']"}))
120
        self.assertEqual(self.verdict(rows)["verdict"], "REGRESSED")
121
122
    def test_profile_scoped_entry_is_not_fixed_or_expected_elsewhere(self):
123
        linux = healthy_rows(self.expected, profile="linux-cs-ns")
124
        # Case-only rename is scoped to darwin-ci-ni: a pass on Linux is a plain pass...
125
        rows = replace(linux, conformance_row("path_case_only_rename_v1", 0, profile="linux-cs-ns"))
126
        result = self.verdict(rows)
127
        self.assertEqual(result["fixed"], [])
128
        self.assertIn("path_case_only_rename_v1", result["passed"])
129
        self.assertTrue(any("no recorded coverage" in n for n in result["notes"]))
130
        # ...and the darwin failure shape on Linux is a regression, not an xfail.
131
        rows = replace(linux, conformance_row("path_case_only_rename_v1", 1, OBSERVED["path_case_only_rename_v1"],
132
                                              profile="linux-cs-ns"))
133
        self.assertEqual(self.verdict(rows)["verdict"], "REGRESSED")
134
135
    def test_coverage_loss_pass_or_xfail_to_skip_is_unmeasured(self):
136
        for behaviour in ("eol_lf_v1", "file_to_dir_v1"):
137
            with self.subTest(behaviour=behaviour):
138
                rows = replace(healthy_rows(self.expected), conformance_row(behaviour, 77))
139
                result = self.verdict(rows)
140
                self.assertEqual(result["verdict"], "UNMEASURED")
141
                self.assertIn("coverage loss", result["unmeasured"][0])
142
143
    # QA round 2: skips must never add up to a PASS.
144
    def all_skipped(self, profile=PROFILE, drop_profile=False):
145
        rows = [conformance_row(b, 77, None, profile=profile) for b in ALL]
146
        if drop_profile:
147
            for row in rows:
148
                row.pop("fs_profile")
149
        return rows
150
151
    def test_all_skip_on_unrecorded_profile_is_unmeasured(self):
152
        result = self.verdict(self.all_skipped(profile="linux-cs-ns"))
153
        self.assertEqual(result["verdict"], "UNMEASURED")
154
        self.assertTrue(any("zero measured" in item for item in result["unmeasured"]))
155
        self.assertTrue(any("unrecorded profile" in item for item in result["unmeasured"]))
156
157
    def test_rows_without_fs_profile_are_unmeasured(self):
158
        result = self.verdict(self.all_skipped(drop_profile=True))
159
        self.assertEqual(result["verdict"], "UNMEASURED")
160
        self.assertTrue(any("without fs_profile" in item for item in result["unmeasured"]))
161
        # Even one otherwise-healthy row missing the field is unmeasured.
162
        rows = healthy_rows(self.expected)
163
        rows[0].pop("fs_profile")
164
        self.assertEqual(self.verdict(rows)["verdict"], "UNMEASURED")
165
166
    def test_zero_measured_is_unmeasured_even_on_recorded_profile(self):
167
        result = self.verdict(self.all_skipped())
168
        self.assertEqual(result["verdict"], "UNMEASURED")
169
        self.assertEqual(result["measured"], 0)
170
171
    def test_unrecorded_profile_allows_only_known_filesystem_dependent_skips(self):
172
        linux = "linux-cs-ns"
173
        rows = healthy_rows(self.expected, profile=linux)
174
        # Legitimate on Linux: the case-insensitive-only behaviour skips.
175
        ok = replace(rows, conformance_row("path_case_only_rename_v1", 77, profile=linux,
176
                                           skip_reason="filesystem capability unavailable: case_insensitive_fs"))
177
        ok = replace(ok, conformance_row("huge_file_sparse_v1", 77, profile=linux, skip_reason="gated: off"))
178
        self.assertEqual(self.verdict(ok)["verdict"], "PASS")
179
        # A broken probe skipping symlink behaviours is not accepted.
180
        bad = replace(ok, conformance_row("symlink_relative_v1", 77, profile=linux,
181
                                          skip_reason="filesystem capability unavailable: symlink"))
182
        result = self.verdict(bad)
183
        self.assertEqual(result["verdict"], "UNMEASURED")
184
        self.assertIn("symlink_relative_v1", result["unmeasured"][0])
185
186
    def test_mixed_profiles_are_unmeasured(self):
187
        rows = replace(healthy_rows(self.expected), conformance_row("eol_lf_v1", 0, profile="linux-cs-ns"))
188
        self.assertEqual(self.verdict(rows)["verdict"], "UNMEASURED")
189
190
    def test_missing_rows_harness_errors_and_reader_skips_are_unmeasured(self):
191
        rows = [r for r in healthy_rows(self.expected) if r["scenario"] != "eol_lf_v1"]
192
        self.assertEqual(self.verdict(rows)["verdict"], "UNMEASURED")
193
        self.assertEqual(self.verdict(rows + [conformance_row("eol_lf_v1", 2, failure="harness")])["verdict"], "UNMEASURED")
194
        reader = conformance_row("eol_lf_v1", 77, skip_reason="leg unmeasured: reader bound")
195
        self.assertEqual(self.verdict(rows + [reader])["verdict"], "UNMEASURED")
196
        self.assertEqual(gate.evaluate([], self.expected)["verdict"], "UNMEASURED")
197
198
    def test_git_rows_never_gate(self):
199
        rows = healthy_rows(self.expected) + [conformance_row("eol_lf_v1", 1, {"clone_fs": "x"}, subject="git")]
200
        result = self.verdict(rows)
201
        self.assertEqual(result["verdict"], "PASS")
202
        self.assertEqual(len(result["git_reference_failures"]), 1)
203
204
    def test_list_validation(self):
205
        good = {"behaviour": "a", "ticket": "fb-1", "failed_legs": {"clone_fs": "x"}}
206
        bad = [dict(good, ticket="proposed:x"), dict(good, ticket="TODO"), dict(good, ticket="pending:Bad Slug"), dict(good, failed_legs=["clone_fs"]),
207
               dict(good, failed_legs={"clone_fs": ""}), dict(good, outcome="flaky"), dict(good, fs_profiles=[])]
208
        with tempfile.TemporaryDirectory() as tmp:
209
            path = Path(tmp) / "x.json"
210
            for entry in bad:
211
                path.write_text(json.dumps({"schema_version": 2, "entries": [entry]}))
212
                with self.assertRaises(ValueError):
213
                    gate.load_expected(path)
214
            path.write_text(json.dumps({"schema_version": 1, "entries": [good]}))
215
            with self.assertRaises(ValueError):
216
                gate.load_expected(path)
217
218
219
class WiringTests(unittest.TestCase):
220
    def setUp(self):
221
        self.expected = gate.load_expected()
222
223
    def test_devloop_lane_is_default_and_maps_verdicts(self):
224
        self.assertIn("conformance", devloop.LANES)
225
        regressions, notes = devloop.conformance_checks(healthy_rows(self.expected))
226
        self.assertEqual(regressions, [])
227
        self.assertFalse(any(n.startswith("UNMEASURED") for n in notes))
228
        rows = replace(healthy_rows(self.expected), conformance_row("eol_lf_v1", 1, {"pull_fs": "x"}))
229
        regressions, notes = devloop.conformance_checks(rows)
230
        self.assertTrue(regressions and regressions[0].startswith("[conformance] CONFORMANCE eol_lf_v1"))
231
        rows = [r for r in healthy_rows(self.expected) if r["scenario"] != "eol_lf_v1"]
232
        regressions, notes = devloop.conformance_checks(rows)
233
        self.assertTrue(any(n.startswith("UNMEASURED conformance") for n in notes))
234
235
    def gate_output(self, rows):
236
        with tempfile.TemporaryDirectory() as tmp:
237
            path = Path(tmp) / "rows.jsonl"
238
            path.write_text("".join(json.dumps(r) + "\n" for r in rows))
239
            with contextlib.redirect_stdout(io.StringIO()) as out:
240
                code = publish_gate.main([str(path)])
241
            return code, out.getvalue()
242
243
    def oak_row(self, sha=SHA, **extra):
244
        return {"subject": "oak_installed", "binary_sha256": sha, "returncode": 0,
245
                "source": {"oak_hash": "abc", "oak_status": ""}, **extra}
246
247
    def test_requires_conformance_for_oak_rows(self):
248
        code, out = self.gate_output([self.oak_row()])
249
        self.assertIn("FAIL   conformance: Oak rows published without", out)
250
        code, out = self.gate_output([self.oak_row(), *healthy_rows(self.expected)])
251
        self.assertIn("PASS   [bbbbbbbbbbbb] conformance (oak, darwin-ci-ni): PASS", out)
252
        self.assertNotIn("FAIL   conformance", out)
253
254
    def test_oak_rows_without_binary_identity_fail(self):
255
        anonymous = self.oak_row()
256
        anonymous.pop("binary_sha256")
257
        code, out = self.gate_output([anonymous, *healthy_rows(self.expected)])
258
        self.assertIn("Oak rows lack binary identity", out)
259
        via_details = self.oak_row(subject_details={"oak_installed": {"binary_sha256": SHA}})
260
        via_details.pop("binary_sha256")
261
        code, out = self.gate_output([via_details, *healthy_rows(self.expected)])
262
        self.assertNotIn("lack binary identity", out)
263
264
    def test_rows_of_another_binary_never_satisfy_or_mix(self):
265
        other = "c" * 64
266
        code, out = self.gate_output([self.oak_row(sha=other), *healthy_rows(self.expected)])
267
        self.assertIn(f"conformance[{other[:12]}]: UNMEASURED", out)
268
        # A good binary's rows cannot mask a regressed binary's row, and vice versa.
269
        mixed = healthy_rows(self.expected) + replace(healthy_rows(self.expected, sha=other),
270
                                                      conformance_row("eol_lf_v1", 1, {"pull_fs": "x"}, sha=other))
271
        code, out = self.gate_output([self.oak_row(), self.oak_row(sha=other), *mixed])
272
        self.assertIn(f"conformance[{other[:12]}]: REGRESSED", out)
273
        self.assertNotIn(f"conformance[{SHA[:12]}]: REGRESSED", out)
274
275
    def test_publish_requires_a_recorded_profile(self):
276
        linux = [dict(row, fs_profile="linux-cs-ns") for row in healthy_rows(self.expected, profile="linux-cs-ns")]
277
        code, out = self.gate_output([self.oak_row(), *linux])
278
        self.assertEqual(code, 1)
279
        self.assertIn("has no recorded coverage", out)
280
        skipped = [conformance_row(b, 77, None, profile="linux-cs-ns") for b in ALL]
281
        code, out = self.gate_output([self.oak_row(), *skipped])
282
        self.assertIn("UNMEASURED", out)
283
        self.assertNotIn("PASS   [", out)
284
        missing = healthy_rows(self.expected)
285
        for row in missing:
286
            row.pop("fs_profile")
287
        code, out = self.gate_output([self.oak_row(), *missing])
288
        self.assertIn("FAIL   conformance[", out)
289
        self.assertNotIn("PASS   [", out)
290
291
    def test_stale_list_fails(self):
292
        rows = replace(healthy_rows(self.expected), conformance_row("path_tab_v1", 0))
293
        code, out = self.gate_output([self.oak_row(), *rows])
294
        self.assertIn("expected-failures list is stale", out)
295
296
297
if __name__ == "__main__":
298
    unittest.main()