Guen commited on
Commit
210b340
·
verified ·
1 Parent(s): ad8ea76

Add the deterministic construction pipeline

Browse files
MANIFEST.json CHANGED
@@ -1,117 +1,142 @@
1
  [
2
- {
3
- "path": "benchmark/benchmark_labelled.jsonl",
4
- "bytes": 10395550,
5
- "why": "the benchmark: 8,710 questions with S*/S_dist/S_stale"
6
- },
7
- {
8
- "path": "benchmark/benchmark.jsonl",
9
- "bytes": 5688514,
10
- "why": "pre-label-resolution form (raw QIDs/PIDs)"
11
- },
12
- {
13
- "path": "benchmark/functional_negatives.jsonl",
14
- "bytes": 1244471,
15
- "why": "per-question functional-negative flags"
16
- },
17
- {
18
- "path": "benchmark/labels.tsv",
19
- "bytes": 302669,
20
- "why": "Wikidata QID/PID -> label dump"
21
- },
22
- {
23
- "path": "benchmark/ids.txt",
24
- "bytes": 78703,
25
- "why": "entity/relation ids used"
26
- },
27
- {
28
- "path": "annotation/annotation-guidelines.md",
29
- "bytes": 36022,
30
- "why": "annotation protocol (EN, governing)"
31
- },
32
- {
33
- "path": "annotation/annotation-guidelines-IT.md",
34
- "bytes": 41924,
35
- "why": "annotation protocol (IT translation)"
36
- },
37
- {
38
- "path": "annotation/SAMPLE_MANIFEST.md",
39
- "bytes": 1432,
40
- "why": "validation sample provenance"
41
- },
42
- {
43
- "path": "paper-supplement/appendices-removed-2026-08-20.tex",
44
- "bytes": 3534,
45
- "why": "composability proof + construction detail (cut from the 4pp camera-ready)"
46
- },
47
- {
48
- "path": "paper-supplement/tab-by-operator-removed-2026-08-20.tex",
49
- "bytes": 1505,
50
- "why": "per-operator CCR table (cut for space)"
51
- },
52
- {
53
- "path": "paper-supplement/tab-rank-metrics-removed-2026-08-20.tex",
54
- "bytes": 837,
55
- "why": "rank-aware metrics table (cut for space)"
56
- },
57
- {
58
- "path": "baselines/bm25-anchor.json",
59
- "bytes": 2035818,
60
- "why": "BM25 retrieval baseline, no temporal filter"
61
- },
62
- {
63
- "path": "baselines/bm25-anchor-tfilter.json",
64
- "bytes": 1500755,
65
- "why": "BM25 retrieval baseline, temporally filtered"
66
- },
67
- {
68
- "path": "baselines/bm25-rag-qwen3.json",
69
- "bytes": 2214656,
70
- "why": "vanilla BM25-RAG end-task baseline"
71
- },
72
- {
73
- "path": "baselines/bm25-rag-qwen3-matched.json",
74
- "bytes": 3103444,
75
- "why": "BM25-RAG at matched decode budget"
76
- },
77
- {
78
- "path": "baselines/v2-grpo-10000.json",
79
- "bytes": 562510,
80
- "why": "NO-RETRIEVAL system -- backs the interval-leak proof (overall EM 0.364, interval EM 1.000)"
81
- },
82
- {
83
- "path": "baselines/v3-sft-baseline.extracted.json",
84
- "bytes": 706508,
85
- "why": "2-hop reference generator -- backs the 3+-hop comparison"
86
- },
87
- {
88
- "path": "baselines/v3-sft-3hop.extracted.json",
89
- "bytes": 710446,
90
- "why": "3-hop reference generator -- backs the 3+-hop comparison"
91
- },
92
- {
93
- "path": "baselines/v3-sft-3hop-seed1337.extracted.json",
94
- "bytes": 874163,
95
- "why": "seed replica (3-seed mean +0.051 +- 0.083)"
96
- },
97
- {
98
- "path": "baselines/v3-sft-3hop-seed7.extracted.json",
99
- "bytes": 880864,
100
- "why": "seed replica"
101
- },
102
- {
103
- "path": "baselines/v3-sft-seed1337.extracted.json",
104
- "bytes": 703367,
105
- "why": "seed replica"
106
- },
107
- {
108
- "path": "baselines/v3-sft-seed7.extracted.json",
109
- "bytes": 704595,
110
- "why": "seed replica"
111
- },
112
- {
113
- "path": "v1.0.1-addendum.md",
114
- "bytes": 5252,
115
- "why": "known issues + evaluation protocol; the interval-leak fix the paper cites"
116
- }
117
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  [
2
+ {
3
+ "path": "benchmark/benchmark_labelled.jsonl",
4
+ "bytes": 10395550,
5
+ "why": "the benchmark: 8,710 questions with S*/S_dist/S_stale"
6
+ },
7
+ {
8
+ "path": "benchmark/benchmark.jsonl",
9
+ "bytes": 5688514,
10
+ "why": "pre-label-resolution form (raw QIDs/PIDs)"
11
+ },
12
+ {
13
+ "path": "benchmark/functional_negatives.jsonl",
14
+ "bytes": 1244471,
15
+ "why": "per-question functional-negative flags"
16
+ },
17
+ {
18
+ "path": "benchmark/labels.tsv",
19
+ "bytes": 302669,
20
+ "why": "Wikidata QID/PID -> label dump"
21
+ },
22
+ {
23
+ "path": "benchmark/ids.txt",
24
+ "bytes": 78703,
25
+ "why": "entity/relation ids used"
26
+ },
27
+ {
28
+ "path": "annotation/annotation-guidelines.md",
29
+ "bytes": 36022,
30
+ "why": "annotation protocol (EN, governing)"
31
+ },
32
+ {
33
+ "path": "annotation/annotation-guidelines-IT.md",
34
+ "bytes": 41924,
35
+ "why": "annotation protocol (IT translation)"
36
+ },
37
+ {
38
+ "path": "annotation/SAMPLE_MANIFEST.md",
39
+ "bytes": 1432,
40
+ "why": "validation sample provenance"
41
+ },
42
+ {
43
+ "path": "paper-supplement/appendices-removed-2026-08-20.tex",
44
+ "bytes": 3534,
45
+ "why": "composability proof + construction detail (cut from the 4pp camera-ready)"
46
+ },
47
+ {
48
+ "path": "paper-supplement/tab-by-operator-removed-2026-08-20.tex",
49
+ "bytes": 1505,
50
+ "why": "per-operator CCR table (cut for space)"
51
+ },
52
+ {
53
+ "path": "paper-supplement/tab-rank-metrics-removed-2026-08-20.tex",
54
+ "bytes": 837,
55
+ "why": "rank-aware metrics table (cut for space)"
56
+ },
57
+ {
58
+ "path": "code/README.md",
59
+ "bytes": 3104,
60
+ "why": "how to run the pipeline; what is and is not included"
61
+ },
62
+ {
63
+ "path": "code/benchmark-design-decisions.md",
64
+ "bytes": 12976,
65
+ "why": "formal operator semantics and design rationale not in the paper"
66
+ },
67
+ {
68
+ "path": "code/build_benchmark.py",
69
+ "bytes": 41785,
70
+ "why": "the 6-stage deterministic construction pipeline"
71
+ },
72
+ {
73
+ "path": "code/indexer.py",
74
+ "bytes": 17603,
75
+ "why": "Triple / ValidityWindow / TemporalKGIndexer -- the foundation every stage imports"
76
+ },
77
+ {
78
+ "path": "code/resolve_labels.py",
79
+ "bytes": 15074,
80
+ "why": "Wikidata QID/PID -> human-readable label resolution"
81
+ },
82
+ {
83
+ "path": "baselines/bm25-anchor.json",
84
+ "bytes": 2035818,
85
+ "why": "BM25 retrieval baseline, no temporal filter"
86
+ },
87
+ {
88
+ "path": "baselines/bm25-anchor-tfilter.json",
89
+ "bytes": 1500755,
90
+ "why": "BM25 retrieval baseline, temporally filtered"
91
+ },
92
+ {
93
+ "path": "baselines/bm25-rag-qwen3.json",
94
+ "bytes": 2214656,
95
+ "why": "vanilla BM25-RAG end-task baseline"
96
+ },
97
+ {
98
+ "path": "baselines/bm25-rag-qwen3-matched.json",
99
+ "bytes": 3103444,
100
+ "why": "BM25-RAG at matched decode budget"
101
+ },
102
+ {
103
+ "path": "baselines/v2-grpo-10000.json",
104
+ "bytes": 562510,
105
+ "why": "NO-RETRIEVAL system -- backs the interval-leak proof (overall EM 0.364, interval EM 1.000)"
106
+ },
107
+ {
108
+ "path": "baselines/v3-sft-baseline.extracted.json",
109
+ "bytes": 706508,
110
+ "why": "2-hop reference generator -- backs the 3+-hop comparison"
111
+ },
112
+ {
113
+ "path": "baselines/v3-sft-3hop.extracted.json",
114
+ "bytes": 710446,
115
+ "why": "3-hop reference generator -- backs the 3+-hop comparison"
116
+ },
117
+ {
118
+ "path": "baselines/v3-sft-3hop-seed1337.extracted.json",
119
+ "bytes": 874163,
120
+ "why": "seed replica (3-seed mean +0.051 +- 0.083)"
121
+ },
122
+ {
123
+ "path": "baselines/v3-sft-3hop-seed7.extracted.json",
124
+ "bytes": 880864,
125
+ "why": "seed replica"
126
+ },
127
+ {
128
+ "path": "baselines/v3-sft-seed1337.extracted.json",
129
+ "bytes": 703367,
130
+ "why": "seed replica"
131
+ },
132
+ {
133
+ "path": "baselines/v3-sft-seed7.extracted.json",
134
+ "bytes": 704595,
135
+ "why": "seed replica"
136
+ },
137
+ {
138
+ "path": "v1.0.1-addendum.md",
139
+ "bytes": 5252,
140
+ "why": "known issues + evaluation protocol; the interval-leak fix the paper cites"
141
+ }
142
+ ]
README.md CHANGED
@@ -57,6 +57,7 @@ negative-dependent evaluation to the functional subset.
57
  | `benchmark/benchmark.jsonl` | same, pre-label-resolution (raw QIDs/PIDs) |
58
  | `benchmark/functional_negatives.jsonl` | per-question functional-negative flags |
59
  | `benchmark/labels.tsv`, `ids.txt` | Wikidata label dump and id list |
 
60
  | `annotation/` | the annotation protocol (EN governing, IT translation) and validation-sample provenance |
61
  | `baselines/` | reference-baseline evaluation outputs (see below) |
62
  | `paper-supplement/` | material cut from the 4-page camera-ready: the composability closed-form proof, construction details, and two tables |
@@ -127,6 +128,5 @@ This matches the paper itself, which is published open access under CC BY.
127
  }
128
  ```
129
 
130
- Dataset DOI: `DOI-TODO` — request one from the repository Settings after the first
131
- push, then update this line, the paper's `tempbench-data` bib entry, and the
132
- `v1.0.1-addendum.md` header, which still names the old DOI.
 
57
  | `benchmark/benchmark.jsonl` | same, pre-label-resolution (raw QIDs/PIDs) |
58
  | `benchmark/functional_negatives.jsonl` | per-question functional-negative flags |
59
  | `benchmark/labels.tsv`, `ids.txt` | Wikidata label dump and id list |
60
+ | `code/` | the **deterministic construction pipeline** — indexer, 6-stage benchmark builder, label resolver, and the design-decisions document. Stdlib only; `python build_benchmark.py --smoke_test` verifies it |
61
  | `annotation/` | the annotation protocol (EN governing, IT translation) and validation-sample provenance |
62
  | `baselines/` | reference-baseline evaluation outputs (see below) |
63
  | `paper-supplement/` | material cut from the 4-page camera-ready: the composability closed-form proof, construction details, and two tables |
 
128
  }
129
  ```
130
 
131
+ Dataset DOI: [`10.57967/hf/10071`](https://doi.org/10.57967/hf/10071)
132
+ (revision `ad8ea76`).
 
code/README.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TempBench construction pipeline
2
+
3
+ The deterministic pipeline that builds TempBench from a temporal knowledge graph.
4
+ This is the code behind the paper's claim that construction is *algorithmic and
5
+ reproducible*, not LLM-generated: given the same source KG and the same seed, it
6
+ reproduces the released benchmark.
7
+
8
+ ## Contents
9
+
10
+ | file | what it does |
11
+ | --- | --- |
12
+ | `indexer.py` | The foundation. `Triple`, `ValidityWindow`, and `TemporalKGIndexer` (entity index + interval tree). Every other file imports it. Loads the TGB 2.0 `tkgl-smallpedia` CSV format. |
13
+ | `build_benchmark.py` | The 6-stage construction pipeline: chain sampling → operator expansion → composability filter → answer-uniqueness filter → MinHash dedup → stratified split, then gold/distractor/stale subgraph construction. |
14
+ | `resolve_labels.py` | Rewrites Wikidata QIDs/PIDs into human-readable labels. Two modes: API (rate-limited) and offline dump. |
15
+ | `benchmark-design-decisions.md` | The formal operator semantics and the design choices the paper does not have room to state. Read this before extending the generator. |
16
+
17
+ ## What is *not* here
18
+
19
+ This directory is the **construction pipeline only**. The reference-baseline
20
+ systems evaluated in the paper are not included; their evaluation outputs ship
21
+ in `../baselines/` and every number in the paper is re-derivable from those.
22
+
23
+ The source KG is **not redistributed**. `tkgl-smallpedia` comes from
24
+ [TGB 2.0](https://arxiv.org/abs/2406.09639) — download
25
+ `tkgl-smallpedia_edgelist.csv` from TGB and point `--kg_path` at it. (550,376
26
+ quadruples, 47,433 entities, 283 relations, 1900–2024.)
27
+
28
+ ## Running it
29
+
30
+ No dependencies beyond the Python standard library. Tested on Python 3.11+.
31
+
32
+ Verify the install with the built-in smoke test, which runs on a synthetic
33
+ 5-triple graph and needs no data:
34
+
35
+ ```bash
36
+ python build_benchmark.py --smoke_test
37
+ ```
38
+
39
+ Then build the benchmark:
40
+
41
+ ```bash
42
+ # 1. Construct. target_n is the pre-filter target; the composability,
43
+ # uniqueness and dedup stages reduce 10,000 -> the released 8,710.
44
+ python build_benchmark.py \
45
+ --kg_path /path/to/tkgl-smallpedia_edgelist.csv \
46
+ --output_dir ./out/ \
47
+ --target_n 10000 --seed 42
48
+
49
+ # 2. Resolve QIDs/PIDs to labels. Dump mode is offline and preferred;
50
+ # the fetch step is the only part that needs network access.
51
+ python resolve_labels.py --collect_ids ./out/benchmark.jsonl \
52
+ --id_output ./out/ids.txt
53
+ python resolve_labels.py --fetch_dump ./out/ids.txt \
54
+ --dump_output ./out/labels.tsv
55
+ python resolve_labels.py --input ./out/benchmark.jsonl \
56
+ --label_dump ./out/labels.tsv \
57
+ --output ./out/benchmark_labelled.jsonl
58
+ ```
59
+
60
+ Step 2 is optional — the benchmark is usable on raw QIDs, which is what you want
61
+ if you are running air-gapped.
62
+
63
+ `--seed 42` is the released configuration. The pipeline is deterministic: the
64
+ only nondeterminism is the seed, and label resolution depends on the Wikidata
65
+ dump you fetch (we ship ours as `../benchmark/labels.tsv`, so use that for an
66
+ exact match).
67
+
68
+ ## Licence
69
+
70
+ CC BY 4.0, same as the rest of TempBench. See the top-level `README.md`.
code/benchmark-design-decisions.md ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TempBench — Benchmark Generator Design Decisions
2
+
3
+ This document records the design choices made while implementing `build_benchmark.py` where the TempBench paper leaves the spec open.
4
+
5
+ Treat this as the source of truth for §5 formal semantics. Anything the paper states verbatim wins; everything below fills gaps.
6
+
7
+ ## 1. Operator semantics
8
+
9
+ The paper commits to four operator types from the TimelineKGQA taxonomy and gives one natural-language example per operator. It does not give formal semantics, a template grammar, or answer-type definitions. Concrete choices:
10
+
11
+ ### 1.1 Point-in-time (PIT)
12
+
13
+ - Paper example: *"Who held role X at time T?"*
14
+ - **Formal semantics**: Given an anchor entity `e_0`, a relation path `(r_1, r_2, ..., r_n)`, and a query time `t_q`, the answer is the terminal object `o_n` reached by walking the chain where each hop is valid at `t_q`.
15
+ - **Template surface**: `"In {year}, what was the {r_n} of {e_0}'s {r_1}'s ... 's {r_{n-1}}?"` (and two surface variants rotating the `{year}` position).
16
+ - **Answer type**: entity.
17
+ - **Complexity**: supports 1-hop, 2-hop, 3+-hop.
18
+
19
+ ### 1.2 Before/after (BA)
20
+
21
+ - Paper example: *"Which entity held role X before entity Y did?"*
22
+ - **Formal semantics**: Same compositional chain as PIT, but the temporal anchor is *not* `t_q` — it is a **sibling fact** elsewhere in the KG. Given chain `C` ending at `o_n` at time `t_a`, a valid BA candidate requires a sibling triple `(penultimate_entity, r_n, sibling_entity, t_ref)` with `t_ref ≠ t_a`. The question asks for `o_n` positioned relative to `sibling_entity`.
23
+ - **Template surface**: `"Who was the {r_n} of {e_0}'s {r_1}'s ... before/after {sibling_entity}?"`. `"before"` when `t_a < t_ref`, `"after"` when `t_a > t_ref`.
24
+ - **Answer type**: entity.
25
+ - **Complexity**: supports 1-hop, 2-hop, 3+-hop. Yield will be lower than PIT — requires a sibling to exist.
26
+ - **Divergence from paper example**: paper's example is 1-hop; we extend to multi-hop by keeping the composition intact and attaching the temporal qualifier to the terminal hop.
27
+
28
+ ### 1.3 Interval (INT)
29
+
30
+ - Paper example: *"During which period did X hold role Y?"*
31
+ - **Known limitation**: `tkgl-smallpedia` is a point-in-time TKG — 100% of triples have `t_start == t_end`. True *period* questions are not expressible.
32
+ - **Operational redefinition**: Ask for the **year** at which a composed chain resolves to a specified terminal. Equivalent to a "when did this hold?" question on a point-in-time KG.
33
+ - **Template surface**: `"In what year was the {r_n} of {e_0}'s {r_1}'s ... equal to {terminal}?"`.
34
+ - **Answer type**: integer year.
35
+ - **Complexity**: supports 1-hop, 2-hop, 3+-hop.
36
+ - **Divergence**: the paper's §5.1 wording ("During which period") has been softened to "In what year did X hold role Y?" to match the benchmark's point-in-time answer type. Resolved 2026-04-23; a footnote at §5.1 now explains the reason for deviating from TimelineKGQA's original phrasing.
37
+
38
+ ### 1.4 Sequence (SEQ)
39
+
40
+ - Paper example: *"What happened to X after event Y?"*
41
+ - §6.5 case study: *"Who led the organisation that acquired [Company X] after [Company X]'s CEO resigned?"*
42
+ - **Formal semantics**: Composed chain ending at `o_n` at time `t_a`, paired with a **reference triple** `(s_ref, r_ref, o_ref, t_ref)` elsewhere in the KG where `t_ref < t_a` (for "after") or `t_ref > t_a` (for "before" phrasing — included under SEQ when the qualifier is an event, versus BA when the qualifier is a sibling entity).
43
+ - **Template surface**: `"After {s_ref} {r_ref} {o_ref}, what was the {r_n} of {e_0}'s {r_1}'s ...?"`.
44
+ - **Answer type**: entity.
45
+ - **Complexity**: supports 1-hop, 2-hop, 3+-hop. Requires a reference triple to exist at an earlier time.
46
+ - **Difference from BA**: BA's temporal anchor is an **entity** (another holder of the same terminal relation); SEQ's is a **triple** (an arbitrary earlier event). Mechanically they are siblings in the code.
47
+
48
+ ## 2. 12-cell distribution
49
+
50
+ Paper §5.2 commits to "all 12 combinations of complexity level × operator type" but gives counts only at the complexity level (`4,000 / 4,000 / 2,000`). Per-cell counts are unspecified.
51
+
52
+ **Chosen distribution** (target):
53
+
54
+ | Operator | 1-hop | 2-hop | 3+-hop |
55
+ |---|---|---|---|
56
+ | Point-in-time | 1,000 | 1,000 | 500 |
57
+ | Before/after | 1,000 | 1,000 | 500 |
58
+ | Interval | 1,000 | 1,000 | 500 |
59
+ | Sequence | 1,000 | 1,000 | 500 |
60
+ | **Total** | **4,000** | **4,000** | **2,000** |
61
+
62
+ Even allocation by operator within each complexity bucket. If any cell under-yields (BA and SEQ depend on sibling/reference availability), we top up with PIT in that complexity bucket — 10K total takes priority over perfect operator balance.
63
+
64
+ ## 3. Answer uniqueness
65
+
66
+ Paper §5.2 Step 4: *"filtered by answer uniqueness (removing ambiguous questions with multiple valid answers at `t_q`)"*. Scope is unspecified.
67
+
68
+ - **Chosen semantics**: Uniqueness applies to the **terminal answer only**. A candidate is retained iff, given the specific `e_0` and the first `n-1` hops of the gold chain, the final `(penultimate_entity, r_n)` pair has exactly one valid object at `t_q`.
69
+ - Intermediate-hop fan-out is **permitted**: if `e_0` has multiple valid `r_1` edges, those still enter the pool as separate chains, and each is independently checked for terminal uniqueness.
70
+ - **For INT questions**: uniqueness means the composed chain holds at exactly one discrete year in the KG. If the same terminal appears at two or more years via the same chain, the candidate is dropped.
71
+
72
+ ## 4. Subgraph construction
73
+
74
+ Paper §5.2 Step 5 provides only loose descriptions; the critical terms ("semantically similar", `Δt`) are not formalised.
75
+
76
+ - **`S_star`**: the gold chain itself, serialised as a list of triples in hop order. Unambiguous.
77
+ - **`S_dist`** ("semantically similar but incorrect"): one hop replaced by a triple sharing the same `(subject, relation)` but a different object, at **any** validity window. Rationale: this produces a factually-wrong-for-`t_q` alternative that would be indistinguishable from the gold triple without temporal reasoning — i.e., the exact failure mode the paper is trying to diagnose.
78
+ - **`S_stale`** ("temporally adjacent version"): one hop replaced by a triple with the **same** `(subject, relation, object)` but a different `t_start` that is not valid at `t_q`. The nearest such neighbour by `|t - t_q|` is preferred when multiple exist; no explicit `Δt` threshold is enforced.
79
+ - **Failure mode**: for ~25–45% of multi-hop candidates, no `S_dist` alternative exists in the KG (the `(s, r)` pair has exactly one object across all time). Those questions ship with `S_dist == S_star`; annotation guidelines should flag them as "distractor not available".
80
+
81
+ ## 5. Chain generation guards
82
+
83
+ Not spec'd in the paper; chosen to keep questions non-degenerate.
84
+
85
+ - **Forward-only chain walk**: each hop must have `triple.subject == current_entity`. The `entity_index` in [code/indexer.py](code/indexer.py) is double-keyed by subject and object, so without this guard the walk becomes an undirected traversal and produces non-chains.
86
+ - **Cycle guard**: no intermediate entity may be revisited within a single chain. This is stricter than the minimum needed (only cycles that return to the anchor produce tautological questions) but keeps all chain entities distinct, which simplifies the subgraph semantics.
87
+ - **Adjacent-relation guard**: two *adjacent* hops may not share a relation. This is the relaxed form of the earlier "no repeated relation anywhere" rule — non-adjacent repeats (e.g. `r_1, r_2, r_1`) are legitimate compositional patterns and are kept.
88
+
89
+ ## 6. Known deviations from paper wording
90
+
91
+ Recorded here so the `.tex` can be aligned in a single pass before submission.
92
+
93
+ 1. ~~§5.1 says *"During which period did X hold role Y?"* for interval. The benchmark produces year-level answers, not periods. Suggested rewording: *"In what year did X hold role Y?"*.~~ **Resolved 2026-04-23.** Step-9 section draft updated; a footnote at §5.1 explains the deviation from TimelineKGQA's original phrasing. The `.tex` operator list does not include example phrasings, so no `.tex` edit was needed.
94
+ 2. §5.1 examples are 1-hop for all four operators. The benchmark extends each operator to 1/2/3+hop; the paper should add a sentence: *"Each operator is generated across all three complexity levels via compositional extension (§5.2)."*.
95
+ 3. The paper's abstract and §1 advertise "10,000 questions"; the current run lands close but not exactly on 10,000 due to yield variability. The exact count should be taken from the shipped `benchmark.jsonl` and written into the `.tex` at camera-ready.
96
+
97
+ ## 7. Revisiting these choices
98
+
99
+ Any of the decisions in §1–§5 can be overridden by:
100
+ - A firmer commitment in a new paper revision (then adjust code to match).
101
+ - A discovered inconsistency with the TimelineKGQA original (then take TimelineKGQA's exact wording).
102
+
103
+ Sections 6.1 and 6.2 are the most likely to change at reviewer request.
104
+
105
+ ## 8. As-built distribution (run of 2026-04-19)
106
+
107
+ Running `build_benchmark.py` at `target_n=10000, seed=42` against [code/data/tkgl-smallpedia_edgelist.csv](code/data/tkgl-smallpedia_edgelist.csv) yields 8,710 questions:
108
+
109
+ | Complexity | PIT | BA | INT | SEQ | Row total | Paper target |
110
+ |---|---|---|---|---|---|---|
111
+ | 1hop | 1,349 | 1,135 | 403 | 1,113 | **4,000** | 4,000 ✓ |
112
+ | 2hop | 1,259 | 1,065 | 435 | 1,241 | **4,000** | 4,000 ✓ |
113
+ | 3plus | 274 | 131 | 26 | 279 | **710** | 2,000 ✗ |
114
+ | **Column** | 2,882 | 2,331 | 864 | 2,633 | **8,710** | 10,000 |
115
+
116
+ Quality: 100% correct chain structure, 0.1% answer-in-question (noise-level), 71.5% of multi-hop candidates have a constructed `S_dist`, 81.3% have `S_stale`. Wikidata label coverage 99.4% (53 QIDs unresolved, fall back to raw IDs).
117
+
118
+ ### Why 3+hop falls short
119
+
120
+ tkgl-smallpedia is 100% point-in-time — every triple has `t_start == t_end`. A 3+hop chain requires every hop to be valid at the same exact year, not merely overlap a window. Year-density of related facts around a given anchor entity is typically 0–3 per year, so 3-hop and 4-hop chains that also pass uniqueness and adjacent-relation filters are genuinely rare. Additional attempt-budget does not help beyond ~710; the structural cap is roughly the count of shortest year-constrained 3-paths that share an anchor.
121
+
122
+ ### Options for closing the 3+hop gap
123
+
124
+ 1. **Edit §5.1/Table tab:bench-stats to 710 (or omit the 2,000 target)**. Honest, simple; reduces the paper's multi-hop headline claim.
125
+ 2. **Switch KG to one with interval or open-ended facts** (ICEWS, YAGO3, the temporal slice of Freebase). Breaks the tkgl-smallpedia commitment in §3 and requires re-running the indexer against a new schema.
126
+ 3. **Allow multi-year windowing for 3+hop chains** (e.g. each hop must be valid at `t_query ± 2 years`). Would ~10× the yield but weakens the temporal semantics — each hop is then only approximately at `t_query`, which the paper's §4 ⊕ operator doesn't formally permit.
127
+ 4. **Accept the 710 count, spend the delta on 1hop/2hop** (paper stays at 10K headline, 3+hop is a smaller evaluation slice). The stratified trim already does this implicitly — 1hop and 2hop are at target, 3+hop is at its ceiling.
128
+
129
+ ### Decision (2026-04-23): Option 1, reframed as a finding
130
+
131
+ **Chosen:** Option 1 with the 3+hop shortfall framed as a structural property of point-in-time multi-hop QA on Wikidata rather than a pipeline failure. New §5.4 "Structural Yield of Point-in-Time Multi-Hop QA" in the `.tex` reports ~710 as the structural ceiling.
132
+
133
+ **Why Option 1, not 2/3/4:**
134
+ - Option 2 (switch KG) was not feasible in the time remaining.
135
+ - Option 3 (multi-year windowing) would weaken the paper's core theoretical contribution — the ⊕ operator's strict timestamp-consistency semantics.
136
+ - Option 4 (inflate 1hop/2hop to hit 10K) looks like gaming the target; asymmetric inflation to hit a round number is exactly what reviewers catch.
137
+
138
+ **Bonus fix rolled into the same pass.** The shipped jsonl has **zero** `implicit` question_type entries — the code in `build_benchmark.py` labels `point_in_time → explicit` and BA/INT/SEQ all as `ordinal`, so the paper's old "3.5K / 3.5K / 3K" question-type row was always misrepresenting reality. The three-way question-type split was dropped entirely from Table 2 in favour of the operator × complexity matrix the paper's §4 is actually built on. This simultaneously resolves Deviation #1 and the question_type mislabelling.
139
+
140
+ **Deviation #2 (§5.1 examples being 1-hop only) resolution:** the rewritten §5.1 spanning sentence now names "the 12-cell operator × complexity matrix reported in Table~\ref{tab:bench-stats}", which makes the multi-hop extension explicit without needing separate worked examples per operator × complexity cell.
141
+
142
+ **Deviation #3 resolution:** all instances of "10K" / "10,000" in abstract, contributions list, §5.2 Step 4, Table 3 row, and appendix pointer now read "8,710" or "8.7K".
code/build_benchmark.py ADDED
@@ -0,0 +1,1151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TempBench Builder
3
+ ==========================
4
+ Constructs a 10K-question multi-hop temporal QA benchmark (see the TempBench paper).
5
+
6
+ Implements the full 6-stage pipeline:
7
+ 1. Question generation from KG triples and templates
8
+ 2. Composability filtering (validate temporal consistency)
9
+ 3. Answer uniqueness filtering (discard ambiguous questions)
10
+ 4. MinHash deduplication (Jaccard similarity threshold)
11
+ 5. Subgraph construction (S_star, S_dist, S_stale)
12
+ 6. Train/dev/test split (stratified by complexity)
13
+
14
+ Output: JSONL benchmark with one question per line, including supporting subgraphs.
15
+
16
+ Usage:
17
+ python build_benchmark.py --kg_path kg.json --output_dir ./benchmark/ --target_n 10000
18
+
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import hashlib
25
+ import json
26
+ import math
27
+ import random
28
+ import sys
29
+ from collections import defaultdict
30
+ from dataclasses import dataclass, asdict
31
+ from pathlib import Path
32
+ from typing import Dict, List, Optional, Set, Tuple
33
+
34
+ from indexer import (
35
+ TemporalKGIndexer,
36
+ Triple,
37
+ ValidityWindow,
38
+ )
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Question generation templates
42
+ # ---------------------------------------------------------------------------
43
+
44
+ QUESTION_TEMPLATES = {
45
+ # The TempBench paper cites the TimelineKGQA taxonomy for four operator types.
46
+ # Each operator takes a compositional chain "path" (= anchor + hop
47
+ # relations, joined by "'s") and attaches an operator-specific temporal
48
+ # qualifier. See benchmark-design-decisions.md §1 for semantics.
49
+ "point_in_time": [
50
+ "In {year}, what was the {final_relation} of {path}?",
51
+ "What was the {final_relation} of {path} in {year}?",
52
+ "{path}'s {final_relation} in {year} was?",
53
+ ],
54
+ "before_after": [
55
+ "Who was the {final_relation} of {path} {qualifier} {sibling}?",
56
+ "{qualifier_cap} {sibling}, who was the {final_relation} of {path}?",
57
+ ],
58
+ "interval": [
59
+ "In what year was the {final_relation} of {path} equal to {terminal}?",
60
+ "When was {terminal} the {final_relation} of {path}?",
61
+ ],
62
+ "sequence": [
63
+ "After {ref_subject} {ref_relation} {ref_object}, what was the {final_relation} of {path}?",
64
+ "What was the {final_relation} of {path} after {ref_subject} {ref_relation} {ref_object}?",
65
+ ],
66
+ }
67
+
68
+
69
+ def _render_composition_path(anchor: str, relations: List[str]) -> str:
70
+ """
71
+ Render the nested possessive prefix for compositional multi-hop questions.
72
+
73
+ Example:
74
+ anchor = "Obama", relations = ["spouse", "country"]
75
+ returns: "Obama's spouse's country"
76
+ Used as the {path} placeholder for the last-but-one hop; the final
77
+ relation becomes the {final_relation} placeholder.
78
+ """
79
+ parts = [anchor] + relations
80
+ return "'s ".join(parts)
81
+
82
+ # ---------------------------------------------------------------------------
83
+ # Data structures
84
+ # ---------------------------------------------------------------------------
85
+
86
+ @dataclass
87
+ class Candidate:
88
+ """An intermediate candidate question before filtering."""
89
+ id: str
90
+ question: str
91
+ t_query: float
92
+ answer: str
93
+ complexity: str # "1hop", "2hop", "3plus"
94
+ operator_type: str # "point_in_time", "before_after", "interval", "sequence"
95
+ question_type: str # "explicit", "implicit", "ordinal"
96
+ gold_chain: List[Triple]
97
+
98
+
99
+ @dataclass
100
+ class BenchmarkQuestion:
101
+ """A final, fully-validated benchmark question."""
102
+ id: str
103
+ question: str
104
+ t_query: float
105
+ answer: str
106
+ complexity: str
107
+ operator_type: str
108
+ question_type: str
109
+ S_star: List[Dict] # Gold chain
110
+ S_dist: List[Dict] # Distractor chain
111
+ S_stale: List[Dict] # Stale-fact chain
112
+ split: str # "train", "dev", "test"
113
+
114
+ def to_jsonl_dict(self) -> Dict:
115
+ """Convert to dict for JSONL serialization."""
116
+ return {
117
+ "id": self.id,
118
+ "question": self.question,
119
+ "t_query": self.t_query,
120
+ "answer": self.answer,
121
+ "complexity": self.complexity,
122
+ "operator_type": self.operator_type,
123
+ "question_type": self.question_type,
124
+ "S_star": self.S_star,
125
+ "S_dist": self.S_dist,
126
+ "S_stale": self.S_stale,
127
+ "split": self.split,
128
+ }
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Stage 1: Question generation (fallback mode)
133
+ # ---------------------------------------------------------------------------
134
+
135
+ class QuestionGenerator:
136
+ """
137
+ Generates candidate questions from KG triples using templates.
138
+ Fallback mode when TimelineKGQA is not available.
139
+ """
140
+
141
+ def __init__(self, indexer: TemporalKGIndexer, seed: int = 42):
142
+ self.indexer = indexer
143
+ self.rng = random.Random(seed)
144
+ self.triples = indexer._all_triples
145
+ self.candidate_id_counter = 0
146
+ # Collect all actual timestamps for point-in-time TKGs (t_start == t_end)
147
+ self._timestamps: List[float] = sorted(
148
+ {t.t_start for t in self.triples}
149
+ )
150
+ # tkgl-smallpedia is 100% point-in-time; multi-hop chains need every
151
+ # hop at exactly the same year. Pre-index (subject, year) → triples
152
+ # so the 2-hop and 3+-hop samplers can forward-chain in O(bucket_size)
153
+ # instead of O(entity_degree across all years).
154
+ self._subject_year: Dict[str, Dict[float, List[Triple]]] = defaultdict(
155
+ lambda: defaultdict(list)
156
+ )
157
+ for t in self.triples:
158
+ self._subject_year[t.subject][t.t_start].append(t)
159
+ self._subjects_with_outgoing: List[str] = list(self._subject_year.keys())
160
+
161
+ # --- Public entry point ---------------------------------------------
162
+
163
+ def generate_candidates(
164
+ self,
165
+ target_candidates: int = 40000,
166
+ min_depth: int = 1,
167
+ max_depth: int = 4,
168
+ ) -> List[Candidate]:
169
+ """
170
+ Generate candidates across the 12-cell matrix (3 complexity levels ×
171
+ 4 temporal operator types). Target per cell is an even split of the
172
+ per-complexity budget (4K/4K/2K per the TempBench paper).
173
+
174
+ Implementation: sample chains per complexity, and for each chain try
175
+ each of the four operator builders. PIT and INT succeed for almost
176
+ every chain; BA requires a sibling fact and SEQ requires an earlier
177
+ reference triple, so those buckets yield less per chain.
178
+ """
179
+ # The TempBench paper commits to 4000 / 4000 / 2000 at target_n = 10000.
180
+ # Scale proportionally to target_candidates (= 4 × target_n from the
181
+ # BenchmarkBuilder).
182
+ per_complexity = {
183
+ "1hop": target_candidates // 10, # 40% of target_n
184
+ "2hop": target_candidates // 10, # 40% of target_n
185
+ "3plus": target_candidates // 20, # 20% of target_n
186
+ }
187
+ # 3× oversample to absorb Stage 3/4 attrition (uniqueness + dedup).
188
+ pool_per_complexity = {k: v * 3 for k, v in per_complexity.items()}
189
+ operators = ["point_in_time", "before_after", "interval", "sequence"]
190
+
191
+ candidates: List[Candidate] = []
192
+ for complexity, pool_target in pool_per_complexity.items():
193
+ sampler = {
194
+ "1hop": lambda n: self._sample_1hop_chains(n),
195
+ "2hop": lambda n: self._sample_2hop_chains(n),
196
+ "3plus": lambda n: self._sample_3plus_chains(n, max_depth),
197
+ }[complexity]
198
+ # Each chain can produce up to len(operators) candidates, so we
199
+ # only need pool_target / len(operators) chains — but many
200
+ # BA/SEQ attempts fail, so keep a healthy buffer.
201
+ chains = sampler(pool_target // 2)
202
+ for chain, t_query in chains:
203
+ for op in operators:
204
+ cand = self._build_operator_candidate(
205
+ op, chain, t_query, complexity
206
+ )
207
+ if cand is not None:
208
+ candidates.append(cand)
209
+
210
+ self.rng.shuffle(candidates)
211
+ return candidates
212
+
213
+ # --- Chain samplers (return chain + t_query, no templating) ---------
214
+
215
+ def _sample_1hop_chains(
216
+ self, target_count: int
217
+ ) -> List[Tuple[List[Triple], float]]:
218
+ chains = []
219
+ sampled = self.rng.sample(
220
+ self.triples, min(len(self.triples), target_count)
221
+ )
222
+ for t in sampled:
223
+ chains.append(([t], t.t_start))
224
+ return chains
225
+
226
+ def _sample_2hop_chains(
227
+ self, target_count: int
228
+ ) -> List[Tuple[List[Triple], float]]:
229
+ """
230
+ Year-first 2-hop sampler. Pick an anchor subject that has outgoing
231
+ facts, pick a year from that subject, then find a second hop from the
232
+ pivot at the same year. Much higher success rate than sampling t1
233
+ first and hoping for a matching t2.
234
+ """
235
+ chains = []
236
+ attempts = 0
237
+ max_attempts = target_count * 8
238
+ while len(chains) < target_count and attempts < max_attempts:
239
+ attempts += 1
240
+ anchor = self.rng.choice(self._subjects_with_outgoing)
241
+ year_index = self._subject_year[anchor]
242
+ year = self.rng.choice(list(year_index.keys()))
243
+ t1_candidates = year_index[year]
244
+ t1 = self.rng.choice(t1_candidates)
245
+
246
+ pivot_year_index = self._subject_year.get(t1.obj)
247
+ if pivot_year_index is None:
248
+ continue
249
+ t2_candidates = [
250
+ t for t in pivot_year_index.get(year, [])
251
+ if t.relation != t1.relation
252
+ and t.obj != t1.subject # cycle guard
253
+ ]
254
+ if not t2_candidates:
255
+ continue
256
+ t2 = self.rng.choice(t2_candidates)
257
+
258
+ chains.append(([t1, t2], year))
259
+ return chains
260
+
261
+ def _sample_3plus_chains(
262
+ self, target_count: int, max_depth: int
263
+ ) -> List[Tuple[List[Triple], float]]:
264
+ """
265
+ Year-first 3+-hop sampler. Pick an anchor subject, pick a year that
266
+ subject has outgoing facts, walk forward through hops at that year.
267
+ Uses the pre-built (subject, year) index for fast forward-chaining.
268
+ """
269
+ chains = []
270
+ attempts = 0
271
+ max_attempts = target_count * 15
272
+ while len(chains) < target_count and attempts < max_attempts:
273
+ attempts += 1
274
+ anchor = self.rng.choice(self._subjects_with_outgoing)
275
+ year_index = self._subject_year[anchor]
276
+ year = self.rng.choice(list(year_index.keys()))
277
+ depth = self.rng.randint(3, min(max_depth, 4))
278
+
279
+ chain: List[Triple] = []
280
+ current = anchor
281
+ visited = {current}
282
+ for _ in range(depth):
283
+ hops = [
284
+ t for t in self._subject_year.get(current, {}).get(year, [])
285
+ if t.obj not in visited
286
+ ]
287
+ if not hops:
288
+ break
289
+ hop = self.rng.choice(hops)
290
+ chain.append(hop)
291
+ current = hop.obj
292
+ visited.add(current)
293
+
294
+ if len(chain) < 3:
295
+ continue
296
+
297
+ if any(
298
+ chain[i].relation == chain[i - 1].relation
299
+ for i in range(1, len(chain))
300
+ ):
301
+ continue
302
+
303
+ window = ValidityWindow.full()
304
+ valid = True
305
+ for triple in chain:
306
+ window = TemporalKGIndexer.compose(window, triple, year)
307
+ if window is None or window.is_empty():
308
+ valid = False
309
+ break
310
+ if not valid:
311
+ continue
312
+
313
+ chains.append((chain, year))
314
+ return chains
315
+
316
+ # --- Operator builders ----------------------------------------------
317
+
318
+ def _build_operator_candidate(
319
+ self,
320
+ operator: str,
321
+ chain: List[Triple],
322
+ t_query: float,
323
+ complexity: str,
324
+ ) -> Optional[Candidate]:
325
+ """Dispatch to the right operator builder."""
326
+ dispatch = {
327
+ "point_in_time": self._build_pit,
328
+ "before_after": self._build_ba,
329
+ "interval": self._build_interval,
330
+ "sequence": self._build_sequence,
331
+ }
332
+ return dispatch[operator](chain, t_query, complexity)
333
+
334
+ def _build_pit(
335
+ self, chain: List[Triple], t_query: float, complexity: str
336
+ ) -> Optional[Candidate]:
337
+ """Point-in-time: "In {year}, what was {path}'s {r_n}?"."""
338
+ path = _render_composition_path(
339
+ chain[0].subject, [h.relation for h in chain[:-1]]
340
+ )
341
+ template = self.rng.choice(QUESTION_TEMPLATES["point_in_time"])
342
+ question = template.format(
343
+ path=path,
344
+ final_relation=chain[-1].relation,
345
+ year=int(t_query),
346
+ )
347
+ return self._make_candidate(
348
+ question, t_query, chain[-1].obj, chain, complexity,
349
+ "point_in_time", "explicit",
350
+ )
351
+
352
+ def _build_ba(
353
+ self, chain: List[Triple], t_query: float, complexity: str
354
+ ) -> Optional[Candidate]:
355
+ """
356
+ Before/after: same chain as PIT, but the temporal anchor is a sibling
357
+ fact (another holder of the terminal relation at a different time).
358
+ The candidate is dropped if no such sibling exists.
359
+ """
360
+ terminal = chain[-1]
361
+ siblings = [
362
+ t for t in self.indexer.entity_index.get(terminal.subject, [])
363
+ if t.subject == terminal.subject
364
+ and t.relation == terminal.relation
365
+ and t.obj != terminal.obj
366
+ and t.t_start != t_query
367
+ ]
368
+ if not siblings:
369
+ return None
370
+ sibling = self.rng.choice(siblings)
371
+ # Qualifier: answer came *before* sibling if t_query < sibling.t_start.
372
+ if sibling.t_start > t_query:
373
+ qualifier, qualifier_cap = "before", "Before"
374
+ else:
375
+ qualifier, qualifier_cap = "after", "After"
376
+
377
+ path = _render_composition_path(
378
+ chain[0].subject, [h.relation for h in chain[:-1]]
379
+ )
380
+ template = self.rng.choice(QUESTION_TEMPLATES["before_after"])
381
+ question = template.format(
382
+ path=path,
383
+ final_relation=terminal.relation,
384
+ qualifier=qualifier,
385
+ qualifier_cap=qualifier_cap,
386
+ sibling=sibling.obj,
387
+ )
388
+ return self._make_candidate(
389
+ question, t_query, terminal.obj, chain, complexity,
390
+ "before_after", "ordinal",
391
+ )
392
+
393
+ def _build_interval(
394
+ self, chain: List[Triple], t_query: float, complexity: str
395
+ ) -> Optional[Candidate]:
396
+ """
397
+ Interval (temporal pinpoint): "In what year was {path}'s {r_n} equal
398
+ to {terminal}?". Answer is the query year. Uniqueness of the year
399
+ is enforced by a custom check in Stage 3 (AnswerUniquenessFilter).
400
+ """
401
+ path = _render_composition_path(
402
+ chain[0].subject, [h.relation for h in chain[:-1]]
403
+ )
404
+ terminal = chain[-1]
405
+ template = self.rng.choice(QUESTION_TEMPLATES["interval"])
406
+ question = template.format(
407
+ path=path,
408
+ final_relation=terminal.relation,
409
+ terminal=terminal.obj,
410
+ )
411
+ return self._make_candidate(
412
+ question, t_query, str(int(t_query)), chain, complexity,
413
+ "interval", "ordinal",
414
+ )
415
+
416
+ def _build_sequence(
417
+ self, chain: List[Triple], t_query: float, complexity: str
418
+ ) -> Optional[Candidate]:
419
+ """
420
+ Sequence: "After {ref_subject} {ref_rel} {ref_obj}, what was {path}'s
421
+ {r_n}?". Reference triple is an earlier fact involving any entity in
422
+ the chain (makes the anchor event contextually relevant).
423
+ """
424
+ chain_entities = {h.subject for h in chain} | {h.obj for h in chain}
425
+ chain_ids = {(h.subject, h.relation, h.obj) for h in chain}
426
+ answer_entity = chain[-1].obj
427
+ refs = []
428
+ for e in chain_entities:
429
+ for t in self.indexer.entity_index.get(e, []):
430
+ if (
431
+ t.t_start < t_query
432
+ and (t.subject, t.relation, t.obj) not in chain_ids
433
+ # The reference must not contain the answer anywhere —
434
+ # otherwise the question literally names its own answer.
435
+ and t.subject != answer_entity
436
+ and t.obj != answer_entity
437
+ ):
438
+ refs.append(t)
439
+ if not refs:
440
+ return None
441
+ ref = self.rng.choice(refs)
442
+ path = _render_composition_path(
443
+ chain[0].subject, [h.relation for h in chain[:-1]]
444
+ )
445
+ template = self.rng.choice(QUESTION_TEMPLATES["sequence"])
446
+ question = template.format(
447
+ path=path,
448
+ final_relation=chain[-1].relation,
449
+ ref_subject=ref.subject,
450
+ ref_relation=ref.relation,
451
+ ref_object=ref.obj,
452
+ )
453
+ return self._make_candidate(
454
+ question, t_query, chain[-1].obj, chain, complexity,
455
+ "sequence", "ordinal",
456
+ )
457
+
458
+ def _make_candidate(
459
+ self,
460
+ question: str,
461
+ t_query: float,
462
+ answer: str,
463
+ chain: List[Triple],
464
+ complexity: str,
465
+ operator_type: str,
466
+ question_type: str,
467
+ ) -> Candidate:
468
+ cand = Candidate(
469
+ id=f"cand_{self.candidate_id_counter}",
470
+ question=question,
471
+ t_query=t_query,
472
+ answer=answer,
473
+ complexity=complexity,
474
+ operator_type=operator_type,
475
+ question_type=question_type,
476
+ gold_chain=chain,
477
+ )
478
+ self.candidate_id_counter += 1
479
+ return cand
480
+
481
+
482
+ # ---------------------------------------------------------------------------
483
+ # Stage 2: Composability filter
484
+ # ---------------------------------------------------------------------------
485
+
486
+ class ComposabilityFilter:
487
+ """Validates temporal consistency of candidate chains."""
488
+
489
+ @staticmethod
490
+ def filter_candidates(candidates: List[Candidate]) -> List[Candidate]:
491
+ """
492
+ Discard candidates whose gold chain has empty composed validity window.
493
+ Uses the ⊕ operator from ValidityWindow.intersect().
494
+ """
495
+ valid = []
496
+
497
+ for cand in candidates:
498
+ # Compose all triples in the chain
499
+ window = ValidityWindow.full()
500
+ is_valid = True
501
+
502
+ for triple in cand.gold_chain:
503
+ window = TemporalKGIndexer.compose(window, triple, cand.t_query)
504
+ if window is None or window.is_empty():
505
+ is_valid = False
506
+ break
507
+
508
+ if is_valid:
509
+ valid.append(cand)
510
+
511
+ return valid
512
+
513
+
514
+ # ---------------------------------------------------------------------------
515
+ # Stage 3: Answer uniqueness filter
516
+ # ---------------------------------------------------------------------------
517
+
518
+ class AnswerUniquenessFilter:
519
+ """Discards ambiguous questions with multiple valid answers at t_query."""
520
+
521
+ def __init__(self, indexer: TemporalKGIndexer):
522
+ self.indexer = indexer
523
+
524
+ def filter_candidates(self, candidates: List[Candidate]) -> List[Candidate]:
525
+ valid = [c for c in candidates if self._answer_is_unique(c)]
526
+ return valid
527
+
528
+ def _answer_is_unique(self, cand: Candidate) -> bool:
529
+ """
530
+ Construction pipeline, Step 4: "removing ambiguous questions with multiple valid
531
+ answers at t_q". Scope is terminal-answer only — intermediate fan-out
532
+ along the chain is permitted.
533
+
534
+ Entity-valued operators (PIT, BA, SEQ): the final hop's (subject,
535
+ relation) must have exactly one valid object at t_q, and that object
536
+ must equal the recorded answer.
537
+
538
+ Year-valued operator (INT): the specific terminal triple (subject,
539
+ relation, object) must be valid at exactly one distinct t in the KG.
540
+ Otherwise the year-answer is ambiguous.
541
+
542
+ See benchmark-design-decisions.md §3 for the full rationale.
543
+ """
544
+ if not cand.gold_chain:
545
+ return False
546
+
547
+ terminal = cand.gold_chain[-1]
548
+
549
+ if cand.operator_type == "interval":
550
+ # Year answer: the specific (s, r, o) triple must be unique in time.
551
+ matches = [
552
+ t for t in self.indexer.entity_index.get(terminal.subject, [])
553
+ if t.subject == terminal.subject
554
+ and t.relation == terminal.relation
555
+ and t.obj == terminal.obj
556
+ ]
557
+ distinct_years = {t.t_start for t in matches}
558
+ return len(distinct_years) == 1
559
+
560
+ # Entity-valued operators: terminal (s, r) must have a single valid
561
+ # object at t_q.
562
+ terminal_objs = {
563
+ t.obj
564
+ for t in self.indexer.entity_index.get(terminal.subject, [])
565
+ if t.subject == terminal.subject
566
+ and t.relation == terminal.relation
567
+ and t.valid_at(cand.t_query)
568
+ }
569
+ return len(terminal_objs) == 1 and cand.answer in terminal_objs
570
+
571
+
572
+ # ---------------------------------------------------------------------------
573
+ # Stage 4: MinHash deduplication
574
+ # ---------------------------------------------------------------------------
575
+
576
+ class MinHasher:
577
+ """
578
+ MinHash with Jaccard similarity for deduplicating near-duplicate questions.
579
+ Uses character 3-grams and 128 hash functions.
580
+ """
581
+
582
+ def __init__(self, num_hashes: int = 128, gram_size: int = 3, seed: int = 42):
583
+ self.num_hashes = num_hashes
584
+ self.gram_size = gram_size
585
+ self.seed = seed
586
+
587
+ @staticmethod
588
+ def _get_grams(text: str, gram_size: int) -> Set[str]:
589
+ """Extract character n-grams from text."""
590
+ text = text.lower()
591
+ return {text[i : i + gram_size] for i in range(len(text) - gram_size + 1)}
592
+
593
+ def _hash_gram(self, gram: str, hash_idx: int) -> int:
594
+ """Compute hash value for a gram and hash function index."""
595
+ seed_str = f"{self.seed}_{hash_idx}_{gram}"
596
+ h = hashlib.sha256(seed_str.encode()).hexdigest()
597
+ return int(h, 16)
598
+
599
+ def signature(self, text: str) -> List[int]:
600
+ """Compute MinHash signature for a text."""
601
+ grams = self._get_grams(text, self.gram_size)
602
+
603
+ if not grams:
604
+ return [0] * self.num_hashes
605
+
606
+ sig = []
607
+ for hash_idx in range(self.num_hashes):
608
+ min_hash = float("inf")
609
+ for gram in grams:
610
+ h = self._hash_gram(gram, hash_idx)
611
+ min_hash = min(min_hash, h)
612
+ sig.append(min_hash)
613
+
614
+ return sig
615
+
616
+ @staticmethod
617
+ def jaccard_similarity(sig_a: List[int], sig_b: List[int]) -> float:
618
+ """Estimate Jaccard similarity from MinHash signatures."""
619
+ if len(sig_a) == 0 or len(sig_b) == 0:
620
+ return 0.0
621
+ matches = sum(1 for a, b in zip(sig_a, sig_b) if a == b)
622
+ return matches / len(sig_a)
623
+
624
+
625
+ class MinHashDeduplicator:
626
+ """Deduplicates candidates using MinHash with Jaccard threshold."""
627
+
628
+ def __init__(self, similarity_threshold: float = 0.8, seed: int = 42):
629
+ self.threshold = similarity_threshold
630
+ self.hasher = MinHasher(num_hashes=128, seed=seed)
631
+
632
+ def deduplicate(self, candidates: List[Candidate]) -> List[Candidate]:
633
+ """
634
+ Remove near-duplicate questions (Jaccard > threshold).
635
+ Keep the first occurrence of each group.
636
+ """
637
+ if not candidates:
638
+ return []
639
+
640
+ # Compute signatures
641
+ sigs = [(c, self.hasher.signature(c.question)) for c in candidates]
642
+
643
+ # Greedy clustering: each candidate either starts a cluster or is merged
644
+ clusters = []
645
+ used = set()
646
+
647
+ for i, (cand_i, sig_i) in enumerate(sigs):
648
+ if i in used:
649
+ continue
650
+
651
+ cluster = [cand_i]
652
+ used.add(i)
653
+
654
+ for j in range(i + 1, len(sigs)):
655
+ if j in used:
656
+ continue
657
+
658
+ cand_j, sig_j = sigs[j]
659
+ sim = self.hasher.jaccard_similarity(sig_i, sig_j)
660
+
661
+ if sim > self.threshold:
662
+ used.add(j)
663
+
664
+ clusters.append(cluster[0]) # Keep first of each cluster
665
+
666
+ return clusters
667
+
668
+
669
+ # ---------------------------------------------------------------------------
670
+ # Stage 5: Subgraph construction
671
+ # ---------------------------------------------------------------------------
672
+
673
+ class SubgraphConstructor:
674
+ """
675
+ Builds three subgraphs for each question:
676
+ - S_star: ground truth chain
677
+ - S_dist: distractor (one wrong hop, same relation, different object)
678
+ - S_stale: stale-fact (one hop replaced by temporally adjacent version)
679
+ """
680
+
681
+ def __init__(self, indexer: TemporalKGIndexer, seed: int = 42):
682
+ self.indexer = indexer
683
+ self.rng = random.Random(seed)
684
+
685
+ def construct(
686
+ self,
687
+ candidate: Candidate,
688
+ ) -> Tuple[List[Dict], List[Dict], List[Dict]]:
689
+ """
690
+ Build S_star, S_dist, S_stale for a candidate.
691
+ Returns (S_star, S_dist, S_stale) as list of triple dicts.
692
+ """
693
+ # S_star: the gold chain
694
+ S_star = [t.to_dict() for t in candidate.gold_chain]
695
+
696
+ # S_dist: replace one hop with a distractor (same relation, different object, valid at t_query)
697
+ S_dist = self._build_distractor(candidate)
698
+
699
+ # S_stale: replace one hop with a temporally adjacent version
700
+ S_stale = self._build_stale(candidate)
701
+
702
+ return S_star, S_dist, S_stale
703
+
704
+ def _build_distractor(self, candidate: Candidate) -> List[Dict]:
705
+ """
706
+ Replace one random hop with a semantically similar but wrong triple.
707
+ Same subject, same relation, different object, valid at t_query.
708
+ """
709
+ if not candidate.gold_chain:
710
+ return [t.to_dict() for t in candidate.gold_chain]
711
+
712
+ S_dist = [t.to_dict() for t in candidate.gold_chain]
713
+ hop_to_replace = self.rng.randint(0, len(candidate.gold_chain) - 1)
714
+ replaced_triple = candidate.gold_chain[hop_to_replace]
715
+
716
+ # Find alternative triples with same (s, r) but different object AT ANY TIME.
717
+ # We can't require valid_at(t_query) — the answer-uniqueness filter has
718
+ # already guaranteed no such alternatives exist, so that constraint would
719
+ # always return an empty list. Taking any alternative object across time
720
+ # gives a semantically plausible but factually wrong distractor (e.g. a
721
+ # former CEO when the question asks about a later year).
722
+ alternatives = [
723
+ t for t in self.indexer.entity_index.get(replaced_triple.subject, [])
724
+ if (t.subject == replaced_triple.subject and
725
+ t.relation == replaced_triple.relation and
726
+ t.obj != replaced_triple.obj)
727
+ ]
728
+
729
+ if alternatives:
730
+ distractor = self.rng.choice(alternatives)
731
+ S_dist[hop_to_replace] = distractor.to_dict()
732
+
733
+ return S_dist
734
+
735
+ def _build_stale(self, candidate: Candidate) -> List[Dict]:
736
+ """
737
+ Replace one hop with a temporally adjacent version
738
+ (same s, r, o but different validity window that does NOT contain t_query).
739
+ """
740
+ if not candidate.gold_chain:
741
+ return [t.to_dict() for t in candidate.gold_chain]
742
+
743
+ S_stale = [t.to_dict() for t in candidate.gold_chain]
744
+ hop_to_replace = self.rng.randint(0, len(candidate.gold_chain) - 1)
745
+ replaced_triple = candidate.gold_chain[hop_to_replace]
746
+
747
+ # Find temporally adjacent versions of the same triple
748
+ adjacent = [
749
+ t for t in self.indexer._all_triples
750
+ if (t.subject == replaced_triple.subject and
751
+ t.relation == replaced_triple.relation and
752
+ t.obj == replaced_triple.obj and
753
+ t.t_start != replaced_triple.t_start and
754
+ not t.valid_at(candidate.t_query))
755
+ ]
756
+
757
+ if adjacent:
758
+ stale_triple = self.rng.choice(adjacent)
759
+ S_stale[hop_to_replace] = stale_triple.to_dict()
760
+
761
+ return S_stale
762
+
763
+
764
+ # ---------------------------------------------------------------------------
765
+ # Stage 6: Train/dev/test split
766
+ # ---------------------------------------------------------------------------
767
+
768
+ class DatasetSplitter:
769
+ """Stratified split by complexity level."""
770
+
771
+ def __init__(self, seed: int = 42):
772
+ self.rng = random.Random(seed)
773
+
774
+ def split(
775
+ self,
776
+ questions: List[BenchmarkQuestion],
777
+ train_frac: float = 0.7,
778
+ dev_frac: float = 0.1,
779
+ test_frac: float = 0.2,
780
+ ) -> List[BenchmarkQuestion]:
781
+ """
782
+ Stratified split by complexity.
783
+ Target: 1-hop: 4K (2.8K train), 2-hop: 4K (2.8K train), 3+-hop: 2K (1.4K train)
784
+ """
785
+ # Group by complexity
786
+ by_complexity: Dict[str, List[BenchmarkQuestion]] = defaultdict(list)
787
+ for q in questions:
788
+ by_complexity[q.complexity].append(q)
789
+
790
+ # Split each group
791
+ result = []
792
+ for complexity, qs in by_complexity.items():
793
+ self.rng.shuffle(qs)
794
+
795
+ n = len(qs)
796
+ train_end = int(n * train_frac)
797
+ dev_end = train_end + int(n * dev_frac)
798
+
799
+ for i, q in enumerate(qs):
800
+ if i < train_end:
801
+ q.split = "train"
802
+ elif i < dev_end:
803
+ q.split = "dev"
804
+ else:
805
+ q.split = "test"
806
+
807
+ result.extend(qs)
808
+
809
+ return result
810
+
811
+
812
+ # ---------------------------------------------------------------------------
813
+ # Main builder
814
+ # ---------------------------------------------------------------------------
815
+
816
+ class BenchmarkBuilder:
817
+ """Orchestrates all six pipeline stages."""
818
+
819
+ def __init__(
820
+ self,
821
+ kg_path: str,
822
+ output_dir: str = "./benchmark/",
823
+ target_n: int = 10000,
824
+ seed: int = 42,
825
+ min_depth: int = 1,
826
+ max_depth: int = 4,
827
+ ):
828
+ self.kg_path = kg_path
829
+ self.output_dir = Path(output_dir)
830
+ self.target_n = target_n
831
+ self.seed = seed
832
+ self.min_depth = min_depth
833
+ self.max_depth = max_depth
834
+ self.rng = random.Random(seed)
835
+
836
+ # Build or load indexer
837
+ self.indexer = TemporalKGIndexer()
838
+ if kg_path.endswith(".json"):
839
+ self.indexer.load_from_json(kg_path)
840
+ else:
841
+ self.indexer.load_tkgl_smallpedia(kg_path)
842
+
843
+ def build(self) -> List[BenchmarkQuestion]:
844
+ """Run the full 6-stage pipeline."""
845
+ print("[Benchmark Builder] Starting pipeline...")
846
+ print(f"[Indexer] {self.indexer}")
847
+
848
+ # Stage 1: Generate candidates
849
+ print("\n[Stage 1] Question generation...")
850
+ gen = QuestionGenerator(self.indexer, seed=self.seed)
851
+ target_candidates = int(self.target_n * 4) # 40K to yield 10K
852
+ candidates = gen.generate_candidates(
853
+ target_candidates=target_candidates,
854
+ min_depth=self.min_depth,
855
+ max_depth=self.max_depth,
856
+ )
857
+ print(f" Generated {len(candidates):,} candidates")
858
+
859
+ # Stage 2: Composability filter
860
+ print("\n[Stage 2] Composability filtering...")
861
+ comp_filter = ComposabilityFilter()
862
+ candidates = comp_filter.filter_candidates(candidates)
863
+ print(f" Passed composability check: {len(candidates):,}")
864
+
865
+ # Stage 3: Answer uniqueness filter
866
+ print("\n[Stage 3] Answer uniqueness filtering...")
867
+ uniq_filter = AnswerUniquenessFilter(self.indexer)
868
+ candidates = uniq_filter.filter_candidates(candidates)
869
+ print(f" Passed uniqueness check: {len(candidates):,}")
870
+
871
+ # Stage 4: MinHash deduplication
872
+ print("\n[Stage 4] MinHash deduplication...")
873
+ deduplicator = MinHashDeduplicator(similarity_threshold=0.8, seed=self.seed)
874
+ candidates = deduplicator.deduplicate(candidates)
875
+ print(f" After deduplication: {len(candidates):,}")
876
+
877
+ # Stratified trim: hit the paper's per-complexity targets
878
+ # (4K / 4K / 2K at target_n = 10K) and, within each complexity, spread
879
+ # across the four operator types. Under-yield in an operator cell
880
+ # is topped up with point-in-time from the same complexity, because
881
+ # PIT is the most reliable operator and degrades the benchmark least
882
+ # if it fills in for a short cell.
883
+ candidates = self._stratified_trim(candidates)
884
+ print(f" Trimmed to target: {len(candidates):,}")
885
+
886
+ # Stage 5: Subgraph construction
887
+ print("\n[Stage 5] Subgraph construction...")
888
+ sg_constructor = SubgraphConstructor(self.indexer, seed=self.seed)
889
+ questions = []
890
+
891
+ for i, cand in enumerate(candidates):
892
+ S_star, S_dist, S_stale = sg_constructor.construct(cand)
893
+
894
+ q = BenchmarkQuestion(
895
+ id=f"q_{i:06d}",
896
+ question=cand.question,
897
+ t_query=cand.t_query,
898
+ answer=cand.answer,
899
+ complexity=cand.complexity,
900
+ operator_type=cand.operator_type,
901
+ question_type=cand.question_type,
902
+ S_star=S_star,
903
+ S_dist=S_dist,
904
+ S_stale=S_stale,
905
+ split="", # Will be set in Stage 6
906
+ )
907
+ questions.append(q)
908
+
909
+ print(f" Subgraphs constructed: {len(questions):,}")
910
+
911
+ # Stage 6: Train/dev/test split
912
+ print("\n[Stage 6] Train/dev/test split (stratified)...")
913
+ splitter = DatasetSplitter(seed=self.seed)
914
+ questions = splitter.split(questions)
915
+
916
+ # Print split statistics
917
+ splits = defaultdict(lambda: defaultdict(int))
918
+ for q in questions:
919
+ splits[q.complexity][q.split] += 1
920
+
921
+ print(" Split distribution:")
922
+ for complexity in ["1hop", "2hop", "3plus"]:
923
+ if complexity in splits:
924
+ train = splits[complexity]["train"]
925
+ dev = splits[complexity]["dev"]
926
+ test = splits[complexity]["test"]
927
+ total = train + dev + test
928
+ print(f" {complexity:8s}: {total:5d} ({train:4d} train, {dev:3d} dev, {test:3d} test)")
929
+
930
+ return questions
931
+
932
+ def _stratified_trim(self, candidates: List[Candidate]) -> List[Candidate]:
933
+ """
934
+ Reduce candidates to per-complexity/per-operator quotas matching paper
935
+ the TempBench paper (4K 1-hop, 4K 2-hop, 2K 3+-hop at target_n = 10K), with each
936
+ complexity split evenly across four operators. Cells that under-yield
937
+ are topped up from PIT in the same complexity.
938
+ """
939
+ per_complexity_target = {
940
+ "1hop": self.target_n * 4 // 10, # 40%
941
+ "2hop": self.target_n * 4 // 10, # 40%
942
+ "3plus": self.target_n * 2 // 10, # 20%
943
+ }
944
+ operators = ("point_in_time", "before_after", "interval", "sequence")
945
+
946
+ # Bucket candidates by (complexity, operator)
947
+ buckets: Dict[Tuple[str, str], List[Candidate]] = defaultdict(list)
948
+ for c in candidates:
949
+ buckets[(c.complexity, c.operator_type)].append(c)
950
+ for bucket in buckets.values():
951
+ self.rng.shuffle(bucket)
952
+
953
+ trimmed: List[Candidate] = []
954
+ for complexity, cx_target in per_complexity_target.items():
955
+ per_op_target = cx_target // len(operators)
956
+ cx_kept: List[Candidate] = []
957
+ # First pass: take up to per_op_target from each operator cell.
958
+ for op in operators:
959
+ cell = buckets.get((complexity, op), [])
960
+ cx_kept.extend(cell[:per_op_target])
961
+ # Top up shortfall with PIT first, then anything available.
962
+ shortfall = cx_target - len(cx_kept)
963
+ if shortfall > 0:
964
+ topup_pool: List[Candidate] = []
965
+ for op in ("point_in_time", "sequence", "before_after", "interval"):
966
+ cell = buckets.get((complexity, op), [])
967
+ if len(cell) > per_op_target:
968
+ topup_pool.extend(cell[per_op_target:])
969
+ self.rng.shuffle(topup_pool)
970
+ cx_kept.extend(topup_pool[:shortfall])
971
+ trimmed.extend(cx_kept)
972
+
973
+ self.rng.shuffle(trimmed)
974
+ return trimmed
975
+
976
+ def save(self, questions: List[BenchmarkQuestion]) -> None:
977
+ """Write benchmark to JSONL file."""
978
+ self.output_dir.mkdir(parents=True, exist_ok=True)
979
+ output_path = self.output_dir / "benchmark.jsonl"
980
+
981
+ with open(output_path, "w", encoding="utf-8") as f:
982
+ for q in questions:
983
+ f.write(json.dumps(q.to_jsonl_dict()) + "\n")
984
+
985
+ print(f"\n[Output] Benchmark saved to {output_path}")
986
+ print(f" {len(questions):,} questions written")
987
+
988
+
989
+ # ---------------------------------------------------------------------------
990
+ # Smoke test
991
+ # ---------------------------------------------------------------------------
992
+
993
+ def smoke_test():
994
+ """Run on synthetic Deutsche Bank KG (same 5 triples as indexer.py tests)."""
995
+ print("=" * 70)
996
+ print("SMOKE TEST: TempBench Builder")
997
+ print("=" * 70)
998
+
999
+ # Create a temporary indexer with synthetic data
1000
+ indexer = TemporalKGIndexer()
1001
+ indexer.build([
1002
+ ("Deutsche_Bank", "has_CFO", "John_Cryan", 2015.0, 2018.0),
1003
+ ("Deutsche_Bank", "has_CFO", "Christian_Sewing", 2018.0, math.inf),
1004
+ ("Deutsche_Bank", "settled", "LIBOR_Case", 2015.25, 2015.25),
1005
+ ("John_Cryan", "member_of", "Deutsche_Bank", 2015.0, 2018.0),
1006
+ ("Christian_Sewing", "member_of", "Deutsche_Bank", 2018.0, math.inf),
1007
+ ])
1008
+
1009
+ print(f"\nIndexer: {indexer}\n")
1010
+
1011
+ # Generate candidates
1012
+ gen = QuestionGenerator(indexer, seed=42)
1013
+ candidates = gen.generate_candidates(
1014
+ target_candidates=100,
1015
+ min_depth=1,
1016
+ max_depth=3,
1017
+ )
1018
+ print(f"Generated {len(candidates)} candidates")
1019
+
1020
+ # Filter by composability
1021
+ comp_filter = ComposabilityFilter()
1022
+ candidates = comp_filter.filter_candidates(candidates)
1023
+ print(f"Passed composability: {len(candidates)}")
1024
+
1025
+ # Filter by uniqueness
1026
+ uniq_filter = AnswerUniquenessFilter(indexer)
1027
+ candidates = uniq_filter.filter_candidates(candidates)
1028
+ print(f"Passed uniqueness: {len(candidates)}")
1029
+
1030
+ # Deduplicate
1031
+ deduplicator = MinHashDeduplicator(similarity_threshold=0.8, seed=42)
1032
+ candidates = deduplicator.deduplicate(candidates)
1033
+ print(f"After deduplication: {len(candidates)}")
1034
+
1035
+ # Build subgraphs
1036
+ sg_constructor = SubgraphConstructor(indexer, seed=42)
1037
+ questions = []
1038
+
1039
+ for i, cand in enumerate(candidates[:min(5, len(candidates))]):
1040
+ S_star, S_dist, S_stale = sg_constructor.construct(cand)
1041
+
1042
+ q = BenchmarkQuestion(
1043
+ id=f"q_{i:06d}",
1044
+ question=cand.question,
1045
+ t_query=cand.t_query,
1046
+ answer=cand.answer,
1047
+ complexity=cand.complexity,
1048
+ operator_type=cand.operator_type,
1049
+ question_type=cand.question_type,
1050
+ S_star=S_star,
1051
+ S_dist=S_dist,
1052
+ S_stale=S_stale,
1053
+ split="train",
1054
+ )
1055
+ questions.append(q)
1056
+
1057
+ print(f"Built {len(questions)} benchmark questions\n")
1058
+
1059
+ # Print sample
1060
+ print("Sample questions:")
1061
+ for q in questions[:3]:
1062
+ print(f"\n ID: {q.id}")
1063
+ print(f" Question: {q.question}")
1064
+ print(f" Complexity: {q.complexity}")
1065
+ print(f" Answer: {q.answer}")
1066
+ print(f" t_query: {q.t_query}")
1067
+ print(f" Operator: {q.operator_type}")
1068
+ print(f" S_star: {len(q.S_star)} triples")
1069
+ print(f" S_dist: {len(q.S_dist)} triples")
1070
+ print(f" S_stale: {len(q.S_stale)} triples")
1071
+
1072
+ print("\n" + "=" * 70)
1073
+ print("SMOKE TEST PASSED")
1074
+ print("=" * 70)
1075
+
1076
+
1077
+ # ---------------------------------------------------------------------------
1078
+ # CLI
1079
+ # ---------------------------------------------------------------------------
1080
+
1081
+ def main():
1082
+ parser = argparse.ArgumentParser(
1083
+ description="Build TempBench: 10K-question temporal QA benchmark"
1084
+ )
1085
+ parser.add_argument(
1086
+ "--kg_path",
1087
+ type=str,
1088
+ default=None,
1089
+ help="Path to KG file (JSON or TKGL CSV)",
1090
+ )
1091
+ parser.add_argument(
1092
+ "--output_dir",
1093
+ type=str,
1094
+ default="./benchmark/",
1095
+ help="Output directory for benchmark JSONL",
1096
+ )
1097
+ parser.add_argument(
1098
+ "--target_n",
1099
+ type=int,
1100
+ default=10000,
1101
+ help="Target number of benchmark questions (default 10000)",
1102
+ )
1103
+ parser.add_argument(
1104
+ "--seed",
1105
+ type=int,
1106
+ default=42,
1107
+ help="Random seed (default 42)",
1108
+ )
1109
+ parser.add_argument(
1110
+ "--min_depth",
1111
+ type=int,
1112
+ default=1,
1113
+ help="Minimum chain depth (default 1)",
1114
+ )
1115
+ parser.add_argument(
1116
+ "--max_depth",
1117
+ type=int,
1118
+ default=4,
1119
+ help="Maximum chain depth (default 4)",
1120
+ )
1121
+ parser.add_argument(
1122
+ "--smoke_test",
1123
+ action="store_true",
1124
+ help="Run smoke test on synthetic data",
1125
+ )
1126
+
1127
+ args = parser.parse_args()
1128
+
1129
+ if args.smoke_test:
1130
+ smoke_test()
1131
+ sys.exit(0)
1132
+
1133
+ if not args.kg_path:
1134
+ print("Error: --kg_path required (or use --smoke_test)")
1135
+ sys.exit(1)
1136
+
1137
+ builder = BenchmarkBuilder(
1138
+ kg_path=args.kg_path,
1139
+ output_dir=args.output_dir,
1140
+ target_n=args.target_n,
1141
+ seed=args.seed,
1142
+ min_depth=args.min_depth,
1143
+ max_depth=args.max_depth,
1144
+ )
1145
+
1146
+ questions = builder.build()
1147
+ builder.save(questions)
1148
+
1149
+
1150
+ if __name__ == "__main__":
1151
+ main()
code/indexer.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TempBench — Temporal KG Indexer
3
+ ===================================
4
+ Implements the dual-index structure (entity index + interval tree temporal index)
5
+ described in the TempBench paper.
6
+
7
+ Usage:
8
+ from indexer import TemporalKGIndexer
9
+
10
+ indexer = TemporalKGIndexer()
11
+ indexer.load_tkgl_smallpedia("path/to/tkgl-smallpedia.csv")
12
+ # or from a list of quadruples:
13
+ indexer.build(quadruples)
14
+
15
+ # Query: all triples valid at a given timestamp
16
+ valid_triples = indexer.query_valid_at(entity="Q1234", t=2015.5)
17
+
18
+ # Query: temporally-filtered 1-hop neighbourhood for an anchor entity
19
+ neighbourhood = indexer.neighbourhood(entity="Q1234", t_query=2015.5)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import csv
25
+ import json
26
+ import math
27
+ from collections import defaultdict
28
+ from dataclasses import dataclass, field
29
+ from typing import Iterator, List, Optional, Tuple
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Data structures
33
+ # ---------------------------------------------------------------------------
34
+
35
+ @dataclass(frozen=True)
36
+ class Triple:
37
+ """A single timestamped KG quadruple."""
38
+ subject: str
39
+ relation: str
40
+ obj: str
41
+ t_start: float # year as float, e.g. 2015.0 or 2015.583 (Aug)
42
+ t_end: float # math.inf for currently-valid facts
43
+
44
+ def valid_at(self, t: float) -> bool:
45
+ return self.t_start <= t <= self.t_end
46
+
47
+ def to_dict(self) -> dict:
48
+ return {
49
+ "s": self.subject,
50
+ "r": self.relation,
51
+ "o": self.obj,
52
+ "t_start": self.t_start,
53
+ "t_end": self.t_end if not math.isinf(self.t_end) else None,
54
+ }
55
+
56
+
57
+ @dataclass
58
+ class ValidityWindow:
59
+ t_start: float
60
+ t_end: float
61
+
62
+ def intersect(self, other: "ValidityWindow", t_query: float) -> Optional["ValidityWindow"]:
63
+ """
64
+ Validity-window intersection clamped to (-inf, t_query], or None if empty.
65
+ This is a building block used by benchmark construction; it is NOT the
66
+ forward-propagating composability operator (that is defined in the
67
+ TempBench paper).
68
+ """
69
+ new_start = max(self.t_start, other.t_start)
70
+ new_end = min(self.t_end, other.t_end, t_query)
71
+ if new_start <= new_end:
72
+ return ValidityWindow(new_start, new_end)
73
+ return None
74
+
75
+ @classmethod
76
+ def full(cls) -> "ValidityWindow":
77
+ return cls(t_start=-math.inf, t_end=math.inf)
78
+
79
+ def is_empty(self) -> bool:
80
+ return self.t_start > self.t_end
81
+
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # Interval tree node (simple augmented BST)
85
+ # ---------------------------------------------------------------------------
86
+
87
+ class _IntervalNode:
88
+ """Node in an augmented interval tree for O(log n) stabbing queries."""
89
+
90
+ def __init__(self, triple: Triple):
91
+ self.triple = triple
92
+ self.max_end = triple.t_end
93
+ self.left: Optional[_IntervalNode] = None
94
+ self.right: Optional[_IntervalNode] = None
95
+
96
+ def update_max(self):
97
+ self.max_end = self.triple.t_end
98
+ if self.left:
99
+ self.max_end = max(self.max_end, self.left.max_end)
100
+ if self.right:
101
+ self.max_end = max(self.max_end, self.right.max_end)
102
+
103
+
104
+ class IntervalTree:
105
+ """
106
+ Temporal index over triple validity windows using a sorted flat array + bisect.
107
+ Handles 500K+ records without recursion limits.
108
+
109
+ For point-in-time TKGs (t_start == t_end, e.g. tkgl-smallpedia), uses a
110
+ timestamp bucket dict for O(1) exact-match lookup.
111
+ For interval TKGs, uses bisect over sorted t_start array + t_end filter.
112
+
113
+ Stabbing query: 'all triples whose [t_start, t_end] contains t'.
114
+ """
115
+
116
+ def __init__(self):
117
+ self._triples: List[Triple] = [] # all triples, unsorted until finalised
118
+ self._sorted_starts: List[float] = [] # sorted t_start values (parallel to _sorted)
119
+ self._sorted: List[Triple] = [] # triples sorted by t_start
120
+ self._buckets: defaultdict[float, List[Triple]] = defaultdict(list) # for point-in-time
121
+ self._finalised = False
122
+ self._size = 0
123
+
124
+ def __len__(self) -> int:
125
+ return self._size
126
+
127
+ def insert(self, triple: Triple) -> None:
128
+ self._triples.append(triple)
129
+ self._buckets[triple.t_start].append(triple)
130
+ self._size += 1
131
+ self._finalised = False
132
+
133
+ def _finalise(self) -> None:
134
+ """Sort triples by t_start for bisect queries. Called lazily before first stab."""
135
+ self._sorted = sorted(self._triples, key=lambda t: t.t_start)
136
+ self._sorted_starts = [t.t_start for t in self._sorted]
137
+ self._finalised = True
138
+
139
+ def stab(self, t: float) -> List[Triple]:
140
+ """Return all triples valid at time t (i.e. t_start <= t <= t_end)."""
141
+ if not self._finalised:
142
+ self._finalise()
143
+
144
+ import bisect
145
+ # All triples with t_start <= t
146
+ right_idx = bisect.bisect_right(self._sorted_starts, t)
147
+ # Filter for t_end >= t
148
+ return [tr for tr in self._sorted[:right_idx] if tr.t_end >= t]
149
+
150
+
151
+ # ---------------------------------------------------------------------------
152
+ # Main indexer
153
+ # ---------------------------------------------------------------------------
154
+
155
+ class TemporalKGIndexer:
156
+ """
157
+ Dual-index structure over a temporal knowledge graph.
158
+
159
+ Attributes
160
+ ----------
161
+ entity_index : dict[str, list[Triple]]
162
+ Maps each entity (subject or object) to all its triples.
163
+ temporal_index : IntervalTree
164
+ Interval tree over all triples for O(log n) temporal filtering.
165
+ """
166
+
167
+ def __init__(self):
168
+ self.entity_index: defaultdict[str, List[Triple]] = defaultdict(list)
169
+ self.temporal_index: IntervalTree = IntervalTree()
170
+ self._all_triples: List[Triple] = []
171
+
172
+ # ------------------------------------------------------------------
173
+ # Loading
174
+ # ------------------------------------------------------------------
175
+
176
+ def build(self, quadruples: List[Tuple[str, str, str, float, float]]) -> None:
177
+ """
178
+ Build index from a list of (subject, relation, object, t_start, t_end) tuples.
179
+ t_end = None or math.inf means currently valid.
180
+ """
181
+ for s, r, o, t_start, t_end in quadruples:
182
+ t_end = t_end if (t_end is not None and not math.isnan(t_end)) else math.inf
183
+ triple = Triple(subject=s, relation=r, obj=o, t_start=t_start, t_end=t_end)
184
+ self._index_triple(triple)
185
+
186
+ def load_tkgl_smallpedia(self, path: str, delimiter: str = ",") -> None:
187
+ """
188
+ Load tkgl-smallpedia from TGB 2.0 edge file.
189
+ Handles the actual TGB 2.0 format: ts,head,tail,relation_type
190
+ where ts is a point-in-time year (event-based TKG).
191
+ Each event is normalised to interval [ts, ts].
192
+ """
193
+ count = 0
194
+ with open(path, "r", encoding="utf-8") as f:
195
+ reader = csv.DictReader(f, delimiter=delimiter)
196
+ for row in reader:
197
+ # TGB 2.0 tkgl-smallpedia format: ts, head, tail, relation_type
198
+ if "ts" in row:
199
+ t = float(row["ts"])
200
+ triple = Triple(
201
+ subject=row["head"],
202
+ relation=row["relation_type"],
203
+ obj=row["tail"],
204
+ t_start=t,
205
+ t_end=t, # point-in-time event normalised to [t, t]
206
+ )
207
+ # Fallback: generic interval format
208
+ else:
209
+ t_start = float(row.get("start_time", row.get("t_start", 0)))
210
+ raw_end = row.get("end_time", row.get("t_end", None))
211
+ t_end = float(raw_end) if raw_end and raw_end.strip() not in ("", "None", "nan") else math.inf
212
+ triple = Triple(
213
+ subject=row.get("subject", row.get("head", "")),
214
+ relation=row.get("relation", row.get("relation_type", "")),
215
+ obj=row.get("object", row.get("tail", "")),
216
+ t_start=t_start,
217
+ t_end=t_end,
218
+ )
219
+ self._index_triple(triple)
220
+ count += 1
221
+ print(f"[Indexer] Loaded {count:,} triples from {path}")
222
+
223
+ def load_from_json(self, path: str) -> None:
224
+ """Load from a JSON list of {s, r, o, t_start, t_end?} dicts."""
225
+ with open(path, "r", encoding="utf-8") as f:
226
+ data = json.load(f)
227
+ for item in data:
228
+ t_end = item.get("t_end", None)
229
+ triple = Triple(
230
+ subject=item["s"],
231
+ relation=item["r"],
232
+ obj=item["o"],
233
+ t_start=float(item["t_start"]),
234
+ t_end=float(t_end) if t_end is not None else math.inf,
235
+ )
236
+ self._index_triple(triple)
237
+ print(f"[Indexer] Loaded {len(self._all_triples):,} triples from {path}")
238
+
239
+ def _index_triple(self, triple: Triple) -> None:
240
+ self._all_triples.append(triple)
241
+ self.entity_index[triple.subject].append(triple)
242
+ self.entity_index[triple.obj].append(triple)
243
+ self.temporal_index.insert(triple)
244
+
245
+ # ------------------------------------------------------------------
246
+ # Event-based normalisation (ICEWS-style)
247
+ # ------------------------------------------------------------------
248
+
249
+ @staticmethod
250
+ def normalise_event(s: str, r: str, o: str, t: float) -> Triple:
251
+ """Convert a point-in-time event (s, r, o, t) to interval form [t, t]."""
252
+ return Triple(subject=s, relation=r, obj=o, t_start=t, t_end=t)
253
+
254
+ # ------------------------------------------------------------------
255
+ # Query interface
256
+ # ------------------------------------------------------------------
257
+
258
+ def neighbourhood(self, entity: str, t_query: float) -> List[Triple]:
259
+ """
260
+ Return the temporally-filtered 1-hop neighbourhood of `entity` at `t_query`.
261
+ i.e., all triples (entity, r, o, τ) or (s, r, entity, τ) where t_query ∈ τ.
262
+ O(degree(entity)) — filtered from entity index.
263
+ """
264
+ return [t for t in self.entity_index.get(entity, []) if t.valid_at(t_query)]
265
+
266
+ def query_valid_at(self, t: float) -> List[Triple]:
267
+ """
268
+ Return all triples in the graph valid at time t.
269
+ Uses interval tree for O(log n + k) performance.
270
+ """
271
+ return self.temporal_index.stab(t)
272
+
273
+ def entities_for_query(self, t_query: float, mention: str) -> List[str]:
274
+ """
275
+ Simple entity linking: return all entities containing `mention` as substring.
276
+ Replace with a proper entity linker (e.g. ELQ, BLINK) in production.
277
+ """
278
+ return [e for e in self.entity_index if mention.lower() in e.lower()]
279
+
280
+ # ------------------------------------------------------------------
281
+ # Chain validity-window intersection (benchmark/SFT construction only)
282
+ # ------------------------------------------------------------------
283
+
284
+ @staticmethod
285
+ def compose(window: ValidityWindow, triple: Triple, t_query: float) -> Optional[ValidityWindow]:
286
+ """
287
+ Extend `window` by `triple` via validity-window intersection clamped to
288
+ t_query. Used only in benchmark/SFT-data construction, not at inference
289
+ (the retriever uses the per-hop valid_at(t_q) filter via neighbourhood()).
290
+ Returns None if the composed window is empty.
291
+ """
292
+ hop_window = ValidityWindow(triple.t_start, triple.t_end)
293
+ return window.intersect(hop_window, t_query)
294
+
295
+ # ------------------------------------------------------------------
296
+ # Sinusoidal temporal encoding
297
+ # ------------------------------------------------------------------
298
+
299
+ @staticmethod
300
+ def temporal_encoding(t: float, dim: int = 64) -> List[float]:
301
+ """
302
+ Sinusoidal temporal positional encoding (following POSTRA, N04).
303
+ Encodes a year float into a `dim`-dimensional vector.
304
+ """
305
+ encoding = []
306
+ for i in range(0, dim, 2):
307
+ freq = 1.0 / (10000 ** (i / dim))
308
+ encoding.append(math.sin(t * freq))
309
+ encoding.append(math.cos(t * freq))
310
+ return encoding[:dim]
311
+
312
+ # ------------------------------------------------------------------
313
+ # Statistics
314
+ # ------------------------------------------------------------------
315
+
316
+ def stats(self) -> dict:
317
+ n_triples = len(self._all_triples)
318
+ n_entities = len(self.entity_index)
319
+ n_relations = len({t.relation for t in self._all_triples})
320
+ n_open_ended = sum(1 for t in self._all_triples if math.isinf(t.t_end))
321
+ n_inferred = 0 # populated during annotation phase; update after tagger runs
322
+ return {
323
+ "n_triples": n_triples,
324
+ "n_entities": n_entities,
325
+ "n_relations": n_relations,
326
+ "n_currently_valid": n_open_ended,
327
+ "n_inferred_windows": n_inferred,
328
+ "pct_timestamped": round(100 * (n_triples - n_inferred) / max(n_triples, 1), 1),
329
+ }
330
+
331
+ def __repr__(self) -> str:
332
+ s = self.stats()
333
+ return (
334
+ f"TemporalKGIndexer("
335
+ f"{s['n_triples']:,} triples, "
336
+ f"{s['n_entities']:,} entities, "
337
+ f"{s['n_relations']:,} relations, "
338
+ f"{s['pct_timestamped']}% explicitly timestamped)"
339
+ )
340
+
341
+
342
+ # ---------------------------------------------------------------------------
343
+ # LLM timestamp tagger scaffold
344
+ # ---------------------------------------------------------------------------
345
+
346
+ class LLMTimestampTagger:
347
+ """
348
+ Scaffold for the LLM-based temporal tagger used when KG metadata lacks
349
+ explicit timestamps (validity-window annotation).
350
+
351
+ Replace `_call_llm` with your actual LLM API call.
352
+ """
353
+
354
+ PROMPT_TEMPLATE = """
355
+ You are a temporal fact extractor. Given a knowledge graph triple and its associated text,
356
+ extract the validity period of the fact as a start year and end year.
357
+
358
+ Triple: ({subject}, {relation}, {object})
359
+ Associated text: {text}
360
+
361
+ Respond in JSON:
362
+ {{"t_start": <year as float or null>, "t_end": <year as float or null, null if currently valid>}}
363
+
364
+ If no temporal information is available, respond with {{"t_start": null, "t_end": null}}.
365
+ """.strip()
366
+
367
+ def __init__(self, llm_client=None, default_window_width: float = 50.0):
368
+ """
369
+ Args:
370
+ llm_client: any object with a .complete(prompt: str) -> str method.
371
+ default_window_width: fallback window width (years) for triples
372
+ where the tagger returns null (low confidence).
373
+ """
374
+ self.llm_client = llm_client
375
+ self.default_window_width = default_window_width
376
+
377
+ def infer_window(self, triple: Triple, associated_text: str = "") -> Tuple[float, float]:
378
+ """
379
+ Infer a validity window for a triple lacking explicit timestamps.
380
+ Returns (t_start, t_end); t_end = math.inf if currently valid.
381
+ """
382
+ if self.llm_client is None:
383
+ # Fallback: return a wide default window centred on 1990
384
+ return (1900.0, math.inf)
385
+
386
+ prompt = self.PROMPT_TEMPLATE.format(
387
+ subject=triple.subject,
388
+ relation=triple.relation,
389
+ object=triple.obj,
390
+ text=associated_text,
391
+ )
392
+ try:
393
+ response = self._call_llm(prompt)
394
+ data = json.loads(response)
395
+ t_start = float(data["t_start"]) if data.get("t_start") is not None else 1900.0
396
+ t_end = float(data["t_end"]) if data.get("t_end") is not None else math.inf
397
+ return (t_start, t_end)
398
+ except Exception:
399
+ return (1900.0, math.inf)
400
+
401
+ def _call_llm(self, prompt: str) -> str:
402
+ """Override this with your actual LLM API call."""
403
+ return self.llm_client.complete(prompt)
404
+
405
+
406
+ # ---------------------------------------------------------------------------
407
+ # Quick test
408
+ # ---------------------------------------------------------------------------
409
+
410
+ if __name__ == "__main__":
411
+ # Smoke test with synthetic quadruples
412
+ indexer = TemporalKGIndexer()
413
+ indexer.build([
414
+ ("Deutsche_Bank", "has_CFO", "John_Cryan", 2015.0, 2018.0),
415
+ ("Deutsche_Bank", "has_CFO", "Christian_Sewing", 2018.0, math.inf),
416
+ ("Deutsche_Bank", "settled", "LIBOR_Case", 2015.25, 2015.25),
417
+ ("John_Cryan", "member_of", "Deutsche_Bank", 2015.0, 2018.0),
418
+ ("Christian_Sewing", "member_of", "Deutsche_Bank", 2018.0, math.inf),
419
+ ])
420
+
421
+ print(indexer)
422
+ print()
423
+
424
+ # Test 1: neighbourhood at query time 2015
425
+ nbrs = indexer.neighbourhood("Deutsche_Bank", t_query=2015.5)
426
+ print(f"Deutsche_Bank neighbourhood at 2015.5: {len(nbrs)} triples")
427
+ for t in nbrs:
428
+ print(f" ({t.subject}, {t.relation}, {t.obj}) [{t.t_start}–{t.t_end}]")
429
+
430
+ print()
431
+
432
+ # Test 2: composability operator
433
+ w = ValidityWindow.full()
434
+ for triple in nbrs[:2]:
435
+ composed = TemporalKGIndexer.compose(w, triple, t_query=2015.5)
436
+ if composed:
437
+ print(f"Composed window after ({triple.relation}): [{composed.t_start}, {composed.t_end}]")
438
+ w = composed
439
+ else:
440
+ print(f"Chain broken at ({triple.relation}) — temporally inconsistent")
441
+
442
+ print()
443
+
444
+ # Test 3: temporal encoding
445
+ enc = TemporalKGIndexer.temporal_encoding(2015.5, dim=8)
446
+ print(f"Temporal encoding for 2015.5 (dim=8): {[round(x, 4) for x in enc]}")
code/resolve_labels.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TempBench — Wikidata Label Resolver
3
+ =======================================
4
+ Converts Wikidata QIDs and PIDs in benchmark JSONL files into human-readable
5
+ English labels, turning machine-generated questions like:
6
+
7
+ "Q230104's P17 in 1929 was?"
8
+
9
+ into:
10
+
11
+ "What country was Poland in 1929?" (after full template rewrite)
12
+ or at minimum: "Danzig's country in 1929 was?"
13
+
14
+ Two modes:
15
+ 1. API mode (default): fetches labels from Wikidata REST API in batches of 50.
16
+ Requires internet access; rate-limited politely (~1 req/s).
17
+ 2. Dump mode (--label_dump): reads from a pre-downloaded TSV label file
18
+ (format: QID<TAB>label<TAB>description, one per line).
19
+ Faster and offline — use this for production runs.
20
+
21
+ Label dump can be produced via:
22
+ python resolve_labels.py --collect_ids benchmark.jsonl --id_output ids.txt
23
+ # then on a machine with internet:
24
+ python resolve_labels.py --fetch_dump ids.txt --dump_output labels.tsv
25
+ # then resolve:
26
+ python resolve_labels.py --input benchmark.jsonl --label_dump labels.tsv --output benchmark_labelled.jsonl
27
+
28
+ Usage (quick / API mode):
29
+ python resolve_labels.py --input benchmark.jsonl --output benchmark_labelled.jsonl
30
+
31
+ Usage (offline / dump mode):
32
+ python resolve_labels.py --input benchmark.jsonl --label_dump labels.tsv --output benchmark_labelled.jsonl
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import json
39
+ import re
40
+ import sys
41
+ import time
42
+ from pathlib import Path
43
+ from typing import Dict, List, Optional, Set
44
+ try:
45
+ import urllib.request
46
+ import urllib.error
47
+ except ImportError:
48
+ pass
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Wikidata API label fetcher
53
+ # ---------------------------------------------------------------------------
54
+
55
+ WIKIDATA_API = "https://www.wikidata.org/w/api.php"
56
+ BATCH_SIZE = 50 # Wikidata allows up to 50 IDs per wbgetentities call
57
+ RETRY_LIMIT = 3
58
+ SLEEP_BETWEEN_BATCHES = 0.5 # seconds — polite rate limiting
59
+
60
+
61
+ def fetch_labels_api(ids: List[str], lang: str = "en") -> Dict[str, str]:
62
+ """
63
+ Fetch English labels for a list of Wikidata IDs (Q-IDs and P-IDs) via API.
64
+ Returns a dict {id: label}. Missing IDs get empty string.
65
+ """
66
+ labels: Dict[str, str] = {}
67
+
68
+ for i in range(0, len(ids), BATCH_SIZE):
69
+ batch = ids[i : i + BATCH_SIZE]
70
+ ids_str = "|".join(batch)
71
+
72
+ url = (
73
+ f"{WIKIDATA_API}?action=wbgetentities"
74
+ f"&ids={ids_str}"
75
+ f"&props=labels"
76
+ f"&languages={lang}"
77
+ f"&format=json"
78
+ )
79
+
80
+ for attempt in range(RETRY_LIMIT):
81
+ try:
82
+ req = urllib.request.Request(
83
+ url,
84
+ headers={"User-Agent": "TempBench/1.0 (research; label resolver)"},
85
+ )
86
+ with urllib.request.urlopen(req, timeout=15) as resp:
87
+ data = json.loads(resp.read().decode("utf-8"))
88
+
89
+ for qid, entity in data.get("entities", {}).items():
90
+ lab = entity.get("labels", {}).get(lang, {}).get("value", "")
91
+ labels[qid] = lab
92
+
93
+ break # success
94
+
95
+ except Exception as e:
96
+ if attempt < RETRY_LIMIT - 1:
97
+ time.sleep(2 ** attempt)
98
+ else:
99
+ print(f"[Warning] API fetch failed for batch {i//BATCH_SIZE}: {e}", file=sys.stderr)
100
+
101
+ time.sleep(SLEEP_BETWEEN_BATCHES)
102
+ print(f" Fetched {min(i + BATCH_SIZE, len(ids))}/{len(ids)} labels...", end="\r", flush=True)
103
+
104
+ print()
105
+ return labels
106
+
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # Dump-based label loader (offline mode)
110
+ # ---------------------------------------------------------------------------
111
+
112
+ def load_label_dump(dump_path: str) -> Dict[str, str]:
113
+ """
114
+ Load a TSV label dump: QID<TAB>label (one entity per line).
115
+ Lines starting with # are comments.
116
+ """
117
+ labels: Dict[str, str] = {}
118
+ with open(dump_path, "r", encoding="utf-8") as f:
119
+ for line in f:
120
+ line = line.strip()
121
+ if not line or line.startswith("#"):
122
+ continue
123
+ parts = line.split("\t", 2)
124
+ if len(parts) >= 2:
125
+ labels[parts[0]] = parts[1]
126
+ print(f"[LabelDump] Loaded {len(labels):,} labels from {dump_path}")
127
+ return labels
128
+
129
+
130
+ def save_label_dump(labels: Dict[str, str], output_path: str) -> None:
131
+ """Save fetched labels to a TSV dump for offline re-use."""
132
+ with open(output_path, "w", encoding="utf-8") as f:
133
+ f.write("# Wikidata label dump for TempBench\n")
134
+ f.write("# Format: QID<TAB>label\n")
135
+ for qid, label in sorted(labels.items()):
136
+ f.write(f"{qid}\t{label}\n")
137
+ print(f"[LabelDump] Saved {len(labels):,} labels to {output_path}")
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # ID extraction
142
+ # ---------------------------------------------------------------------------
143
+
144
+ QID_PATTERN = re.compile(r'\b(Q\d+|P\d+)\b')
145
+
146
+
147
+ def extract_ids_from_jsonl(path: str) -> Set[str]:
148
+ """Extract all unique Wikidata QIDs and PIDs from a benchmark JSONL."""
149
+ ids: Set[str] = set()
150
+ with open(path, "r", encoding="utf-8") as f:
151
+ for line in f:
152
+ line = line.strip()
153
+ if not line:
154
+ continue
155
+ ids.update(QID_PATTERN.findall(line))
156
+ return ids
157
+
158
+
159
+ # ---------------------------------------------------------------------------
160
+ # Question rewriter
161
+ # ---------------------------------------------------------------------------
162
+
163
+ RELATION_TEMPLATES: Dict[str, str] = {
164
+ # Standard Wikidata properties → natural language verbs/phrases
165
+ "P17": "country",
166
+ "P19": "place of birth",
167
+ "P20": "place of death",
168
+ "P21": "sex or gender",
169
+ "P22": "father",
170
+ "P25": "mother",
171
+ "P26": "spouse",
172
+ "P27": "country of citizenship",
173
+ "P39": "position held",
174
+ "P40": "child",
175
+ "P50": "author",
176
+ "P57": "director",
177
+ "P131": "located in",
178
+ "P136": "genre",
179
+ "P155": "follows",
180
+ "P156": "followed by",
181
+ "P159": "headquarters",
182
+ "P166": "award received",
183
+ "P175": "performer",
184
+ "P176": "manufacturer",
185
+ "P178": "developer",
186
+ "P184": "doctoral advisor",
187
+ "P185": "doctoral student",
188
+ "P190": "twinned with",
189
+ "P276": "location",
190
+ "P286": "head coach",
191
+ "P355": "subsidiary",
192
+ "P361": "part of",
193
+ "P413": "position played",
194
+ "P452": "industry",
195
+ "P488": "chairperson",
196
+ "P495": "country of origin",
197
+ "P527": "has part",
198
+ "P571": "inception",
199
+ "P576": "dissolved",
200
+ "P577": "publication date",
201
+ "P580": "start time",
202
+ "P582": "end time",
203
+ "P598": "commander",
204
+ "P607": "conflict",
205
+ "P664": "organizer",
206
+ "P710": "participant",
207
+ "P737": "influenced by",
208
+ "P749": "parent organization",
209
+ "P800": "notable work",
210
+ "P921": "main subject",
211
+ "P1037": "manager",
212
+ "P1308": "officeholder",
213
+ "P2632": "point in time",
214
+ "P3342": "significant person",
215
+ }
216
+
217
+
218
+ class LabelApplier:
219
+ """
220
+ Applies resolved labels to benchmark questions and subgraphs.
221
+ Replaces QIDs/PIDs in-place and rewrites question text.
222
+ """
223
+
224
+ def __init__(self, labels: Dict[str, str]):
225
+ self.labels = labels
226
+
227
+ def resolve(self, qid: str) -> str:
228
+ """Return human-readable label for a QID/PID, falling back to the raw ID."""
229
+ label = self.labels.get(qid, "")
230
+ return label if label else qid
231
+
232
+ def resolve_relation(self, pid: str) -> str:
233
+ """Return a natural-language relation phrase, using RELATION_TEMPLATES first."""
234
+ if pid in RELATION_TEMPLATES:
235
+ return RELATION_TEMPLATES[pid]
236
+ # Fallback to fetched label
237
+ label = self.labels.get(pid, "")
238
+ return label if label else pid
239
+
240
+ def rewrite_question(self, question: str, t_query: float) -> str:
241
+ """
242
+ Rewrite a machine-generated question by substituting labels for QIDs/PIDs.
243
+ Also rewrites common template patterns for naturalness.
244
+ """
245
+ # Step 1: find all QIDs/PIDs in the question
246
+ qids = QID_PATTERN.findall(question)
247
+ substituted = question
248
+ for qid in qids:
249
+ if re.match(r'^P\d+$', qid):
250
+ substituted = substituted.replace(qid, self.resolve_relation(qid))
251
+ else:
252
+ substituted = substituted.replace(qid, self.resolve(qid))
253
+
254
+ # Step 2: rewrite common template patterns
255
+ # Pattern: "X's RELATION in YEAR was?" → "What was X's RELATION in YEAR?"
256
+ m = re.match(r"^(.+)'s (.+) in (\d{4}) was\?$", substituted)
257
+ if m:
258
+ subj, rel, year = m.group(1), m.group(2), m.group(3)
259
+ substituted = f"What was {subj}'s {rel} in {year}?"
260
+
261
+ # Pattern: "Who was the RELATION of ENTITY in YEAR?" → keep as-is (already natural)
262
+ # Pattern: "Who was the RELATION of ENTITY before OTHER?" → keep as-is
263
+
264
+ return substituted
265
+
266
+ def rewrite_triple(self, triple: dict) -> dict:
267
+ """Apply labels to a single triple dict {s, r, o, t_start, t_end}."""
268
+ return {
269
+ **triple,
270
+ "s": self.resolve(triple["s"]),
271
+ "s_id": triple["s"],
272
+ "r": self.resolve_relation(triple["r"]),
273
+ "r_id": triple["r"],
274
+ "o": self.resolve(triple["o"]),
275
+ "o_id": triple["o"],
276
+ }
277
+
278
+ def rewrite_question_record(self, record: dict) -> dict:
279
+ """Apply labels to all fields of a benchmark question record."""
280
+ out = dict(record)
281
+
282
+ out["answer_raw"] = record["answer"]
283
+ out["answer"] = self.resolve(record["answer"])
284
+ out["question_raw"] = record["question"]
285
+ out["question"] = self.rewrite_question(record["question"], record["t_query"])
286
+
287
+ for field in ("S_star", "S_dist", "S_stale"):
288
+ if field in record and record[field]:
289
+ out[field] = [self.rewrite_triple(t) for t in record[field]]
290
+
291
+ return out
292
+
293
+
294
+ # ---------------------------------------------------------------------------
295
+ # Main pipeline
296
+ # ---------------------------------------------------------------------------
297
+
298
+ def resolve_benchmark(
299
+ input_path: str,
300
+ output_path: str,
301
+ label_dump: Optional[str] = None,
302
+ lang: str = "en",
303
+ save_dump: Optional[str] = None,
304
+ ) -> None:
305
+ """
306
+ Full label resolution pipeline for a benchmark JSONL file.
307
+ """
308
+ print(f"[Resolver] Input: {input_path}")
309
+
310
+ # Step 1: extract all IDs
311
+ print("[Step 1] Extracting Wikidata IDs...")
312
+ ids = extract_ids_from_jsonl(input_path)
313
+ print(f" Found {len(ids):,} unique IDs (Q-IDs + P-IDs)")
314
+
315
+ # Step 2: load or fetch labels
316
+ if label_dump and Path(label_dump).exists():
317
+ labels = load_label_dump(label_dump)
318
+ # Fetch any IDs missing from the dump
319
+ missing = [qid for qid in ids if qid not in labels]
320
+ if missing:
321
+ print(f"[Step 2] Fetching {len(missing):,} labels missing from dump via API...")
322
+ fetched = fetch_labels_api(missing, lang=lang)
323
+ labels.update(fetched)
324
+ else:
325
+ print(f"[Step 2] Fetching {len(ids):,} labels from Wikidata API...")
326
+ labels = fetch_labels_api(sorted(ids), lang=lang)
327
+
328
+ if save_dump:
329
+ save_label_dump(labels, save_dump)
330
+
331
+ # Coverage report
332
+ resolved = sum(1 for qid in ids if labels.get(qid, ""))
333
+ unresolved = [qid for qid in ids if not labels.get(qid, "")]
334
+ print(f" Label coverage: {resolved}/{len(ids)} ({100*resolved/max(len(ids),1):.1f}%)")
335
+ if unresolved:
336
+ print(f" Unresolved IDs (using raw): {unresolved[:10]}{'...' if len(unresolved)>10 else ''}")
337
+
338
+ # Step 3: apply labels to all records
339
+ print("[Step 3] Applying labels to benchmark records...")
340
+ applier = LabelApplier(labels)
341
+ out_path = Path(output_path)
342
+ out_path.parent.mkdir(parents=True, exist_ok=True)
343
+
344
+ n_written = 0
345
+ with open(input_path, "r", encoding="utf-8") as fin, \
346
+ open(output_path, "w", encoding="utf-8") as fout:
347
+ for line in fin:
348
+ line = line.strip()
349
+ if not line:
350
+ continue
351
+ record = json.loads(line)
352
+ resolved_record = applier.rewrite_question_record(record)
353
+ fout.write(json.dumps(resolved_record, ensure_ascii=False) + "\n")
354
+ n_written += 1
355
+
356
+ print(f"[Resolver] Done — {n_written:,} records written to {output_path}")
357
+
358
+
359
+ # ---------------------------------------------------------------------------
360
+ # CLI
361
+ # ---------------------------------------------------------------------------
362
+
363
+ def main():
364
+ parser = argparse.ArgumentParser(
365
+ description="Resolve Wikidata QIDs/PIDs in TempBench benchmark JSONL to human-readable labels."
366
+ )
367
+ parser.add_argument("--input", required=False, help="Input benchmark JSONL path")
368
+ parser.add_argument("--output", required=False, help="Output labelled JSONL path")
369
+ parser.add_argument("--label_dump", default=None, help="Path to pre-fetched TSV label dump (QID<TAB>label)")
370
+ parser.add_argument("--save_dump", default=None, help="Save fetched labels to this TSV file for reuse")
371
+ parser.add_argument("--lang", default="en", help="Wikidata label language (default: en)")
372
+ parser.add_argument("--collect_ids", default=None, help="Only collect IDs from JSONL and write to --id_output")
373
+ parser.add_argument("--id_output", default="ids.txt", help="Output file for collected IDs")
374
+ parser.add_argument("--fetch_dump", default=None, help="Fetch labels for IDs in this file and save to --dump_output")
375
+ parser.add_argument("--dump_output", default="labels.tsv", help="Output file for fetched label dump")
376
+
377
+ args = parser.parse_args()
378
+
379
+ # Mode 1: just collect IDs
380
+ if args.collect_ids:
381
+ ids = extract_ids_from_jsonl(args.collect_ids)
382
+ with open(args.id_output, "w") as f:
383
+ for qid in sorted(ids):
384
+ f.write(qid + "\n")
385
+ print(f"[ID Collector] {len(ids):,} unique IDs written to {args.id_output}")
386
+ return
387
+
388
+ # Mode 2: fetch dump from ID list
389
+ if args.fetch_dump:
390
+ with open(args.fetch_dump) as f:
391
+ ids = [line.strip() for line in f if line.strip() and not line.startswith("#")]
392
+ print(f"[DumpFetcher] Fetching labels for {len(ids):,} IDs...")
393
+ labels = fetch_labels_api(ids, lang=args.lang)
394
+ save_label_dump(labels, args.dump_output)
395
+ return
396
+
397
+ # Mode 3: full resolution
398
+ if not args.input or not args.output:
399
+ parser.error("--input and --output are required for label resolution")
400
+
401
+ resolve_benchmark(
402
+ input_path=args.input,
403
+ output_path=args.output,
404
+ label_dump=args.label_dump,
405
+ lang=args.lang,
406
+ save_dump=args.save_dump,
407
+ )
408
+
409
+
410
+ if __name__ == "__main__":
411
+ main()
v1.0.1-addendum.md CHANGED
@@ -1,101 +1,101 @@
1
- # TempBench dataset card — v1.0.1 addendum
2
-
3
- Ready-to-paste section for the TempBench dataset card (DOI `10.57967/hf/8930`).
4
- Append under a "Known issues and evaluation protocol (v1.0.1)" heading. All
5
- numbers below were computed directly from the released artifacts
6
- (`benchmark_labelled.jsonl` and the reference-baseline evaluation outputs);
7
- regeneration commands are listed at the end.
8
-
9
- ---
10
-
11
- ## Known issues and evaluation protocol (v1.0.1)
12
-
13
- ### 1. Interval-operator answer leakage through `t_query`
14
-
15
- **Mechanism.** Every `interval` question's answer is a year, and the
16
- construction pipeline sets the question's `t_query` field exactly equal to that
17
- gold answer year. This holds for 864/864 (100.0%) of interval questions and for
18
- 0.0% of every other operator. Any evaluation protocol that exposes `t_query` to
19
- the system — in particular, prompt templates that render a `<t={t_query}>`
20
- prefix — makes the interval slice answerable by copying the timestamp out of
21
- the prompt, with no retrieval and no reasoning.
22
-
23
- **Affected fraction (exact, per split).**
24
-
25
- | Split | questions | interval | share |
26
- |---|---:|---:|---:|
27
- | train | 6,096 | 601 | 9.86% |
28
- | dev | 871 | 100 | 11.48% |
29
- | test | 1,743 | 163 | 9.35% |
30
- | **all** | **8,710** | **864** | **9.92%** |
31
-
32
- **Evidence that the leak is exploited, not merely exploitable.** Reference
33
- systems with no retrieval at all (prompt is `<t={t_query}> {question}\nAnswer:`)
34
- score at or near 1.0 on the interval slice: a no-retrieval T-GRPO policy scores
35
- overall EM 0.364 but interval EM 1.000; a no-retrieval SFT baseline scores
36
- 0.305 overall but 0.994 on interval. On retrieval-conditioned reference
37
- systems, excluding the interval slice moves overall test EM from 0.865 to 0.851
38
- (CoT), 0.896 to 0.885 (terse), and 0.138 to 0.113 (BM25 vanilla RAG). The
39
- interval slice also posts the highest values on every retrieval-quality slice
40
- (TRP 0.376, CCR 0.920, and stale-blind CCR 0.773 where all other operators fall
41
- to 0.03–0.08), so per-operator retrieval comparisons involving interval are
42
- contaminated as well.
43
-
44
- **Evaluation-protocol fix.** Do not render `<t={t_query}>` (or otherwise expose
45
- `t_query`) for interval questions. Interval questions are self-contained: the
46
- reference event is stated in the question text, and the query year appears in
47
- the question text for only 2/864 interval items. When comparing against the
48
- reference-baseline numbers shipped with v1.0, either apply the same protocol or
49
- report EM with the interval slice excluded alongside overall EM. Do not report
50
- interval-slice accuracy obtained under a `t_query`-exposing protocol as a
51
- capability result.
52
-
53
- **What is not affected.** The gold supporting subgraphs (`S_star`), distractor
54
- subgraphs (`S_dist`), and stale subgraphs (`S_stale`) of interval questions are
55
- correct as released; the leak is a property of the evaluation-prompt protocol,
56
- not of the graph annotations. Question text, answers, and all non-interval
57
- operators are unaffected.
58
-
59
- ### 2. Stale negatives: construction property and intended use
60
-
61
- `S_stale` replaces one gold hop with the same `(s, r, o)` at a time invalid at
62
- `t_query`. Two properties of this construction should inform how the negatives
63
- are used:
64
-
65
- - **Excluded by a correct temporal filter, by definition.** The source KG is
66
- point-in-time (`t_start == t_end`), so validity at `t_query` reduces to
67
- exact-year equality, and a stale negative — required at construction to be
68
- invalid at `t_query` — is removed by any correctly implemented temporal
69
- filter. Empirically, 0 of the 1,429 functional stale negatives in the test
70
- split are valid at `t_query`, and the temporally-filtered reference retriever
71
- retrieves 0 of them (stale negative-hit-rate 0.000). This is a structural
72
- consequence, not a measured difficulty. Stale negatives should not be
73
- described as hard negatives for temporally-aware systems.
74
- - **100% BM25-tied: invisible to lexical ranking.** A stale negative and the
75
- gold hop it replaces differ only in the validity window, which is not a
76
- lexical feature. Under BM25 over `label(s) label(r) label(o)` documents,
77
- 1,429/1,429 (100.0%) of functional stale pairs score as exact ties.
78
-
79
- **Intended use.** The stale negatives are a diagnostic instrument for
80
- time-blind retrieval: a system that ignores temporal validity admits wrong-time
81
- evidence of the gold fact's type into 85.9% of retrievals (the exact released
82
- stale triple into 8.7%), while a temporally-filtered system admits none. They
83
- measure whether a retriever applies temporal filtering at all, not how well it
84
- ranks under temporal ambiguity. Per-question functional-negative flags ship
85
- with the release; stale-dependent evaluation should be restricted to the
86
- functional subset (1,429/1,743 test questions), and the interval × stale cell
87
- (n=12 functional) is too small to support slice-level claims.
88
-
89
- ---
90
-
91
- ## Regeneration
92
-
93
- From the code release, `code/` directory, CPU-only:
94
-
95
- ```
96
- python camera_ready_tables.py --leak # leak mechanism + EM with/without interval
97
- python camera_ready_tables.py --neg # negative-hit-rate + BM25-tie analysis
98
- python eval_negatives_ranking.py # rebuilds the negatives-ranking artifact (~4 min)
99
- ```
100
-
101
- Split counts derive from the `split` field of `benchmark_labelled.jsonl`.
 
1
+ # TempBench dataset card — v1.0.1 addendum
2
+
3
+ Ready-to-paste section for the TempBench dataset card (DOI `10.57967/hf/10071`).
4
+ Append under a "Known issues and evaluation protocol (v1.0.1)" heading. All
5
+ numbers below were computed directly from the released artifacts
6
+ (`benchmark_labelled.jsonl` and the reference-baseline evaluation outputs);
7
+ regeneration commands are listed at the end.
8
+
9
+ ---
10
+
11
+ ## Known issues and evaluation protocol (v1.0.1)
12
+
13
+ ### 1. Interval-operator answer leakage through `t_query`
14
+
15
+ **Mechanism.** Every `interval` question's answer is a year, and the
16
+ construction pipeline sets the question's `t_query` field exactly equal to that
17
+ gold answer year. This holds for 864/864 (100.0%) of interval questions and for
18
+ 0.0% of every other operator. Any evaluation protocol that exposes `t_query` to
19
+ the system — in particular, prompt templates that render a `<t={t_query}>`
20
+ prefix — makes the interval slice answerable by copying the timestamp out of
21
+ the prompt, with no retrieval and no reasoning.
22
+
23
+ **Affected fraction (exact, per split).**
24
+
25
+ | Split | questions | interval | share |
26
+ |---|---:|---:|---:|
27
+ | train | 6,096 | 601 | 9.86% |
28
+ | dev | 871 | 100 | 11.48% |
29
+ | test | 1,743 | 163 | 9.35% |
30
+ | **all** | **8,710** | **864** | **9.92%** |
31
+
32
+ **Evidence that the leak is exploited, not merely exploitable.** Reference
33
+ systems with no retrieval at all (prompt is `<t={t_query}> {question}\nAnswer:`)
34
+ score at or near 1.0 on the interval slice: a no-retrieval T-GRPO policy scores
35
+ overall EM 0.364 but interval EM 1.000; a no-retrieval SFT baseline scores
36
+ 0.305 overall but 0.994 on interval. On retrieval-conditioned reference
37
+ systems, excluding the interval slice moves overall test EM from 0.865 to 0.851
38
+ (CoT), 0.896 to 0.885 (terse), and 0.138 to 0.113 (BM25 vanilla RAG). The
39
+ interval slice also posts the highest values on every retrieval-quality slice
40
+ (TRP 0.376, CCR 0.920, and stale-blind CCR 0.773 where all other operators fall
41
+ to 0.03–0.08), so per-operator retrieval comparisons involving interval are
42
+ contaminated as well.
43
+
44
+ **Evaluation-protocol fix.** Do not render `<t={t_query}>` (or otherwise expose
45
+ `t_query`) for interval questions. Interval questions are self-contained: the
46
+ reference event is stated in the question text, and the query year appears in
47
+ the question text for only 2/864 interval items. When comparing against the
48
+ reference-baseline numbers shipped with v1.0, either apply the same protocol or
49
+ report EM with the interval slice excluded alongside overall EM. Do not report
50
+ interval-slice accuracy obtained under a `t_query`-exposing protocol as a
51
+ capability result.
52
+
53
+ **What is not affected.** The gold supporting subgraphs (`S_star`), distractor
54
+ subgraphs (`S_dist`), and stale subgraphs (`S_stale`) of interval questions are
55
+ correct as released; the leak is a property of the evaluation-prompt protocol,
56
+ not of the graph annotations. Question text, answers, and all non-interval
57
+ operators are unaffected.
58
+
59
+ ### 2. Stale negatives: construction property and intended use
60
+
61
+ `S_stale` replaces one gold hop with the same `(s, r, o)` at a time invalid at
62
+ `t_query`. Two properties of this construction should inform how the negatives
63
+ are used:
64
+
65
+ - **Excluded by a correct temporal filter, by definition.** The source KG is
66
+ point-in-time (`t_start == t_end`), so validity at `t_query` reduces to
67
+ exact-year equality, and a stale negative — required at construction to be
68
+ invalid at `t_query` — is removed by any correctly implemented temporal
69
+ filter. Empirically, 0 of the 1,429 functional stale negatives in the test
70
+ split are valid at `t_query`, and the temporally-filtered reference retriever
71
+ retrieves 0 of them (stale negative-hit-rate 0.000). This is a structural
72
+ consequence, not a measured difficulty. Stale negatives should not be
73
+ described as hard negatives for temporally-aware systems.
74
+ - **100% BM25-tied: invisible to lexical ranking.** A stale negative and the
75
+ gold hop it replaces differ only in the validity window, which is not a
76
+ lexical feature. Under BM25 over `label(s) label(r) label(o)` documents,
77
+ 1,429/1,429 (100.0%) of functional stale pairs score as exact ties.
78
+
79
+ **Intended use.** The stale negatives are a diagnostic instrument for
80
+ time-blind retrieval: a system that ignores temporal validity admits wrong-time
81
+ evidence of the gold fact's type into 85.9% of retrievals (the exact released
82
+ stale triple into 8.7%), while a temporally-filtered system admits none. They
83
+ measure whether a retriever applies temporal filtering at all, not how well it
84
+ ranks under temporal ambiguity. Per-question functional-negative flags ship
85
+ with the release; stale-dependent evaluation should be restricted to the
86
+ functional subset (1,429/1,743 test questions), and the interval × stale cell
87
+ (n=12 functional) is too small to support slice-level claims.
88
+
89
+ ---
90
+
91
+ ## Regeneration
92
+
93
+ From the code release, `code/` directory, CPU-only:
94
+
95
+ ```
96
+ python camera_ready_tables.py --leak # leak mechanism + EM with/without interval
97
+ python camera_ready_tables.py --neg # negative-hit-rate + BM25-tie analysis
98
+ python eval_negatives_ranking.py # rebuilds the negatives-ranking artifact (~4 min)
99
+ ```
100
+
101
+ Split counts derive from the `split` field of `benchmark_labelled.jsonl`.