from __future__ import annotations import json from pathlib import Path import numpy as np import pytest from telen.static_benchmark import ( ALQAC_PRIMARY_TEST_SPLITS, SparseBM25, dense_top_k, evaluate_rankings, load_alqac_retrieval, paired_bootstrap_difference, reorder_ranking_prefix, reciprocal_rank_fusion, stable_top_k, ) from scripts.run_static_benchmark import parse_systems def _write_json(path: Path, payload: object) -> None: path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") def _alqac_fixture(tmp_path: Path) -> Path: root = tmp_path / "alqac" year_root = root / "ALQAC_2023" year_root.mkdir(parents=True) _write_json( year_root / "law.json", [ { "id": "Luật Mẫu", "articles": [ {"id": "1", "text": "Điều 1. Phạm vi điều chỉnh."}, {"id": "2", "text": "Điều 2. Đối tượng áp dụng."}, ], } ], ) for split, article_id in ( ("public_test_GOLD", "1"), ("private_test_GOLD", "2"), ): _write_json( year_root / f"{split}.json", [ { "question_id": "reused-id", "question_type": "Tự luận", "text": f"Câu hỏi từ {split}", "relevant_articles": [ {"law_id": "Luật Mẫu", "article_id": article_id} ], } ], ) return root def test_stable_top_k_breaks_score_ties_by_identifier() -> None: ids = np.asarray(["z", "a", "m", "b"]) lexical = np.argsort(ids, kind="stable") result = stable_top_k( np.asarray([0.0, 1.0, 1.0, 1.0]), k=2, lexicographic_indices=lexical, identifiers=ids, ) assert result.tolist() == [1, 3] def test_sparse_bm25_and_dense_rank_expected_documents() -> None: ids = ("d2", "d1", "d3") documents = ("thuế thu nhập cá nhân", "bảo vệ môi trường", "đấu thầu") bm25 = SparseBM25().fit(documents) lexical = bm25.rank(("thuế cá nhân",), ids, k=3) assert lexical[0, 0] == 0 query = np.asarray([[1.0, 0.0]], dtype=np.float32) corpus = np.asarray([[0.2, 0.0], [0.9, 0.0], [0.1, 0.0]], dtype=np.float32) dense = dense_top_k(query, corpus, ids, k=3) assert dense[0, 0] == 1 def test_rrf_and_binary_qrel_metrics() -> None: first = np.asarray([[0, 1, 2], [2, 1, 0]], dtype=np.int32) second = np.asarray([[1, 0, 2], [2, 0, 1]], dtype=np.int32) fused = reciprocal_rank_fusion((first, second), ("a", "b", "c"), k=3) assert fused.shape == (2, 3) assert fused[1, 0] == 2 padded = np.tile(np.arange(100, dtype=np.int32), (2, 1)) summary, observations = evaluate_rankings( padded, (frozenset({0}), frozenset({9, 99})), ) assert summary["hit_at_1"] == 0.5 assert summary["recall_at_100"] == 1.0 assert observations["ndcg_at_10"][0] == pytest.approx(1.0) def test_paired_bootstrap_is_reproducible() -> None: baseline = np.asarray([0.0, 0.5, 1.0]) treatment = np.asarray([0.5, 0.5, 1.0]) first = paired_bootstrap_difference(baseline, treatment, samples=200, seed=7) second = paired_bootstrap_difference(baseline, treatment, samples=200, seed=7) assert first == second assert first["observed_difference"] == pytest.approx(1 / 6) def test_reorder_ranking_prefix_preserves_tail_and_breaks_ties_by_id() -> None: rankings = np.array([[2, 0, 1, 3]], dtype=np.int32) scores = np.array([[0.2, 0.9, 0.9]], dtype=np.float32) reranked = reorder_ranking_prefix(rankings, scores, ["b", "a", "d", "c"]) assert reranked.tolist() == [[1, 0, 2, 3]] def test_static_runner_accepts_telen_base_and_enforces_dependencies() -> None: assert parse_systems("predecessor_dense") == ("predecessor_dense",) with pytest.raises(Exception, match="requires bge_m3"): parse_systems("bge_reranker") def test_alqac_loader_namespaces_reused_query_ids_and_maps_article_qrels( tmp_path: Path, ) -> None: root = _alqac_fixture(tmp_path) dataset = load_alqac_retrieval(root, year="2023") assert dataset.query_ids == ( "ALQAC-2023/public_test_GOLD/reused-id", "ALQAC-2023/private_test_GOLD/reused-id", ) assert dataset.corpus_texts[0].startswith("Luật Mẫu\nĐiều 1") assert dataset.relevant_indices == (frozenset({0}), frozenset({1})) assert dataset.query_metadata[0]["question_type"] == "Tự luận" assert dataset.audit["query_count"] == 2 assert dataset.audit["qrel_count"] == 2 assert dataset.audit["splits"] == list(ALQAC_PRIMARY_TEST_SPLITS["2023"]) def test_alqac_loader_rejects_unverified_and_orphan_qrels(tmp_path: Path) -> None: root = _alqac_fixture(tmp_path) with pytest.raises(ValueError, match="not admissible"): load_alqac_retrieval(root, year="2023", splits=("unverified_train",)) gold = root / "ALQAC_2023/public_test_GOLD.json" payload = json.loads(gold.read_text(encoding="utf-8")) payload[0]["relevant_articles"][0]["article_id"] = "missing" _write_json(gold, payload) with pytest.raises(ValueError, match="missing article"): load_alqac_retrieval( root, year="2023", splits=("public_test_GOLD",), )