TabQueryBench commited on
Commit
8951aae
·
verified ·
1 Parent(s): 6e4df56

Upload Figure 6 tail-threshold code bundle

Browse files
evaluation/tail/tail_threshold_code/README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This directory contains the minimum local code needed to reproduce the Figure 6 tail-threshold stress analysis and render its paper-facing outputs.
2
+
3
+ Main entrypoints:
4
+ - `scripts/run_tail_threshold.py`: computes the tail-threshold experiment and writes a run bundle.
5
+ - `scripts/render_tail_stress_main_figure.py`: renders the main stress figure from summary CSV tables.
6
+ - `scripts/render_tail_metric_combined_tikz.py`: renders the combined submetric figure as PGFPlots/TikZ.
7
+
8
+ Key dependencies included here:
9
+ - `src/eval/tail_threshold/runner.py`
10
+ - `src/eval/common.py`
11
+ - `scripts/render_tail_metric_model_grid.py`
12
+
13
+ Expected result inputs:
14
+ - `evaluation/tail/tail_threshold_runs/20260505_latest48_keyset_tail_threshold/summaries/`
15
+ - `evaluation/tail/tail_threshold_runs/20260505_latest48_keyset_tail_threshold/tables/`
16
+
17
+ Expected rendered outputs:
18
+ - `evaluation/tail/tail_threshold_final/`
evaluation/tail/tail_threshold_code/manifest.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "artifact": "figure6_tail_threshold_code_bundle",
3
+ "purpose": "Minimum code bundle for computing and rendering Figure 6 tail-threshold stress artifacts",
4
+ "source_repo_subpaths": [
5
+ "scripts/run_tail_threshold.py",
6
+ "scripts/render_tail_stress_main_figure.py",
7
+ "scripts/render_tail_metric_combined_tikz.py",
8
+ "scripts/render_tail_metric_model_grid.py",
9
+ "src/eval/tail_threshold/runner.py",
10
+ "src/eval/common.py"
11
+ ],
12
+ "source_run_tag": "20260505_latest48_keyset_tail_threshold",
13
+ "notes": [
14
+ "The run bundle itself lives under evaluation/tail/tail_threshold_runs/20260505_latest48_keyset_tail_threshold.",
15
+ "The final rendered figure assets live under evaluation/tail/tail_threshold_final."
16
+ ]
17
+ }
evaluation/tail/tail_threshold_code/scripts/render_tail_metric_combined_tikz.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Render the combined tail-submetric preview as a native PGFPlots figure."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+ import sys
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
14
+ if str(PROJECT_ROOT) not in sys.path:
15
+ sys.path.insert(0, str(PROJECT_ROOT))
16
+
17
+ from scripts.render_tail_metric_model_grid import _load_model_threshold, _metric_pivot, _model_order
18
+ from scripts.render_tail_stress_main_figure import DECOMP_COLORS
19
+
20
+
21
+ METRICS = [
22
+ ("tail_set_consistency", "Tail set consistency"),
23
+ ("tail_mass_similarity", "Tail mass similarity"),
24
+ ("tail_concentration_consistency", "Tail concentration consistency"),
25
+ ]
26
+
27
+ COLOR_NAMES = {
28
+ "tail_set_consistency": "tailsetmetric",
29
+ "tail_mass_similarity": "tailmassmetric",
30
+ "tail_concentration_consistency": "tailconcmetric",
31
+ }
32
+
33
+
34
+ def _build_parser() -> argparse.ArgumentParser:
35
+ parser = argparse.ArgumentParser(description=__doc__)
36
+ parser.add_argument("--tables-dir", type=Path, required=True)
37
+ parser.add_argument("--embedded-output", type=Path, required=True)
38
+ parser.add_argument("--standalone-output", type=Path)
39
+ parser.add_argument("--paper-embedded-output", type=Path)
40
+ return parser
41
+
42
+
43
+ def _fmt(value: float) -> str:
44
+ return f"{value:.6f}"
45
+
46
+
47
+ def _write(path: Path, text: str) -> None:
48
+ path.parent.mkdir(parents=True, exist_ok=True)
49
+ path.write_text(text, encoding="utf-8")
50
+
51
+
52
+ def _build_embedded_tex(df: pd.DataFrame) -> str:
53
+ model_order = _model_order(df)
54
+ payloads: list[dict[str, object]] = []
55
+
56
+ for metric, label in METRICS:
57
+ pivot = _metric_pivot(df, metric, model_order)
58
+ values = pivot.to_numpy(dtype=float)
59
+ payloads.append(
60
+ {
61
+ "metric": metric,
62
+ "label": label,
63
+ "mean": np.nanmean(values, axis=1),
64
+ "q25": np.nanquantile(values, 0.25, axis=1),
65
+ "q75": np.nanquantile(values, 0.75, axis=1),
66
+ "vmin": np.nanmin(values, axis=1),
67
+ "vmax": np.nanmax(values, axis=1),
68
+ }
69
+ )
70
+
71
+ offsets = [-0.24, 0.0, 0.24]
72
+ box_width = 0.18
73
+
74
+ lines: list[str] = []
75
+ lines.append(r"\definecolor{tailsetmetric}{HTML}{" + DECOMP_COLORS["tail_set_consistency_mean"].lstrip("#") + "}")
76
+ lines.append(r"\definecolor{tailmassmetric}{HTML}{" + DECOMP_COLORS["tail_mass_similarity_mean"].lstrip("#") + "}")
77
+ lines.append(r"\definecolor{tailconcmetric}{HTML}{" + DECOMP_COLORS["tail_concentration_consistency_mean"].lstrip("#") + "}")
78
+ lines.append(r"\begin{tikzpicture}")
79
+ lines.append(r"\begin{axis}[")
80
+ lines.append(r" width=17.6cm,")
81
+ lines.append(r" height=6.9cm,")
82
+ lines.append(r" xmin=-0.65, xmax=" + _fmt(len(model_order) - 0.35) + ",")
83
+ lines.append(r" ymin=0.0, ymax=1.0,")
84
+ lines.append(r" xtick={0,...," + str(len(model_order) - 1) + r"},")
85
+ lines.append(r" xticklabels={" + ",".join(model_order) + r"},")
86
+ lines.append(r" xticklabel style={rotate=30, anchor=east, font=\small},")
87
+ lines.append(r" yticklabel style={font=\small},")
88
+ lines.append(r" xlabel={Model},")
89
+ lines.append(r" ylabel={Score},")
90
+ lines.append(r" axis line style={draw=gray!65, line width=0.8pt},")
91
+ lines.append(r" tick style={black, line width=0.8pt},")
92
+ lines.append(r" grid=major,")
93
+ lines.append(r" major grid style={draw=gray!22, dashed},")
94
+ lines.append(r" axis background/.style={fill=white},")
95
+ lines.append(r" label style={font=\small},")
96
+ lines.append(r" clip=false,")
97
+ lines.append(r"]")
98
+
99
+ for boundary in range(len(model_order) - 1):
100
+ x = boundary + 0.5
101
+ lines.append(
102
+ r"\draw[gray!22, line width=0.6pt] (axis cs:"
103
+ + _fmt(x)
104
+ + r",0.0) -- (axis cs:"
105
+ + _fmt(x)
106
+ + r",1.0);"
107
+ )
108
+
109
+ for payload, offset in zip(payloads, offsets):
110
+ metric = str(payload["metric"])
111
+ color_name = COLOR_NAMES[metric]
112
+ means = np.asarray(payload["mean"], dtype=float)
113
+ q25 = np.asarray(payload["q25"], dtype=float)
114
+ q75 = np.asarray(payload["q75"], dtype=float)
115
+ vmin = np.asarray(payload["vmin"], dtype=float)
116
+ vmax = np.asarray(payload["vmax"], dtype=float)
117
+
118
+ for idx in range(len(model_order)):
119
+ if np.isnan(means[idx]):
120
+ continue
121
+ xpos = idx + offset
122
+ left = xpos - box_width / 2.0
123
+ right = xpos + box_width / 2.0
124
+ low = vmin[idx]
125
+ high = vmax[idx]
126
+ cap_left = xpos - 0.045
127
+ cap_right = xpos + 0.045
128
+ box_bottom = q25[idx]
129
+ box_top = max(q25[idx] + 1e-6, q75[idx])
130
+ mean = means[idx]
131
+
132
+ lines.append(
133
+ r"\path[fill="
134
+ + color_name
135
+ + r", fill opacity=0.28, draw=none] (axis cs:"
136
+ + _fmt(left)
137
+ + ","
138
+ + _fmt(box_bottom)
139
+ + r") rectangle (axis cs:"
140
+ + _fmt(right)
141
+ + ","
142
+ + _fmt(box_top)
143
+ + r");"
144
+ )
145
+ lines.append(
146
+ r"\draw["
147
+ + color_name
148
+ + r", line width=1.15pt] (axis cs:"
149
+ + _fmt(xpos)
150
+ + ","
151
+ + _fmt(low)
152
+ + r") -- (axis cs:"
153
+ + _fmt(xpos)
154
+ + ","
155
+ + _fmt(high)
156
+ + r");"
157
+ )
158
+ lines.append(
159
+ r"\draw["
160
+ + color_name
161
+ + r", line width=1.15pt] (axis cs:"
162
+ + _fmt(cap_left)
163
+ + ","
164
+ + _fmt(low)
165
+ + r") -- (axis cs:"
166
+ + _fmt(cap_right)
167
+ + ","
168
+ + _fmt(low)
169
+ + r");"
170
+ )
171
+ lines.append(
172
+ r"\draw["
173
+ + color_name
174
+ + r", line width=1.15pt] (axis cs:"
175
+ + _fmt(cap_left)
176
+ + ","
177
+ + _fmt(high)
178
+ + r") -- (axis cs:"
179
+ + _fmt(cap_right)
180
+ + ","
181
+ + _fmt(high)
182
+ + r");"
183
+ )
184
+ lines.append(
185
+ r"\addplot[only marks, mark=square*, mark size=2.2pt, color="
186
+ + color_name
187
+ + r"] coordinates {("
188
+ + _fmt(xpos)
189
+ + ","
190
+ + _fmt(mean)
191
+ + r")};"
192
+ )
193
+
194
+ lines.append(
195
+ r"\node[anchor=west, font=\small] at (rel axis cs:0.01,1.035) {"
196
+ r"\textcolor{tailsetmetric}{Tail set consistency}"
197
+ r"\quad"
198
+ r"\textcolor{tailmassmetric}{Tail mass similarity}"
199
+ r"\quad"
200
+ r"\textcolor{tailconcmetric}{Tail concentration consistency}"
201
+ r"};"
202
+ )
203
+ lines.append(
204
+ r"\node[anchor=east, font=\small, text=gray!70!black] at (rel axis cs:0.995,1.035) {"
205
+ r"square = mean \quad whisker = min--max \quad box = IQR"
206
+ r"};"
207
+ )
208
+ lines.append(r"\end{axis}")
209
+ lines.append(r"\end{tikzpicture}")
210
+ lines.append("")
211
+ return "\n".join(lines)
212
+
213
+
214
+ def _build_standalone_tex(embedded_name: str) -> str:
215
+ return "\n".join(
216
+ [
217
+ r"\documentclass[tikz,border=6pt]{standalone}",
218
+ r"\usepackage{pgfplots}",
219
+ r"\pgfplotsset{compat=1.18}",
220
+ r"\begin{document}",
221
+ r"\input{" + embedded_name + r"}",
222
+ r"\end{document}",
223
+ "",
224
+ ]
225
+ )
226
+
227
+
228
+ def main() -> int:
229
+ args = _build_parser().parse_args()
230
+ df = _load_model_threshold(args.tables_dir)
231
+ embedded_tex = _build_embedded_tex(df)
232
+ _write(args.embedded_output, embedded_tex)
233
+
234
+ if args.paper_embedded_output:
235
+ _write(args.paper_embedded_output, embedded_tex)
236
+
237
+ if args.standalone_output:
238
+ standalone_tex = _build_standalone_tex(args.embedded_output.name)
239
+ _write(args.standalone_output, standalone_tex)
240
+
241
+ return 0
242
+
243
+
244
+ if __name__ == "__main__":
245
+ raise SystemExit(main())
evaluation/tail/tail_threshold_code/scripts/render_tail_metric_model_grid.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Render six model-by-threshold metric figures for tail submetrics."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+ import sys
9
+
10
+ import matplotlib
11
+
12
+ matplotlib.use("Agg")
13
+ import matplotlib.pyplot as plt
14
+ import numpy as np
15
+ import pandas as pd
16
+ from matplotlib import colors as mcolors
17
+ from matplotlib.lines import Line2D
18
+ from matplotlib.patches import Patch
19
+
20
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
21
+ if str(PROJECT_ROOT) not in sys.path:
22
+ sys.path.insert(0, str(PROJECT_ROOT))
23
+
24
+ from scripts.render_tail_stress_main_figure import MODEL_COLORS, THRESHOLD_ORDER
25
+
26
+
27
+ METRICS = [
28
+ ("tail_set_consistency", "Tail set consistency score"),
29
+ ("tail_mass_similarity", "Tail mass similarity score"),
30
+ ("tail_concentration_consistency", "Tail concentration consistency score"),
31
+ ]
32
+
33
+
34
+ def _build_parser() -> argparse.ArgumentParser:
35
+ parser = argparse.ArgumentParser(description=__doc__)
36
+ parser.add_argument("--tables-dir", type=Path, required=True)
37
+ parser.add_argument("--output-dir", type=Path, required=True)
38
+ return parser
39
+
40
+
41
+ def _configure_style() -> None:
42
+ plt.rcParams.update(
43
+ {
44
+ "font.family": "DejaVu Sans",
45
+ "font.size": 8,
46
+ "axes.titlesize": 10.0,
47
+ "axes.labelsize": 9,
48
+ "xtick.labelsize": 8,
49
+ "ytick.labelsize": 8,
50
+ "legend.fontsize": 8,
51
+ "axes.facecolor": "white",
52
+ "figure.facecolor": "white",
53
+ "axes.edgecolor": "#444444",
54
+ "axes.linewidth": 0.8,
55
+ "grid.color": "#D9D9D9",
56
+ "grid.linestyle": "--",
57
+ "grid.linewidth": 0.7,
58
+ "pdf.fonttype": 42,
59
+ "ps.fonttype": 42,
60
+ }
61
+ )
62
+
63
+
64
+ def _blend_with_white(color: str, strength: float) -> tuple[float, float, float]:
65
+ base = np.array(mcolors.to_rgb(color), dtype=float)
66
+ white = np.array([1.0, 1.0, 1.0], dtype=float)
67
+ mixed = base * (1.0 - strength) + white * strength
68
+ return tuple(float(v) for v in mixed)
69
+
70
+
71
+ def _style_axis(ax: plt.Axes) -> None:
72
+ ax.grid(axis="y")
73
+ ax.grid(axis="x", visible=False)
74
+ ax.set_axisbelow(True)
75
+ ax.spines["top"].set_visible(False)
76
+ ax.spines["right"].set_visible(False)
77
+
78
+
79
+ def _load_model_threshold(tables_dir: Path) -> pd.DataFrame:
80
+ path = tables_dir / "model_threshold_summary.csv"
81
+ df = pd.read_csv(path)
82
+ df = df[df["model_label"].isin(MODEL_COLORS)].copy()
83
+ df["threshold_label"] = pd.Categorical(df["threshold_label"], categories=THRESHOLD_ORDER, ordered=True)
84
+ df = df.sort_values(["model_label", "threshold_label"]).reset_index(drop=True)
85
+ return df
86
+
87
+
88
+ def _model_order(df: pd.DataFrame) -> list[str]:
89
+ present = set(df["model_label"].dropna().unique().tolist())
90
+ return [label for label in MODEL_COLORS if label in present]
91
+
92
+
93
+ def _metric_pivot(df: pd.DataFrame, metric: str, model_order: list[str]) -> pd.DataFrame:
94
+ pivot = (
95
+ df.pivot_table(index="model_label", columns="threshold_label", values=metric, aggfunc="mean")
96
+ .reindex(index=model_order, columns=THRESHOLD_ORDER)
97
+ .astype(float)
98
+ )
99
+ return pivot
100
+
101
+
102
+ def _save(fig: plt.Figure, path: Path) -> None:
103
+ path.parent.mkdir(parents=True, exist_ok=True)
104
+ fig.savefig(path, dpi=300, facecolor="white")
105
+ if path.suffix.lower() == ".png":
106
+ fig.savefig(path.with_suffix(".pdf"), dpi=300, facecolor="white")
107
+ plt.close(fig)
108
+
109
+
110
+ def _threshold_legend_handles() -> list[Patch]:
111
+ samples = [("10%", 0.00), ("2%", 0.30), ("0.5%", 0.55), ("0.001%", 0.80)]
112
+ return [
113
+ Patch(facecolor=_blend_with_white("#666666", strength), edgecolor="none", label=label)
114
+ for label, strength in samples
115
+ ]
116
+
117
+
118
+ def render_errorbar_style(df: pd.DataFrame, output_dir: Path) -> list[Path]:
119
+ model_order = _model_order(df)
120
+ x = np.arange(len(model_order))
121
+ outputs: list[Path] = []
122
+
123
+ for metric, ylabel in METRICS:
124
+ pivot = _metric_pivot(df, metric, model_order)
125
+ values = pivot.to_numpy(dtype=float)
126
+ means = np.nanmean(values, axis=1)
127
+ lows = means - np.nanmin(values, axis=1)
128
+ highs = np.nanmax(values, axis=1) - means
129
+ q25 = np.nanquantile(values, 0.25, axis=1)
130
+ q75 = np.nanquantile(values, 0.75, axis=1)
131
+
132
+ fig, ax = plt.subplots(figsize=(8.3, 4.6), constrained_layout=True)
133
+ for idx, model in enumerate(model_order):
134
+ base = MODEL_COLORS[model]
135
+ # IQR band
136
+ ax.add_patch(
137
+ plt.Rectangle(
138
+ (x[idx] - 0.26, q25[idx]),
139
+ 0.52,
140
+ max(1e-6, q75[idx] - q25[idx]),
141
+ facecolor=_blend_with_white(base, 0.55),
142
+ edgecolor="none",
143
+ alpha=0.85,
144
+ zorder=1,
145
+ )
146
+ )
147
+ ax.errorbar(
148
+ x[idx],
149
+ means[idx],
150
+ yerr=np.array([[lows[idx]], [highs[idx]]]),
151
+ fmt="s",
152
+ color=base,
153
+ markersize=4.8,
154
+ elinewidth=1.7,
155
+ capsize=4,
156
+ capthick=1.2,
157
+ zorder=3,
158
+ )
159
+
160
+ ax.set_xticks(x, model_order, rotation=30, ha="right")
161
+ ax.set_ylabel(ylabel)
162
+ ax.set_xlabel("Model")
163
+ ax.set_ylim(0.0, min(1.0, np.nanmax(values) + 0.08))
164
+ ax.set_title(f"{ylabel}: threshold sweep summarized as mean + range", loc="left", pad=6)
165
+ _style_axis(ax)
166
+
167
+ legend_items = [
168
+ Line2D([0], [0], marker="s", color="#555555", linestyle="none", markersize=5, label="Mean over thresholds"),
169
+ Line2D([0], [0], color="#555555", linewidth=1.7, label="Min-max over thresholds"),
170
+ Patch(facecolor="#D9D9D9", edgecolor="none", label="IQR over thresholds"),
171
+ ]
172
+ ax.legend(handles=legend_items, loc="upper left", frameon=False, ncols=3)
173
+ ax.text(
174
+ 0.995,
175
+ 0.02,
176
+ "Each model summarizes the full 10-threshold sweep",
177
+ transform=ax.transAxes,
178
+ ha="right",
179
+ va="bottom",
180
+ fontsize=7.2,
181
+ color="#666666",
182
+ )
183
+
184
+ out = output_dir / f"{metric}__errorbar_summary.png"
185
+ _save(fig, out)
186
+ outputs.append(out)
187
+
188
+ return outputs
189
+
190
+
191
+ def render_layered_bar_style(df: pd.DataFrame, output_dir: Path) -> list[Path]:
192
+ model_order = _model_order(df)
193
+ x = np.arange(len(model_order))
194
+ shade_strengths = np.linspace(0.00, 0.82, len(THRESHOLD_ORDER))
195
+ outputs: list[Path] = []
196
+
197
+ for metric, ylabel in METRICS:
198
+ pivot = _metric_pivot(df, metric, model_order)
199
+ fig, ax = plt.subplots(figsize=(8.3, 4.8), constrained_layout=True)
200
+
201
+ for idx, model in enumerate(model_order):
202
+ base = MODEL_COLORS[model]
203
+ column = pivot.loc[model].to_list()
204
+ # draw from light to dark so broader/taller bars remain visible
205
+ for threshold_idx in range(len(THRESHOLD_ORDER) - 1, -1, -1):
206
+ value = column[threshold_idx]
207
+ if pd.isna(value):
208
+ continue
209
+ strength = float(shade_strengths[threshold_idx])
210
+ ax.bar(
211
+ x[idx],
212
+ float(value),
213
+ width=0.72,
214
+ color=_blend_with_white(base, strength),
215
+ edgecolor="white",
216
+ linewidth=0.55,
217
+ zorder=2 + threshold_idx * 0.01,
218
+ )
219
+
220
+ ax.set_xticks(x, model_order, rotation=30, ha="right")
221
+ ax.set_ylabel(ylabel)
222
+ ax.set_xlabel("Model")
223
+ ax.set_ylim(0.0, min(1.0, float(np.nanmax(pivot.to_numpy(dtype=float))) + 0.08))
224
+ ax.set_title(f"{ylabel}: layered threshold bars", loc="left", pad=6)
225
+ _style_axis(ax)
226
+ legend = ax.legend(
227
+ handles=_threshold_legend_handles(),
228
+ title="Threshold shading",
229
+ loc="upper left",
230
+ frameon=False,
231
+ ncols=4,
232
+ )
233
+ legend.get_title().set_fontsize(8)
234
+ ax.text(
235
+ 0.995,
236
+ 0.02,
237
+ "Darker bars = broader tail threshold; lighter bars = rarer tail threshold",
238
+ transform=ax.transAxes,
239
+ ha="right",
240
+ va="bottom",
241
+ fontsize=7.2,
242
+ color="#666666",
243
+ )
244
+
245
+ out = output_dir / f"{metric}__layered_bars.png"
246
+ _save(fig, out)
247
+ outputs.append(out)
248
+
249
+ return outputs
250
+
251
+
252
+ def main() -> int:
253
+ args = _build_parser().parse_args()
254
+ _configure_style()
255
+ df = _load_model_threshold(args.tables_dir)
256
+ output_dir = args.output_dir
257
+ output_dir.mkdir(parents=True, exist_ok=True)
258
+
259
+ outputs = []
260
+ outputs.extend(render_errorbar_style(df, output_dir))
261
+ outputs.extend(render_layered_bar_style(df, output_dir))
262
+ for path in outputs:
263
+ print(path)
264
+ return 0
265
+
266
+
267
+ if __name__ == "__main__":
268
+ raise SystemExit(main())
evaluation/tail/tail_threshold_code/scripts/render_tail_stress_main_figure.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Render a paper-ready multi-panel tail stress figure from summary CSVs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from pathlib import Path
8
+
9
+ import matplotlib
10
+
11
+ matplotlib.use("Agg")
12
+ import matplotlib.pyplot as plt
13
+ import numpy as np
14
+ import pandas as pd
15
+ from matplotlib import colors as mcolors
16
+
17
+
18
+ THRESHOLD_ORDER = ["10%", "8%", "6%", "4%", "2%", "1%", "0.5%", "0.1%", "0.01%", "0.001%"]
19
+
20
+ # Frozen paper color convention from README.md.
21
+ MODEL_COLORS = {
22
+ "RealTabFormer": "#332288",
23
+ "TVAE": "#4477AA",
24
+ "ForestDiffusion": "#228833",
25
+ "TabDDPM": "#EE7733",
26
+ "TabSyn": "#66CCEE",
27
+ "TabDiff": "#AA3377",
28
+ "CTGAN": "#EE6677",
29
+ "ARF": "#777777",
30
+ "BayesNet": "#CCBB44",
31
+ "TabPFGen": "#009988",
32
+ "TabbyFlow": "#882255",
33
+ }
34
+
35
+ TAIL_COLOR = "#E4572E"
36
+ HEAD_COLOR = "#4C78A8"
37
+ DECOMP_COLORS = {
38
+ "tail_set_consistency_mean": "#D1495B",
39
+ "tail_mass_similarity_mean": "#2A9D8F",
40
+ "tail_concentration_consistency_mean": "#6D597A",
41
+ }
42
+ DECOMP_LABELS = {
43
+ "tail_set_consistency_mean": "Tail set consistency",
44
+ "tail_mass_similarity_mean": "Tail mass similarity",
45
+ "tail_concentration_consistency_mean": "Tail concentration consistency",
46
+ }
47
+ MODEL_LABEL_OFFSETS = {
48
+ "ARF": (6, 8),
49
+ "BayesNet": (6, -12),
50
+ "CTGAN": (6, -10),
51
+ "ForestDiffusion": (6, -10),
52
+ "RealTabFormer": (6, 8),
53
+ "TVAE": (6, 8),
54
+ "TabDDPM": (6, -10),
55
+ "TabDiff": (6, 8),
56
+ "TabPFGen": (6, 8),
57
+ "TabSyn": (6, 6),
58
+ "TabbyFlow": (6, -10),
59
+ }
60
+
61
+
62
+ def _build_parser() -> argparse.ArgumentParser:
63
+ parser = argparse.ArgumentParser(description=__doc__)
64
+ parser.add_argument(
65
+ "--tables-dir",
66
+ type=Path,
67
+ required=True,
68
+ help="Directory containing tail-threshold summary CSV files.",
69
+ )
70
+ parser.add_argument(
71
+ "--output-dir",
72
+ type=Path,
73
+ required=True,
74
+ help="Directory where the PNG/PDF figure will be written.",
75
+ )
76
+ return parser
77
+
78
+
79
+ def _read_required_tables(tables_dir: Path) -> dict[str, pd.DataFrame]:
80
+ file_map = {
81
+ "global": "global_threshold_summary.csv",
82
+ "model_fragility": "model_fragility_summary.csv",
83
+ "model_threshold": "model_threshold_summary.csv",
84
+ "prefix_threshold": "prefix_threshold_summary.csv",
85
+ "dataset_threshold": "dataset_threshold_summary.csv",
86
+ }
87
+ tables: dict[str, pd.DataFrame] = {}
88
+ for key, name in file_map.items():
89
+ path = tables_dir / name
90
+ if not path.exists():
91
+ raise FileNotFoundError(f"Missing required input CSV: {path}")
92
+ tables[key] = pd.read_csv(path)
93
+ return tables
94
+
95
+
96
+ def _ordered(df: pd.DataFrame, label_col: str = "threshold_label") -> pd.DataFrame:
97
+ ordered = df.copy()
98
+ ordered[label_col] = pd.Categorical(ordered[label_col], categories=THRESHOLD_ORDER, ordered=True)
99
+ ordered = ordered.sort_values(label_col).reset_index(drop=True)
100
+ return ordered
101
+
102
+
103
+ def _configure_style() -> None:
104
+ plt.rcParams.update(
105
+ {
106
+ "font.family": "DejaVu Sans",
107
+ "font.size": 8,
108
+ "axes.titlesize": 10.5,
109
+ "axes.labelsize": 9,
110
+ "xtick.labelsize": 8,
111
+ "ytick.labelsize": 8,
112
+ "legend.fontsize": 8,
113
+ "axes.facecolor": "white",
114
+ "figure.facecolor": "white",
115
+ "axes.edgecolor": "#444444",
116
+ "axes.linewidth": 0.8,
117
+ "grid.color": "#D9D9D9",
118
+ "grid.linestyle": "--",
119
+ "grid.linewidth": 0.7,
120
+ "pdf.fonttype": 42,
121
+ "ps.fonttype": 42,
122
+ }
123
+ )
124
+
125
+
126
+ def _style_axis(ax: plt.Axes) -> None:
127
+ ax.grid(axis="y")
128
+ ax.grid(axis="x", visible=False)
129
+ ax.set_axisbelow(True)
130
+ ax.spines["top"].set_visible(False)
131
+ ax.spines["right"].set_visible(False)
132
+
133
+
134
+ def _blend_with_white(color: str, strength: float) -> tuple[float, float, float]:
135
+ base = np.array(mcolors.to_rgb(color), dtype=float)
136
+ white = np.array([1.0, 1.0, 1.0], dtype=float)
137
+ mixed = base * (1.0 - strength) + white * strength
138
+ return tuple(float(v) for v in mixed)
139
+
140
+
141
+ def _shade_ultra_tail(ax: plt.Axes) -> None:
142
+ ax.axvspan(6.5, 9.5, color="#EFEFEF", alpha=1.0, zorder=0)
143
+ ax.axvline(6.5, color="#999999", linestyle="--", linewidth=1.0, zorder=1)
144
+ ax.text(
145
+ 7.95,
146
+ 0.985,
147
+ "Low-support\nultra-tail",
148
+ transform=ax.get_xaxis_transform(),
149
+ ha="center",
150
+ va="top",
151
+ fontsize=7.5,
152
+ color="#555555",
153
+ )
154
+
155
+
156
+ def _render_panel_a(ax: plt.Axes, global_df: pd.DataFrame) -> None:
157
+ x = list(range(len(global_df)))
158
+ tail = global_df["tail_overall_mean"].tolist()
159
+ head = global_df["head_proxy_mean"].tolist()
160
+
161
+ _shade_ultra_tail(ax)
162
+ ax.plot(x, tail, color=TAIL_COLOR, marker="o", linewidth=2.0, markersize=4.4, label="Tail score", zorder=3)
163
+ ax.plot(x, head, color=HEAD_COLOR, marker="o", linewidth=2.0, markersize=4.4, label="Head proxy score", zorder=3)
164
+
165
+ ax.set_xticks(x, global_df["threshold_label"].tolist(), rotation=30, ha="right")
166
+ ax.set_ylim(0.20, 0.60)
167
+ ax.set_ylabel("Score")
168
+ ax.set_xlabel("Tail threshold")
169
+ ax.set_title("A. Tail degrades while head remains stable", loc="left", pad=6)
170
+ _style_axis(ax)
171
+
172
+ ax.text(
173
+ 0.03,
174
+ 0.53,
175
+ f"Tail: {tail[0]:.3f} -> {tail[6]:.3f}",
176
+ transform=ax.transAxes,
177
+ color=TAIL_COLOR,
178
+ fontsize=8,
179
+ fontweight="bold",
180
+ bbox={"facecolor": "white", "edgecolor": "none", "alpha": 0.85, "pad": 2.5},
181
+ )
182
+ ax.text(
183
+ 0.03,
184
+ 0.45,
185
+ f"Head: {head[0]:.3f} -> {head[-1]:.3f}",
186
+ transform=ax.transAxes,
187
+ color=HEAD_COLOR,
188
+ fontsize=8,
189
+ fontweight="bold",
190
+ bbox={"facecolor": "white", "edgecolor": "none", "alpha": 0.85, "pad": 2.5},
191
+ )
192
+ ax.legend(loc="lower left", frameon=False, ncols=1, bbox_to_anchor=(0.005, 0.005))
193
+
194
+
195
+ def _render_panel_b(ax: plt.Axes, global_df: pd.DataFrame) -> None:
196
+ x = list(range(len(global_df)))
197
+ baseline = global_df.iloc[0]
198
+
199
+ for metric in (
200
+ "tail_set_consistency_mean",
201
+ "tail_mass_similarity_mean",
202
+ "tail_concentration_consistency_mean",
203
+ ):
204
+ base_value = float(baseline[metric])
205
+ values = [float(v) / base_value if base_value else 0.0 for v in global_df[metric].tolist()]
206
+ ax.plot(
207
+ x,
208
+ values,
209
+ marker="o",
210
+ linewidth=2.0,
211
+ markersize=4.2,
212
+ color=DECOMP_COLORS[metric],
213
+ label=DECOMP_LABELS[metric],
214
+ )
215
+
216
+ _shade_ultra_tail(ax)
217
+ ax.axhline(1.0, color="#888888", linestyle="--", linewidth=1.0)
218
+ ax.set_xticks(x, global_df["threshold_label"].tolist(), rotation=30, ha="right")
219
+ ax.set_ylim(0.60, 1.12)
220
+ ax.set_ylabel("Relative score vs. 10% threshold")
221
+ ax.set_xlabel("Tail threshold")
222
+ ax.set_title("B. Tail set consistency and tail mass similarity break first", loc="left", pad=6)
223
+ _style_axis(ax)
224
+ ax.legend(loc="lower left", frameon=False)
225
+
226
+
227
+ def _render_panel_c(ax: plt.Axes, model_threshold_df: pd.DataFrame) -> None:
228
+ ordered = _ordered(model_threshold_df)
229
+ ordered = ordered[ordered["model_label"].isin(MODEL_COLORS)].copy()
230
+ model_labels = [label for label in MODEL_COLORS if label in set(ordered["model_label"].dropna().unique().tolist())]
231
+ shade_strengths = np.linspace(0.0, 0.78, len(THRESHOLD_ORDER))
232
+
233
+ x_all: list[float] = []
234
+ y_all: list[float] = []
235
+
236
+ for label in model_labels:
237
+ subset = ordered[ordered["model_label"] == label].copy()
238
+ subset = subset.dropna(subset=["tail_set_consistency", "tail_mass_similarity"])
239
+ if subset.empty:
240
+ continue
241
+ x_vals = subset["tail_set_consistency"].astype(float).tolist()
242
+ y_vals = subset["tail_mass_similarity"].astype(float).tolist()
243
+ x_all.extend(x_vals)
244
+ y_all.extend(y_vals)
245
+
246
+ base_color = MODEL_COLORS[label]
247
+ ax.plot(x_vals, y_vals, color=base_color, linewidth=1.0, alpha=0.38, zorder=1)
248
+
249
+ for idx, (_, row) in enumerate(subset.iterrows()):
250
+ color = _blend_with_white(base_color, float(shade_strengths[idx]))
251
+ size = 36 if idx == 0 else 28
252
+ ax.scatter(
253
+ [float(row["tail_set_consistency"])],
254
+ [float(row["tail_mass_similarity"])],
255
+ s=size,
256
+ color=color,
257
+ edgecolor="white",
258
+ linewidth=0.55,
259
+ zorder=2 + idx * 0.01,
260
+ )
261
+
262
+ first = subset.iloc[0]
263
+ dx, dy = MODEL_LABEL_OFFSETS.get(label, (6, 6))
264
+ ax.annotate(
265
+ label,
266
+ (float(first["tail_set_consistency"]), float(first["tail_mass_similarity"])),
267
+ xytext=(dx, dy),
268
+ textcoords="offset points",
269
+ fontsize=7.3,
270
+ ha="left",
271
+ va="center",
272
+ color="#333333",
273
+ bbox={"facecolor": "white", "edgecolor": "none", "alpha": 0.84, "pad": 1.2},
274
+ zorder=4,
275
+ )
276
+
277
+ if not x_all or not y_all:
278
+ ax.text(0.5, 0.5, "No paper-roster models available", ha="center", va="center", fontsize=9, color="#666666")
279
+ ax.set_axis_off()
280
+ return
281
+
282
+ ax.set_xlim(max(0.0, min(x_all) - 0.02), min(1.0, max(x_all) + 0.06))
283
+ ax.set_ylim(max(0.0, min(y_all) - 0.03), min(1.0, max(y_all) + 0.06))
284
+ ax.set_xlabel("Tail set consistency score")
285
+ ax.set_ylabel("Tail mass similarity score")
286
+ ax.set_title("C. Tail set consistency and tail mass similarity erode together", loc="left", pad=6)
287
+ _style_axis(ax)
288
+
289
+ threshold_handles = [
290
+ plt.Line2D(
291
+ [0],
292
+ [0],
293
+ marker="o",
294
+ color="none",
295
+ markerfacecolor=_blend_with_white("#666666", strength),
296
+ markeredgecolor="white",
297
+ markeredgewidth=0.5,
298
+ markersize=5,
299
+ label=label,
300
+ )
301
+ for strength, label in [
302
+ (shade_strengths[0], "10%"),
303
+ (shade_strengths[5], "1%"),
304
+ (shade_strengths[-1], "0.001%"),
305
+ ]
306
+ ]
307
+ legend = ax.legend(
308
+ handles=threshold_handles,
309
+ title="Threshold shading",
310
+ loc="lower right",
311
+ frameon=False,
312
+ ncols=3,
313
+ bbox_to_anchor=(1.0, 1.02),
314
+ borderaxespad=0.0,
315
+ handletextpad=0.4,
316
+ columnspacing=0.9,
317
+ )
318
+ legend.get_title().set_fontsize(7.8)
319
+ ax.add_artist(legend)
320
+ ax.text(
321
+ 0.995,
322
+ 0.03,
323
+ "Same hue = same model\nlighter points = rarer threshold",
324
+ transform=ax.transAxes,
325
+ ha="right",
326
+ va="bottom",
327
+ fontsize=7.2,
328
+ color="#666666",
329
+ )
330
+
331
+
332
+ def render_main_figure(tables_dir: Path, output_dir: Path) -> tuple[Path, Path]:
333
+ tables = _read_required_tables(tables_dir)
334
+ global_df = _ordered(tables["global"])
335
+
336
+ _configure_style()
337
+ fig = plt.figure(figsize=(7.1, 3.55), constrained_layout=True)
338
+ fig.set_constrained_layout_pads(w_pad=0.02, h_pad=0.02, wspace=0.04, hspace=0.06)
339
+ mosaic = fig.subplot_mosaic(
340
+ [["T", "T"], ["A", "B"]],
341
+ height_ratios=[0.18, 1.0],
342
+ )
343
+
344
+ mosaic["T"].axis("off")
345
+ mosaic["T"].text(
346
+ 0.0,
347
+ 0.72,
348
+ "Tail stress testing reveals rare-event fragility",
349
+ fontsize=10.5,
350
+ fontweight="bold",
351
+ ha="left",
352
+ va="center",
353
+ )
354
+
355
+ _render_panel_a(mosaic["A"], global_df)
356
+ _render_panel_b(mosaic["B"], global_df)
357
+
358
+ output_dir.mkdir(parents=True, exist_ok=True)
359
+ png_path = output_dir / "tail_stress_main_figure.png"
360
+ pdf_path = output_dir / "tail_stress_main_figure.pdf"
361
+ fig.savefig(png_path, dpi=300, facecolor="white")
362
+ fig.savefig(pdf_path, dpi=300, facecolor="white")
363
+ plt.close(fig)
364
+ return png_path, pdf_path
365
+
366
+
367
+ def main() -> int:
368
+ parser = _build_parser()
369
+ args = parser.parse_args()
370
+ png_path, pdf_path = render_main_figure(args.tables_dir, args.output_dir)
371
+ print(png_path)
372
+ print(pdf_path)
373
+ return 0
374
+
375
+
376
+ if __name__ == "__main__":
377
+ raise SystemExit(main())
evaluation/tail/tail_threshold_code/scripts/run_tail_threshold.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run the global tail-threshold sensitivity experiment."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
12
+ if str(PROJECT_ROOT) not in sys.path:
13
+ sys.path.insert(0, str(PROJECT_ROOT))
14
+
15
+ from src.eval.tail_threshold.runner import (
16
+ DEFAULT_THRESHOLD_PCTS,
17
+ build_tail_threshold_preview,
18
+ run_tail_threshold_experiment,
19
+ )
20
+
21
+
22
+ def parse_args() -> argparse.Namespace:
23
+ parser = argparse.ArgumentParser(description="Run global tail-threshold sensitivity diagnostics.")
24
+ parser.add_argument("--run-tag", type=str, default=None, help="Optional output run tag.")
25
+ parser.add_argument(
26
+ "--datasets",
27
+ type=str,
28
+ default="",
29
+ help="Optional comma-separated dataset ids. Empty means all datasets.",
30
+ )
31
+ parser.add_argument(
32
+ "--root-names",
33
+ type=str,
34
+ default="",
35
+ help=(
36
+ "Optional comma-separated synthetic root names. "
37
+ "Example: TabQueryBench-SynDataSuccess-main"
38
+ ),
39
+ )
40
+ parser.add_argument(
41
+ "--threshold-percentages",
42
+ type=str,
43
+ default=",".join(f"{value:g}" for value in DEFAULT_THRESHOLD_PCTS),
44
+ help="Comma-separated tail thresholds in percentage points.",
45
+ )
46
+ parser.add_argument(
47
+ "--all-asset-runs",
48
+ action="store_true",
49
+ help="Disable latest-only filtering within the same model/server.",
50
+ )
51
+ parser.add_argument(
52
+ "--max-workers",
53
+ type=int,
54
+ default=4,
55
+ help="Parallel workers across datasets.",
56
+ )
57
+ parser.add_argument(
58
+ "--representatives-per-prefix",
59
+ type=int,
60
+ default=2,
61
+ help="How many representative datasets to keep for each prefix family.",
62
+ )
63
+ parser.add_argument(
64
+ "--plot-only-from-run-dir",
65
+ type=Path,
66
+ default=None,
67
+ help="Instead of recomputing dataset outputs, rebuild summaries/figures from an existing run dir.",
68
+ )
69
+ return parser.parse_args()
70
+
71
+
72
+ def _parse_threshold_percentages(text: str) -> list[float]:
73
+ values: list[float] = []
74
+ for chunk in text.split(","):
75
+ token = chunk.strip()
76
+ if not token:
77
+ continue
78
+ values.append(float(token))
79
+ return values
80
+
81
+
82
+ def main() -> None:
83
+ args = parse_args()
84
+ datasets = [item.strip() for item in args.datasets.split(",") if item.strip()] or None
85
+ root_names = [item.strip() for item in args.root_names.split(",") if item.strip()] or None
86
+ if args.plot_only_from_run_dir is not None:
87
+ manifest = build_tail_threshold_preview(
88
+ source_run_dir=args.plot_only_from_run_dir,
89
+ run_tag=args.run_tag,
90
+ latest_only=not args.all_asset_runs,
91
+ threshold_percentages=_parse_threshold_percentages(args.threshold_percentages),
92
+ representatives_per_prefix=max(1, args.representatives_per_prefix),
93
+ )
94
+ else:
95
+ manifest = run_tail_threshold_experiment(
96
+ run_tag=args.run_tag,
97
+ datasets=datasets,
98
+ latest_only=not args.all_asset_runs,
99
+ root_names=root_names,
100
+ threshold_percentages=_parse_threshold_percentages(args.threshold_percentages),
101
+ max_workers=max(1, args.max_workers),
102
+ representatives_per_prefix=max(1, args.representatives_per_prefix),
103
+ )
104
+ print(json.dumps(manifest, ensure_ascii=False, indent=2))
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
evaluation/tail/tail_threshold_code/src/eval/common.py ADDED
@@ -0,0 +1,1629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared utilities for synthetic-data evaluation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import hashlib
7
+ import json
8
+ import math
9
+ import os
10
+ import re
11
+ import sqlite3
12
+ import time
13
+ from collections import Counter, defaultdict
14
+ from dataclasses import asdict, dataclass
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Any, Iterable
18
+
19
+ from src.eval.subitem_workload_v2.paths import (
20
+ SUPPORTED_LINE_VERSIONS,
21
+ normalize_line_version,
22
+ registry_dir,
23
+ run_manifest_dir,
24
+ runs_root,
25
+ )
26
+ from src.eval.subitem_workload_v2.registry import load_registry_rows
27
+
28
+ PROJECT_ROOT = Path(__file__).resolve().parents[2]
29
+
30
+
31
+ def _env_path(name: str, default: Path) -> Path:
32
+ value = os.environ.get(name, "").strip()
33
+ return Path(value).expanduser() if value else default
34
+
35
+
36
+ DATA_ROOT = _env_path("EVAL_REAL_DATA_ROOT", PROJECT_ROOT / "data")
37
+ LOGS_ROOT = _env_path("EVAL_LOGS_ROOT", PROJECT_ROOT / "logs" / "runs")
38
+ OUTPUT_ROOT = _env_path("EVAL_OUTPUT_ROOT", PROJECT_ROOT / "Evaluation")
39
+ SQL_RESULT_ROLE_ANNOTATION_ROOT = DATA_ROOT / "sql_result_role_annotations_v1" / "datasets"
40
+
41
+ PROVENANCE_CONTRACT_VERSION = "evaluation_source_provenance_v1"
42
+ SQL_SOURCE_VERSION_ENV_VAR = "EVAL_SQL_SOURCE_VERSION"
43
+ SQL_SOURCE_VERSION_V1 = "v1"
44
+ SQL_SOURCE_VERSION_V2 = "v2"
45
+ SQL_SOURCE_VERSION_V3 = "v3"
46
+ SQL_SOURCE_VERSION_V4 = "v4"
47
+ CURRENT_SQL_SOURCE_VERSIONS = tuple(SUPPORTED_LINE_VERSIONS)
48
+ SQL_SOURCE_VERSION_CHOICES = (
49
+ SQL_SOURCE_VERSION_V1,
50
+ *CURRENT_SQL_SOURCE_VERSIONS,
51
+ )
52
+ DEFAULT_SQL_SOURCE_VERSION = SQL_SOURCE_VERSION_V2
53
+
54
+ _SQL_SOURCE_LABELS = {
55
+ SQL_SOURCE_VERSION_V1: "v1_legacy",
56
+ SQL_SOURCE_VERSION_V2: "v2_current",
57
+ SQL_SOURCE_VERSION_V3: "v3_current",
58
+ SQL_SOURCE_VERSION_V4: "v4_current",
59
+ }
60
+ _SQL_SOURCE_DESCRIPTIONS = {
61
+ SQL_SOURCE_VERSION_V1: "legacy grounded SQL runs under logs/runs/",
62
+ SQL_SOURCE_VERSION_V2: "current registry-backed workload SQL under logs/subitem_workload_v2/",
63
+ SQL_SOURCE_VERSION_V3: "current registry-backed workload SQL under logs/subitem_workload_v3/",
64
+ SQL_SOURCE_VERSION_V4: "current registry-backed workload SQL under logs/subitem_workload_v4/",
65
+ }
66
+ _SQL_SOURCE_ALIASES = {
67
+ "v1": SQL_SOURCE_VERSION_V1,
68
+ "legacy": SQL_SOURCE_VERSION_V1,
69
+ "v1_legacy": SQL_SOURCE_VERSION_V1,
70
+ "logs/runs": SQL_SOURCE_VERSION_V1,
71
+ "logs\\runs": SQL_SOURCE_VERSION_V1,
72
+ "v2": SQL_SOURCE_VERSION_V2,
73
+ "query_registry_v2": SQL_SOURCE_VERSION_V2,
74
+ "current": SQL_SOURCE_VERSION_V2,
75
+ "v2_current": SQL_SOURCE_VERSION_V2,
76
+ "subitem_workload_v2": SQL_SOURCE_VERSION_V2,
77
+ "logs/subitem_workload_v2": SQL_SOURCE_VERSION_V2,
78
+ "logs\\subitem_workload_v2": SQL_SOURCE_VERSION_V2,
79
+ "v3": SQL_SOURCE_VERSION_V3,
80
+ "v3_current": SQL_SOURCE_VERSION_V3,
81
+ "query_registry_v3": SQL_SOURCE_VERSION_V3,
82
+ "subitem_workload_v3": SQL_SOURCE_VERSION_V3,
83
+ "logs/subitem_workload_v3": SQL_SOURCE_VERSION_V3,
84
+ "logs\\subitem_workload_v3": SQL_SOURCE_VERSION_V3,
85
+ "v4": SQL_SOURCE_VERSION_V4,
86
+ "v4_current": SQL_SOURCE_VERSION_V4,
87
+ "query_registry_v4": SQL_SOURCE_VERSION_V4,
88
+ "subitem_workload_v4": SQL_SOURCE_VERSION_V4,
89
+ "logs/subitem_workload_v4": SQL_SOURCE_VERSION_V4,
90
+ "logs\\subitem_workload_v4": SQL_SOURCE_VERSION_V4,
91
+ }
92
+
93
+ ROOT_CONFIGS = {
94
+ "SynOutput": {
95
+ "path": _env_path("EVAL_SYNOUTPUT_ROOT", PROJECT_ROOT / "SynOutput"),
96
+ "server_type": "rtx_pro_6000",
97
+ "gpu_hour_ratio": 1.0,
98
+ },
99
+ "SynOutput-5090": {
100
+ "path": _env_path("EVAL_SYNOUTPUT_5090_ROOT", PROJECT_ROOT / "SynOutput-5090"),
101
+ "server_type": "rtx_5090",
102
+ "gpu_hour_ratio": 1.0,
103
+ },
104
+ "Benchmark-trainonly-v1": {
105
+ "path": _env_path("EVAL_BENCHMARK_TRAINONLY_ROOT", PROJECT_ROOT / "remote-output-Benchmark-trainonly-v1"),
106
+ "server_type": "trainonly_serial",
107
+ "gpu_hour_ratio": 1.0,
108
+ },
109
+ "Hyperparameter-trainonly-v1": {
110
+ "path": _env_path(
111
+ "EVAL_HYPERPARAMETER_TRAINONLY_ROOT",
112
+ PROJECT_ROOT / "hyperparameter" / "output-Benchmark-trainonly-v1",
113
+ ),
114
+ "server_type": "hyperparameter_trainonly",
115
+ "gpu_hour_ratio": 1.0,
116
+ },
117
+ "TabQueryBench-SynDataSuccess-main": {
118
+ "path": _env_path(
119
+ "EVAL_TABQUERYBENCH_MAIN_ROOT",
120
+ Path("/data/jialinzhang/TabQueryBench/SynDataSuccess/main"),
121
+ ),
122
+ "server_type": "server_authoritative_main",
123
+ "gpu_hour_ratio": 1.0,
124
+ },
125
+ }
126
+
127
+ USD_PER_GPU_HOUR = 1.0
128
+ MAX_FALLBACK_GPU_SECONDS = 12 * 3600
129
+ MISSING_TEXT = {"", "null", "none", "nan", "na", "n/a", "<null>"}
130
+ TIMESTAMP_RE = re.compile(r"(\d{8}_\d{6})")
131
+ RUNTIME_RESULT_RE = re.compile(r"(?P<prefix>.+?)__runtime_result\.json$", re.IGNORECASE)
132
+ TRAIN_TIME_RE = re.compile(
133
+ r"(?:totoal|total)\s+training\s+time\s*=\s*([0-9]+(?:\.[0-9]+)?)",
134
+ re.IGNORECASE,
135
+ )
136
+ SAMPLE_TIME_RE = re.compile(
137
+ r"(?:totoal|total)\s+sampling\s+time\s*=\s*([0-9]+(?:\.[0-9]+)?)",
138
+ re.IGNORECASE,
139
+ )
140
+ GENERIC_SECONDS_RE = re.compile(
141
+ r"(?:elapsed|duration|runtime|wall\s*time|completed\s+in|finished\s+in)\D+([0-9]+(?:\.[0-9]+)?)\s*(?:seconds|secs|s)?",
142
+ re.IGNORECASE,
143
+ )
144
+ SUBITEM_RUNS_PATH_RE = re.compile(
145
+ r"/logs/subitem_workload_(v[234])/runs/(?P<suffix>.+)$",
146
+ re.IGNORECASE,
147
+ )
148
+
149
+
150
+ @dataclass
151
+ class SyntheticAsset:
152
+ dataset_id: str
153
+ model_id: str
154
+ server_type: str
155
+ root_name: str
156
+ root_path: str
157
+ asset_dir: str
158
+ run_id: str
159
+ synthetic_csv_path: str
160
+ metadata_paths: list[str]
161
+ log_paths: list[str]
162
+ discovered_via: str
163
+ timestamp_utc: str | None
164
+ synthetic_source_mtime_utc: str | None
165
+ synthetic_source_size_bytes: int | None
166
+ gpu_seconds_raw: float
167
+ gpu_hours_equivalent: float
168
+ gpu_hours_source: str
169
+ cost_usd: float
170
+
171
+ @property
172
+ def asset_key(self) -> str:
173
+ return f"{self.dataset_id}__{self.server_type}__{self.model_id}__{self.run_id}"
174
+
175
+ @property
176
+ def model_server_key(self) -> str:
177
+ return f"{self.model_id}__{self.server_type}"
178
+
179
+ def to_dict(self) -> dict[str, Any]:
180
+ row = asdict(self)
181
+ row["asset_key"] = self.asset_key
182
+ row["model_server_key"] = self.model_server_key
183
+ row["provenance_contract_version"] = PROVENANCE_CONTRACT_VERSION
184
+ row["synthetic_source_path"] = row["synthetic_csv_path"]
185
+ row["synthetic_source_root_name"] = row["root_name"]
186
+ row["synthetic_source_root_path"] = row["root_path"]
187
+ row["synthetic_source_asset_dir"] = row["asset_dir"]
188
+ row["synthetic_source_run_id"] = row["run_id"]
189
+ row["synthetic_source_discovered_via"] = row["discovered_via"]
190
+ return row
191
+
192
+
193
+ def now_run_tag() -> str:
194
+ return datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
195
+
196
+
197
+ def read_json(path: Path, default: Any = None) -> Any:
198
+ if not path.exists():
199
+ return default
200
+ try:
201
+ return json.loads(path.read_text(encoding="utf-8"))
202
+ except Exception:
203
+ return default
204
+
205
+
206
+ def write_json(path: Path, payload: Any) -> None:
207
+ path.parent.mkdir(parents=True, exist_ok=True)
208
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
209
+
210
+
211
+ def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
212
+ path.parent.mkdir(parents=True, exist_ok=True)
213
+ with path.open("w", encoding="utf-8") as f:
214
+ for row in rows:
215
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
216
+
217
+
218
+ def write_csv(path: Path, rows: list[dict[str, Any]], fieldnames: list[str] | None = None) -> None:
219
+ path.parent.mkdir(parents=True, exist_ok=True)
220
+ if fieldnames is None:
221
+ keys: set[str] = set()
222
+ for row in rows:
223
+ keys.update(row.keys())
224
+ fieldnames = sorted(keys)
225
+ with path.open("w", encoding="utf-8", newline="") as f:
226
+ writer = csv.DictWriter(f, fieldnames=fieldnames)
227
+ writer.writeheader()
228
+ for row in rows:
229
+ writer.writerow({key: row.get(key) for key in fieldnames})
230
+
231
+
232
+ def format_duration(seconds: float | int | None) -> str:
233
+ if seconds is None:
234
+ return "--:--:--"
235
+ total_seconds = max(0, int(round(float(seconds))))
236
+ hours, rem = divmod(total_seconds, 3600)
237
+ minutes, secs = divmod(rem, 60)
238
+ return f"{hours:02d}:{minutes:02d}:{secs:02d}"
239
+
240
+
241
+ @dataclass
242
+ class TaskProgressTracker:
243
+ task_name: str
244
+ total_steps: int
245
+ step_label: str = "datasets"
246
+ substep_label: str = "assets"
247
+ total_substeps: int = 0
248
+ completed_steps: int = 0
249
+ completed_substeps: int = 0
250
+
251
+ def __post_init__(self) -> None:
252
+ self._start_ts = time.monotonic()
253
+ self._last_print_ts = self._start_ts
254
+
255
+ def print_start(self, extra: str = "") -> None:
256
+ parts = [
257
+ f"[{self.task_name}] start",
258
+ f"{self.step_label}=0/{self.total_steps}",
259
+ ]
260
+ if self.total_substeps > 0:
261
+ parts.append(f"{self.substep_label}=0/{self.total_substeps}")
262
+ if extra:
263
+ parts.append(extra)
264
+ print(" | ".join(parts), flush=True)
265
+
266
+ def advance(self, *, step_name: str, substeps_done: int = 0, extra: str = "") -> None:
267
+ self.completed_steps += 1
268
+ self.completed_substeps += max(0, int(substeps_done))
269
+ elapsed = time.monotonic() - self._start_ts
270
+ avg_per_step = (elapsed / self.completed_steps) if self.completed_steps > 0 else None
271
+ remaining_steps = max(0, self.total_steps - self.completed_steps)
272
+ eta_seconds = (avg_per_step * remaining_steps) if avg_per_step is not None else None
273
+
274
+ parts = [
275
+ f"[{self.task_name}] {self.step_label}={self.completed_steps}/{self.total_steps}",
276
+ ]
277
+ if self.total_substeps > 0:
278
+ parts.append(f"{self.substep_label}={self.completed_substeps}/{self.total_substeps}")
279
+ parts.extend(
280
+ [
281
+ f"elapsed={format_duration(elapsed)}",
282
+ f"eta={format_duration(eta_seconds)}",
283
+ f"done={step_name}",
284
+ ]
285
+ )
286
+ if extra:
287
+ parts.append(extra)
288
+ print(" | ".join(parts), flush=True)
289
+
290
+
291
+ def make_task_run_dir(task_name: str, run_tag: str) -> Path:
292
+ run_dir = OUTPUT_ROOT / task_name / "runs" / run_tag
293
+ run_dir.mkdir(parents=True, exist_ok=True)
294
+ write_json(OUTPUT_ROOT / task_name / "LATEST_RUN.json", {"run_tag": run_tag, "run_dir": str(run_dir.resolve())})
295
+ return run_dir
296
+
297
+
298
+ def list_dataset_ids() -> list[str]:
299
+ out: list[str] = []
300
+ if not DATA_ROOT.exists():
301
+ return out
302
+ for path in sorted(DATA_ROOT.iterdir()):
303
+ if not path.is_dir():
304
+ continue
305
+ if path.name.startswith("."):
306
+ continue
307
+ train_csv = resolve_real_split_path(path.name, split="train")
308
+ if train_csv.exists():
309
+ out.append(path.name)
310
+ return out
311
+
312
+
313
+ def resolve_dataset_dir(dataset_id: str) -> Path:
314
+ return DATA_ROOT / dataset_id
315
+
316
+
317
+ def resolve_real_split_path(dataset_id: str, split: str = "train") -> Path:
318
+ candidates = [
319
+ DATA_ROOT / dataset_id / f"{dataset_id}-{split}.csv",
320
+ DATA_ROOT / dataset_id / "raw" / f"{dataset_id}-{split}.csv",
321
+ ]
322
+ for path in candidates:
323
+ if path.exists():
324
+ return path
325
+ return candidates[0]
326
+
327
+
328
+ def resolve_field_registry_path(dataset_id: str) -> Path | None:
329
+ candidates = [
330
+ DATA_ROOT / dataset_id / "metadata_core" / "field_registry.json",
331
+ DATA_ROOT / dataset_id / "metadata" / "field_registry.json",
332
+ ]
333
+ for path in candidates:
334
+ if path.exists():
335
+ return path
336
+ return None
337
+
338
+
339
+ def load_field_registry(dataset_id: str) -> dict[str, Any]:
340
+ path = resolve_field_registry_path(dataset_id)
341
+ if path is None:
342
+ return {}
343
+ return read_json(path, {}) or {}
344
+
345
+
346
+ def load_field_type_hints(dataset_id: str) -> dict[str, str]:
347
+ payload = load_field_registry(dataset_id)
348
+ hints: dict[str, str] = {}
349
+ for item in payload.get("fields", []) if isinstance(payload, dict) else []:
350
+ if not isinstance(item, dict):
351
+ continue
352
+ name = str(item.get("name") or "").strip()
353
+ if not name:
354
+ continue
355
+ semantic = str(item.get("semantic_type") or "").strip().lower()
356
+ declared = str(item.get("declared_type") or "").strip().lower()
357
+ hints[name] = semantic or declared
358
+ return hints
359
+
360
+
361
+ def resolve_sql_result_role_annotation_path(dataset_id: str) -> Path:
362
+ return SQL_RESULT_ROLE_ANNOTATION_ROOT / dataset_id / "outputs" / "sql_result_roles_ai_v1.json"
363
+
364
+
365
+ def load_sql_result_role_annotations(
366
+ dataset_id: str,
367
+ *,
368
+ sql_source_version: str | None = None,
369
+ ) -> dict[tuple[str, str], dict[str, Any]]:
370
+ path = resolve_sql_result_role_annotation_path(dataset_id)
371
+ payload = read_json(path, {}) or {}
372
+ query_annotations = payload.get("query_annotations") if isinstance(payload, dict) else []
373
+ requested_version = normalize_sql_source_version(sql_source_version) if sql_source_version else None
374
+
375
+ output: dict[tuple[str, str], dict[str, Any]] = {}
376
+ if not isinstance(query_annotations, list):
377
+ return output
378
+
379
+ for item in query_annotations:
380
+ if not isinstance(item, dict):
381
+ continue
382
+ version_text = str(item.get("sql_source_version") or "").strip()
383
+ query_id = str(item.get("query_id") or "").strip()
384
+ if not query_id:
385
+ continue
386
+ try:
387
+ normalized_version = normalize_sql_source_version(version_text or requested_version or DEFAULT_SQL_SOURCE_VERSION)
388
+ except Exception:
389
+ continue
390
+ if requested_version and normalized_version != requested_version:
391
+ continue
392
+ output[(normalized_version, query_id)] = item
393
+ return output
394
+
395
+
396
+ def parse_timestamp_text(value: str | None) -> datetime | None:
397
+ if not value:
398
+ return None
399
+ text = str(value).strip()
400
+ try:
401
+ if text.endswith("Z"):
402
+ text = text[:-1] + "+00:00"
403
+ parsed = datetime.fromisoformat(text)
404
+ if parsed.tzinfo is None:
405
+ parsed = parsed.replace(tzinfo=timezone.utc)
406
+ return parsed.astimezone(timezone.utc)
407
+ except Exception:
408
+ pass
409
+ match = TIMESTAMP_RE.search(text)
410
+ if not match:
411
+ return None
412
+ try:
413
+ return datetime.strptime(match.group(1), "%Y%m%d_%H%M%S").replace(tzinfo=timezone.utc)
414
+ except Exception:
415
+ return None
416
+
417
+
418
+ def _candidate_timestamps(*values: str | Path | None) -> list[datetime]:
419
+ out: list[datetime] = []
420
+ for value in values:
421
+ if value is None:
422
+ continue
423
+ parsed = parse_timestamp_text(str(value))
424
+ if parsed is not None:
425
+ out.append(parsed)
426
+ return out
427
+
428
+
429
+ def _stat_mtime_ts(path: Path | None) -> datetime | None:
430
+ if path is None or not path.exists():
431
+ return None
432
+ try:
433
+ return datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc)
434
+ except Exception:
435
+ return None
436
+
437
+
438
+ def _stat_size_bytes(path: Path | None) -> int | None:
439
+ if path is None or not path.exists():
440
+ return None
441
+ try:
442
+ return int(path.stat().st_size)
443
+ except Exception:
444
+ return None
445
+
446
+
447
+ def _resolved_path_text(path: Path | None) -> str:
448
+ if path is None:
449
+ return ""
450
+ try:
451
+ return str(path.expanduser().resolve())
452
+ except Exception:
453
+ return str(path)
454
+
455
+
456
+ def _path_provenance_fields(prefix: str, path: Path | None) -> dict[str, Any]:
457
+ mtime = _stat_mtime_ts(path)
458
+ return {
459
+ f"{prefix}_path": _resolved_path_text(path),
460
+ f"{prefix}_exists": bool(path and path.exists()),
461
+ f"{prefix}_mtime_utc": (mtime.isoformat() if mtime is not None else None),
462
+ f"{prefix}_size_bytes": _stat_size_bytes(path),
463
+ }
464
+
465
+
466
+ def _sha256_text(text: str) -> str:
467
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
468
+
469
+
470
+ def _resolve_registry_backed_path(raw_path: str | Path | None) -> Path:
471
+ text = str(raw_path or "").strip()
472
+ if not text:
473
+ return Path("")
474
+ candidate = Path(text).expanduser()
475
+ if candidate.exists():
476
+ return candidate
477
+
478
+ normalized = text.replace("\\", "/")
479
+ marker = "/SQLagent/"
480
+ if marker in normalized:
481
+ suffix = normalized.split(marker, 1)[1].lstrip("/")
482
+ rebased = (PROJECT_ROOT / suffix).resolve()
483
+ if rebased.exists():
484
+ return rebased
485
+
486
+ if normalized.startswith("SQLagent/"):
487
+ rebased = (PROJECT_ROOT / normalized[len("SQLagent/"):]).resolve()
488
+ if rebased.exists():
489
+ return rebased
490
+
491
+ match = SUBITEM_RUNS_PATH_RE.search(normalized)
492
+ if match:
493
+ version = match.group(1).lower()
494
+ suffix = match.group("suffix").lstrip("/")
495
+ rebased = (runs_root(version) / suffix).resolve()
496
+ if rebased.exists():
497
+ return rebased
498
+
499
+ return candidate
500
+
501
+
502
+ def sql_source_family(version: str | None) -> str:
503
+ normalized = normalize_sql_source_version(version)
504
+ return "legacy" if normalized == SQL_SOURCE_VERSION_V1 else "current"
505
+
506
+
507
+ def sql_source_line_version(version: str | None) -> str:
508
+ normalized = normalize_sql_source_version(version)
509
+ return normalized if normalized in CURRENT_SQL_SOURCE_VERSIONS else ""
510
+
511
+
512
+ def sql_source_registry_root(version: str | None) -> Path | None:
513
+ normalized = normalize_sql_source_version(version)
514
+ if normalized == SQL_SOURCE_VERSION_V1:
515
+ return None
516
+ return registry_dir(normalized)
517
+
518
+
519
+ def is_current_sql_source_version(version: str | None) -> bool:
520
+ return normalize_sql_source_version(version) in CURRENT_SQL_SOURCE_VERSIONS
521
+
522
+
523
+ def real_split_provenance(dataset_id: str, split: str = "train") -> dict[str, Any]:
524
+ real_path = resolve_real_split_path(dataset_id, split=split)
525
+ return {
526
+ "provenance_contract_version": PROVENANCE_CONTRACT_VERSION,
527
+ "real_reference_split": split,
528
+ "real_source_kind": "reference_split_csv",
529
+ "real_source_dataset_id": dataset_id,
530
+ "real_source_split": split,
531
+ **_path_provenance_fields("real_source", real_path),
532
+ }
533
+
534
+
535
+ def resolve_latest_task_run_dir(task_name: str) -> Path | None:
536
+ latest_path = OUTPUT_ROOT / task_name / "LATEST_RUN.json"
537
+ payload = read_json(latest_path, {}) or {}
538
+ run_dir = payload.get("run_dir")
539
+ if not run_dir:
540
+ return None
541
+ candidate = Path(str(run_dir))
542
+ return candidate if candidate.exists() else None
543
+
544
+
545
+ def resolve_requested_sql_source_version(
546
+ task_name: str | None = None,
547
+ default: str = DEFAULT_SQL_SOURCE_VERSION,
548
+ ) -> str:
549
+ override = str(os.environ.get(SQL_SOURCE_VERSION_ENV_VAR) or "").strip()
550
+ if override:
551
+ return normalize_sql_source_version(override)
552
+ if task_name:
553
+ return resolve_latest_task_sql_source_version(task_name, default=default)
554
+ return normalize_sql_source_version(default)
555
+
556
+
557
+ def resolve_latest_task_sql_source_version(task_name: str, default: str = DEFAULT_SQL_SOURCE_VERSION) -> str:
558
+ run_dir = resolve_latest_task_run_dir(task_name)
559
+ if run_dir is None:
560
+ return normalize_sql_source_version(default)
561
+ manifest = read_json(run_dir / "manifest.json", {}) or {}
562
+ try:
563
+ return normalize_sql_source_version(str(manifest.get("sql_source_version") or default))
564
+ except Exception:
565
+ return normalize_sql_source_version(default)
566
+
567
+
568
+ def resolve_task_run_dir_for_sql_source(
569
+ task_name: str,
570
+ sql_source_version: str | None = None,
571
+ *,
572
+ default: str = DEFAULT_SQL_SOURCE_VERSION,
573
+ ) -> Path | None:
574
+ requested = resolve_requested_sql_source_version(task_name=task_name, default=default)
575
+ target_version = normalize_sql_source_version(sql_source_version or requested)
576
+ latest_run_dir = resolve_latest_task_run_dir(task_name)
577
+ if latest_run_dir is not None:
578
+ latest_manifest = read_json(latest_run_dir / "manifest.json", {}) or {}
579
+ latest_version = str(latest_manifest.get("sql_source_version") or "").strip()
580
+ if latest_version:
581
+ try:
582
+ if normalize_sql_source_version(latest_version) == target_version:
583
+ return latest_run_dir
584
+ except Exception:
585
+ pass
586
+
587
+ runs_root_dir = OUTPUT_ROOT / task_name / "runs"
588
+ if not runs_root_dir.exists():
589
+ return None
590
+
591
+ ranked: list[tuple[int, int, str, Path]] = []
592
+ for candidate in runs_root_dir.iterdir():
593
+ if not candidate.is_dir():
594
+ continue
595
+ manifest_path = candidate / "manifest.json"
596
+ if not manifest_path.exists():
597
+ continue
598
+ manifest = read_json(manifest_path, {}) or {}
599
+ manifest_version = str(manifest.get("sql_source_version") or "").strip()
600
+ if not manifest_version:
601
+ continue
602
+ try:
603
+ if normalize_sql_source_version(manifest_version) != target_version:
604
+ continue
605
+ except Exception:
606
+ continue
607
+ ranked.append(
608
+ (
609
+ int(manifest.get("dataset_count") or 0),
610
+ int(manifest.get("asset_count") or 0),
611
+ candidate.name,
612
+ candidate.resolve(),
613
+ )
614
+ )
615
+ if not ranked:
616
+ return None
617
+ ranked.sort(reverse=True)
618
+ return ranked[0][3]
619
+
620
+
621
+ def build_sql_source_provenance(
622
+ *,
623
+ sql_source_version: str,
624
+ sql_source_kind: str,
625
+ sql_source_selection_mode: str,
626
+ source_run_id: str = "",
627
+ sql_file_path: Path | None = None,
628
+ manifest_path: Path | None = None,
629
+ registry_path: Path | None = None,
630
+ run_dir: Path | None = None,
631
+ dataset_dir: Path | None = None,
632
+ registry_version: str = "",
633
+ declared_version: str = "",
634
+ declared_label: str = "",
635
+ sql_file_sha256: str = "",
636
+ ) -> dict[str, Any]:
637
+ normalized = normalize_sql_source_version(sql_source_version)
638
+ registry_root = sql_source_registry_root(normalized)
639
+ return {
640
+ "provenance_contract_version": PROVENANCE_CONTRACT_VERSION,
641
+ "sql_source_family": sql_source_family(normalized),
642
+ "sql_source_line_version": sql_source_line_version(normalized),
643
+ "sql_source_version": normalized,
644
+ "sql_source_label": sql_source_label(normalized),
645
+ "sql_source_description": sql_source_description(normalized),
646
+ "sql_source_root": _resolved_path_text(sql_source_root(normalized)),
647
+ "sql_source_registry_root": _resolved_path_text(registry_root),
648
+ "sql_source_kind": sql_source_kind,
649
+ "sql_source_selection_mode": sql_source_selection_mode,
650
+ "sql_source_registry_version": str(registry_version or ""),
651
+ "sql_source_declared_version": str(declared_version or ""),
652
+ "sql_source_declared_label": str(declared_label or ""),
653
+ "sql_source_file_sha256": str(sql_file_sha256 or ""),
654
+ "source_run_id": str(source_run_id or ""),
655
+ "sql_origin_path": _resolved_path_text(sql_file_path),
656
+ **_path_provenance_fields("sql_source_file", sql_file_path),
657
+ **_path_provenance_fields("sql_source_manifest", manifest_path),
658
+ **_path_provenance_fields("sql_source_registry", registry_path),
659
+ **_path_provenance_fields("sql_source_run_dir", run_dir),
660
+ **_path_provenance_fields("sql_source_dataset_dir", dataset_dir),
661
+ }
662
+
663
+
664
+ def _find_local_artifact_by_name(search_root: Path, name: str) -> Path | None:
665
+ if not name:
666
+ return None
667
+ for path in search_root.rglob(name):
668
+ if path.is_file():
669
+ return path
670
+ return None
671
+
672
+
673
+ def _choose_synthetic_csv(candidates: list[Path]) -> Path | None:
674
+ filtered = _list_synthetic_csv_candidates(candidates)
675
+ if not filtered:
676
+ return None
677
+ filtered.sort(key=lambda p: (parse_timestamp_text(p.name) or _stat_mtime_ts(p) or datetime.min.replace(tzinfo=timezone.utc)))
678
+ return filtered[-1]
679
+
680
+
681
+ def _list_synthetic_csv_candidates(candidates: Iterable[Path]) -> list[Path]:
682
+ return [path for path in candidates if _is_synthetic_candidate_csv(path)]
683
+
684
+
685
+ def _is_synthetic_candidate_csv(path: Path) -> bool:
686
+ lname = path.name.lower()
687
+ stem = path.stem.lower()
688
+ if "train_continuous_imputed" in lname:
689
+ return False
690
+ for suffix in ("real", "test", "val", "train"):
691
+ if f"__{suffix}.csv" in lname or lname.endswith(f"_{suffix}.csv") or stem.endswith(f"_{suffix}"):
692
+ return False
693
+ return True
694
+
695
+
696
+ def _synthetic_candidate_sort_key(path: Path) -> datetime:
697
+ return parse_timestamp_text(path.name) or _stat_mtime_ts(path) or datetime.min.replace(tzinfo=timezone.utc)
698
+
699
+
700
+ def _runtime_result_prefix(path: Path) -> str:
701
+ match = RUNTIME_RESULT_RE.match(path.name)
702
+ if match:
703
+ return str(match.group("prefix") or "").strip()
704
+ return path.stem
705
+
706
+
707
+ def _match_runtime_payload_for_synthetic_csv(runtime_files: list[Path], synthetic_csv_path: Path) -> tuple[dict[str, Any], Path | None]:
708
+ synthetic_name = synthetic_csv_path.name
709
+ for runtime_file in sorted(runtime_files, reverse=True):
710
+ prefix = _runtime_result_prefix(runtime_file)
711
+ if prefix and synthetic_name.startswith(prefix):
712
+ return read_json(runtime_file, {}) or {}, runtime_file
713
+ if runtime_files:
714
+ chosen = sorted(runtime_files)[-1]
715
+ return read_json(chosen, {}) or {}, chosen
716
+ return {}, None
717
+
718
+
719
+ def _derive_run_id_for_candidate(runtime_run_id: str, synthetic_csv_path: Path) -> str:
720
+ stem = synthetic_csv_path.stem
721
+ if runtime_run_id and runtime_run_id in stem:
722
+ suffix = stem.split(runtime_run_id, 1)[1].strip("_-")
723
+ if suffix:
724
+ return f"{runtime_run_id}__{suffix}"
725
+ return runtime_run_id
726
+ if runtime_run_id:
727
+ return runtime_run_id
728
+ return stem
729
+
730
+
731
+ def _extract_gpu_seconds_from_logs(log_paths: list[Path], synthetic_csv_path: Path | None = None) -> tuple[float, str]:
732
+ explicit_seconds = 0.0
733
+ saw_explicit = False
734
+ for path in log_paths:
735
+ try:
736
+ text = path.read_text(encoding="utf-8", errors="ignore")
737
+ except Exception:
738
+ continue
739
+ for regex in [TRAIN_TIME_RE, SAMPLE_TIME_RE, GENERIC_SECONDS_RE]:
740
+ for match in regex.findall(text):
741
+ try:
742
+ explicit_seconds += float(match)
743
+ saw_explicit = True
744
+ except Exception:
745
+ continue
746
+ if saw_explicit and explicit_seconds > 0:
747
+ return explicit_seconds, "explicit_log_seconds"
748
+
749
+ inferred_seconds = 0.0
750
+ for path in log_paths:
751
+ start_ts = parse_timestamp_text(path.name) or parse_timestamp_text(path.stem)
752
+ end_ts = _stat_mtime_ts(path)
753
+ if start_ts is not None and end_ts is not None:
754
+ delta = (end_ts - start_ts).total_seconds()
755
+ if 0 < delta <= MAX_FALLBACK_GPU_SECONDS:
756
+ inferred_seconds += delta
757
+ if inferred_seconds > 0:
758
+ return inferred_seconds, "log_mtime_fallback"
759
+
760
+ if log_paths and synthetic_csv_path is not None and synthetic_csv_path.exists():
761
+ start_candidates = [parse_timestamp_text(path.name) for path in log_paths]
762
+ start_candidates = [item for item in start_candidates if item is not None]
763
+ end_ts = _stat_mtime_ts(synthetic_csv_path)
764
+ if start_candidates and end_ts is not None:
765
+ delta = (end_ts - min(start_candidates)).total_seconds()
766
+ if 0 < delta <= MAX_FALLBACK_GPU_SECONDS:
767
+ return delta, "artifact_mtime_fallback"
768
+
769
+ return 0.0, "unavailable_zero"
770
+
771
+
772
+ def _extract_gpu_seconds_from_runtime_payload(runtime_payload: dict[str, Any] | None) -> tuple[float, str] | None:
773
+ if not isinstance(runtime_payload, dict):
774
+ return None
775
+ timings = runtime_payload.get("timings")
776
+ if not isinstance(timings, dict):
777
+ return None
778
+ total_seconds = 0.0
779
+ saw_duration = False
780
+ for stage_name in ("train", "generate"):
781
+ stage_payload = timings.get(stage_name)
782
+ if not isinstance(stage_payload, dict):
783
+ continue
784
+ raw_value = stage_payload.get("duration_sec")
785
+ if raw_value is None:
786
+ continue
787
+ try:
788
+ duration_sec = float(raw_value)
789
+ except Exception:
790
+ continue
791
+ if duration_sec > 0:
792
+ total_seconds += duration_sec
793
+ saw_duration = True
794
+ if saw_duration:
795
+ return total_seconds, "runtime_result_timings"
796
+ return None
797
+
798
+
799
+ def _hyperparameter_tabsyn_is_consistent_batch(env_overrides: dict[str, Any]) -> bool:
800
+ # Accept any successful Tabsyn hyperparameter run that explicitly varies
801
+ # training knobs. Older code only admitted one very specific sweep shape,
802
+ # which filtered out newer smoke/BO runs (e.g. smaller batch sizes).
803
+ keys = {str(k): v for k, v in env_overrides.items()}
804
+ has_batch = any(
805
+ str(keys.get(name) or "").strip()
806
+ for name in (
807
+ "TABSYN_VAE_BATCH_SIZE",
808
+ "TABSYN_DIFFUSION_BATCH_SIZE",
809
+ "TABSYN_VAE_ENCODE_BATCH_SIZE",
810
+ "TABSYN_VAE_EVAL_BATCH_SIZE",
811
+ "TABSYN_VAE_INFER_BATCH_SIZE",
812
+ )
813
+ )
814
+ has_epoch = any(
815
+ str(keys.get(name) or "").strip()
816
+ for name in (
817
+ "TABSYN_VAE_EPOCHS",
818
+ "TABSYN_DIFFUSION_MAX_EPOCHS",
819
+ )
820
+ )
821
+ if not (has_batch and has_epoch):
822
+ return False
823
+ num_workers = str(keys.get("TABSYN_VAE_NUM_WORKERS") or "").strip()
824
+ if num_workers and num_workers != "0":
825
+ return False
826
+ return True
827
+
828
+
829
+ def _should_keep_hyperparameter_run(*, model_id: str, run_config_payload: dict[str, Any], runtime_payload: dict[str, Any]) -> bool:
830
+ if str(runtime_payload.get("train_status") or "").strip().lower() != "success":
831
+ return False
832
+ if str(runtime_payload.get("generate_status") or "").strip().lower() != "success":
833
+ return False
834
+ env_overrides = run_config_payload.get("env_overrides")
835
+ if not isinstance(env_overrides, dict) or not env_overrides:
836
+ return False
837
+ if str(model_id or "").strip().lower() == "tabsyn":
838
+ if _hyperparameter_tabsyn_is_consistent_batch(env_overrides):
839
+ return True
840
+ cli_args = run_config_payload.get("cli_args")
841
+ cli_args = cli_args if isinstance(cli_args, dict) else {}
842
+ has_epoch_signal = bool(str(cli_args.get("epochs") or "").strip()) or any(
843
+ str(env_overrides.get(name) or "").strip()
844
+ for name in ("TABSYN_VAE_EPOCHS", "TABSYN_DIFFUSION_MAX_EPOCHS")
845
+ )
846
+ has_batch_signal = any(
847
+ str(env_overrides.get(name) or "").strip()
848
+ for name in (
849
+ "TABSYN_VAE_BATCH_SIZE",
850
+ "TABSYN_DIFFUSION_BATCH_SIZE",
851
+ "TABSYN_VAE_ENCODE_BATCH_SIZE",
852
+ "TABSYN_VAE_EVAL_BATCH_SIZE",
853
+ "TABSYN_VAE_INFER_BATCH_SIZE",
854
+ )
855
+ )
856
+ return has_epoch_signal and has_batch_signal
857
+ return True
858
+
859
+
860
+ def _has_substantive_hyperparameter_overrides(env_overrides: dict[str, Any]) -> bool:
861
+ for key, value in env_overrides.items():
862
+ if str(key).startswith("BENCHMARK_"):
863
+ continue
864
+ if value is None:
865
+ continue
866
+ if str(value).strip():
867
+ return True
868
+ return False
869
+
870
+
871
+ def _build_asset(
872
+ *,
873
+ dataset_id: str,
874
+ model_id: str,
875
+ root_name: str,
876
+ asset_dir: Path,
877
+ run_id: str,
878
+ synthetic_csv_path: Path,
879
+ metadata_paths: list[Path],
880
+ log_paths: list[Path],
881
+ discovered_via: str,
882
+ runtime_payload: dict[str, Any] | None = None,
883
+ ) -> SyntheticAsset:
884
+ cfg = ROOT_CONFIGS[root_name]
885
+ timestamp_candidates = []
886
+ timestamp_candidates.extend(_candidate_timestamps(run_id, synthetic_csv_path.name))
887
+ timestamp_candidates.extend(item for item in (_stat_mtime_ts(synthetic_csv_path), _stat_mtime_ts(asset_dir)) if item is not None)
888
+ timestamp = max(timestamp_candidates) if timestamp_candidates else None
889
+ runtime_timing = _extract_gpu_seconds_from_runtime_payload(runtime_payload)
890
+ if runtime_timing is not None:
891
+ gpu_seconds_raw, gpu_source = runtime_timing
892
+ else:
893
+ gpu_seconds_raw, gpu_source = _extract_gpu_seconds_from_logs(log_paths, synthetic_csv_path)
894
+ gpu_hours_equivalent = (gpu_seconds_raw / 3600.0) * float(cfg["gpu_hour_ratio"])
895
+ return SyntheticAsset(
896
+ dataset_id=dataset_id,
897
+ model_id=model_id,
898
+ server_type=str(cfg["server_type"]),
899
+ root_name=root_name,
900
+ root_path=str(Path(cfg["path"]).resolve()),
901
+ asset_dir=str(asset_dir.resolve()),
902
+ run_id=run_id,
903
+ synthetic_csv_path=str(synthetic_csv_path.resolve()),
904
+ metadata_paths=[str(path.resolve()) for path in metadata_paths],
905
+ log_paths=[str(path.resolve()) for path in log_paths],
906
+ discovered_via=discovered_via,
907
+ timestamp_utc=(timestamp.isoformat() if timestamp is not None else None),
908
+ synthetic_source_mtime_utc=(_stat_mtime_ts(synthetic_csv_path).isoformat() if _stat_mtime_ts(synthetic_csv_path) is not None else None),
909
+ synthetic_source_size_bytes=_stat_size_bytes(synthetic_csv_path),
910
+ gpu_seconds_raw=round(gpu_seconds_raw, 6),
911
+ gpu_hours_equivalent=round(gpu_hours_equivalent, 6),
912
+ gpu_hours_source=gpu_source,
913
+ cost_usd=round(gpu_hours_equivalent * USD_PER_GPU_HOUR, 6),
914
+ )
915
+
916
+
917
+ def _discover_assets_in_synoutput(dataset_id: str, root_name: str) -> list[SyntheticAsset]:
918
+ root = Path(ROOT_CONFIGS[root_name]["path"])
919
+ dataset_root = root / dataset_id
920
+ if not dataset_root.exists():
921
+ return []
922
+ assets: list[SyntheticAsset] = []
923
+ for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()):
924
+ model_id = model_dir.name
925
+ for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
926
+ manifest_path = run_dir / "manifest.json"
927
+ if not manifest_path.exists():
928
+ continue
929
+ manifest = read_json(manifest_path, {}) or {}
930
+ runtime_result = manifest.get("runtime_result") if isinstance(manifest, dict) else {}
931
+ artifacts = runtime_result.get("artifacts") if isinstance(runtime_result, dict) else {}
932
+ desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name
933
+ synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None
934
+ if synthetic_csv_path is None:
935
+ synthetic_csv_path = _choose_synthetic_csv(list((run_dir / "synthetic").glob("*.csv")))
936
+ if synthetic_csv_path is None:
937
+ continue
938
+ run_id = str(runtime_result.get("run_id") or manifest.get("run_id") or run_dir.name)
939
+ log_paths = sorted((run_dir / "logs").glob("*.log"))
940
+ metadata_paths = [manifest_path] + sorted((run_dir / "meta").glob("*.json"))
941
+ assets.append(
942
+ _build_asset(
943
+ dataset_id=dataset_id,
944
+ model_id=model_id,
945
+ root_name=root_name,
946
+ asset_dir=run_dir,
947
+ run_id=run_id,
948
+ synthetic_csv_path=synthetic_csv_path,
949
+ metadata_paths=metadata_paths,
950
+ log_paths=log_paths,
951
+ discovered_via="manifest_json",
952
+ )
953
+ )
954
+ return assets
955
+
956
+
957
+ def _discover_assets_in_synoutput_5090(dataset_id: str, root_name: str) -> list[SyntheticAsset]:
958
+ root = Path(ROOT_CONFIGS[root_name]["path"])
959
+ dataset_root = root / dataset_id
960
+ if not dataset_root.exists():
961
+ return []
962
+ assets: list[SyntheticAsset] = []
963
+ for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()):
964
+ model_id = model_dir.name
965
+ runtime_files = sorted((model_dir / "metadata").glob("*__runtime_result.json"))
966
+ synthetic_candidates = sorted(
967
+ _list_synthetic_csv_candidates((model_dir / "synthetic_data").glob("*.csv")),
968
+ key=_synthetic_candidate_sort_key,
969
+ )
970
+ if not synthetic_candidates:
971
+ continue
972
+ metadata_paths_all = sorted((model_dir / "metadata").glob("*.json"))
973
+ log_paths = sorted((model_dir / "logs").glob("*.log"))
974
+
975
+ for synthetic_csv_path in synthetic_candidates:
976
+ runtime_payload, matched_runtime = _match_runtime_payload_for_synthetic_csv(runtime_files, synthetic_csv_path)
977
+ runtime_run_id = str(runtime_payload.get("run_id") or model_dir.name)
978
+ run_id = _derive_run_id_for_candidate(runtime_run_id, synthetic_csv_path)
979
+ metadata_paths = list(metadata_paths_all)
980
+ if matched_runtime is not None and matched_runtime not in metadata_paths:
981
+ metadata_paths = [matched_runtime] + metadata_paths
982
+ assets.append(
983
+ _build_asset(
984
+ dataset_id=dataset_id,
985
+ model_id=model_id,
986
+ root_name=root_name,
987
+ asset_dir=model_dir,
988
+ run_id=run_id,
989
+ synthetic_csv_path=synthetic_csv_path,
990
+ metadata_paths=metadata_paths,
991
+ log_paths=log_paths,
992
+ discovered_via=("runtime_result_json_matched" if matched_runtime is not None else "synthetic_csv_scan"),
993
+ )
994
+ )
995
+ return assets
996
+
997
+
998
+ def _discover_assets_in_trainonly_root(dataset_id: str, root_name: str) -> list[SyntheticAsset]:
999
+ root = Path(ROOT_CONFIGS[root_name]["path"])
1000
+ dataset_root = root / dataset_id
1001
+ if not dataset_root.exists():
1002
+ return []
1003
+ assets: list[SyntheticAsset] = []
1004
+ for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()):
1005
+ model_id = model_dir.name
1006
+ for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
1007
+ runtime_path = run_dir / "runtime_result.json"
1008
+ runtime_payload = read_json(runtime_path, {}) or {}
1009
+ if not isinstance(runtime_payload, dict):
1010
+ continue
1011
+ artifacts = runtime_payload.get("artifacts") if isinstance(runtime_payload.get("artifacts"), dict) else {}
1012
+ desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name
1013
+ candidate_files = list(run_dir.glob("*.csv"))
1014
+ synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None
1015
+ if synthetic_csv_path is None:
1016
+ synthetic_csv_path = _choose_synthetic_csv(candidate_files)
1017
+ if synthetic_csv_path is None:
1018
+ continue
1019
+
1020
+ run_id = str(runtime_payload.get("run_id") or run_dir.name)
1021
+ log_paths = sorted(run_dir.glob("*.log"))
1022
+ metadata_paths = [runtime_path] if runtime_path.exists() else []
1023
+ for extra in [
1024
+ run_dir / "input_snapshot.json",
1025
+ run_dir / "run_config.json",
1026
+ run_dir / "public_gate" / "public_gate_report.json",
1027
+ run_dir / "public_gate" / "normalized_schema_snapshot.json",
1028
+ run_dir / "public_gate" / "staged_input_manifest.json",
1029
+ ]:
1030
+ if extra.exists() and extra not in metadata_paths:
1031
+ metadata_paths.append(extra)
1032
+ assets.append(
1033
+ _build_asset(
1034
+ dataset_id=dataset_id,
1035
+ model_id=model_id,
1036
+ root_name=root_name,
1037
+ asset_dir=run_dir,
1038
+ run_id=run_id,
1039
+ synthetic_csv_path=synthetic_csv_path,
1040
+ metadata_paths=metadata_paths,
1041
+ log_paths=log_paths,
1042
+ discovered_via="runtime_result_json",
1043
+ runtime_payload=runtime_payload,
1044
+ )
1045
+ )
1046
+ return assets
1047
+
1048
+
1049
+ def _discover_assets_in_hyperparameter_trainonly_root(dataset_id: str, root_name: str) -> list[SyntheticAsset]:
1050
+ root = Path(ROOT_CONFIGS[root_name]["path"])
1051
+ dataset_root = root / dataset_id
1052
+ if not dataset_root.exists():
1053
+ return []
1054
+ assets: list[SyntheticAsset] = []
1055
+ for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()):
1056
+ model_id = model_dir.name
1057
+ candidate_runs: list[tuple[Path, dict[str, Any], dict[str, Any], bool]] = []
1058
+ for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
1059
+ runtime_path = run_dir / "runtime_result.json"
1060
+ run_config_path = run_dir / "run_config.json"
1061
+ runtime_payload = read_json(runtime_path, {}) or {}
1062
+ run_config_payload = read_json(run_config_path, {}) or {}
1063
+ if not isinstance(runtime_payload, dict) or not isinstance(run_config_payload, dict):
1064
+ continue
1065
+ if not _should_keep_hyperparameter_run(
1066
+ model_id=model_id,
1067
+ run_config_payload=run_config_payload,
1068
+ runtime_payload=runtime_payload,
1069
+ ):
1070
+ continue
1071
+ env_overrides = run_config_payload.get("env_overrides")
1072
+ env_overrides = env_overrides if isinstance(env_overrides, dict) else {}
1073
+ candidate_runs.append(
1074
+ (
1075
+ run_dir,
1076
+ runtime_payload,
1077
+ run_config_payload,
1078
+ _has_substantive_hyperparameter_overrides(env_overrides),
1079
+ )
1080
+ )
1081
+
1082
+ if not candidate_runs:
1083
+ continue
1084
+ keep_only_substantive = any(item[3] for item in candidate_runs)
1085
+ for run_dir, runtime_payload, run_config_payload, has_substantive_overrides in candidate_runs:
1086
+ if keep_only_substantive and not has_substantive_overrides:
1087
+ continue
1088
+ artifacts = runtime_payload.get("artifacts") if isinstance(runtime_payload.get("artifacts"), dict) else {}
1089
+ desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name
1090
+ candidate_files = list(run_dir.glob("*.csv"))
1091
+ synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None
1092
+ if synthetic_csv_path is None:
1093
+ synthetic_csv_path = _choose_synthetic_csv(candidate_files)
1094
+ if synthetic_csv_path is None:
1095
+ continue
1096
+
1097
+ run_id = str(runtime_payload.get("run_id") or run_dir.name)
1098
+ log_paths = sorted(run_dir.glob("*.log"))
1099
+ metadata_paths = [runtime_path] if runtime_path.exists() else []
1100
+ for extra in [
1101
+ run_config_path,
1102
+ run_dir / "input_snapshot.json",
1103
+ run_dir / "public_gate" / "public_gate_report.json",
1104
+ run_dir / "public_gate" / "normalized_schema_snapshot.json",
1105
+ run_dir / "public_gate" / "staged_input_manifest.json",
1106
+ ]:
1107
+ if extra.exists() and extra not in metadata_paths:
1108
+ metadata_paths.append(extra)
1109
+ assets.append(
1110
+ _build_asset(
1111
+ dataset_id=dataset_id,
1112
+ model_id=model_id,
1113
+ root_name=root_name,
1114
+ asset_dir=run_dir,
1115
+ run_id=run_id,
1116
+ synthetic_csv_path=synthetic_csv_path,
1117
+ metadata_paths=metadata_paths,
1118
+ log_paths=log_paths,
1119
+ discovered_via="runtime_result_json_hyperparameter",
1120
+ runtime_payload=runtime_payload,
1121
+ )
1122
+ )
1123
+ return assets
1124
+
1125
+
1126
+ def discover_synthetic_assets(
1127
+ *,
1128
+ datasets: list[str] | None = None,
1129
+ latest_only: bool = True,
1130
+ root_names: list[str] | tuple[str, ...] | None = None,
1131
+ ) -> list[SyntheticAsset]:
1132
+ dataset_ids = datasets or list_dataset_ids()
1133
+ requested_roots = [str(item).strip() for item in (root_names or []) if str(item).strip()]
1134
+ if requested_roots:
1135
+ invalid = sorted(set(requested_roots) - set(ROOT_CONFIGS.keys()))
1136
+ if invalid:
1137
+ raise ValueError(f"Unsupported synthetic root names: {invalid}. Available: {sorted(ROOT_CONFIGS.keys())}")
1138
+ active_roots = requested_roots or list(ROOT_CONFIGS.keys())
1139
+ assets: list[SyntheticAsset] = []
1140
+ for dataset_id in dataset_ids:
1141
+ for root_name in active_roots:
1142
+ if root_name == "SynOutput":
1143
+ assets.extend(_discover_assets_in_synoutput(dataset_id, root_name))
1144
+ elif root_name == "SynOutput-5090":
1145
+ assets.extend(_discover_assets_in_synoutput_5090(dataset_id, root_name))
1146
+ elif root_name == "Benchmark-trainonly-v1":
1147
+ assets.extend(_discover_assets_in_trainonly_root(dataset_id, root_name))
1148
+ elif root_name == "Hyperparameter-trainonly-v1":
1149
+ assets.extend(_discover_assets_in_hyperparameter_trainonly_root(dataset_id, root_name))
1150
+ elif root_name == "TabQueryBench-SynDataSuccess-main":
1151
+ assets.extend(_discover_assets_in_trainonly_root(dataset_id, root_name))
1152
+ if not latest_only:
1153
+ return sorted(assets, key=lambda item: (item.dataset_id, item.server_type, item.model_id, item.timestamp_utc or ""))
1154
+
1155
+ latest_map: dict[tuple[str, str, str], SyntheticAsset] = {}
1156
+ for asset in assets:
1157
+ key = (asset.dataset_id, asset.server_type, asset.model_id)
1158
+ current = latest_map.get(key)
1159
+ asset_ts = parse_timestamp_text(asset.timestamp_utc or "")
1160
+ current_ts = parse_timestamp_text(current.timestamp_utc or "") if current else None
1161
+ if current is None or ((asset_ts or datetime.min.replace(tzinfo=timezone.utc)) >= (current_ts or datetime.min.replace(tzinfo=timezone.utc))):
1162
+ latest_map[key] = asset
1163
+ return sorted(latest_map.values(), key=lambda item: (item.dataset_id, item.server_type, item.model_id))
1164
+
1165
+
1166
+ def split_sql_statements(sql_text: str) -> list[str]:
1167
+ statements: list[str] = []
1168
+ buf: list[str] = []
1169
+ in_single = False
1170
+ in_double = False
1171
+ prev = ""
1172
+ for ch in sql_text:
1173
+ if ch == "'" and not in_double and prev != "\\":
1174
+ in_single = not in_single
1175
+ elif ch == '"' and not in_single and prev != "\\":
1176
+ in_double = not in_double
1177
+ if ch == ";" and not in_single and not in_double:
1178
+ stmt = "".join(buf).strip()
1179
+ if stmt:
1180
+ statements.append(stmt)
1181
+ buf = []
1182
+ else:
1183
+ buf.append(ch)
1184
+ prev = ch
1185
+ tail = "".join(buf).strip()
1186
+ if tail:
1187
+ statements.append(tail)
1188
+ cleaned = []
1189
+ for stmt in statements:
1190
+ lines = [line for line in stmt.splitlines() if not line.strip().startswith("--")]
1191
+ candidate = "\n".join(lines).strip()
1192
+ if candidate:
1193
+ cleaned.append(candidate)
1194
+ return cleaned
1195
+
1196
+
1197
+ def normalize_sql_source_version(value: str | None) -> str:
1198
+ text = str(value or "").strip().lower()
1199
+ if not text:
1200
+ return DEFAULT_SQL_SOURCE_VERSION
1201
+ match = re.search(r"(v[1-4])", text)
1202
+ if match and match.group(1) in SQL_SOURCE_VERSION_CHOICES:
1203
+ candidate = match.group(1)
1204
+ if candidate == SQL_SOURCE_VERSION_V1 and "subitem_workload" in text:
1205
+ candidate = ""
1206
+ if candidate:
1207
+ return candidate
1208
+ version = _SQL_SOURCE_ALIASES.get(text)
1209
+ if version is None:
1210
+ raise ValueError(
1211
+ f"Unsupported sql source version: {value!r}. Expected one of: {', '.join(SQL_SOURCE_VERSION_CHOICES)}"
1212
+ )
1213
+ return version
1214
+
1215
+
1216
+ def sql_source_label(version: str | None) -> str:
1217
+ normalized = normalize_sql_source_version(version)
1218
+ return _SQL_SOURCE_LABELS[normalized]
1219
+
1220
+
1221
+ def sql_source_description(version: str | None) -> str:
1222
+ normalized = normalize_sql_source_version(version)
1223
+ return _SQL_SOURCE_DESCRIPTIONS[normalized]
1224
+
1225
+
1226
+ def sql_source_root(version: str | None) -> Path:
1227
+ normalized = normalize_sql_source_version(version)
1228
+ if normalized == SQL_SOURCE_VERSION_V1:
1229
+ return LOGS_ROOT
1230
+ if normalized in CURRENT_SQL_SOURCE_VERSIONS:
1231
+ return runs_root(normalized)
1232
+ raise ValueError(f"Unsupported sql source version: {version!r}")
1233
+
1234
+
1235
+ def resolve_sql_run_dir(*, sql_source_version: str, run_id: str, dataset_id: str | None = None) -> Path:
1236
+ normalized = normalize_sql_source_version(sql_source_version)
1237
+ if normalized == SQL_SOURCE_VERSION_V1:
1238
+ return LOGS_ROOT / run_id
1239
+ if not dataset_id:
1240
+ raise ValueError("dataset_id is required when resolving a current workload run directory.")
1241
+ return runs_root(normalized) / run_id / dataset_id
1242
+
1243
+
1244
+ def _load_latest_v1_sql_query_groups(
1245
+ *,
1246
+ dataset_ids: Iterable[str] | None = None,
1247
+ engines: tuple[str, ...] = ("cli",),
1248
+ ) -> dict[tuple[str, str], dict[str, Any]]:
1249
+ grouped: dict[tuple[str, str], dict[str, Any]] = {}
1250
+ if not LOGS_ROOT.exists():
1251
+ return grouped
1252
+
1253
+ dataset_filter = {str(item).strip() for item in dataset_ids or [] if str(item).strip()}
1254
+ for manifest_path in LOGS_ROOT.rglob("run_manifest.json"):
1255
+ payload = read_json(manifest_path, {}) or {}
1256
+ if str(payload.get("status") or "") != "completed":
1257
+ continue
1258
+ if str(payload.get("mode") or "") != "template_grounded_sql_qa":
1259
+ continue
1260
+ dataset_id = str(payload.get("dataset_id") or "").strip()
1261
+ if not dataset_id:
1262
+ continue
1263
+ if dataset_filter and dataset_id not in dataset_filter:
1264
+ continue
1265
+ engine = str(payload.get("engine") or "").strip()
1266
+ if engines and engine not in engines:
1267
+ continue
1268
+ question_record = payload.get("question_record")
1269
+ if not isinstance(question_record, dict):
1270
+ continue
1271
+ question_id = str(question_record.get("question_id") or "").strip()
1272
+ if not question_id:
1273
+ continue
1274
+ sql_path = manifest_path.parent / "generated_sql.sql"
1275
+ if not sql_path.exists():
1276
+ continue
1277
+ ended_at = str(payload.get("ended_at") or payload.get("started_at") or "")
1278
+ key = (dataset_id, question_id)
1279
+ current = grouped.get(key)
1280
+ if current is None:
1281
+ grouped[key] = {
1282
+ "payload": payload,
1283
+ "sql_path": sql_path,
1284
+ "sort_dt": parse_timestamp_text(ended_at) or _stat_mtime_ts(sql_path) or datetime.min.replace(tzinfo=timezone.utc),
1285
+ "manifest_path": manifest_path,
1286
+ }
1287
+ continue
1288
+ new_dt = parse_timestamp_text(ended_at) or _stat_mtime_ts(sql_path) or datetime.min.replace(tzinfo=timezone.utc)
1289
+ if new_dt >= current.get("sort_dt", datetime.min.replace(tzinfo=timezone.utc)):
1290
+ grouped[key] = {
1291
+ "payload": payload,
1292
+ "sql_path": sql_path,
1293
+ "sort_dt": new_dt,
1294
+ "manifest_path": manifest_path,
1295
+ }
1296
+ return grouped
1297
+
1298
+
1299
+ def _current_query_manifest_path(
1300
+ *,
1301
+ run_id: str,
1302
+ dataset_id: str,
1303
+ query_record_id: str,
1304
+ sql_source_version: str,
1305
+ ) -> Path:
1306
+ normalized = normalize_line_version(sql_source_version)
1307
+ return run_manifest_dir(run_id, dataset_id, line_version=normalized) / query_record_id / "run_manifest.json"
1308
+
1309
+
1310
+ def _load_latest_current_sql_query_groups(
1311
+ *,
1312
+ sql_source_version: str,
1313
+ dataset_ids: Iterable[str] | None = None,
1314
+ engines: tuple[str, ...] = ("cli",),
1315
+ require_accepted_for_eval: bool = True,
1316
+ ) -> dict[tuple[str, str], dict[str, Any]]:
1317
+ grouped: dict[tuple[str, str], dict[str, Any]] = {}
1318
+ normalized = normalize_sql_source_version(sql_source_version)
1319
+ registry_root = registry_dir(normalized)
1320
+ if not registry_root.exists():
1321
+ return grouped
1322
+
1323
+ dataset_filter = {str(item).strip() for item in dataset_ids or [] if str(item).strip()}
1324
+ for registry_path in sorted(registry_root.glob(f"*_query_registry_{normalized}.jsonl")):
1325
+ for row in load_registry_rows(registry_path):
1326
+ dataset_id = str(row.get("dataset_id") or "").strip()
1327
+ if not dataset_id:
1328
+ continue
1329
+ if dataset_filter and dataset_id not in dataset_filter:
1330
+ continue
1331
+ engine = str(row.get("engine") or "").strip()
1332
+ if engines and engine not in engines:
1333
+ continue
1334
+ if require_accepted_for_eval and not bool(row.get("accepted_for_eval")):
1335
+ continue
1336
+ query_record_id = str(row.get("query_record_id") or "").strip()
1337
+ if not query_record_id:
1338
+ continue
1339
+ sql_path = _resolve_registry_backed_path(row.get("sql_path"))
1340
+ if not sql_path.exists():
1341
+ continue
1342
+ run_id = str(row.get("round_id") or "").strip()
1343
+ manifest_path = _current_query_manifest_path(
1344
+ run_id=run_id,
1345
+ dataset_id=dataset_id,
1346
+ query_record_id=query_record_id,
1347
+ sql_source_version=normalized,
1348
+ )
1349
+ manifest = read_json(manifest_path, {}) or {}
1350
+ sort_dt = (
1351
+ parse_timestamp_text(str(manifest.get("ended_at") or manifest.get("started_at") or ""))
1352
+ or _stat_mtime_ts(sql_path)
1353
+ or _stat_mtime_ts(manifest_path)
1354
+ or _stat_mtime_ts(registry_path)
1355
+ or datetime.min.replace(tzinfo=timezone.utc)
1356
+ )
1357
+ key = (dataset_id, query_record_id)
1358
+ current = grouped.get(key)
1359
+ if current is None or sort_dt >= current.get("sort_dt", datetime.min.replace(tzinfo=timezone.utc)):
1360
+ grouped[key] = {
1361
+ "row": row,
1362
+ "sql_path": sql_path,
1363
+ "registry_path": registry_path,
1364
+ "manifest_path": manifest_path,
1365
+ "manifest": manifest,
1366
+ "sql_source_version": normalized,
1367
+ "sort_dt": sort_dt,
1368
+ }
1369
+ return grouped
1370
+
1371
+
1372
+ def load_latest_sql_queries_by_dataset(
1373
+ *,
1374
+ dataset_ids: Iterable[str],
1375
+ engines: tuple[str, ...] = ("cli",),
1376
+ include_all_statements: bool = True,
1377
+ sql_source_version: str = DEFAULT_SQL_SOURCE_VERSION,
1378
+ ) -> dict[str, list[dict[str, Any]]]:
1379
+ dataset_ids = [str(item).strip() for item in dataset_ids if str(item).strip()]
1380
+ normalized_source = normalize_sql_source_version(sql_source_version)
1381
+ rows_by_dataset: dict[str, list[dict[str, Any]]] = defaultdict(list)
1382
+ if normalized_source == SQL_SOURCE_VERSION_V1:
1383
+ grouped = _load_latest_v1_sql_query_groups(dataset_ids=dataset_ids, engines=engines)
1384
+ for (dataset_id, question_id), item in sorted(grouped.items()):
1385
+ payload = item["payload"]
1386
+ sql_text = item["sql_path"].read_text(encoding="utf-8", errors="ignore")
1387
+ sql_file_hash = _sha256_text(sql_text)
1388
+ statements = split_sql_statements(sql_text)
1389
+ if not statements:
1390
+ continue
1391
+ if not include_all_statements:
1392
+ statements = statements[:1]
1393
+ question_record = payload.get("question_record") or {}
1394
+ provenance = build_sql_source_provenance(
1395
+ sql_source_version=SQL_SOURCE_VERSION_V1,
1396
+ sql_source_kind="legacy_grounded_run_manifest",
1397
+ sql_source_selection_mode="latest_per_question_id",
1398
+ source_run_id=str(payload.get("run_id") or ""),
1399
+ sql_file_path=item["sql_path"],
1400
+ manifest_path=item["manifest_path"],
1401
+ run_dir=item["manifest_path"].parent,
1402
+ declared_version=str(payload.get("sql_source_version") or ""),
1403
+ declared_label=str(payload.get("sql_source_label") or ""),
1404
+ sql_file_sha256=sql_file_hash,
1405
+ )
1406
+ for idx, statement in enumerate(statements, start=1):
1407
+ rows_by_dataset[dataset_id].append(
1408
+ {
1409
+ "dataset_id": dataset_id,
1410
+ "question_id": question_id,
1411
+ "query_id": f"{question_id}__sql{idx}",
1412
+ "sql_index": idx,
1413
+ "question": str(payload.get("question") or question_record.get("question") or ""),
1414
+ "template_id": str(question_record.get("template_id") or ""),
1415
+ "template_name": str(question_record.get("template_name") or ""),
1416
+ "family_id": str(question_record.get("primary_family") or ""),
1417
+ "canonical_subitem_id": str(question_record.get("canonical_subitem_id") or ""),
1418
+ "intended_facet_id": str(question_record.get("intended_facet_id") or ""),
1419
+ "variant_semantic_role": str(question_record.get("variant_semantic_role") or ""),
1420
+ "stable_question_id": str(question_record.get("stable_question_id") or ""),
1421
+ "query_identity_stable_key": str(question_record.get("query_identity_stable_key") or ""),
1422
+ "source_run_id": str(payload.get("run_id") or ""),
1423
+ "engine": str(payload.get("engine") or ""),
1424
+ "model": str(payload.get("model") or ""),
1425
+ "sql": statement,
1426
+ **provenance,
1427
+ }
1428
+ )
1429
+ else:
1430
+ grouped = _load_latest_current_sql_query_groups(
1431
+ sql_source_version=normalized_source,
1432
+ dataset_ids=dataset_ids,
1433
+ engines=engines,
1434
+ require_accepted_for_eval=True,
1435
+ )
1436
+ for (dataset_id, query_record_id), item in sorted(grouped.items()):
1437
+ row = item["row"]
1438
+ manifest = item["manifest"] if isinstance(item.get("manifest"), dict) else {}
1439
+ question_record = manifest.get("question_record") if isinstance(manifest, dict) else {}
1440
+ sql_text = item["sql_path"].read_text(encoding="utf-8", errors="ignore")
1441
+ sql_file_hash = str(row.get("sql_sha256") or "") or _sha256_text(sql_text)
1442
+ statements = split_sql_statements(sql_text)
1443
+ if not statements:
1444
+ continue
1445
+ if not include_all_statements:
1446
+ statements = statements[:1]
1447
+ declared_version = str(row.get("sql_source_version") or manifest.get("sql_source_version") or "")
1448
+ declared_label = str(row.get("sql_source_label") or manifest.get("sql_source_label") or "")
1449
+ run_id = str(row.get("round_id") or "")
1450
+ current_runs_root = runs_root(normalized_source)
1451
+ run_root = current_runs_root / run_id
1452
+ dataset_dir = run_root / dataset_id
1453
+ provenance = build_sql_source_provenance(
1454
+ sql_source_version=normalized_source,
1455
+ sql_source_kind="current_query_registry",
1456
+ sql_source_selection_mode="latest_per_query_record_id",
1457
+ source_run_id=run_id,
1458
+ sql_file_path=item["sql_path"],
1459
+ manifest_path=item["manifest_path"],
1460
+ registry_path=item["registry_path"],
1461
+ run_dir=run_root,
1462
+ dataset_dir=dataset_dir,
1463
+ registry_version=str(row.get("registry_version") or ""),
1464
+ declared_version=declared_version,
1465
+ declared_label=declared_label,
1466
+ sql_file_sha256=sql_file_hash,
1467
+ )
1468
+ for idx, statement in enumerate(statements, start=1):
1469
+ query_id = query_record_id if len(statements) == 1 else f"{query_record_id}__sql{idx}"
1470
+ rows_by_dataset[dataset_id].append(
1471
+ {
1472
+ "dataset_id": dataset_id,
1473
+ "question_id": query_record_id,
1474
+ "query_id": query_id,
1475
+ "sql_index": idx,
1476
+ "question": str(row.get("question_text") or question_record.get("question") or ""),
1477
+ "template_id": str(row.get("template_id") or question_record.get("template_id") or ""),
1478
+ "template_name": str(row.get("template_name") or question_record.get("template_name") or ""),
1479
+ "family_id": str(row.get("family_id") or question_record.get("family_id") or ""),
1480
+ "canonical_subitem_id": str(row.get("canonical_subitem_id") or question_record.get("canonical_subitem_id") or ""),
1481
+ "intended_facet_id": str(row.get("intended_facet_id") or question_record.get("intended_facet_id") or ""),
1482
+ "variant_semantic_role": str(row.get("variant_semantic_role") or question_record.get("variant_semantic_role") or ""),
1483
+ "stable_question_id": query_record_id,
1484
+ "query_identity_stable_key": str(row.get("query_identity_stable_key") or f"{dataset_id}::{query_record_id}"),
1485
+ "source_run_id": run_id,
1486
+ "engine": str(row.get("engine") or manifest.get("engine") or ""),
1487
+ "model": str(manifest.get("model") or ""),
1488
+ "sql": statement,
1489
+ "accepted_for_eval": bool(row.get("accepted_for_eval")),
1490
+ **provenance,
1491
+ }
1492
+ )
1493
+ return {dataset_id: rows_by_dataset.get(dataset_id, []) for dataset_id in dataset_ids}
1494
+
1495
+
1496
+ def load_latest_sql_queries(
1497
+ *,
1498
+ dataset_id: str,
1499
+ engines: tuple[str, ...] = ("cli",),
1500
+ include_all_statements: bool = True,
1501
+ sql_source_version: str = DEFAULT_SQL_SOURCE_VERSION,
1502
+ ) -> list[dict[str, Any]]:
1503
+ return load_latest_sql_queries_by_dataset(
1504
+ dataset_ids=[dataset_id],
1505
+ engines=engines,
1506
+ include_all_statements=include_all_statements,
1507
+ sql_source_version=sql_source_version,
1508
+ ).get(dataset_id, [])
1509
+
1510
+
1511
+ def materialize_csv_to_sqlite(csv_path: Path, sqlite_path: Path, table_name: str) -> None:
1512
+ if sqlite_path.exists():
1513
+ sqlite_path.unlink()
1514
+ sqlite_path.parent.mkdir(parents=True, exist_ok=True)
1515
+
1516
+ def _sqlite_ident(name: str) -> str:
1517
+ return f'"{str(name).replace("\"", "\"\"")}"'
1518
+
1519
+ def _sniff_delimiter(path: Path) -> str:
1520
+ try:
1521
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
1522
+ sample = handle.read(4096)
1523
+ dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
1524
+ return dialect.delimiter
1525
+ except Exception:
1526
+ return ","
1527
+
1528
+ def _repair_single_field_row(row: list[str], delimiter: str) -> list[str]:
1529
+ if len(row) != 1:
1530
+ return row
1531
+ cell = str(row[0] or "")
1532
+ if delimiter not in cell:
1533
+ return row
1534
+ repaired = cell.strip()
1535
+ if repaired.startswith('"') and repaired.endswith('"') and len(repaired) >= 2:
1536
+ repaired = repaired[1:-1]
1537
+ repaired = repaired.replace('""', '"')
1538
+ try:
1539
+ return next(csv.reader([repaired], delimiter=delimiter))
1540
+ except Exception:
1541
+ return repaired.split(delimiter)
1542
+
1543
+ def _infer_header_from_synthetic(dataset_id: str, width: int) -> list[str] | None:
1544
+ try:
1545
+ assets = discover_synthetic_assets(
1546
+ datasets=[dataset_id],
1547
+ root_names=["TabQueryBench-SynDataSuccess-main"],
1548
+ )
1549
+ except Exception:
1550
+ return None
1551
+ for asset in assets:
1552
+ synthetic_path = Path(asset.synthetic_csv_path)
1553
+ if not synthetic_path.exists():
1554
+ continue
1555
+ try:
1556
+ delimiter = _sniff_delimiter(synthetic_path)
1557
+ with synthetic_path.open("r", encoding="utf-8-sig", newline="") as synthetic_file:
1558
+ synthetic_reader = csv.reader(synthetic_file, delimiter=delimiter)
1559
+ synthetic_headers = next(synthetic_reader, [])
1560
+ except Exception:
1561
+ continue
1562
+ normalized = [str(header or "").strip() for header in synthetic_headers]
1563
+ if len(normalized) == width and all(normalized):
1564
+ return normalized
1565
+ return None
1566
+
1567
+ def _normalize_headers(first_row: list[str]) -> tuple[list[str], bool]:
1568
+ cleaned = [str(header or "").strip() for header in first_row]
1569
+ counts = Counter(cleaned)
1570
+ has_duplicates = any(name and count > 1 for name, count in counts.items())
1571
+ has_empty = any(not name for name in cleaned)
1572
+ if has_duplicates or has_empty:
1573
+ inferred = _infer_header_from_synthetic(table_name, len(first_row))
1574
+ if inferred:
1575
+ return inferred, True
1576
+ return [f"col_{idx}" for idx in range(1, len(first_row) + 1)], True
1577
+ return cleaned, False
1578
+
1579
+ conn = sqlite3.connect(sqlite_path)
1580
+ try:
1581
+ cur = conn.cursor()
1582
+ delimiter = _sniff_delimiter(csv_path)
1583
+ with csv_path.open("r", encoding="utf-8-sig", newline="") as f:
1584
+ reader = csv.reader(f, delimiter=delimiter)
1585
+ first_row = _repair_single_field_row(next(reader, []), delimiter)
1586
+ if not first_row:
1587
+ raise ValueError(f"Empty header: {csv_path}")
1588
+ headers, headerless = _normalize_headers(first_row)
1589
+ col_defs = ", ".join([f"{_sqlite_ident(header)} TEXT" for header in headers])
1590
+ cur.execute(f"DROP TABLE IF EXISTS {_sqlite_ident(table_name)}")
1591
+ cur.execute(f"CREATE TABLE {_sqlite_ident(table_name)} ({col_defs})")
1592
+ placeholders = ",".join(["?" for _ in headers])
1593
+ insert_sql = f"INSERT INTO {_sqlite_ident(table_name)} VALUES ({placeholders})"
1594
+ batch: list[list[str]] = []
1595
+ if headerless:
1596
+ row = list(first_row)
1597
+ if len(row) < len(headers):
1598
+ row = row + [""] * (len(headers) - len(row))
1599
+ elif len(row) > len(headers):
1600
+ row = row[: len(headers)]
1601
+ batch.append(row)
1602
+ for row in reader:
1603
+ row = _repair_single_field_row(row, delimiter)
1604
+ if len(row) < len(headers):
1605
+ row = row + [""] * (len(headers) - len(row))
1606
+ elif len(row) > len(headers):
1607
+ row = row[: len(headers)]
1608
+ batch.append(row)
1609
+ if len(batch) >= 1000:
1610
+ cur.executemany(insert_sql, batch)
1611
+ batch.clear()
1612
+ if batch:
1613
+ cur.executemany(insert_sql, batch)
1614
+ conn.commit()
1615
+ finally:
1616
+ conn.close()
1617
+
1618
+
1619
+ def normalize_missing(value: Any) -> bool:
1620
+ if value is None:
1621
+ return True
1622
+ return str(value).strip().lower() in MISSING_TEXT
1623
+
1624
+
1625
+ def mean_or_none(values: Iterable[float | None]) -> float | None:
1626
+ cleaned = [float(value) for value in values if value is not None and not math.isnan(float(value))]
1627
+ if not cleaned:
1628
+ return None
1629
+ return sum(cleaned) / len(cleaned)
evaluation/tail/tail_threshold_code/src/eval/tail_threshold/runner.py ADDED
@@ -0,0 +1,1562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run global tail-threshold sensitivity diagnostics and visualizations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import math
7
+ import re
8
+ from collections import Counter, defaultdict
9
+ from concurrent.futures import ProcessPoolExecutor, as_completed
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from statistics import mean
13
+ from typing import Any
14
+
15
+ import matplotlib
16
+
17
+ matplotlib.use("Agg")
18
+ import matplotlib.pyplot as plt
19
+ import numpy as np
20
+ from matplotlib.colors import LinearSegmentedColormap
21
+
22
+ from src.eval.common import (
23
+ SyntheticAsset,
24
+ TaskProgressTracker,
25
+ discover_synthetic_assets,
26
+ list_dataset_ids,
27
+ make_task_run_dir,
28
+ now_run_tag,
29
+ resolve_real_split_path,
30
+ write_csv,
31
+ write_json,
32
+ )
33
+
34
+ PROJECT_ROOT = Path(__file__).resolve().parents[3]
35
+ EVALUATION_ROOT = PROJECT_ROOT / "Evaluation"
36
+ TAIL_THRESHOLD_ROOT = EVALUATION_ROOT / "tail_threshold"
37
+
38
+ DEFAULT_THRESHOLD_PCTS = [10.0, 8.0, 6.0, 4.0, 2.0, 1.0, 0.5, 0.1, 0.01, 0.001]
39
+ DEFAULT_NUMERIC_BINS = 10
40
+ DEFAULT_MAX_WORKERS = 4
41
+ DEFAULT_REPRESENTATIVES_PER_PREFIX = 2
42
+
43
+ MODEL_LABELS = {
44
+ "arf": "ARF",
45
+ "bayesnet": "BayesNet",
46
+ "cdtd": "CDTD",
47
+ "codi": "CoDi",
48
+ "ctgan": "CTGAN",
49
+ "forestdiffusion": "ForestDiffusion",
50
+ "goggle": "GOGGLE",
51
+ "realtabformer": "RealTabFormer",
52
+ "rtf": "RealTabFormer",
53
+ "tabbyflow": "TabbyFlow",
54
+ "tabddpm": "TabDDPM",
55
+ "tabdiff": "TabDiff",
56
+ "tabpfgen": "TabPFGen",
57
+ "tabsyn": "TabSyn",
58
+ "tvae": "TVAE",
59
+ }
60
+
61
+ TAIL_COLOR = "#E76F51"
62
+ HEAD_COLOR = "#4C78A8"
63
+ SUBMETRIC_COLORS = {
64
+ "tail_set_consistency": "#C8553D",
65
+ "tail_mass_similarity": "#2A9D8F",
66
+ "tail_concentration_consistency": "#6D597A",
67
+ "tail_anchor_coverage": "#577590",
68
+ }
69
+ PREFIX_COLORS = {"c": "#577590", "m": "#43AA8B", "n": "#F3722C"}
70
+ REPRESENTATIVE_KIND_COLORS = {"fragility": "#E76F51", "hardness": "#6D597A"}
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class ThresholdSpec:
75
+ index: int
76
+ pct: float
77
+ ratio: float
78
+ label: str
79
+ subgroup_keep_ratio: float
80
+
81
+
82
+ def _threshold_specs(percentages: list[float] | None = None) -> list[ThresholdSpec]:
83
+ values = percentages or DEFAULT_THRESHOLD_PCTS
84
+ specs: list[ThresholdSpec] = []
85
+ for idx, pct in enumerate(values):
86
+ pct_value = float(pct)
87
+ ratio = pct_value / 100.0
88
+ label = f"{pct_value:g}%"
89
+ specs.append(
90
+ ThresholdSpec(
91
+ index=idx,
92
+ pct=pct_value,
93
+ ratio=ratio,
94
+ label=label,
95
+ subgroup_keep_ratio=max(0.0, 1.0 - ratio),
96
+ )
97
+ )
98
+ return specs
99
+
100
+
101
+ def _threshold_label_token(label: str) -> str:
102
+ token = re.sub(r"[^0-9A-Za-z]+", "_", str(label or "").strip()).strip("_").lower()
103
+ return token or "threshold"
104
+
105
+
106
+ def _closest_threshold_label(
107
+ threshold_specs: list[ThresholdSpec],
108
+ target_pct: float,
109
+ *,
110
+ exclude: set[str] | None = None,
111
+ ) -> str | None:
112
+ blocked = exclude or set()
113
+ candidates = [spec for spec in threshold_specs if spec.label not in blocked]
114
+ if not candidates:
115
+ return None
116
+ ranked = sorted(candidates, key=lambda spec: (abs(float(spec.pct) - float(target_pct)), -float(spec.pct), spec.index))
117
+ return ranked[0].label
118
+
119
+
120
+ def _fragility_anchor_plan(threshold_specs: list[ThresholdSpec]) -> dict[str, Any]:
121
+ labels = [spec.label for spec in threshold_specs]
122
+ if not labels:
123
+ return {
124
+ "anchor_label": None,
125
+ "primary_label": None,
126
+ "secondary_label": None,
127
+ "rarest_label": None,
128
+ "comparison_labels": [],
129
+ }
130
+
131
+ anchor_label = labels[0]
132
+ rarest_label = labels[-1]
133
+ used = {anchor_label}
134
+ primary_label = _closest_threshold_label(threshold_specs, 0.5, exclude=used)
135
+ if primary_label:
136
+ used.add(primary_label)
137
+ secondary_label = _closest_threshold_label(threshold_specs, 0.1, exclude=used)
138
+ if secondary_label:
139
+ used.add(secondary_label)
140
+
141
+ comparison_labels: list[str] = []
142
+ for label in [primary_label, secondary_label, rarest_label]:
143
+ if label and label != anchor_label and label not in comparison_labels:
144
+ comparison_labels.append(label)
145
+
146
+ return {
147
+ "anchor_label": anchor_label,
148
+ "primary_label": primary_label,
149
+ "secondary_label": secondary_label,
150
+ "rarest_label": rarest_label,
151
+ "comparison_labels": comparison_labels,
152
+ }
153
+
154
+
155
+ def _score_lookup(entries: dict[str, dict[str, Any]], label: str | None) -> float | None:
156
+ if not label:
157
+ return None
158
+ return _to_float((entries.get(label) or {}).get("tail_overall_score"))
159
+
160
+
161
+ def _attach_legacy_fragility_fields(payload: dict[str, Any], entries: dict[str, dict[str, Any]]) -> None:
162
+ legacy_score_fields = {
163
+ "10%": "tail_10pct",
164
+ "0.5%": "tail_0_5pct",
165
+ "0.1%": "tail_0_1pct",
166
+ "0.001%": "tail_0_001pct",
167
+ }
168
+ for label, field_name in legacy_score_fields.items():
169
+ payload[field_name] = _score_lookup(entries, label)
170
+
171
+ tail_10 = payload.get("tail_10pct")
172
+ tail_05 = payload.get("tail_0_5pct")
173
+ tail_01 = payload.get("tail_0_1pct")
174
+ tail_0001 = payload.get("tail_0_001pct")
175
+ payload["fragility_10_to_0_5"] = round(float(tail_10) - float(tail_05), 6) if tail_10 is not None and tail_05 is not None else None
176
+ payload["fragility_10_to_0_1"] = round(float(tail_10) - float(tail_01), 6) if tail_10 is not None and tail_01 is not None else None
177
+ payload["fragility_10_to_0_001"] = (
178
+ round(float(tail_10) - float(tail_0001), 6) if tail_10 is not None and tail_0001 is not None else None
179
+ )
180
+
181
+
182
+ def _read_csv_rows(path: Path) -> tuple[list[str], list[dict[str, str]]]:
183
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
184
+ reader = csv.DictReader(handle)
185
+ rows = [dict(row) for row in reader]
186
+ columns = [str(col) for col in (reader.fieldnames or [])]
187
+ return columns, rows
188
+
189
+
190
+ def _to_float(value: Any) -> float | None:
191
+ if value is None:
192
+ return None
193
+ text = str(value).strip()
194
+ if not text or text.lower() in {"nan", "null", "none"}:
195
+ return None
196
+ try:
197
+ return float(text)
198
+ except Exception:
199
+ return None
200
+
201
+
202
+ def _mean(values: list[float | None]) -> float | None:
203
+ cleaned = [float(value) for value in values if value is not None]
204
+ if not cleaned:
205
+ return None
206
+ return round(sum(cleaned) / len(cleaned), 6)
207
+
208
+
209
+ def _is_missing(value: Any) -> bool:
210
+ if value is None:
211
+ return True
212
+ text = str(value).strip().lower()
213
+ return text in {"", "nan", "none", "null", "na", "n/a"}
214
+
215
+
216
+ def _safe_float(value: Any) -> float | None:
217
+ try:
218
+ if _is_missing(value):
219
+ return None
220
+ return float(str(value).strip())
221
+ except Exception:
222
+ return None
223
+
224
+
225
+ def _is_id_like(name: str) -> bool:
226
+ text = str(name).strip().lower()
227
+ return text in {"id", "row_id", "index"} or text.endswith("_id")
228
+
229
+
230
+ def _load_target_column(dataset_id: str, columns: list[str]) -> str:
231
+ semantics_path = PROJECT_ROOT / "data" / dataset_id / "metadata" / "dataset_semantics.yaml"
232
+ if semantics_path.exists():
233
+ for raw in semantics_path.read_text(encoding="utf-8").splitlines():
234
+ line = raw.strip()
235
+ if line.startswith("target_column:"):
236
+ target = line.split(":", 1)[1].strip()
237
+ if target in columns:
238
+ return target
239
+ priors = ["class", "target", "label", "y", "outcome"]
240
+ lower_map = {col.lower(): col for col in columns}
241
+ for prior in priors:
242
+ if prior in lower_map:
243
+ return lower_map[prior]
244
+ return columns[-1]
245
+
246
+
247
+ def _quantile_edges(values: list[float], bins: int) -> list[float]:
248
+ if not values:
249
+ return []
250
+ arr = np.asarray(values, dtype=float)
251
+ quantiles = np.linspace(0, 1, bins + 1)
252
+ edges = np.quantile(arr, quantiles).tolist()
253
+ deduped: list[float] = []
254
+ for value in edges:
255
+ current = float(value)
256
+ if not deduped or abs(current - deduped[-1]) > 1e-12:
257
+ deduped.append(current)
258
+ return deduped
259
+
260
+
261
+ def _bin_numeric(value: float, edges: list[float]) -> str:
262
+ if not edges or len(edges) < 2:
263
+ return "q1"
264
+ for idx in range(len(edges) - 1):
265
+ left = edges[idx]
266
+ right = edges[idx + 1]
267
+ if idx == len(edges) - 2:
268
+ if left <= value <= right:
269
+ return f"q{idx + 1}"
270
+ if left <= value < right:
271
+ return f"q{idx + 1}"
272
+ if value < edges[0]:
273
+ return "below_q1"
274
+ return f"above_q{len(edges) - 1}"
275
+
276
+
277
+ def _build_transformers(
278
+ rows_real: list[dict[str, str]],
279
+ feature_columns: list[str],
280
+ numeric_bins: int,
281
+ ) -> dict[str, dict[str, Any]]:
282
+ transformers: dict[str, dict[str, Any]] = {}
283
+ for column in feature_columns:
284
+ raw_values = [row.get(column) for row in rows_real]
285
+ total = max(1, len(raw_values))
286
+ numeric_values = [value for value in (_safe_float(item) for item in raw_values) if value is not None]
287
+ numeric_ratio = len(numeric_values) / total
288
+ unique_numeric = len({round(value, 8) for value in numeric_values})
289
+ is_continuous_numeric = numeric_ratio >= 0.95 and unique_numeric >= 20
290
+ if is_continuous_numeric:
291
+ transformers[column] = {"mode": "numeric_bin", "edges": _quantile_edges(numeric_values, bins=numeric_bins)}
292
+ else:
293
+ transformers[column] = {"mode": "categorical"}
294
+ return transformers
295
+
296
+
297
+ def _tokenize(value: Any, rule: dict[str, Any]) -> str:
298
+ if _is_missing(value):
299
+ return "__MISSING__"
300
+ mode = str(rule.get("mode") or "categorical")
301
+ text = str(value).strip()
302
+ if mode == "numeric_bin":
303
+ numeric_value = _safe_float(value)
304
+ if numeric_value is None:
305
+ return "__MISSING__"
306
+ return _bin_numeric(numeric_value, rule.get("edges") or [])
307
+ return text
308
+
309
+
310
+ def _build_key_counter(
311
+ rows: list[dict[str, str]],
312
+ feature_columns: list[str],
313
+ transformers: dict[str, dict[str, Any]],
314
+ ) -> Counter[str]:
315
+ counter: Counter[str] = Counter()
316
+ for row in rows:
317
+ for column in feature_columns:
318
+ token = _tokenize(row.get(column), transformers[column])
319
+ counter[f"{column}::{token}"] += 1
320
+ return counter
321
+
322
+
323
+ def _sorted_support_items(counter: Counter[str], *, reverse: bool) -> list[tuple[str, int]]:
324
+ if reverse:
325
+ return sorted(((key, int(value)) for key, value in counter.items() if int(value) > 0), key=lambda item: (-item[1], item[0]))
326
+ return sorted(((key, int(value)) for key, value in counter.items() if int(value) > 0), key=lambda item: (item[1], item[0]))
327
+
328
+
329
+ def _select_bottom_band(items: list[tuple[str, int]], ratio: float) -> tuple[set[str], int]:
330
+ if not items:
331
+ return set(), 0
332
+ keep_n = max(1, int(math.ceil(len(items) * max(0.0, float(ratio)))))
333
+ selected = items[:keep_n]
334
+ gate = int(selected[-1][1]) if selected else 0
335
+ return {key for key, _ in selected}, gate
336
+
337
+
338
+ def _select_top_band(items: list[tuple[str, int]], keep_ratio: float) -> tuple[set[str], int]:
339
+ if not items:
340
+ return set(), 0
341
+ keep_n = max(1, int(math.ceil(len(items) * max(0.0, float(keep_ratio)))))
342
+ selected = items[:keep_n]
343
+ gate = int(selected[-1][1]) if selected else 0
344
+ return {key for key, _ in selected}, gate
345
+
346
+
347
+ def _tv_similarity_over_keys(real_counts: Counter[str], syn_counts: Counter[str], keys: set[str]) -> float:
348
+ if not keys:
349
+ return 1.0
350
+ real_total = sum(real_counts.get(key, 0) for key in keys)
351
+ syn_total = sum(syn_counts.get(key, 0) for key in keys)
352
+ if real_total <= 0 and syn_total <= 0:
353
+ return 1.0
354
+ if real_total <= 0 or syn_total <= 0:
355
+ return 0.0
356
+ tv = 0.0
357
+ for key in keys:
358
+ pr = real_counts.get(key, 0) / real_total
359
+ ps = syn_counts.get(key, 0) / syn_total
360
+ tv += abs(pr - ps)
361
+ return max(0.0, min(1.0, 1.0 - 0.5 * tv))
362
+
363
+
364
+ def _band_metrics(
365
+ *,
366
+ real_counts: Counter[str],
367
+ syn_counts: Counter[str],
368
+ n_real: int,
369
+ n_syn: int,
370
+ real_keys: set[str],
371
+ syn_keys: set[str],
372
+ effective_gate_real: int,
373
+ effective_gate_syn: int,
374
+ ) -> dict[str, float]:
375
+ union_keys = real_keys | syn_keys
376
+ inter_keys = real_keys & syn_keys
377
+ set_consistency = (len(inter_keys) / len(union_keys)) if union_keys else 1.0
378
+
379
+ mass_real = (sum(real_counts.get(key, 0) for key in real_keys) / max(1, n_real)) if real_keys else 0.0
380
+ mass_syn_on_real = (sum(syn_counts.get(key, 0) for key in real_keys) / max(1, n_syn)) if real_keys else 0.0
381
+ if mass_real <= 1e-12:
382
+ mass_similarity = 1.0 if mass_syn_on_real <= 1e-12 else 0.0
383
+ else:
384
+ mass_similarity = 1.0 - abs(mass_syn_on_real - mass_real) / mass_real
385
+ mass_similarity = max(0.0, min(1.0, mass_similarity))
386
+
387
+ concentration_consistency = _tv_similarity_over_keys(real_counts, syn_counts, union_keys)
388
+ anchor_coverage = (sum(1 for key in real_keys if syn_counts.get(key, 0) > 0) / len(real_keys)) if real_keys else 1.0
389
+
390
+ return {
391
+ "set_consistency": float(set_consistency),
392
+ "mass_similarity": float(mass_similarity),
393
+ "concentration_consistency": float(concentration_consistency),
394
+ "anchor_coverage": float(anchor_coverage),
395
+ "real_key_count": float(len(real_keys)),
396
+ "syn_key_count": float(len(syn_keys)),
397
+ "union_key_count": float(len(union_keys)),
398
+ "effective_gate_real": float(effective_gate_real),
399
+ "effective_gate_syn": float(effective_gate_syn),
400
+ }
401
+
402
+
403
+ def _normalize_model_id(model_id: str) -> str:
404
+ key = str(model_id or "").strip().lower()
405
+ if key == "rtf":
406
+ return "realtabformer"
407
+ return key
408
+
409
+
410
+ def _model_label(model_id: str) -> str:
411
+ key = _normalize_model_id(model_id)
412
+ return MODEL_LABELS.get(key, key or "unknown")
413
+
414
+
415
+ def _natural_key(text: str) -> list[Any]:
416
+ return [int(chunk) if chunk.isdigit() else chunk.lower() for chunk in re.split(r"(\d+)", text)]
417
+
418
+
419
+ def _model_sort_key(model_id: str) -> tuple[int, Any]:
420
+ return (0, _natural_key(_model_label(model_id)))
421
+
422
+
423
+ def _dataset_prefix(dataset_id: str) -> str:
424
+ return str(dataset_id or "").strip().lower()[:1]
425
+
426
+
427
+ def _asset_payload(asset: SyntheticAsset) -> dict[str, Any]:
428
+ payload = asset.to_dict()
429
+ raw_model_id = str(payload.get("model_id") or "")
430
+ payload["model_id_raw"] = raw_model_id
431
+ payload["model_id"] = _normalize_model_id(raw_model_id)
432
+ payload["model_label"] = _model_label(payload["model_id"])
433
+ return payload
434
+
435
+
436
+ def _run_dataset_threshold_sweep(
437
+ dataset_id: str,
438
+ dataset_assets: list[SyntheticAsset],
439
+ threshold_specs: list[ThresholdSpec],
440
+ numeric_bins: int,
441
+ ) -> tuple[str, list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]:
442
+ real_csv = resolve_real_split_path(dataset_id, split="train")
443
+ if not real_csv.exists():
444
+ return dataset_id, [], [], {"dataset_id": dataset_id, "status": "missing_real_csv", "asset_count": len(dataset_assets)}
445
+
446
+ columns, rows_real = _read_csv_rows(real_csv)
447
+ if not columns or not rows_real:
448
+ return dataset_id, [], [], {"dataset_id": dataset_id, "status": "empty_real_csv", "asset_count": len(dataset_assets)}
449
+
450
+ target_column = _load_target_column(dataset_id, columns)
451
+ feature_columns = [column for column in columns if column != target_column and not _is_id_like(column)]
452
+ if not feature_columns:
453
+ return dataset_id, [], [], {"dataset_id": dataset_id, "status": "no_feature_columns", "asset_count": len(dataset_assets)}
454
+
455
+ transformers = _build_transformers(rows_real, feature_columns, numeric_bins=numeric_bins)
456
+ real_counts = _build_key_counter(rows_real, feature_columns, transformers)
457
+ real_tail_items = _sorted_support_items(real_counts, reverse=False)
458
+ real_head_items = _sorted_support_items(real_counts, reverse=True)
459
+ n_real = len(rows_real)
460
+
461
+ real_band_map: dict[str, dict[str, Any]] = {}
462
+ real_diagnostic_rows: list[dict[str, Any]] = []
463
+ for spec in threshold_specs:
464
+ tail_real_keys, tail_real_gate = _select_bottom_band(real_tail_items, spec.ratio)
465
+ head_real_keys, head_real_gate = _select_top_band(real_head_items, spec.subgroup_keep_ratio)
466
+ real_tail_mass = (sum(real_counts.get(key, 0) for key in tail_real_keys) / max(1, n_real)) if tail_real_keys else 0.0
467
+ real_head_mass = (sum(real_counts.get(key, 0) for key in head_real_keys) / max(1, n_real)) if head_real_keys else 0.0
468
+ real_band_map[spec.label] = {
469
+ "tail_real_keys": tail_real_keys,
470
+ "tail_real_gate": tail_real_gate,
471
+ "head_real_keys": head_real_keys,
472
+ "head_real_gate": head_real_gate,
473
+ }
474
+ real_diagnostic_rows.append(
475
+ {
476
+ "dataset_id": dataset_id,
477
+ "dataset_prefix": _dataset_prefix(dataset_id),
478
+ "threshold_label": spec.label,
479
+ "threshold_pct": spec.pct,
480
+ "tail_ratio": spec.ratio,
481
+ "subgroup_keep_ratio": spec.subgroup_keep_ratio,
482
+ "real_row_count": n_real,
483
+ "real_total_key_count": len(real_tail_items),
484
+ "real_tail_key_count": len(tail_real_keys),
485
+ "real_head_key_count": len(head_real_keys),
486
+ "real_tail_mass": round(real_tail_mass, 6),
487
+ "real_head_mass": round(real_head_mass, 6),
488
+ "tail_effective_gate_real": tail_real_gate,
489
+ "head_effective_gate_real": head_real_gate,
490
+ }
491
+ )
492
+
493
+ asset_rows: list[dict[str, Any]] = []
494
+ for asset in dataset_assets:
495
+ asset_payload = _asset_payload(asset)
496
+ _, rows_syn = _read_csv_rows(Path(asset.synthetic_csv_path))
497
+ syn_counts = _build_key_counter(rows_syn, feature_columns, transformers)
498
+ syn_tail_items = _sorted_support_items(syn_counts, reverse=False)
499
+ syn_head_items = _sorted_support_items(syn_counts, reverse=True)
500
+ n_syn = len(rows_syn)
501
+
502
+ for spec in threshold_specs:
503
+ real_band = real_band_map[spec.label]
504
+ tail_syn_keys, tail_syn_gate = _select_bottom_band(syn_tail_items, spec.ratio)
505
+ head_syn_keys, head_syn_gate = _select_top_band(syn_head_items, spec.subgroup_keep_ratio)
506
+
507
+ tail_metrics = _band_metrics(
508
+ real_counts=real_counts,
509
+ syn_counts=syn_counts,
510
+ n_real=n_real,
511
+ n_syn=n_syn,
512
+ real_keys=real_band["tail_real_keys"],
513
+ syn_keys=tail_syn_keys,
514
+ effective_gate_real=int(real_band["tail_real_gate"]),
515
+ effective_gate_syn=tail_syn_gate,
516
+ )
517
+ head_metrics = _band_metrics(
518
+ real_counts=real_counts,
519
+ syn_counts=syn_counts,
520
+ n_real=n_real,
521
+ n_syn=n_syn,
522
+ real_keys=real_band["head_real_keys"],
523
+ syn_keys=head_syn_keys,
524
+ effective_gate_real=int(real_band["head_real_gate"]),
525
+ effective_gate_syn=head_syn_gate,
526
+ )
527
+
528
+ tail_overall_score = _mean(
529
+ [
530
+ tail_metrics["set_consistency"],
531
+ tail_metrics["mass_similarity"],
532
+ tail_metrics["concentration_consistency"],
533
+ ]
534
+ )
535
+ head_overall_score = _mean(
536
+ [
537
+ head_metrics["set_consistency"],
538
+ head_metrics["mass_similarity"],
539
+ head_metrics["concentration_consistency"],
540
+ ]
541
+ )
542
+
543
+ asset_rows.append(
544
+ {
545
+ **asset_payload,
546
+ "dataset_id": dataset_id,
547
+ "dataset_prefix": _dataset_prefix(dataset_id),
548
+ "threshold_label": spec.label,
549
+ "threshold_pct": spec.pct,
550
+ "tail_ratio": spec.ratio,
551
+ "subgroup_keep_ratio": spec.subgroup_keep_ratio,
552
+ "real_row_count": n_real,
553
+ "synthetic_row_count": n_syn,
554
+ "feature_column_count": len(feature_columns),
555
+ "tail_set_consistency": round(tail_metrics["set_consistency"], 6),
556
+ "tail_mass_similarity": round(tail_metrics["mass_similarity"], 6),
557
+ "tail_concentration_consistency": round(tail_metrics["concentration_consistency"], 6),
558
+ "tail_anchor_coverage": round(tail_metrics["anchor_coverage"], 6),
559
+ "tail_overall_score": tail_overall_score,
560
+ "tail_real_key_count": int(tail_metrics["real_key_count"]),
561
+ "tail_syn_key_count": int(tail_metrics["syn_key_count"]),
562
+ "tail_union_key_count": int(tail_metrics["union_key_count"]),
563
+ "tail_effective_gate_real": int(tail_metrics["effective_gate_real"]),
564
+ "tail_effective_gate_syn": int(tail_metrics["effective_gate_syn"]),
565
+ "head_set_consistency": round(head_metrics["set_consistency"], 6),
566
+ "head_mass_similarity": round(head_metrics["mass_similarity"], 6),
567
+ "head_concentration_consistency": round(head_metrics["concentration_consistency"], 6),
568
+ "head_anchor_coverage": round(head_metrics["anchor_coverage"], 6),
569
+ "head_proxy_overall_score": head_overall_score,
570
+ "head_real_key_count": int(head_metrics["real_key_count"]),
571
+ "head_syn_key_count": int(head_metrics["syn_key_count"]),
572
+ "head_union_key_count": int(head_metrics["union_key_count"]),
573
+ "head_effective_gate_real": int(head_metrics["effective_gate_real"]),
574
+ "head_effective_gate_syn": int(head_metrics["effective_gate_syn"]),
575
+ "tail_head_gap": round((head_overall_score or 0.0) - (tail_overall_score or 0.0), 6)
576
+ if head_overall_score is not None and tail_overall_score is not None
577
+ else None,
578
+ }
579
+ )
580
+
581
+ manifest_row = {
582
+ "dataset_id": dataset_id,
583
+ "status": "ok",
584
+ "asset_count": len(dataset_assets),
585
+ "real_row_count": n_real,
586
+ "feature_column_count": len(feature_columns),
587
+ "real_total_key_count": len(real_tail_items),
588
+ }
589
+ return dataset_id, asset_rows, real_diagnostic_rows, manifest_row
590
+
591
+
592
+ def _score_cmap() -> LinearSegmentedColormap:
593
+ cmap = LinearSegmentedColormap.from_list(
594
+ "tail_threshold_scores",
595
+ ["#FFF7EC", "#FDD49E", "#FC8D59", "#D7301F", "#7F0000"],
596
+ )
597
+ cmap.set_bad("#ECEFF3")
598
+ return cmap
599
+
600
+
601
+ def _save(fig: plt.Figure, path: Path) -> None:
602
+ path.parent.mkdir(parents=True, exist_ok=True)
603
+ fig.tight_layout()
604
+ fig.savefig(path, dpi=240, bbox_inches="tight")
605
+ plt.close(fig)
606
+
607
+
608
+ def _threshold_axis(ax: plt.Axes, specs: list[ThresholdSpec], *, xlabel: str = "Tail threshold (% of keys)") -> None:
609
+ xs = [spec.pct for spec in specs]
610
+ ax.set_xscale("log")
611
+ ax.invert_xaxis()
612
+ ax.set_xticks(xs)
613
+ ax.set_xticklabels([spec.label for spec in specs], rotation=0)
614
+ ax.set_xlabel(xlabel)
615
+
616
+
617
+ def _quantile(values: list[float], q: float) -> float:
618
+ if not values:
619
+ return float("nan")
620
+ return float(np.quantile(np.asarray(values, dtype=float), q))
621
+
622
+
623
+ def _aggregate_group_mean(
624
+ rows: list[dict[str, Any]],
625
+ *,
626
+ group_keys: list[str],
627
+ value_fields: list[str],
628
+ ) -> list[dict[str, Any]]:
629
+ grouped: dict[tuple[Any, ...], list[dict[str, Any]]] = defaultdict(list)
630
+ for row in rows:
631
+ grouped[tuple(row.get(key) for key in group_keys)].append(row)
632
+
633
+ out: list[dict[str, Any]] = []
634
+ for key_tuple, items in sorted(grouped.items()):
635
+ payload = {group_key: key_tuple[idx] for idx, group_key in enumerate(group_keys)}
636
+ for field in value_fields:
637
+ payload[field] = _mean([_to_float(item.get(field)) for item in items])
638
+ payload["asset_count"] = len(items)
639
+ out.append(payload)
640
+ return out
641
+
642
+
643
+ def _build_global_threshold_summary(
644
+ asset_rows: list[dict[str, Any]],
645
+ threshold_specs: list[ThresholdSpec],
646
+ ) -> list[dict[str, Any]]:
647
+ out: list[dict[str, Any]] = []
648
+ for spec in threshold_specs:
649
+ items = [row for row in asset_rows if row.get("threshold_label") == spec.label]
650
+ if not items:
651
+ continue
652
+ tail_scores = [_to_float(row.get("tail_overall_score")) for row in items]
653
+ head_scores = [_to_float(row.get("head_proxy_overall_score")) for row in items]
654
+ tail_clean = [float(value) for value in tail_scores if value is not None]
655
+ head_clean = [float(value) for value in head_scores if value is not None]
656
+ out.append(
657
+ {
658
+ "threshold_label": spec.label,
659
+ "threshold_pct": spec.pct,
660
+ "tail_ratio": spec.ratio,
661
+ "subgroup_keep_ratio": spec.subgroup_keep_ratio,
662
+ "tail_overall_mean": _mean(tail_scores),
663
+ "tail_overall_median": round(_quantile(tail_clean, 0.5), 6) if tail_clean else None,
664
+ "tail_overall_p25": round(_quantile(tail_clean, 0.25), 6) if tail_clean else None,
665
+ "tail_overall_p75": round(_quantile(tail_clean, 0.75), 6) if tail_clean else None,
666
+ "head_proxy_mean": _mean(head_scores),
667
+ "head_proxy_median": round(_quantile(head_clean, 0.5), 6) if head_clean else None,
668
+ "tail_head_gap_mean": _mean([_to_float(row.get("tail_head_gap")) for row in items]),
669
+ "tail_set_consistency_mean": _mean([_to_float(row.get("tail_set_consistency")) for row in items]),
670
+ "tail_mass_similarity_mean": _mean([_to_float(row.get("tail_mass_similarity")) for row in items]),
671
+ "tail_concentration_consistency_mean": _mean(
672
+ [_to_float(row.get("tail_concentration_consistency")) for row in items]
673
+ ),
674
+ "tail_anchor_coverage_mean": _mean([_to_float(row.get("tail_anchor_coverage")) for row in items]),
675
+ "asset_count": len(items),
676
+ }
677
+ )
678
+ return out
679
+
680
+
681
+ def _compute_model_fragility(
682
+ model_summary_rows: list[dict[str, Any]],
683
+ threshold_specs: list[ThresholdSpec],
684
+ ) -> list[dict[str, Any]]:
685
+ by_model: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict)
686
+ for row in model_summary_rows:
687
+ by_model[str(row.get("model_id") or "")][str(row.get("threshold_label") or "")] = row
688
+
689
+ plan = _fragility_anchor_plan(threshold_specs)
690
+ anchor_label = plan["anchor_label"]
691
+ comparison_labels = list(plan["comparison_labels"])
692
+ labels_to_capture = [label for label in [anchor_label, *comparison_labels] if label]
693
+ out: list[dict[str, Any]] = []
694
+ for model_id in sorted(by_model.keys(), key=_model_sort_key):
695
+ entries = by_model[model_id]
696
+ payload = {
697
+ "model_id": model_id,
698
+ "model_label": _model_label(model_id),
699
+ "anchor_threshold_label": anchor_label,
700
+ "primary_comparison_label": plan["primary_label"],
701
+ "secondary_comparison_label": plan["secondary_label"],
702
+ "rarest_threshold_label": plan["rarest_label"],
703
+ }
704
+ for label in labels_to_capture:
705
+ payload[f"tail_at_{_threshold_label_token(label)}"] = _score_lookup(entries, label)
706
+
707
+ anchor_score = _score_lookup(entries, anchor_label)
708
+ payload["anchor_tail_score"] = anchor_score
709
+ primary_score = _score_lookup(entries, plan["primary_label"])
710
+ secondary_score = _score_lookup(entries, plan["secondary_label"])
711
+ rarest_score = _score_lookup(entries, plan["rarest_label"])
712
+ payload["primary_comparison_tail_score"] = primary_score
713
+ payload["secondary_comparison_tail_score"] = secondary_score
714
+ payload["rarest_tail_score"] = rarest_score
715
+ payload["primary_fragility_drop"] = (
716
+ round(float(anchor_score) - float(primary_score), 6)
717
+ if anchor_score is not None and primary_score is not None
718
+ else None
719
+ )
720
+ payload["secondary_fragility_drop"] = (
721
+ round(float(anchor_score) - float(secondary_score), 6)
722
+ if anchor_score is not None and secondary_score is not None
723
+ else None
724
+ )
725
+ payload["anchor_to_rarest_fragility_drop"] = (
726
+ round(float(anchor_score) - float(rarest_score), 6)
727
+ if anchor_score is not None and rarest_score is not None
728
+ else None
729
+ )
730
+ for label in comparison_labels:
731
+ compare_score = _score_lookup(entries, label)
732
+ payload[f"fragility_{_threshold_label_token(anchor_label)}_to_{_threshold_label_token(label)}"] = (
733
+ round(float(anchor_score) - float(compare_score), 6)
734
+ if anchor_score is not None and compare_score is not None
735
+ else None
736
+ )
737
+ _attach_legacy_fragility_fields(payload, entries)
738
+ out.append(payload)
739
+ return out
740
+
741
+
742
+ def _compute_dataset_fragility(
743
+ dataset_summary_rows: list[dict[str, Any]],
744
+ threshold_specs: list[ThresholdSpec],
745
+ ) -> list[dict[str, Any]]:
746
+ by_dataset: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict)
747
+ for row in dataset_summary_rows:
748
+ by_dataset[str(row.get("dataset_id") or "")][str(row.get("threshold_label") or "")] = row
749
+
750
+ plan = _fragility_anchor_plan(threshold_specs)
751
+ anchor_label = plan["anchor_label"]
752
+ comparison_labels = list(plan["comparison_labels"])
753
+ out: list[dict[str, Any]] = []
754
+ for dataset_id, entries in sorted(by_dataset.items()):
755
+ anchor_score = _score_lookup(entries, anchor_label)
756
+ if anchor_score is None:
757
+ continue
758
+ primary_score = _score_lookup(entries, plan["primary_label"])
759
+ secondary_score = _score_lookup(entries, plan["secondary_label"])
760
+ rarest_score = _score_lookup(entries, plan["rarest_label"])
761
+ payload = {
762
+ "dataset_id": dataset_id,
763
+ "dataset_prefix": _dataset_prefix(dataset_id),
764
+ "anchor_threshold_label": anchor_label,
765
+ "primary_comparison_label": plan["primary_label"],
766
+ "secondary_comparison_label": plan["secondary_label"],
767
+ "rarest_threshold_label": plan["rarest_label"],
768
+ "anchor_tail_score": anchor_score,
769
+ "primary_comparison_tail_score": primary_score,
770
+ "secondary_comparison_tail_score": secondary_score,
771
+ "rarest_tail_score": rarest_score,
772
+ "primary_fragility_drop": round(anchor_score - primary_score, 6) if primary_score is not None else None,
773
+ "secondary_fragility_drop": round(anchor_score - secondary_score, 6) if secondary_score is not None else None,
774
+ "anchor_to_rarest_fragility_drop": round(anchor_score - rarest_score, 6) if rarest_score is not None else None,
775
+ }
776
+ for label in [anchor_label, *comparison_labels]:
777
+ if label:
778
+ payload[f"tail_at_{_threshold_label_token(label)}"] = _score_lookup(entries, label)
779
+ for label in comparison_labels:
780
+ compare_score = _score_lookup(entries, label)
781
+ payload[f"fragility_{_threshold_label_token(anchor_label)}_to_{_threshold_label_token(label)}"] = (
782
+ round(anchor_score - compare_score, 6) if compare_score is not None else None
783
+ )
784
+ _attach_legacy_fragility_fields(payload, entries)
785
+ out.append(
786
+ payload
787
+ )
788
+ return out
789
+
790
+
791
+ def _select_representative_datasets(
792
+ dataset_fragility_rows: list[dict[str, Any]],
793
+ per_prefix: int,
794
+ ) -> list[dict[str, Any]]:
795
+ by_prefix: dict[str, list[dict[str, Any]]] = defaultdict(list)
796
+ for row in dataset_fragility_rows:
797
+ by_prefix[str(row.get("dataset_prefix") or "?")].append(row)
798
+
799
+ selected: list[dict[str, Any]] = []
800
+ used: set[str] = set()
801
+ for prefix in sorted(by_prefix.keys()):
802
+ pool = by_prefix[prefix]
803
+ fragility_candidates = sorted(
804
+ [row for row in pool if row.get("primary_fragility_drop") is not None],
805
+ key=lambda row: float(row["primary_fragility_drop"]),
806
+ reverse=True,
807
+ )
808
+ hardness_candidates = sorted(
809
+ [row for row in pool if row.get("anchor_tail_score") is not None],
810
+ key=lambda row: float(row["anchor_tail_score"]),
811
+ )
812
+
813
+ picks: list[tuple[str, dict[str, Any]]] = []
814
+ if fragility_candidates:
815
+ picks.append(("fragility", fragility_candidates[0]))
816
+ for candidate in hardness_candidates:
817
+ if not picks or candidate["dataset_id"] != picks[0][1]["dataset_id"]:
818
+ picks.append(("hardness", candidate))
819
+ break
820
+
821
+ extra_candidates = []
822
+ for candidate in fragility_candidates:
823
+ if candidate["dataset_id"] not in {row["dataset_id"] for _, row in picks}:
824
+ extra_candidates.append(("fragility", candidate))
825
+ for candidate in hardness_candidates:
826
+ if candidate["dataset_id"] not in {row["dataset_id"] for _, row in picks}:
827
+ extra_candidates.append(("hardness", candidate))
828
+
829
+ picks = picks[:per_prefix]
830
+ for kind, row in extra_candidates:
831
+ if len(picks) >= per_prefix:
832
+ break
833
+ picks.append((kind, row))
834
+
835
+ for kind, row in picks:
836
+ dataset_id = str(row["dataset_id"])
837
+ if dataset_id in used:
838
+ continue
839
+ used.add(dataset_id)
840
+ selected.append(
841
+ {
842
+ **row,
843
+ "selection_kind": kind,
844
+ "selection_reason": (
845
+ f"largest drop from {row.get('anchor_threshold_label')} to {row.get('primary_comparison_label')}"
846
+ if kind == "fragility"
847
+ else f"lowest tail score already at {row.get('anchor_threshold_label')}"
848
+ ),
849
+ }
850
+ )
851
+ return selected
852
+
853
+
854
+ def _plot_global_tail_vs_head(
855
+ summary_rows: list[dict[str, Any]],
856
+ threshold_specs: list[ThresholdSpec],
857
+ out_path: Path,
858
+ ) -> None:
859
+ x = [spec.pct for spec in threshold_specs]
860
+ tail = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))["tail_overall_mean"]) for spec in threshold_specs]
861
+ head = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))["head_proxy_mean"]) for spec in threshold_specs]
862
+ p25 = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))["tail_overall_p25"]) for spec in threshold_specs]
863
+ p75 = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))["tail_overall_p75"]) for spec in threshold_specs]
864
+
865
+ fig, ax = plt.subplots(figsize=(10.5, 6.0))
866
+ ax.fill_between(x, p25, p75, color=TAIL_COLOR, alpha=0.14, label="Tail IQR")
867
+ ax.plot(x, tail, marker="o", linewidth=2.6, color=TAIL_COLOR, label="Tail score")
868
+ ax.plot(x, head, marker="o", linewidth=2.4, color=HEAD_COLOR, label="Head proxy score")
869
+ _threshold_axis(ax, threshold_specs)
870
+ ax.set_ylim(0, 1.02)
871
+ ax.set_ylabel("Score")
872
+ ax.set_title("Global tail fragility: tail degrades faster than the head support band")
873
+ ax.grid(axis="y", linestyle="--", alpha=0.28)
874
+ ax.legend()
875
+ _save(fig, out_path)
876
+
877
+
878
+ def _plot_global_tail_submetrics(
879
+ summary_rows: list[dict[str, Any]],
880
+ threshold_specs: list[ThresholdSpec],
881
+ out_path: Path,
882
+ ) -> None:
883
+ metric_fields = [
884
+ ("tail_set_consistency_mean", "Tail set consistency"),
885
+ ("tail_mass_similarity_mean", "Tail mass similarity"),
886
+ ("tail_concentration_consistency_mean", "Tail concentration consistency"),
887
+ ("tail_anchor_coverage_mean", "Tail anchor coverage"),
888
+ ]
889
+ x = [spec.pct for spec in threshold_specs]
890
+ fig, ax = plt.subplots(figsize=(10.5, 6.0))
891
+ for metric_field, label in metric_fields:
892
+ y = [float((next(row for row in summary_rows if row["threshold_label"] == spec.label))[metric_field]) for spec in threshold_specs]
893
+ ax.plot(x, y, marker="o", linewidth=2.3, label=label, color=SUBMETRIC_COLORS.get(metric_field.replace("_mean", ""), None))
894
+ _threshold_axis(ax, threshold_specs)
895
+ ax.set_ylim(0, 1.02)
896
+ ax.set_ylabel("Score")
897
+ ax.set_title("Which tail behaviors break first as the threshold gets rarer?")
898
+ ax.grid(axis="y", linestyle="--", alpha=0.28)
899
+ ax.legend(loc="lower left")
900
+ _save(fig, out_path)
901
+
902
+
903
+ def _plot_tail_distribution_boxplot(
904
+ asset_rows: list[dict[str, Any]],
905
+ threshold_specs: list[ThresholdSpec],
906
+ out_path: Path,
907
+ ) -> None:
908
+ labels = [spec.label for spec in threshold_specs]
909
+ data = [
910
+ [float(row["tail_overall_score"]) for row in asset_rows if row.get("threshold_label") == spec.label and row.get("tail_overall_score") is not None]
911
+ for spec in threshold_specs
912
+ ]
913
+ fig, ax = plt.subplots(figsize=(11.0, 6.2))
914
+ box = ax.boxplot(data, patch_artist=True, showfliers=False, widths=0.58)
915
+ for patch in box["boxes"]:
916
+ patch.set_facecolor("#F4A261")
917
+ patch.set_alpha(0.55)
918
+ patch.set_edgecolor("#9C4F2F")
919
+ for median_line in box["medians"]:
920
+ median_line.set_color("#7F0000")
921
+ median_line.set_linewidth(1.8)
922
+ ax.set_xticks(np.arange(1, len(labels) + 1))
923
+ ax.set_xticklabels(labels, rotation=25, ha="right")
924
+ ax.set_ylim(0, 1.02)
925
+ ax.set_ylabel("Tail overall score")
926
+ ax.set_title("Asset-level tail score distribution across thresholds")
927
+ ax.grid(axis="y", linestyle="--", alpha=0.25)
928
+ _save(fig, out_path)
929
+
930
+
931
+ def _plot_threshold_key_diagnostics(
932
+ diagnostic_rows: list[dict[str, Any]],
933
+ threshold_specs: list[ThresholdSpec],
934
+ out_path: Path,
935
+ ) -> None:
936
+ x = [spec.pct for spec in threshold_specs]
937
+ key_medians: list[float] = []
938
+ key_means: list[float] = []
939
+ frac_le_one: list[float] = []
940
+ frac_le_two: list[float] = []
941
+ tail_mass_medians: list[float] = []
942
+ for spec in threshold_specs:
943
+ rows = [row for row in diagnostic_rows if row.get("threshold_label") == spec.label]
944
+ key_counts = [float(row["real_tail_key_count"]) for row in rows]
945
+ tail_masses = [float(row["real_tail_mass"]) for row in rows]
946
+ key_medians.append(float(np.median(key_counts)) if key_counts else 0.0)
947
+ key_means.append(float(np.mean(key_counts)) if key_counts else 0.0)
948
+ frac_le_one.append((sum(1 for value in key_counts if value <= 1.0) / len(key_counts)) if key_counts else 0.0)
949
+ frac_le_two.append((sum(1 for value in key_counts if value <= 2.0) / len(key_counts)) if key_counts else 0.0)
950
+ tail_mass_medians.append(float(np.median(tail_masses)) if tail_masses else 0.0)
951
+
952
+ fig, axes = plt.subplots(1, 2, figsize=(13.0, 5.2))
953
+
954
+ axes[0].plot(x, key_medians, marker="o", linewidth=2.4, color="#264653", label="Median tail key count")
955
+ axes[0].plot(x, key_means, marker="o", linewidth=2.0, color="#2A9D8F", label="Mean tail key count")
956
+ axes[0].plot(x, tail_mass_medians, marker="o", linewidth=2.0, color="#E9C46A", label="Median real tail mass")
957
+ _threshold_axis(axes[0], threshold_specs)
958
+ axes[0].set_ylabel("Count / mass")
959
+ axes[0].set_title("How much tail evidence is left?")
960
+ axes[0].grid(axis="y", linestyle="--", alpha=0.25)
961
+ axes[0].legend()
962
+
963
+ axes[1].plot(x, frac_le_one, marker="o", linewidth=2.4, color="#C8553D", label="Datasets with <= 1 tail key")
964
+ axes[1].plot(x, frac_le_two, marker="o", linewidth=2.2, color="#6D597A", label="Datasets with <= 2 tail keys")
965
+ _threshold_axis(axes[1], threshold_specs)
966
+ axes[1].set_ylim(0, 1.02)
967
+ axes[1].set_ylabel("Fraction of datasets")
968
+ axes[1].set_title("When does the tail become statistically tiny?")
969
+ axes[1].grid(axis="y", linestyle="--", alpha=0.25)
970
+ axes[1].legend()
971
+
972
+ _save(fig, out_path)
973
+
974
+
975
+ def _plot_model_heatmap(
976
+ model_summary_rows: list[dict[str, Any]],
977
+ threshold_specs: list[ThresholdSpec],
978
+ out_path: Path,
979
+ ) -> None:
980
+ model_ids = sorted({str(row.get("model_id") or "") for row in model_summary_rows}, key=_model_sort_key)
981
+ lookup = {(str(row["model_id"]), str(row["threshold_label"])): _to_float(row.get("tail_overall_score")) for row in model_summary_rows}
982
+ mat = np.full((len(model_ids), len(threshold_specs)), np.nan, dtype=float)
983
+ for row_idx, model_id in enumerate(model_ids):
984
+ for col_idx, spec in enumerate(threshold_specs):
985
+ value = lookup.get((model_id, spec.label))
986
+ if value is not None:
987
+ mat[row_idx, col_idx] = float(value)
988
+
989
+ fig, ax = plt.subplots(figsize=(11.8, 6.6))
990
+ im = ax.imshow(mat, aspect="auto", cmap=_score_cmap(), vmin=0.0, vmax=1.0)
991
+ ax.set_xticks(np.arange(len(threshold_specs)))
992
+ ax.set_xticklabels([spec.label for spec in threshold_specs], rotation=25, ha="right")
993
+ ax.set_yticks(np.arange(len(model_ids)))
994
+ ax.set_yticklabels([_model_label(model_id) for model_id in model_ids])
995
+ ax.set_title("Model-by-threshold heatmap of tail fidelity")
996
+ for row_idx in range(mat.shape[0]):
997
+ for col_idx in range(mat.shape[1]):
998
+ value = mat[row_idx, col_idx]
999
+ if np.isnan(value):
1000
+ continue
1001
+ ax.text(
1002
+ col_idx,
1003
+ row_idx,
1004
+ f"{value:.2f}",
1005
+ ha="center",
1006
+ va="center",
1007
+ fontsize=7.5,
1008
+ color="white" if value >= 0.52 else "black",
1009
+ )
1010
+ fig.colorbar(im, ax=ax, fraction=0.03, pad=0.02)
1011
+ _save(fig, out_path)
1012
+
1013
+
1014
+ def _plot_model_fragility_bar(
1015
+ model_fragility_rows: list[dict[str, Any]],
1016
+ out_path: Path,
1017
+ ) -> None:
1018
+ rows = [row for row in model_fragility_rows if row.get("primary_fragility_drop") is not None]
1019
+ if not rows:
1020
+ return
1021
+ rows = sorted(rows, key=lambda row: float(row["primary_fragility_drop"]), reverse=True)
1022
+ labels = [str(row["model_label"]) for row in rows]
1023
+ values = [float(row["primary_fragility_drop"]) for row in rows]
1024
+ colors = [TAIL_COLOR if value >= 0 else "#4C78A8" for value in values]
1025
+ anchor_label = str(rows[0].get("anchor_threshold_label") or "anchor")
1026
+ compare_label = str(rows[0].get("primary_comparison_label") or "comparison")
1027
+
1028
+ fig, ax = plt.subplots(figsize=(11.0, 6.0))
1029
+ bars = ax.bar(np.arange(len(rows)), values, color=colors, alpha=0.82)
1030
+ ax.set_xticks(np.arange(len(rows)))
1031
+ ax.set_xticklabels(labels, rotation=35, ha="right")
1032
+ ax.set_ylabel(f"Tail fragility: score({anchor_label}) - score({compare_label})")
1033
+ ax.set_title("Which models lose the most once the tail becomes rarer?")
1034
+ ax.axhline(0.0, color="#333333", linewidth=1.0)
1035
+ ax.grid(axis="y", linestyle="--", alpha=0.24)
1036
+ for bar, value in zip(bars, values):
1037
+ ax.text(bar.get_x() + bar.get_width() / 2.0, value + 0.01, f"{value:.2f}", ha="center", va="bottom", fontsize=8)
1038
+ _save(fig, out_path)
1039
+
1040
+
1041
+ def _plot_dataset_heatmap(
1042
+ dataset_summary_rows: list[dict[str, Any]],
1043
+ dataset_fragility_rows: list[dict[str, Any]],
1044
+ threshold_specs: list[ThresholdSpec],
1045
+ out_path: Path,
1046
+ ) -> None:
1047
+ ordered_datasets = [
1048
+ row["dataset_id"]
1049
+ for row in sorted(
1050
+ dataset_fragility_rows,
1051
+ key=lambda row: (
1052
+ -float(row["primary_fragility_drop"]) if row.get("primary_fragility_drop") is not None else 0.0,
1053
+ str(row["dataset_id"]),
1054
+ ),
1055
+ )
1056
+ ]
1057
+ lookup = {(str(row["dataset_id"]), str(row["threshold_label"])): _to_float(row.get("tail_overall_score")) for row in dataset_summary_rows}
1058
+ mat = np.full((len(ordered_datasets), len(threshold_specs)), np.nan, dtype=float)
1059
+ for row_idx, dataset_id in enumerate(ordered_datasets):
1060
+ for col_idx, spec in enumerate(threshold_specs):
1061
+ value = lookup.get((dataset_id, spec.label))
1062
+ if value is not None:
1063
+ mat[row_idx, col_idx] = float(value)
1064
+
1065
+ fig_h = max(12.0, len(ordered_datasets) * 0.24)
1066
+ fig, ax = plt.subplots(figsize=(10.8, fig_h))
1067
+ im = ax.imshow(mat, aspect="auto", cmap=_score_cmap(), vmin=0.0, vmax=1.0)
1068
+ ax.set_xticks(np.arange(len(threshold_specs)))
1069
+ ax.set_xticklabels([spec.label for spec in threshold_specs], rotation=25, ha="right")
1070
+ ax.set_yticks(np.arange(len(ordered_datasets)))
1071
+ ax.set_yticklabels([dataset_id.upper() for dataset_id in ordered_datasets], fontsize=8)
1072
+ ax.set_title("Dataset-by-threshold heatmap ordered by tail fragility")
1073
+ fig.colorbar(im, ax=ax, fraction=0.03, pad=0.02)
1074
+ _save(fig, out_path)
1075
+
1076
+
1077
+ def _plot_prefix_lines(
1078
+ prefix_summary_rows: list[dict[str, Any]],
1079
+ threshold_specs: list[ThresholdSpec],
1080
+ out_path: Path,
1081
+ ) -> None:
1082
+ x = [spec.pct for spec in threshold_specs]
1083
+ fig, ax = plt.subplots(figsize=(10.6, 6.0))
1084
+ for prefix in ["c", "m", "n"]:
1085
+ rows = [row for row in prefix_summary_rows if row.get("dataset_prefix") == prefix]
1086
+ if not rows:
1087
+ continue
1088
+ lookup = {str(row["threshold_label"]): row for row in rows}
1089
+ y = [float(lookup[spec.label]["tail_overall_score"]) for spec in threshold_specs if lookup.get(spec.label)]
1090
+ x_used = [spec.pct for spec in threshold_specs if lookup.get(spec.label)]
1091
+ ax.plot(x_used, y, marker="o", linewidth=2.4, label=prefix.upper(), color=PREFIX_COLORS[prefix])
1092
+ _threshold_axis(ax, threshold_specs)
1093
+ ax.set_ylim(0, 1.02)
1094
+ ax.set_ylabel("Tail score")
1095
+ ax.set_title("Tail fragility differs by dataset family")
1096
+ ax.grid(axis="y", linestyle="--", alpha=0.25)
1097
+ ax.legend(title="Dataset prefix")
1098
+ _save(fig, out_path)
1099
+
1100
+
1101
+ def _plot_representative_grid(
1102
+ representative_rows: list[dict[str, Any]],
1103
+ dataset_summary_rows: list[dict[str, Any]],
1104
+ diagnostic_rows: list[dict[str, Any]],
1105
+ threshold_specs: list[ThresholdSpec],
1106
+ out_path: Path,
1107
+ ) -> None:
1108
+ if not representative_rows:
1109
+ return
1110
+ selected_ids = [str(row["dataset_id"]) for row in representative_rows]
1111
+ ncols = 2
1112
+ nrows = int(math.ceil(len(selected_ids) / ncols))
1113
+ fig, axes = plt.subplots(nrows, ncols, figsize=(13.0, max(4.6 * nrows, 5.0)))
1114
+ axes_list = np.atleast_1d(axes).reshape(-1)
1115
+
1116
+ summary_lookup: dict[tuple[str, str], dict[str, Any]] = {
1117
+ (str(row["dataset_id"]), str(row["threshold_label"])): row for row in dataset_summary_rows
1118
+ }
1119
+ diag_lookup: dict[tuple[str, str], dict[str, Any]] = {
1120
+ (str(row["dataset_id"]), str(row["threshold_label"])): row for row in diagnostic_rows
1121
+ }
1122
+ primary_handles: list[Any] = []
1123
+ primary_labels: list[str] = []
1124
+ secondary_handles: list[Any] = []
1125
+ secondary_labels: list[str] = []
1126
+
1127
+ for ax, rep in zip(axes_list, representative_rows):
1128
+ dataset_id = str(rep["dataset_id"])
1129
+ x = [spec.pct for spec in threshold_specs]
1130
+ tail = [float(summary_lookup[(dataset_id, spec.label)]["tail_overall_score"]) for spec in threshold_specs]
1131
+ head = [float(summary_lookup[(dataset_id, spec.label)]["head_proxy_overall_score"]) for spec in threshold_specs]
1132
+ key_count = [float(diag_lookup[(dataset_id, spec.label)]["real_tail_key_count"]) for spec in threshold_specs]
1133
+ ax.plot(x, tail, marker="o", linewidth=2.4, color=TAIL_COLOR, label="Tail")
1134
+ ax.plot(x, head, marker="o", linewidth=2.1, color=HEAD_COLOR, label="Head proxy")
1135
+ _threshold_axis(ax, threshold_specs)
1136
+ ax.set_ylim(0, 1.02)
1137
+ ax.grid(axis="y", linestyle="--", alpha=0.22)
1138
+ ax.set_title(f"{dataset_id.upper()} | {rep['selection_kind']}: {rep['selection_reason']}")
1139
+ ax2 = ax.twinx()
1140
+ ax2.plot(x, key_count, marker="s", linewidth=1.6, color="#6D597A", alpha=0.8, label="Tail keys")
1141
+ ax2.set_ylabel("Real tail keys", color="#6D597A")
1142
+ ax2.tick_params(axis="y", labelcolor="#6D597A")
1143
+ if not primary_handles:
1144
+ primary_handles, primary_labels = ax.get_legend_handles_labels()
1145
+ secondary_handles, secondary_labels = ax2.get_legend_handles_labels()
1146
+
1147
+ for ax in axes_list[len(representative_rows) :]:
1148
+ ax.axis("off")
1149
+
1150
+ if primary_handles or secondary_handles:
1151
+ fig.legend(primary_handles + secondary_handles, primary_labels + secondary_labels, loc="upper center", ncol=3, frameon=False)
1152
+ fig.suptitle("Representative datasets where tail fidelity is especially fragile", y=1.02, fontsize=13)
1153
+ _save(fig, out_path)
1154
+
1155
+
1156
+ def _plot_representative_model_lines(
1157
+ representative_rows: list[dict[str, Any]],
1158
+ model_summary_rows: list[dict[str, Any]],
1159
+ threshold_specs: list[ThresholdSpec],
1160
+ out_dir: Path,
1161
+ ) -> list[str]:
1162
+ if not representative_rows:
1163
+ return []
1164
+
1165
+ figures: list[str] = []
1166
+ model_lookup: dict[tuple[str, str, str], dict[str, Any]] = {
1167
+ (str(row["dataset_id"]), str(row["model_id"]), str(row["threshold_label"])): row for row in model_summary_rows
1168
+ }
1169
+ for rep in representative_rows:
1170
+ dataset_id = str(rep["dataset_id"])
1171
+ dataset_rows = [row for row in model_summary_rows if row.get("dataset_id") == dataset_id]
1172
+ model_ids = sorted({str(row["model_id"]) for row in dataset_rows}, key=_model_sort_key)
1173
+ x = [spec.pct for spec in threshold_specs]
1174
+ fig, ax = plt.subplots(figsize=(10.8, 6.0))
1175
+ for model_id in model_ids:
1176
+ y = []
1177
+ x_used = []
1178
+ for spec in threshold_specs:
1179
+ row = model_lookup.get((dataset_id, model_id, spec.label))
1180
+ if row is None or row.get("tail_overall_score") is None:
1181
+ continue
1182
+ x_used.append(spec.pct)
1183
+ y.append(float(row["tail_overall_score"]))
1184
+ if not y:
1185
+ continue
1186
+ linewidth = 2.6 if model_id in {"realtabformer", "bayesnet", "ctgan", "tvae"} else 1.5
1187
+ alpha = 0.95 if linewidth > 2.0 else 0.7
1188
+ ax.plot(x_used, y, marker="o", linewidth=linewidth, alpha=alpha, label=_model_label(model_id))
1189
+ _threshold_axis(ax, threshold_specs)
1190
+ ax.set_ylim(0, 1.02)
1191
+ ax.set_ylabel("Tail score")
1192
+ ax.set_title(f"{dataset_id.upper()} model lines across tail thresholds")
1193
+ ax.grid(axis="y", linestyle="--", alpha=0.24)
1194
+ ax.legend(ncol=2, fontsize=8)
1195
+ path = out_dir / f"{dataset_id}_model_lines.png"
1196
+ _save(fig, path)
1197
+ figures.append(str(path.resolve()))
1198
+ return figures
1199
+
1200
+
1201
+ def _build_dataset_model_summary(asset_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
1202
+ grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list)
1203
+ for row in asset_rows:
1204
+ grouped[(str(row["dataset_id"]), str(row["model_id"]), str(row["threshold_label"]))].append(row)
1205
+
1206
+ out: list[dict[str, Any]] = []
1207
+ for (dataset_id, model_id, threshold_label), items in sorted(grouped.items()):
1208
+ base = items[0]
1209
+ out.append(
1210
+ {
1211
+ "dataset_id": dataset_id,
1212
+ "dataset_prefix": base.get("dataset_prefix"),
1213
+ "model_id": model_id,
1214
+ "model_label": _model_label(model_id),
1215
+ "threshold_label": threshold_label,
1216
+ "threshold_pct": base.get("threshold_pct"),
1217
+ "tail_ratio": base.get("tail_ratio"),
1218
+ "tail_overall_score": _mean([_to_float(item.get("tail_overall_score")) for item in items]),
1219
+ "head_proxy_overall_score": _mean([_to_float(item.get("head_proxy_overall_score")) for item in items]),
1220
+ "tail_set_consistency": _mean([_to_float(item.get("tail_set_consistency")) for item in items]),
1221
+ "tail_mass_similarity": _mean([_to_float(item.get("tail_mass_similarity")) for item in items]),
1222
+ "tail_concentration_consistency": _mean(
1223
+ [_to_float(item.get("tail_concentration_consistency")) for item in items]
1224
+ ),
1225
+ "asset_count": len(items),
1226
+ }
1227
+ )
1228
+ return out
1229
+
1230
+
1231
+ def _load_existing_dataset_outputs(source_run_dir: Path) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
1232
+ asset_rows: list[dict[str, Any]] = []
1233
+ diagnostic_rows: list[dict[str, Any]] = []
1234
+ manifest_rows: list[dict[str, Any]] = []
1235
+
1236
+ datasets_dir = source_run_dir / "datasets"
1237
+ if not datasets_dir.exists():
1238
+ return asset_rows, diagnostic_rows, manifest_rows
1239
+
1240
+ for dataset_dir in sorted(path for path in datasets_dir.iterdir() if path.is_dir()):
1241
+ dataset_id = dataset_dir.name
1242
+ asset_files = sorted(dataset_dir.glob("tail_threshold_asset_scores__*.csv"))
1243
+ diagnostic_files = sorted(dataset_dir.glob("tail_threshold_real_diagnostics__*.csv"))
1244
+ dataset_asset_rows: list[dict[str, Any]] = []
1245
+ dataset_diagnostic_rows: list[dict[str, Any]] = []
1246
+ for path in asset_files:
1247
+ _, rows = _read_csv_rows(path)
1248
+ dataset_asset_rows.extend(rows)
1249
+ for path in diagnostic_files:
1250
+ _, rows = _read_csv_rows(path)
1251
+ dataset_diagnostic_rows.extend(rows)
1252
+ asset_rows.extend(dataset_asset_rows)
1253
+ diagnostic_rows.extend(dataset_diagnostic_rows)
1254
+ manifest_rows.append(
1255
+ {
1256
+ "dataset_id": dataset_id,
1257
+ "status": "ok" if dataset_asset_rows or dataset_diagnostic_rows else "empty",
1258
+ "asset_count": len({str(row.get("asset_key") or "") for row in dataset_asset_rows if row.get("asset_key")}),
1259
+ "row_count": len(dataset_asset_rows),
1260
+ }
1261
+ )
1262
+
1263
+ return asset_rows, diagnostic_rows, manifest_rows
1264
+
1265
+
1266
+ def _infer_threshold_specs_from_rows(
1267
+ asset_rows: list[dict[str, Any]],
1268
+ fallback_percentages: list[float] | None = None,
1269
+ ) -> list[ThresholdSpec]:
1270
+ pairs: list[tuple[float, str]] = []
1271
+ seen: set[tuple[float, str]] = set()
1272
+ for row in asset_rows:
1273
+ pct = _to_float(row.get("threshold_pct"))
1274
+ label = str(row.get("threshold_label") or "").strip()
1275
+ if pct is None or not label:
1276
+ continue
1277
+ key = (float(pct), label)
1278
+ if key in seen:
1279
+ continue
1280
+ seen.add(key)
1281
+ pairs.append(key)
1282
+ if not pairs:
1283
+ return _threshold_specs(fallback_percentages)
1284
+ pairs = sorted(pairs, key=lambda item: float(item[0]), reverse=True)
1285
+ return [
1286
+ ThresholdSpec(
1287
+ index=idx,
1288
+ pct=float(pct),
1289
+ ratio=float(pct) / 100.0,
1290
+ label=label,
1291
+ subgroup_keep_ratio=max(0.0, 1.0 - (float(pct) / 100.0)),
1292
+ )
1293
+ for idx, (pct, label) in enumerate(pairs)
1294
+ ]
1295
+
1296
+
1297
+ def _materialize_tail_threshold_outputs(
1298
+ *,
1299
+ run_dir: Path,
1300
+ asset_rows: list[dict[str, Any]],
1301
+ diagnostic_rows: list[dict[str, Any]],
1302
+ dataset_manifest_rows: list[dict[str, Any]],
1303
+ threshold_specs: list[ThresholdSpec],
1304
+ latest_only: bool,
1305
+ representatives_per_prefix: int,
1306
+ source_run_dir: Path | None = None,
1307
+ synthetic_root_filter: tuple[str, ...] | list[str] | None = None,
1308
+ ) -> dict[str, Any]:
1309
+ threshold_summary_rows = _build_global_threshold_summary(asset_rows, threshold_specs)
1310
+ model_summary_rows = _aggregate_group_mean(
1311
+ asset_rows,
1312
+ group_keys=["model_id", "model_label", "threshold_label", "threshold_pct", "tail_ratio"],
1313
+ value_fields=[
1314
+ "tail_overall_score",
1315
+ "head_proxy_overall_score",
1316
+ "tail_set_consistency",
1317
+ "tail_mass_similarity",
1318
+ "tail_concentration_consistency",
1319
+ "tail_anchor_coverage",
1320
+ "tail_head_gap",
1321
+ ],
1322
+ )
1323
+ dataset_summary_rows = _aggregate_group_mean(
1324
+ asset_rows,
1325
+ group_keys=["dataset_id", "dataset_prefix", "threshold_label", "threshold_pct", "tail_ratio"],
1326
+ value_fields=[
1327
+ "tail_overall_score",
1328
+ "head_proxy_overall_score",
1329
+ "tail_set_consistency",
1330
+ "tail_mass_similarity",
1331
+ "tail_concentration_consistency",
1332
+ "tail_anchor_coverage",
1333
+ "tail_head_gap",
1334
+ ],
1335
+ )
1336
+ prefix_summary_rows = _aggregate_group_mean(
1337
+ asset_rows,
1338
+ group_keys=["dataset_prefix", "threshold_label", "threshold_pct", "tail_ratio"],
1339
+ value_fields=[
1340
+ "tail_overall_score",
1341
+ "head_proxy_overall_score",
1342
+ "tail_set_consistency",
1343
+ "tail_mass_similarity",
1344
+ "tail_concentration_consistency",
1345
+ "tail_anchor_coverage",
1346
+ "tail_head_gap",
1347
+ ],
1348
+ )
1349
+ dataset_model_summary_rows = _build_dataset_model_summary(asset_rows)
1350
+ model_fragility_rows = _compute_model_fragility(model_summary_rows, threshold_specs)
1351
+ dataset_fragility_rows = _compute_dataset_fragility(dataset_summary_rows, threshold_specs)
1352
+ representative_rows = _select_representative_datasets(dataset_fragility_rows, representatives_per_prefix)
1353
+
1354
+ summary_dir = run_dir / "summaries"
1355
+ tables_dir = run_dir / "tables"
1356
+ figures_dir = run_dir / "figures"
1357
+ representatives_dir = figures_dir / "representatives"
1358
+ representatives_dir.mkdir(parents=True, exist_ok=True)
1359
+
1360
+ write_csv(summary_dir / "tail_threshold_asset_scores__all_datasets.csv", asset_rows)
1361
+ write_csv(summary_dir / "tail_threshold_real_diagnostics__all_datasets.csv", diagnostic_rows)
1362
+ write_csv(summary_dir / "tail_threshold_dataset_manifest__all_datasets.csv", dataset_manifest_rows)
1363
+
1364
+ write_csv(tables_dir / "global_threshold_summary.csv", threshold_summary_rows)
1365
+ write_csv(tables_dir / "model_threshold_summary.csv", model_summary_rows)
1366
+ write_csv(tables_dir / "dataset_threshold_summary.csv", dataset_summary_rows)
1367
+ write_csv(tables_dir / "prefix_threshold_summary.csv", prefix_summary_rows)
1368
+ write_csv(tables_dir / "dataset_model_threshold_summary.csv", dataset_model_summary_rows)
1369
+ write_csv(tables_dir / "model_fragility_summary.csv", model_fragility_rows)
1370
+ write_csv(tables_dir / "dataset_fragility_summary.csv", dataset_fragility_rows)
1371
+ write_csv(tables_dir / "representative_datasets.csv", representative_rows)
1372
+
1373
+ figure_paths: list[str] = []
1374
+
1375
+ global_tail_head = figures_dir / "01_global_tail_vs_head_proxy.png"
1376
+ _plot_global_tail_vs_head(threshold_summary_rows, threshold_specs, global_tail_head)
1377
+ figure_paths.append(str(global_tail_head.resolve()))
1378
+
1379
+ global_tail_submetrics = figures_dir / "02_global_tail_submetrics.png"
1380
+ _plot_global_tail_submetrics(threshold_summary_rows, threshold_specs, global_tail_submetrics)
1381
+ figure_paths.append(str(global_tail_submetrics.resolve()))
1382
+
1383
+ distribution_boxplot = figures_dir / "03_tail_score_distribution_boxplot.png"
1384
+ _plot_tail_distribution_boxplot(asset_rows, threshold_specs, distribution_boxplot)
1385
+ figure_paths.append(str(distribution_boxplot.resolve()))
1386
+
1387
+ diagnostics_plot = figures_dir / "04_threshold_key_diagnostics.png"
1388
+ _plot_threshold_key_diagnostics(diagnostic_rows, threshold_specs, diagnostics_plot)
1389
+ figure_paths.append(str(diagnostics_plot.resolve()))
1390
+
1391
+ model_heatmap = figures_dir / "05_model_threshold_heatmap.png"
1392
+ _plot_model_heatmap(model_summary_rows, threshold_specs, model_heatmap)
1393
+ figure_paths.append(str(model_heatmap.resolve()))
1394
+
1395
+ model_fragility_bar = figures_dir / "06_model_fragility_bar.png"
1396
+ _plot_model_fragility_bar(model_fragility_rows, model_fragility_bar)
1397
+ figure_paths.append(str(model_fragility_bar.resolve()))
1398
+
1399
+ dataset_heatmap = figures_dir / "07_dataset_threshold_heatmap.png"
1400
+ _plot_dataset_heatmap(dataset_summary_rows, dataset_fragility_rows, threshold_specs, dataset_heatmap)
1401
+ figure_paths.append(str(dataset_heatmap.resolve()))
1402
+
1403
+ prefix_lines = figures_dir / "08_prefix_threshold_lines.png"
1404
+ _plot_prefix_lines(prefix_summary_rows, threshold_specs, prefix_lines)
1405
+ figure_paths.append(str(prefix_lines.resolve()))
1406
+
1407
+ representative_grid = figures_dir / "09_representative_dataset_grid.png"
1408
+ _plot_representative_grid(representative_rows, dataset_summary_rows, diagnostic_rows, threshold_specs, representative_grid)
1409
+ if representative_grid.exists():
1410
+ figure_paths.append(str(representative_grid.resolve()))
1411
+
1412
+ figure_paths.extend(_plot_representative_model_lines(representative_rows, dataset_model_summary_rows, threshold_specs, representatives_dir))
1413
+
1414
+ manifest = {
1415
+ "task": "tail_threshold",
1416
+ "run_tag": run_dir.name,
1417
+ "run_dir": str(run_dir.resolve()),
1418
+ "dataset_count": len({str(row.get('dataset_id') or '') for row in asset_rows if row.get('dataset_id')}),
1419
+ "asset_count": len(asset_rows),
1420
+ "latest_only": latest_only,
1421
+ "synthetic_root_filter": [str(item) for item in (synthetic_root_filter or []) if str(item).strip()],
1422
+ "threshold_percentages": [spec.pct for spec in threshold_specs],
1423
+ "threshold_labels": [spec.label for spec in threshold_specs],
1424
+ "representative_dataset_count": len(representative_rows),
1425
+ "representative_datasets": representative_rows,
1426
+ "source_run_dir": str(source_run_dir.resolve()) if source_run_dir is not None else None,
1427
+ "figure_count": len(figure_paths),
1428
+ "figures": figure_paths,
1429
+ }
1430
+ write_json(run_dir / "manifest.json", manifest)
1431
+ return manifest
1432
+
1433
+
1434
+ def build_tail_threshold_preview(
1435
+ *,
1436
+ source_run_dir: Path,
1437
+ run_tag: str | None = None,
1438
+ latest_only: bool = True,
1439
+ threshold_percentages: list[float] | None = None,
1440
+ representatives_per_prefix: int = DEFAULT_REPRESENTATIVES_PER_PREFIX,
1441
+ ) -> dict[str, Any]:
1442
+ source_dir = source_run_dir.expanduser().resolve()
1443
+ asset_rows, diagnostic_rows, dataset_manifest_rows = _load_existing_dataset_outputs(source_dir)
1444
+ if not asset_rows:
1445
+ raise FileNotFoundError(f"No dataset-level tail-threshold outputs found under: {source_dir}")
1446
+ threshold_specs = _infer_threshold_specs_from_rows(asset_rows, fallback_percentages=threshold_percentages)
1447
+ out_run_dir = make_task_run_dir("tail_threshold", run_tag or f"{source_dir.name}__preview")
1448
+ return _materialize_tail_threshold_outputs(
1449
+ run_dir=out_run_dir,
1450
+ asset_rows=asset_rows,
1451
+ diagnostic_rows=diagnostic_rows,
1452
+ dataset_manifest_rows=dataset_manifest_rows,
1453
+ threshold_specs=threshold_specs,
1454
+ latest_only=latest_only,
1455
+ representatives_per_prefix=representatives_per_prefix,
1456
+ source_run_dir=source_dir,
1457
+ synthetic_root_filter=None,
1458
+ )
1459
+
1460
+
1461
+ def run_tail_threshold_experiment(
1462
+ *,
1463
+ run_tag: str | None = None,
1464
+ datasets: list[str] | None = None,
1465
+ latest_only: bool = True,
1466
+ root_names: tuple[str, ...] | list[str] | None = None,
1467
+ threshold_percentages: list[float] | None = None,
1468
+ max_workers: int = DEFAULT_MAX_WORKERS,
1469
+ numeric_bins: int = DEFAULT_NUMERIC_BINS,
1470
+ representatives_per_prefix: int = DEFAULT_REPRESENTATIVES_PER_PREFIX,
1471
+ ) -> dict[str, Any]:
1472
+ dataset_ids = datasets or list_dataset_ids()
1473
+ threshold_specs = _threshold_specs(threshold_percentages)
1474
+ run_dir = make_task_run_dir("tail_threshold", run_tag or now_run_tag())
1475
+ normalized_root_names = tuple(str(item).strip() for item in (root_names or []) if str(item).strip())
1476
+ assets = discover_synthetic_assets(
1477
+ datasets=dataset_ids,
1478
+ latest_only=latest_only,
1479
+ root_names=normalized_root_names,
1480
+ )
1481
+
1482
+ asset_rows: list[dict[str, Any]] = []
1483
+ diagnostic_rows: list[dict[str, Any]] = []
1484
+ dataset_manifest_rows: list[dict[str, Any]] = []
1485
+
1486
+ dataset_asset_map = {dataset_id: [asset for asset in assets if asset.dataset_id == dataset_id] for dataset_id in dataset_ids}
1487
+ progress = TaskProgressTracker(
1488
+ task_name="tail_threshold",
1489
+ total_steps=len(dataset_ids),
1490
+ step_label="datasets",
1491
+ substep_label="assets",
1492
+ total_substeps=sum(len(dataset_asset_map.get(dataset_id, [])) for dataset_id in dataset_ids),
1493
+ )
1494
+ progress.print_start(
1495
+ extra=(
1496
+ f"run_dir={run_dir.resolve()} | thresholds={','.join(spec.label for spec in threshold_specs)} "
1497
+ f"| latest_only={latest_only}"
1498
+ f" | roots={','.join(normalized_root_names) if normalized_root_names else 'all'}"
1499
+ )
1500
+ )
1501
+
1502
+ def _consume(
1503
+ dataset_id: str,
1504
+ dataset_asset_rows: list[dict[str, Any]],
1505
+ dataset_diagnostic_rows: list[dict[str, Any]],
1506
+ manifest_row: dict[str, Any],
1507
+ ) -> None:
1508
+ dataset_manifest_rows.append(manifest_row)
1509
+ progress.advance(
1510
+ step_name=dataset_id,
1511
+ substeps_done=int(manifest_row.get("asset_count") or 0),
1512
+ extra=f"status={manifest_row.get('status')}",
1513
+ )
1514
+ asset_rows.extend(dataset_asset_rows)
1515
+ diagnostic_rows.extend(dataset_diagnostic_rows)
1516
+ if dataset_asset_rows:
1517
+ write_csv(
1518
+ run_dir / "datasets" / dataset_id / f"tail_threshold_asset_scores__{dataset_id}.csv",
1519
+ dataset_asset_rows,
1520
+ )
1521
+ if dataset_diagnostic_rows:
1522
+ write_csv(
1523
+ run_dir / "datasets" / dataset_id / f"tail_threshold_real_diagnostics__{dataset_id}.csv",
1524
+ dataset_diagnostic_rows,
1525
+ )
1526
+
1527
+ if max_workers > 1 and len(dataset_ids) > 1:
1528
+ with ProcessPoolExecutor(max_workers=max_workers) as executor:
1529
+ futures = {
1530
+ executor.submit(
1531
+ _run_dataset_threshold_sweep,
1532
+ dataset_id,
1533
+ dataset_asset_map.get(dataset_id, []),
1534
+ threshold_specs,
1535
+ numeric_bins,
1536
+ ): dataset_id
1537
+ for dataset_id in dataset_ids
1538
+ }
1539
+ for future in as_completed(futures):
1540
+ _consume(*future.result())
1541
+ else:
1542
+ for dataset_id in dataset_ids:
1543
+ _consume(
1544
+ *_run_dataset_threshold_sweep(
1545
+ dataset_id,
1546
+ dataset_asset_map.get(dataset_id, []),
1547
+ threshold_specs,
1548
+ numeric_bins,
1549
+ )
1550
+ )
1551
+
1552
+ return _materialize_tail_threshold_outputs(
1553
+ run_dir=run_dir,
1554
+ asset_rows=asset_rows,
1555
+ diagnostic_rows=diagnostic_rows,
1556
+ dataset_manifest_rows=dataset_manifest_rows,
1557
+ threshold_specs=threshold_specs,
1558
+ latest_only=latest_only,
1559
+ representatives_per_prefix=representatives_per_prefix,
1560
+ source_run_dir=None,
1561
+ synthetic_root_filter=normalized_root_names,
1562
+ )