File size: 11,957 Bytes
a06d854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Measure answer-string coverage and question-query retrieval recall.

These are noisy diagnostics, not answer accuracy: aliases and paraphrases can
be valid when the normalized gold string is absent, while common strings can
occur in irrelevant documents.
"""

from __future__ import annotations

import argparse
import json
import re
import unicodedata
from collections import Counter, defaultdict
from functools import lru_cache
from pathlib import Path
from typing import Any

try:
    from .common import read_jsonl, write_jsonl
    from .corpus_db import connect, fts_counts, fts_exists, search_docids
except ImportError:  # direct script execution
    from common import read_jsonl, write_jsonl
    from corpus_db import connect, fts_counts, fts_exists, search_docids


def normalize_for_match(text: str) -> str:
    decomposed = unicodedata.normalize("NFKD", text or "")
    without_marks = "".join(character for character in decomposed if not unicodedata.combining(character))
    return re.sub(r"[^\w]+", " ", without_marks.casefold(), flags=re.UNICODE).strip()


def is_lexically_evaluable(answer: str) -> bool:
    normalized = normalize_for_match(answer)
    return normalized not in {"yes", "no", "true", "false"} and len(normalized.replace(" ", "")) >= 3


def contains_answer(text: str, answer: str) -> bool:
    needle = normalize_for_match(answer)
    return bool(needle) and needle in normalize_for_match(text)


def provenance_documents(connection, qid: str) -> list[dict[str, Any]]:
    return [
        dict(row)
        for row in connection.execute(
            """
            SELECT d.url_id AS docid, d.canonical_url AS url
            FROM document_qids AS q JOIN documents AS d USING(url_id)
            WHERE q.qid=? AND d.status='success'
            """,
            (qid,),
        )
    ]


def failure_category(source: str, error: str) -> str:
    value = f"{source} {error}".casefold()
    if "robots.txt disallows" in value:
        return "robots_disallowed"
    if "robots.txt" in value:
        return "robots_unavailable_or_invalid"
    if "challenge" in value or "captcha" in value or "security verification" in value:
        return "challenge_or_captcha"
    status = re.search(r"http\s+([45]\d\d)", value)
    if status:
        return f"http_{status.group(1)}"
    if "timeout" in value:
        return "timeout"
    if "too large" in value or "exceeded byte limit" in value:
        return "response_too_large"
    if "unsupported content" in value or "non-text content" in value:
        return "unsupported_or_non_text"
    if "pdf" in value:
        return "pdf_extraction"
    if "extracted only" in value:
        return "too_little_text"
    if "connect" in value or "name or service not known" in value:
        return "connection_or_dns"
    return "other"


def corpus_statistics(connection) -> dict[str, Any]:
    status = dict(connection.execute("SELECT status, count(*) FROM documents GROUP BY status").fetchall())
    sources = dict(
        connection.execute(
            "SELECT source, count(*) FROM documents WHERE status='success' GROUP BY source ORDER BY count(*) DESC"
        ).fetchall()
    )
    content_types = dict(
        connection.execute(
            """
            SELECT content_type, count(*)
            FROM documents
            WHERE status='success'
            GROUP BY content_type
            ORDER BY count(*) DESC
            LIMIT 20
            """
        ).fetchall()
    )
    text = connection.execute(
        """
        SELECT count(*) AS documents, coalesce(sum(length(text)), 0) AS characters,
               count(DISTINCT content_hash) AS unique_hashes
        FROM documents WHERE status='success'
        """
    ).fetchone()
    failure_categories: Counter[str] = Counter()
    failure_details = []
    for row in connection.execute(
        """
        SELECT source, error, count(*) AS count
        FROM documents WHERE status='failed'
        GROUP BY source, error
        ORDER BY count(*) DESC
        """
    ):
        failure_categories[failure_category(row["source"], row["error"])] += row["count"]
        if len(failure_details) < 30:
            failure_details.append(dict(row))
    index_counts = None
    if fts_exists(connection):
        index_counts = fts_counts(connection)
    return {
        "status": status,
        "successful_sources": sources,
        "successful_content_types_top_20": content_types,
        "successful_text_characters": int(text["characters"]),
        "successful_unique_content_hashes": int(text["unique_hashes"]),
        "exact_duplicate_successes_excluded_from_fts": int(text["documents"] - text["unique_hashes"]),
        "fts_documents": index_counts["documents"] if index_counts else None,
        "fts_chunks": index_counts["chunks"] if index_counts else None,
        "failure_categories": dict(failure_categories.most_common()),
        "top_failure_details": failure_details,
    }


def audit(
    database: Path,
    data_paths: list[Path],
    *,
    k: int,
    limit: int = 0,
    only_with_fetched_provenance: bool = False,
) -> tuple[dict, list[dict]]:
    samples = [record for path in data_paths for record in read_jsonl(path)]
    connection = connect(database, readonly=True)

    @lru_cache(maxsize=32768)
    def normalized_document(docid: str) -> str:
        row = connection.execute(
            "SELECT text FROM documents WHERE url_id=? AND status='success'",
            (docid,),
        ).fetchone()
        return normalize_for_match(row["text"]) if row else ""

    provenance_by_qid: defaultdict[str, list[dict[str, Any]]] = defaultdict(list)
    provenance_status_by_qid: defaultdict[str, Counter[str]] = defaultdict(Counter)
    for row in connection.execute(
        """
        SELECT q.qid, d.url_id AS docid, d.canonical_url AS url, d.status
        FROM document_qids AS q JOIN documents AS d USING(url_id)
        """
    ):
        provenance_status_by_qid[row["qid"]][row["status"]] += 1
        if row["status"] == "success":
            provenance_by_qid[row["qid"]].append({"docid": row["docid"], "url": row["url"]})

    input_samples = len(samples)
    if only_with_fetched_provenance:
        fetched_qids = set(provenance_by_qid)
        samples = [
            sample
            for sample in samples
            if (sample["metadata"].get("manifest_qid") or sample["metadata"]["qid"]) in fetched_qids
        ]
    if limit:
        samples = samples[:limit]
    results: list[dict[str, Any]] = []
    aggregate: Counter[str] = Counter()
    by_difficulty: defaultdict[str, Counter[str]] = defaultdict(Counter)

    for sample in samples:
        metadata = sample["metadata"]
        qid = metadata.get("manifest_qid") or metadata["qid"]
        question = metadata["question"]
        answer = metadata.get("answer") or sample.get("label", "")
        evaluable = is_lexically_evaluable(answer)
        normalized_answer = normalize_for_match(answer)
        provenance = provenance_by_qid[qid]
        provenance_status = provenance_status_by_qid[qid]
        provenance_hit = evaluable and any(
            normalized_answer in normalized_document(document["docid"]) for document in provenance
        )
        try:
            retrieved_docids = search_docids(connection, question, k)
        except ValueError:
            retrieved_docids = []
        retrieval_hit = evaluable and any(
            normalized_answer in normalized_document(docid) for docid in retrieved_docids
        )
        result = {
            "qid": metadata["qid"],
            "manifest_qid": qid,
            "difficulty": int(metadata["difficulty"]),
            "lexically_evaluable": evaluable,
            "manifest_provenance_documents": sum(provenance_status.values()),
            "fetched_provenance_documents": len(provenance),
            "failed_provenance_documents": provenance_status["failed"],
            "pending_provenance_documents": provenance_status["pending"],
            "answer_in_fetched_provenance": bool(provenance_hit),
            f"answer_in_question_search_top_{k}": bool(retrieval_hit),
            "retrieved_documents": len(retrieved_docids),
        }
        results.append(result)
        counters = (aggregate, by_difficulty[str(metadata["difficulty"])])
        for counter in counters:
            counter["questions"] += 1
            counter["lexically_evaluable"] += evaluable
            counter["has_manifest_provenance"] += bool(provenance_status)
            counter["has_fetched_provenance"] += bool(provenance)
            counter["answer_in_fetched_provenance"] += provenance_hit
            counter[f"answer_in_question_search_top_{k}"] += retrieval_hit

    def summarize(counter: Counter[str]) -> dict[str, Any]:
        evaluable = counter["lexically_evaluable"]
        return {
            **dict(counter),
            "provenance_answer_coverage": counter["answer_in_fetched_provenance"] / evaluable if evaluable else None,
            f"question_search_recall_at_{k}": counter[f"answer_in_question_search_top_{k}"] / evaluable
            if evaluable
            else None,
        }

    summary = {
        "database": str(database),
        "top_k": k,
        "input_questions": input_samples,
        "selected_questions": len(samples),
        "only_with_fetched_provenance": only_with_fetched_provenance,
        "corpus": corpus_statistics(connection),
        "normalized_document_cache": {
            "hits": normalized_document.cache_info().hits,
            "misses": normalized_document.cache_info().misses,
            "maxsize": normalized_document.cache_info().maxsize,
            "currsize": normalized_document.cache_info().currsize,
        },
        "overall": summarize(aggregate),
        "by_difficulty": {difficulty: summarize(counter) for difficulty, counter in sorted(by_difficulty.items())},
        "interpretation": (
            "Normalized answer-string matching is a noisy proxy, not a lower or upper bound. "
            "It excludes yes/no answers and misses aliases or paraphrases, while common answers can occur incidentally. "
            "Provenance coverage asks whether a fetched teacher-visited page contains the answer; retrieval recall asks whether "
            "the original question retrieves a document containing the answer string. When only_with_fetched_provenance is "
            "true, the report "
            "is a fetch/search smoke test and is selection-biased, not a corpus-wide coverage estimate."
        ),
    }
    connection.close()
    return summary, results


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--database", type=Path, required=True)
    parser.add_argument("--data", type=Path, nargs="+", required=True, help="prepared train/test JSONL")
    parser.add_argument("--top-k", type=int, default=20)
    parser.add_argument("--limit", type=int, default=0)
    parser.add_argument(
        "--only-with-fetched-provenance",
        action="store_true",
        help="biased smoke mode: audit only qids having at least one successfully fetched visited page",
    )
    parser.add_argument("--output-dir", type=Path, required=True)
    args = parser.parse_args()
    if args.top_k < 1 or args.limit < 0:
        parser.error("--top-k must be >= 1 and --limit must be non-negative")
    summary, per_question = audit(
        args.database,
        args.data,
        k=args.top_k,
        limit=args.limit,
        only_with_fetched_provenance=args.only_with_fetched_provenance,
    )
    args.output_dir.mkdir(parents=True, exist_ok=True)
    (args.output_dir / "summary.json").write_text(
        json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )
    write_jsonl(args.output_dir / "per_question.jsonl", per_question)
    print(json.dumps(summary, indent=2, sort_keys=True))


if __name__ == "__main__":
    main()