File size: 7,041 Bytes
651b674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""A small, reviewable retrieval check; not an estimate of fact extraction F1."""

from __future__ import annotations

import hashlib
import json
from pathlib import Path
from statistics import mean

from .retrieval import DomainRetriever


def _resolve(graph: dict, references: list[dict], case_id: str) -> list[str]:
    result = []
    for reference in references:
        matches = [node["id"] for node in graph["nodes"]
                   if node["kind"] in {"catalog_value", "example"}
                   and node["label"] == reference.get("label")
                   and node["properties"].get("category") == reference.get("category")]
        if len(matches) != 1:
            raise ValueError(f"Benchmark {case_id}: reference must resolve to one node: {reference}")
        result.append(matches[0])
    return list(dict.fromkeys(result))


def evaluate_retrieval(graph: dict, index_path: Path, benchmark_path: Path, limit: int = 5) -> dict:
    """Compare canonical, enriched-text and graph context with the same gold."""
    raw = Path(benchmark_path).read_bytes()
    benchmark = json.loads(raw)
    cases = benchmark.get("cases")
    if not isinstance(cases, list) or not cases:
        raise ValueError("Retrieval benchmark requires a nonempty cases list")
    retriever = DomainRetriever(graph, index_path)
    nodes = {node["id"] for node in graph["nodes"]}
    rows = []
    seen = set()
    identical_hits = True
    identical_content = True
    for case in cases:
        case_id = case.get("id")
        if not isinstance(case_id, str) or not case_id or case_id in seen:
            raise ValueError("Benchmark case IDs must be unique nonempty strings")
        seen.add(case_id)
        expected = _resolve(graph, case.get("expected", []), case_id)
        forbidden = _resolve(graph, case.get("forbidden", []), case_id)
        expected_context = case.get("expected_context", [])
        if not isinstance(expected_context, list) or not set(expected_context) <= nodes:
            raise ValueError(f"Benchmark {case_id}: unknown expected context node")
        unknown_expected = case.get("unknown_expected", not expected)
        if type(unknown_expected) is not bool or unknown_expected != (not expected):
            raise ValueError(f"Benchmark {case_id}: unknown_expected must agree with empty expected nodes")
        row = {
            "id": case_id, "query": case["query"], "category": case.get("category"),
            "tags": case.get("tags", []), "expected_ids": expected,
            "expected_context_ids": expected_context, "unknown_expected": unknown_expected, "modes": {},
        }
        results = {}
        for mode in ("flat", "enriched_flat", "graph"):
            result = retriever.search(case["query"], category=case.get("category"), limit=limit, mode=mode)
            results[mode] = result
            found = [hit["node_id"] for hit in result["hits"]]
            relevant = set(expected) & set(found)
            context_ids = set(result["context"]["node_ids"]) | set(result["context"]["global_rule_ids"])
            row["modes"][mode] = {
                "retrieved_ids": found, "unknown": result["unknown"],
                "node_recall_at_k": len(relevant) / len(expected) if expected else None,
                "node_precision_at_k": len(relevant) / len(found) if expected and found else (0.0 if expected else None),
                "context_coverage": len(set(expected_context) & context_ids) / len(expected_context) if expected_context else None,
                "unknown_false_match": unknown_expected and bool(found),
                "forbidden_hit_ids": sorted(set(forbidden) & set(found)),
                "context_node_count": len(context_ids), "context_edge_count": len(result["context"]["edge_ids"]),
            }
        identical_hits &= results["enriched_flat"]["hits"] == results["graph"]["hits"]
        for key in ("nodes", "global_rules", "sources"):
            identical_content &= results["enriched_flat"]["context"][key] == results["graph"]["context"][key]
        rows.append(row)
    summary = {}
    for mode in ("flat", "enriched_flat", "graph"):
        values = [row["modes"][mode] for row in rows]
        positives = [value for row, value in zip(rows, values) if not row["unknown_expected"]]
        negatives = [value for row, value in zip(rows, values) if row["unknown_expected"]]
        context_scored = [value["context_coverage"] for value in values if value["context_coverage"] is not None]
        summary[mode] = {
            "node_recall_at_k": mean(v["node_recall_at_k"] for v in positives) if positives else None,
            "node_precision_at_k": mean(v["node_precision_at_k"] for v in positives) if positives else None,
            "context_coverage": mean(context_scored) if context_scored else None,
            "unknown_false_match_rate": sum(v["unknown_false_match"] for v in negatives) / len(negatives) if negatives else None,
            "known_query_abstention_rate": sum(v["unknown"] for v in positives) / len(positives) if positives else None,
            "forbidden_hit_cases": sum(bool(v["forbidden_hit_ids"]) for v in values),
            "mean_context_nodes": mean(v["context_node_count"] for v in values),
        }
    return {
        "report_version": "1.0", "graph_id": graph["graph_id"],
        "index_version": retriever.manifest["index_version"], "config_hash": retriever.manifest["config_hash"],
        "benchmark_sha256": hashlib.sha256(raw).hexdigest(), "benchmark_title": benchmark.get("title"),
        "limit": limit, "case_count": len(rows),
        "positive_case_count": sum(not row["unknown_expected"] for row in rows),
        "unknown_case_count": sum(row["unknown_expected"] for row in rows),
        "summary": summary, "cases": rows,
        "comparability": {"identical_enriched_graph_hits": identical_hits, "identical_enriched_graph_context_content": identical_content},
        "limitations": [
            "Небольшой ручной набор проверок каталога; не train/val, не оценка качества извлечения фактов и не репрезентативный ASR-бенчмарк.",
            "flat использует канонические названия. enriched_flat и graph имеют одинаковые кандидаты и текстовый контекст; graph дополнительно передаёт рёбра.",
            "Разница flat и enriched_flat показывает вклад обогащения и подбора контекста. Вклад самой структуры рёбер в качество verifier здесь не измеряется.",
            "Recall считается по заданным целевым узлам; coverage — по отдельно указанным узлам контекста. OOV означает отсутствие уверенного словарного соответствия, а не ложность факта.",
        ],
    }