Reversible clean-root candidate rebuilt from oak/benchmarks main@009dead264ca; original repository retained.

tests/test_drift.py in oak/benchmarks

tests/test_drift.py 198 lines · 8.2 KB · python
1
"""Drift checks (oakbench.drift): the harness must describe the Oak it measures."""
2
3
from __future__ import annotations
4
5
import json
6
import os
7
import shutil
8
import stat
9
import sys
10
import tempfile
11
import unittest
12
from pathlib import Path
13
from unittest import mock
14
15
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
16
17
from oakbench import drift  # noqa: E402
18
from oakbench import oak_sqlite_reader  # noqa: E402
19
20
ROOT = Path(__file__).resolve().parents[1]
21
FAKE_OAK = """#!/bin/sh
22
if [ "$1" = help ]; then
23
cat <<'EOF'
24
Usage: oak [OPTIONS] <COMMAND>
25
26
Commands:
27
  status       Show the status
28
  log          Show history
29
  help         Print help
30
31
Options:
32
  -h, --help  Print help
33
EOF
34
elif [ "$1" = status ]; then
35
cat <<'EOF'
36
Usage: oak status [OPTIONS]
37
38
Options:
39
      --json       Emit JSON
40
      --porcelain  Stable rows
41
  -h, --help       Print help
42
EOF
43
elif [ "$1" = log ]; then
44
cat <<'EOF'
45
Usage: oak log [OPTIONS] [PATH]...
46
47
Options:
48
  -n, --limit <LIMIT>  Max commits
49
      --oneline        Compact
50
  -h, --help           Print help
51
EOF
52
fi
53
"""
54
55
56
def local_oak_bin() -> str | None:
57
    candidates = [os.environ.get("OAK_BIN"), str(ROOT.parent / "oak" / "target" / "release" / "oak")]
58
    return next((c for c in candidates if c and Path(c).is_file()), None)
59
60
61
class FakeOakTest(unittest.TestCase):
62
    def setUp(self) -> None:
63
        self.tmp = tempfile.mkdtemp()
64
        self.addCleanup(shutil.rmtree, self.tmp)
65
        self.bin = str(Path(self.tmp) / "oak")
66
        Path(self.bin).write_text(FAKE_OAK)
67
        os.chmod(self.bin, os.stat(self.bin).st_mode | stat.S_IEXEC)
68
        drift._help.cache_clear()
69
70
    def test_documented_flags_pass(self) -> None:
71
        self.assertEqual(drift.check_oak_argv(self.bin, ["status", "--porcelain"]), [])
72
        self.assertEqual(drift.check_oak_argv(self.bin, ["log", "-n", "5", "--oneline", "app/x.py"]), [])
73
74
    def test_missing_flag_is_reported(self) -> None:
75
        problems = drift.check_oak_argv(self.bin, ["log", "-S", "term"])
76
        self.assertEqual(len(problems), 1)
77
        self.assertIn("flag `-S`", problems[0])
78
79
    def test_flag_prefix_does_not_count_as_documented(self) -> None:
80
        # `--porc` must not match `--porcelain`.
81
        self.assertEqual(len(drift.check_oak_argv(self.bin, ["status", "--porc"])), 1)
82
83
    def test_missing_subcommand_is_reported(self) -> None:
84
        problems = drift.check_oak_argv(self.bin, ["show", "HEAD"])
85
        self.assertIn("not an oak subcommand", problems[0])
86
87
    def test_shell_steps_are_parsed(self) -> None:
88
        argvs = list(drift._shell_oak_argvs(
89
            f"cd ../b && {self.bin} status --json && cur=$({self.bin} log -n 1) && echo hi", {self.bin}))
90
        self.assertIn(["status", "--json"], argvs)
91
        self.assertIn(["log", "-n", "1"], argvs)
92
93
94
class MappingDriftTest(unittest.TestCase):
95
    def test_repo_mappings_agree(self) -> None:
96
        self.assertEqual(drift.mapping_drift(), [])
97
98
    def test_disagreement_is_reported(self) -> None:
99
        with tempfile.TemporaryDirectory() as tmp:
100
            config = Path(tmp)
101
            shutil.copy(ROOT / "config" / "command_semantics.json", config / "command_semantics.json")
102
            (config / "subject_kinds").mkdir()
103
            oak = json.loads((ROOT / "config" / "subject_kinds" / "oak.json").read_text())
104
            oak["commands"]["status"]["core-equivalent"] = ["status"]
105
            (config / "subject_kinds" / "oak.json").write_text(json.dumps(oak))
106
            with mock.patch.object(drift, "CONFIG", config):
107
                problems = drift.mapping_drift()
108
        self.assertEqual(len(problems), 1)
109
        self.assertIn("status/core-equivalent", problems[0])
110
111
112
class SchemaDriftTest(unittest.TestCase):
113
    def fake_repo(self, tmp: str, versions: list[str]) -> Path:
114
        source = Path(tmp) / "core" / "src"
115
        source.mkdir(parents=True)
116
        (source / "sqlite.rs").write_text("\n".join(f'Migration {{ version: "{v}", required: true }},' for v in versions))
117
        return Path(tmp)
118
119
    def test_reader_matching_newest_migration_passes(self) -> None:
120
        with tempfile.TemporaryDirectory() as tmp:
121
            repo = self.fake_repo(tmp, ["0001_init", oak_sqlite_reader.KNOWN_MAX_MIGRATION])
122
            self.assertEqual(drift.schema_drift(repo), [])
123
124
    def test_newer_oak_migration_is_reported(self) -> None:
125
        with tempfile.TemporaryDirectory() as tmp:
126
            repo = self.fake_repo(tmp, [oak_sqlite_reader.KNOWN_MAX_MIGRATION, "9999_future_change"])
127
            problems = drift.schema_drift(repo)
128
        self.assertEqual(len(problems), 1)
129
        self.assertIn("9999_future_change", problems[0])
130
        self.assertIn("unmeasured", problems[0])
131
132
133
@unittest.skipUnless(local_oak_bin(), "no local Oak build (set OAK_BIN or build ../oak)")
134
class LiveOakDriftTest(unittest.TestCase):
135
    """Fails loudly when Oak changes underneath the suite. Fix the harness, not the test."""
136
137
    def test_every_oak_command_the_suite_runs_exists(self) -> None:
138
        drift._help.cache_clear()
139
        self.assertEqual(drift.cli_flag_drift(local_oak_bin()), [])
140
141
    def test_reader_knows_oak_newest_schema(self) -> None:
142
        oak_repo = Path(local_oak_bin()).parents[2]
143
        if not (oak_repo / "core" / "src" / "sqlite.rs").is_file():
144
            self.skipTest("Oak binary is not inside a source checkout")
145
        self.assertEqual(drift.schema_drift(oak_repo), [])
146
147
148
# Steps that pass on exit 0 AND on a failure code. Each one can hide a wrong
149
# result behind a "pass", so each is reviewed and justified here. A new
150
# tolerant step fails test_tolerant_steps_are_reviewed until it is listed.
151
REVIEWED_TOLERANT_STEPS = {
152
    # Frozen v1 identity (ADR-0005); superseded by history_archaeology_v2,
153
    # which requires exit 0 and checks answers.
154
    ("git", "history_archaeology", "history.pickaxe"): "frozen v1",
155
    ("oak", "history_archaeology", "history.file_history"): "frozen v1",
156
    ("oak", "history_archaeology", "history.pickaxe"): "frozen v1",
157
    # Error-text cost measurements: the error output is the measurement.
158
    ("git", "vcs_error_recovery", "error.commit_nothing"): "error text is the measurement",
159
    ("oak", "vcs_error_recovery", "error.commit_nothing"): "error text is the measurement",
160
    ("git", "vcs_error_recovery", "error.unknown_subcommand"): "error text is the measurement",
161
    ("oak", "vcs_error_recovery", "error.unknown_subcommand"): "error text is the measurement",
162
    # Dirty pull: each VCS may refuse or merge; the recovery arc follows.
163
    ("git", "sync_pull_dirty", "sync.pull_dirty"): "refuse-or-merge both valid",
164
    ("oak", "sync_pull_dirty", "sync.pull_dirty"): "refuse-or-merge both valid",
165
    # KNOWN WEAK ORACLE (2026-11-09 audit): a diverged push that wrongly
166
    # succeeds (exit 0) passes this step. Needs a sync_push_divergence_v2
167
    # that requires rejection or checks the remote head.
168
    ("oak", "sync_push_divergence", "error.push_diverged"): "known weak oracle",
169
}
170
171
172
class TolerantStepsTest(unittest.TestCase):
173
    def test_tolerant_steps_are_reviewed(self) -> None:
174
        import workflow_ab
175
        from oakbench.subjects import Subject
176
177
        ctx = {"branch": "b", "remote_dir": "../r", "clone_b": "../cb", "clone_a": "../ca",
178
               "repo_dir": "r", "measure_dir": "../ca", "oak_repo": "o/r"}
179
        found = set()
180
        for kind in ("git", "oak"):
181
            subject = Subject(name=kind, kind=kind, label=kind, bin=Path(kind))
182
            for name, workflow in workflow_ab.WORKFLOWS.items():
183
                for track in ("agent-default", "core-equivalent"):
184
                    for factory in (workflow.prepare, workflow.steps):
185
                        if factory is None:
186
                            continue
187
                        steps = factory(subject, track, ctx) if workflow.remote_purpose else factory(subject, track)
188
                        for step in steps:
189
                            codes = set(step.expected_returncodes)
190
                            if 0 in codes and len(codes) > 1:
191
                                found.add((kind, name, step.operation))
192
        self.assertEqual(found - set(REVIEWED_TOLERANT_STEPS), set(),
193
                         "new step passes on both success and failure exit codes; review it")
194
        self.assertEqual(set(REVIEWED_TOLERANT_STEPS) - found, set(), "stale entry: step is no longer tolerant")
195
196
197
if __name__ == "__main__":
198
    unittest.main()