File size: 10,556 Bytes
46d70d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace

from app import cli
from app.engine import regression_gate as rg
from app.engine.embedder import TextEmbedder
from app.engine.rerank_lab import RerankerUnavailableError
from app.engine.suite import build_export_bundle
from app.schemas import ExportRequest, SampleQuestionItem, SearchRequest
from app.storage.project_store import LoadedRun, ProjectStore


def _seed_suite(data_dir: Path, run_id: str) -> list[SampleQuestionItem]:
    store = ProjectStore(runs_dir=data_dir / "runs", suites_dir=data_dir / "suites")
    questions = [
        SampleQuestionItem(
            id="q_refund",
            query="refund money back guarantee",
            expected_doc_ids=[0],
        ),
        SampleQuestionItem(
            id="q_shoes",
            query="waterproof trail running shoes",
            expected_doc_ids=[5],
        ),
        SampleQuestionItem(
            id="q_k8s",
            query="kubernetes pvc mount error",
            expected_doc_ids=[10],
        ),
        SampleQuestionItem(
            id="q_quantum",
            query="quantum entanglement photon optics",
            expected_doc_ids=[15],
        ),
    ]
    store.save_suite(run_id, questions)
    return questions


def test_cli_list_pin_and_check_all_formats(
    synthetic_run: LoadedRun,
    synthetic_embedder: TextEmbedder,
    tmp_path: Path,
    capsys,
):
    data_dir = synthetic_run.run_dir.parent.parent
    run_id = synthetic_run.manifest.run_id

    # 1. list before pin
    rc = cli.main(["list", "--data-dir", str(data_dir)])
    assert rc == 0
    out = capsys.readouterr().out
    assert run_id in out
    assert "no" in out

    # 2. pin fails cleanly with exit 2 when suite is empty
    rc_empty = cli.main(
        ["pin", "--run", run_id, "--data-dir", str(data_dir)],
        embedder_override=synthetic_embedder,
    )
    assert rc_empty == 2
    err_empty = capsys.readouterr().err
    assert "no sample suite questions" in err_empty.lower()
    assert "Traceback" not in err_empty

    # 3. Seed suite & pin with portable --out + --critical + --config (exported recipe.json)
    _seed_suite(data_dir, run_id)
    recipe_search = SearchRequest(query="", mode="convex", alpha=0.55)
    recipe_bundle = build_export_bundle(synthetic_run, ExportRequest(search=recipe_search))
    recipe_path = tmp_path / "recipe.json"
    recipe_path.write_text(json.dumps(recipe_bundle.recipe_json, indent=2), encoding="utf-8")

    portable_bl = tmp_path / "ostra.baseline.json"
    rc_pin = cli.main(
        [
            "pin",
            "--run",
            run_id,
            "--config",
            str(recipe_path),
            "--label",
            "Release v1",
            "--margin",
            "0.02",
            "--critical",
            "q_refund,q_k8s",
            "--out",
            str(portable_bl),
            "--data-dir",
            str(data_dir),
        ],
        embedder_override=synthetic_embedder,
    )
    assert rc_pin == 0
    assert portable_bl.exists()
    pin_out = capsys.readouterr().out
    assert "Release v1" in pin_out

    # 4. list after pin shows pinned = yes
    assert cli.main(["list", "--data-dir", str(data_dir)]) == 0
    list_out = capsys.readouterr().out
    assert "yes" in list_out

    # 5. check --format table (default) with omitted --config uses contract.search_config
    rc_tbl = cli.main(
        ["check", "--run", run_id, "--data-dir", str(data_dir)],
        embedder_override=synthetic_embedder,
    )
    assert rc_tbl == 0
    tbl_out = capsys.readouterr().out
    assert "OSTRA REGRESSION GATE: GATE PASS" in tbl_out
    assert "MRR" in tbl_out

    # 6. check --format markdown --out report.md using external --baseline & --config
    md_out_path = tmp_path / "gate.md"
    rc_md = cli.main(
        [
            "check",
            "--run",
            run_id,
            "--baseline",
            str(portable_bl),
            "--config",
            str(recipe_path),
            "--format",
            "markdown",
            "--out",
            str(md_out_path),
            "--data-dir",
            str(data_dir),
        ],
        embedder_override=synthetic_embedder,
    )
    assert rc_md == 0
    md_stdout = capsys.readouterr().out
    assert md_out_path.exists()
    assert md_out_path.read_text(encoding="utf-8") == md_stdout
    assert "## Ostra Regression Gate: PASS" in md_stdout

    # 7. check --format json produces valid BaselineCheckResponse JSON
    rc_json = cli.main(
        [
            "check",
            "--run",
            run_id,
            "--format",
            "json",
            "--data-dir",
            str(data_dir),
        ],
        embedder_override=synthetic_embedder,
    )
    assert rc_json == 0
    parsed = json.loads(capsys.readouterr().out)
    assert parsed["verdict"] == "PASS"
    assert parsed["exit_code"] == 0
    assert parsed["config_diff"] == []


def test_cli_exit_codes_for_warn_fail_and_errors(
    synthetic_run: LoadedRun,
    synthetic_embedder: TextEmbedder,
    tmp_path: Path,
    monkeypatch,
    capsys,
):
    data_dir = synthetic_run.run_dir.parent.parent
    run_id = synthetic_run.manifest.run_id
    _seed_suite(data_dir, run_id)

    # Pin baseline first (locking q_refund as critical)
    assert (
        cli.main(
            [
                "pin",
                "--run",
                run_id,
                "--critical",
                "q_refund",
                "--data-dir",
                str(data_dir),
            ],
            embedder_override=synthetic_embedder,
        )
        == 0
    )
    capsys.readouterr()

    # 1. FAIL_REGRESSION -> exit code 1 (quarantining doc 0 breaks critical q_refund)
    bad_cfg = tmp_path / "bad_search.json"
    bad_cfg.write_text(json.dumps({"excluded_doc_ids": [0]}), encoding="utf-8")
    rc_fail = cli.main(
        [
            "check",
            "--run",
            run_id,
            "--config",
            str(bad_cfg),
            "--data-dir",
            str(data_dir),
        ],
        embedder_override=synthetic_embedder,
    )
    assert rc_fail == 1
    out_fail = capsys.readouterr().out
    assert "REGRESSION DETECTED" in out_fail

    # 2. WARN_NOISE -> exit 0 normally, exit 2 with --strict-warn
    # Simulate non-critical rank drop on q_shoes (#1 -> #4) while critical q_refund stays #1
    real_search = rg.run_hybrid_search

    def warn_search(run, emb, req: SearchRequest):
        res = real_search(run, emb, req)
        if "waterproof" in req.query:
            # Push doc 5 down to rank 4 to trigger rank_drop -> WARN_NOISE
            rows = list(res.waterfall_rows)
            doc5 = [r for r in rows if r.doc_id == 5]
            others = [r for r in rows if r.doc_id != 5]
            if doc5 and len(others) >= 3:
                reordered = others[:3] + doc5 + others[3:]
                return SimpleNamespace(
                    waterfall_rows=reordered,
                    pinned_row=res.pinned_row,
                    pinned_stage_diagnosis=res.pinned_stage_diagnosis,
                    calibration=res.calibration,
                )
        return res

    monkeypatch.setattr(rg, "run_hybrid_search", warn_search)
    rc_warn = cli.main(
        [
            "check",
            "--run",
            run_id,
            "--margin",
            "0.25",
            "--data-dir",
            str(data_dir),
        ],
        embedder_override=synthetic_embedder,
    )
    assert rc_warn == 0
    assert "MINOR DIP (WITHIN NOISE)" in capsys.readouterr().out

    rc_strict = cli.main(
        [
            "check",
            "--run",
            run_id,
            "--margin",
            "0.25",
            "--strict-warn",
            "--data-dir",
            str(data_dir),
        ],
        embedder_override=synthetic_embedder,
    )
    assert rc_strict == 2
    capsys.readouterr()

    # 3. RerankerUnavailableError -> clean stderr + exit code 2 (zero traceback)
    def raise_reranker(*_args, **_kwargs):
        raise RerankerUnavailableError("Cross-encoder weights not cached locally.")

    monkeypatch.setattr(rg, "run_hybrid_search", raise_reranker)
    rc_rr = cli.main(
        ["check", "--run", run_id, "--data-dir", str(data_dir)],
        embedder_override=synthetic_embedder,
    )
    assert rc_rr == 2
    err_rr = capsys.readouterr().err
    assert "Cross-encoder weights not cached locally" in err_rr
    assert "Traceback" not in err_rr

    # 4. Missing run -> clean stderr + exit code 2
    rc_missing = cli.main(
        ["check", "--run", "does_not_exist", "--data-dir", str(data_dir)],
        embedder_override=synthetic_embedder,
    )
    assert rc_missing == 2
    err_missing = capsys.readouterr().err
    assert "not found" in err_missing.lower()
    assert "Traceback" not in err_missing

    # 5. Missing baseline -> clean stderr + exit code 2
    ProjectStore(runs_dir=data_dir / "runs", suites_dir=data_dir / "suites").delete_baseline(run_id)
    rc_no_bl = cli.main(
        ["check", "--run", run_id, "--data-dir", str(data_dir)],
        embedder_override=synthetic_embedder,
    )
    assert rc_no_bl == 2
    err_no_bl = capsys.readouterr().err
    assert "no pinned baseline" in err_no_bl.lower()
    assert "Traceback" not in err_no_bl


def test_cli_subprocess_entrypoint(synthetic_run: LoadedRun):
    data_dir = synthetic_run.run_dir.parent.parent
    run_id = synthetic_run.manifest.run_id
    backend_dir = Path(__file__).resolve().parents[1]

    proc_help = subprocess.run(
        [sys.executable, "-m", "app.cli", "--help"],
        cwd=backend_dir,
        capture_output=True,
        text=True,
        check=False,
    )
    assert proc_help.returncode == 0
    assert "list" in proc_help.stdout and "pin" in proc_help.stdout and "check" in proc_help.stdout

    proc_list = subprocess.run(
        [sys.executable, "-m", "app.cli", "list", "--data-dir", str(data_dir)],
        cwd=backend_dir,
        capture_output=True,
        text=True,
        check=False,
    )
    assert proc_list.returncode == 0
    assert run_id in proc_list.stdout

    proc_err = subprocess.run(
        [sys.executable, "-m", "app.cli", "check", "--run", "missing_run", "--data-dir", str(data_dir)],
        cwd=backend_dir,
        capture_output=True,
        text=True,
        check=False,
    )
    assert proc_err.returncode == 2
    assert "Traceback" not in proc_err.stderr