File size: 10,437 Bytes
6549139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""Builds the published ClaimCheck evaluation dataset.

Every case is run through the live implementation. The dataset carries three
distinct judgements, because they answer three different questions:

  expected_status    what ClaimCheck's documented rules say should happen
  claimcheck_status  what the implementation actually returns
  human_verdict      whether that outcome actually helps a user
                     (acceptable / false_positive / false_negative)

Conflating those is how verifier benchmarks end up flattering themselves. A row
can be perfectly spec-conformant and still be a false positive.
"""
import json, os, sys, time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.dirname(HERE))
import app
from build_cases import C as AUTHORED

OUT_DIR = os.path.join(HERE, "dataset", "data")
os.makedirs(OUT_DIR, exist_ok=True)

HUMAN = {"known_false_positive": "false_positive", "known_false_negative": "false_negative"}

# Corrections applied to generated cases whose label was wrong about the
# documented rules, keyed by focus_value. Each entry states the spec-conformant
# status, the human verdict, and why. These are recorded here rather than edited
# into the cases so the correction is auditable.
OVERRIDES = {
    "meaningfully better": ("not_extracted", "acceptable",
        "Vague prose yields no claim at all; it lowers coverage instead of being scored."),
    "last year": ("not_extracted", "acceptable",
        "Relative dates never become claims: they cannot be resolved without a generation date."),
    "昨年": ("not_extracted", "acceptable",
        "相対表現は claim にならない。counts.relative_date_mentions に計上されるのみ。"),
    "2.": ("not_extracted", "acceptable",
        "List markers at a line start are excluded from numeric extraction."),
    "堅調に推移している": ("not_extracted", "acceptable",
        "A qualitative statement produces no checkable claim; this is what coverage is for."),
    "2023年": ("unsupported", "false_positive",
        "昭和48年 + 創業50周年 = 2023 is correct, but derivation is arithmetic over NUMBERS only - "
        "date arithmetic is not performed, so a correct answer is flagged. The answer-level verdict is retry."),
    'Subscription revenue declined 8% year over year in the second quarter.': ("approximate", "false_negative",
        "grew -> declined is a semantic reversal, but character similarity is 0.97 so the quote reads as a "
        "paraphrase. The answer is still flagged (verdict=retry) because approximate does not count as grounded."),
    "国内売上高は前年同期比で7%減少した": ("approximate", "false_negative",
        "増加 -> 減少 differs by one character, so similarity stays high and the reversal is not called "
        "contradicted. The single most important limitation of character-level matching on Japanese."),
    "anyone still on release 4.2 or older must update without delay": ("unsupported", "false_positive",
        "A faithful paraphrase rewritten word for word falls below the similarity threshold."),
    "サービス障害に起因する間接的な損害について当社は一切の賠償責任を負わない": ("unsupported", "false_positive",
        "意味を保った法務的な言い換えだが、語をほぼ入れ替えているため閾値に届かない。"),
    "service credits apply in any calendar month that falls below 99.9% uptime": ("unsupported", "false_positive",
        "A faithful restatement scoring 0.61: below the approximate threshold, so a correct answer is flagged."),
    "データセンター向けの電力需要は前年度から約12%伸びた": ("contradicted", "false_positive",
        "増えた -> 伸びた は忠実な言い換えだが類似度0.81が approximate 閾値0.82をわずかに下回り、"
        "contradicted の帯に落ちる。閾値境界の典型的な偽陽性。"),
    "We opened 21 new distribution centres in 2025.": ("approximate", "acceptable",
        "The quote status understates it, but the NUMERIC claim 21 inside the quote is unsupported, so the "
        "layered design still flags the answer. Read the claims inside a quote, not only the quote status."),
    "本件は民法第719条に基づく不法行為に当たる": ("approximate", "acceptable",
        "第709条 -> 第719条 は QUOTE では approximate に留まるが、ENTITY 第719条 が contradicted を返すため "
        "多層で捕捉できている。"),
}

cases = []
for c in AUTHORED:
    d = dict(c); d["source"] = "authored"; cases.append(d)
with open(os.path.join(HERE, "workflow_cases.json"), encoding="utf-8") as f:
    for c in json.load(f):
        d = {k: c[k] for k in ("language", "claim_type", "category", "context",
                               "answer", "focus_value", "expected_status", "rationale") if k in c}
        d["source"] = "generated"
        cases.append(d)

# Deduplicate on (context, answer, focus_value).
seen, uniq = set(), []
for c in cases:
    k = (c["context"], c["answer"], c["focus_value"])
    if k in seen:
        continue
    seen.add(k)
    uniq.append(c)
dropped_dupes = len(cases) - len(uniq)
cases = uniq

rows, bad_focus = [], []
for i, c in enumerate(cases):
    cid = "cc-%03d" % i
    focus = c.get("focus_value") or ""
    if focus and focus not in c["answer"]:
        bad_focus.append((cid, focus)); continue

    t0 = time.perf_counter()
    res = app.gate(c["answer"], c["context"], "", "", "", "", "")
    latency = (time.perf_counter() - t0) * 1000.0
    ver = res.get("verify") or {}
    claims = ver.get("claims") or []

    # A literal can be claimed by more than one extractor: a model number inside
    # 「」 is both a QUOTE and an ENTITY. Resolve to the claim type the case is
    # actually about, or the row measures the wrong check.
    actual, evidence, nearest, sim = None, None, None, None
    if focus:
        want = c["claim_type"]
        ordered = ([cl for cl in claims if cl.get("type") == want]
                   + [cl for cl in claims if cl.get("type") != want])
        for cl in ordered:                                  # exact value match
            if cl.get("value") == focus:
                actual, evidence = cl.get("status"), cl.get("evidence")
                nearest, sim = cl.get("nearest_context_value"), cl.get("similarity"); break
        if actual is None:                                  # then containment
            for cl in ordered:
                v = str(cl.get("value") or "")
                if v and (v in focus or focus in v):
                    actual, evidence = cl.get("status"), cl.get("evidence")
                    nearest, sim = cl.get("nearest_context_value"), cl.get("similarity"); break
    if actual is None:
        actual = "not_extracted"

    ov = OVERRIDES.get(focus)
    expected = c["expected_status"]
    human = HUMAN.get(c["category"], "acceptable")
    rationale = c["rationale"]
    if ov:
        expected, human, rationale = ov[0], ov[1], ov[2]

    rows.append({
        "case_id": cid,
        "source": c["source"],
        "language": c["language"],
        "claim_type": c["claim_type"],
        "category": c["category"],
        "context": c["context"],
        "answer": c["answer"],
        "focus_value": focus,
        "expected_status": expected,
        "claimcheck_status": actual,
        "agrees": bool(actual == expected),
        "human_verdict": human,
        "evidence": evidence,
        "nearest_context_value": nearest,
        "similarity": sim,
        "verdict": res.get("verdict"),
        "grounding_score": ver.get("grounding_score"),
        "coverage": ver.get("coverage"),
        "claims_total": (ver.get("counts") or {}).get("claims_total"),
        "sentences_unverified": (ver.get("counts") or {}).get("sentences_unverified"),
        "latency_ms": round(latency, 3),
        "rationale": rationale,
    })

if bad_focus:
    print("DROPPED (focus_value not a substring of answer):", bad_focus)

path = os.path.join(OUT_DIR, "eval.jsonl")
with open(path, "w", encoding="utf-8") as f:
    for r in rows:
        f.write(json.dumps(r, ensure_ascii=False) + "\n")

from collections import Counter
agree = sum(1 for r in rows if r["agrees"])
print("cases=%d (deduped %d) | spec-conformant=%d (%.1f%%)" % (len(rows), dropped_dupes, agree, 100.0*agree/len(rows)))
print("sources:", dict(Counter(r["source"] for r in rows)))
print("languages:", dict(Counter(r["language"] for r in rows)))
print("human_verdict:", dict(Counter(r["human_verdict"] for r in rows)))
print()
print("conformance by claim type:")
for t in ("NUMERIC", "DATE", "QUOTE", "ENTITY", "URL"):
    sub = [r for r in rows if r["claim_type"] == t]
    if sub:
        a = sum(1 for r in sub if r["agrees"])
        print("  %-8s %3d/%3d (%.0f%%)" % (t, a, len(sub), 100.0*a/len(sub)))
print()
print("DISAGREEMENTS (spec label vs implementation):")
for r in rows:
    if not r["agrees"]:
        print("  %-8s %-7s %-8s expected=%-14s actual=%-14s %r" % (
            r["case_id"], r["source"][:7], r["claim_type"], r["expected_status"],
            r["claimcheck_status"], (r["focus_value"] or "")[:30]))
print()
print("ANSWER-LEVEL behaviour (the number that actually matters in production):")
should_flag = [r for r in rows if r["category"] in
               ("hallucinated", "contradicted", "adversarial", "known_false_negative")]
flagged = [r for r in should_flag if r["verdict"] != "pass"]
print("  answers that should be flagged and were: %d/%d (%.0f%%)"
      % (len(flagged), len(should_flag), 100.0*len(flagged)/max(1, len(should_flag))))
clean = [r for r in rows if r["category"] in ("grounded", "derived")]
passed = [r for r in clean if r["verdict"] == "pass"]
print("  clean answers that passed: %d/%d (%.0f%%)  [the rest were annotated, not blocked]"
      % (len(passed), len(clean), 100.0*len(passed)/max(1, len(clean))))
fp = [r for r in rows if r["human_verdict"] == "false_positive"]
fn = [r for r in rows if r["human_verdict"] == "false_negative"]
print("  known false positives: %d (%.1f%% of set) | known false negatives: %d"
      % (len(fp), 100.0*len(fp)/len(rows), len(fn)))

lat = sorted(r["latency_ms"] for r in rows)
print("\nlatency p50=%.2fms p95=%.2fms max=%.2fms" % (lat[len(lat)//2], lat[int(len(lat)*0.95)], lat[-1]))
print("wrote", path)