File size: 23,007 Bytes
1a54d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c26fc3c
1a54d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cd3517
1a54d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cd3517
 
 
 
1a54d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c26fc3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a54d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cd3517
 
 
 
 
1a54d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cd3517
 
 
1a54d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cd3517
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a54d18
 
 
 
 
c26fc3c
1a54d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c26fc3c
1a54d18
3cd3517
1a54d18
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// The release generator supplies fractions. Convert to percent or percentage points only at display time.
const get = id => document.getElementById(id);
const emptyRelease = {runs: [], curves: [], examples: []};
const threshold = 0.05;
const metrics = {
  reward: {name: "Mean reward", unit: "reward"},
  accuracy: {name: "Validation accuracy", unit: "percent"},
  delta: {name: "Own minus donor accuracy", unit: "points"},
  novel_rate: {name: "Novel-token usage", unit: "percent"},
  loss: {name: "Training loss", unit: "loss"},
};
let release = emptyRelease;
let lastPayload = "";
let loading = false;
let page = 0;
const present = value => value !== null && value !== undefined && value !== "";
const number = value => typeof value === "number" && Number.isFinite(value);
const pretty = value => String(value ?? "—").replaceAll("_", " ");
const percent = value => number(value) ? (100 * value).toFixed(1) + "%" : "—";
const points = value => number(value) ? (value > 0 ? "+" : "") + (100 * value).toFixed(1) : "—";
const interval = ci => Array.isArray(ci) && ci.length === 2 && ci.every(number) && ci[0] <= ci[1];
const count = value => number(value) ? value.toLocaleString() : "—";
const symbolNames = Array.from({length: 32}, (_, i) => "<|z" + String(i).padStart(2, "0") + "|>");

// Use text nodes for every experiment field, including untrusted generated tokens and prompts.
function node(tag, className, value) {
  const item = document.createElement(tag);
  if (className) item.className = className;
  if (present(value)) item.textContent = String(value);
  return item;
}

function message(target, text) {
  get(target).replaceChildren(node("p", "empty", text));
}

function options(id, choices, allLabel) {
  const select = get(id);
  const previous = select.value;
  const list = allLabel ? [["", allLabel], ...choices] : choices;
  select.replaceChildren(...list.map(([value, name]) => new Option(name, String(value))));
  if (list.some(([value]) => String(value) === previous)) select.value = previous;
  select.disabled = !choices.length;
}

function unique(values) {
  return [...new Set(values.filter(present).map(String))]
    .sort((a, b) => a.localeCompare(b, undefined, {numeric: true}));
}

function applyFilters() {
  for (const [key, label] of [["task", "All tasks"], ["arm", "All arms"], ["seed", "All seeds"]]) {
    const values = unique(release.runs.map(run => run[key]));
    options(key, values.map(value => [value, pretty(value)]), label);
  }
}

function filteredRuns() {
  return release.runs.filter(run => ["task", "arm", "seed"].every(key => {
    return !get(key).value || String(run[key]) === get(key).value;
  }));
}

function runLabel(run) {
  const name = run.arm || run.id || "Run";
  return [pretty(name), present(run.seed) ? "seed " + run.seed : ""].filter(Boolean).join(" · ");
}

function setTableHead() {
  const row = node("tr");
  for (const label of ["Run", "Task", "Arm", "Seed", "Stage", "Questions", "Own", "Donor", "Difference (pp)", "95% interval (pp)", "Random", "Direct", "Novel use", "Novel mass", "Novel-only gap (pp)", "Changed / exposed traces", "Hybrid accuracy", "Same-state accuracy"]) {
    const cell = node("th", "", label);
    cell.scope = "col";
    row.append(cell);
  }
  get("measurement-head").replaceChildren(row);
}

function updateResults() {
  const runs = filteredRuns();
  get("measurement-count").textContent = "(" + runs.length + ")";
  get("measurement-details").hidden = !runs.length;
  get("measurement-body").replaceChildren(...runs.map(run => {
    const row = node("tr");
    const ci = interval(run.ci) ? points(run.ci[0]) + " to " + points(run.ci[1]) : "—";
    const values = [run.id, pretty(run.task), pretty(run.arm), run.seed, pretty(run.stage), count(run.n),
      percent(run.accuracy), percent(run.donor_accuracy), points(run.delta), ci, percent(run.conditions?.random),
      percent(run.conditions?.direct), percent(run.novel_rate), percent(run.novel_mass), points(run.targeted?.gap),
      run.targeted ? count(run.targeted.changed) + " / " + count(run.targeted.exposed) : "—",
      percent(run.cf_accuracy), percent(run.same_accuracy)];
    for (const value of values) row.append(node("td", "", present(value) ? value : "—"));
    return row;
  }));
  const measured = runs.filter(run => number(run.delta));
  if (!measured.length) {
    message("effects", runs.length ? "A paired trace estimate is unavailable for this selection." :
      release.runs.length ? "No evaluation matches these filters." : "Paired measurements will appear after the first held-out evaluation.");
    return;
  }
  // Use one symmetric range across rows and include every published interval endpoint.
  const bounds = measured.flatMap(run => interval(run.ci) ? [run.delta, ...run.ci] : [run.delta]);
  const extent = Math.min(1, Math.max(.10, Math.ceil(Math.max(...bounds.map(Math.abs)) * 10) / 10));
  const location = value => ((value + extent) / (2 * extent) * 100) + "%";
  const chart = node("div", "effect-chart");
  for (const run of measured) {
    const row = node("div", "effect-row");
    const label = node("div", "effect-label", runLabel(run));
    label.append(node("small", "", [run.task, run.stage].filter(present).map(pretty).join(" · ")));
    label.title = run.id || "";
    const ruler = node("div", "ruler");
    ruler.setAttribute("aria-hidden", "true");
    const target = node("span", "threshold");
    target.style.left = location(threshold);
    ruler.append(target);
    if (interval(run.ci)) {
      const whisker = node("span", "whisker");
      whisker.style.left = location(run.ci[0]);
      whisker.style.width = ((run.ci[1] - run.ci[0]) / (2 * extent) * 100) + "%";
      ruler.append(whisker);
    }
    const dot = node("span", "point");
    dot.style.left = location(run.delta);
    ruler.append(dot);
    const value = node("div", "effect-value", points(run.delta));
    if (interval(run.ci)) value.append(node("span", "sr", ", interval " + points(run.ci[0]) + " to " + points(run.ci[1])));
    row.append(label, ruler, value);
    chart.append(row);
  }
  const axis = node("div", "effect-row");
  const scale = node("div", "scale");
  for (const value of [-extent, 0, extent]) scale.append(node("span", "", String(Math.round(value * 100))));
  axis.append(node("span"), scale, node("span"));
  const legend = node("p", "legend", "Points show the paired estimate. Whiskers show its 95% interval when available. ");
  legend.append(node("b", "", "Dashed line"), document.createTextNode(" marks +5 pp."));
  chart.append(axis, legend);
  get("effects").replaceChildren(chart);
}

// A release can contain several tasks, splits, and stages for the same checkpoint.
function evaluationKey(run) {
  return JSON.stringify([run.id, run.stage, run.task, run.arm, run.seed, run.split]);
}

function updateSymbolPicker() {
  const runs = filteredRuns();
  const previous = get("symbol-eval").value;
  options("symbol-eval", runs.map(run => [evaluationKey(run), [run.id, run.stage, run.task, run.split].filter(present).join(" · ")]));
  if (!runs.some(run => evaluationKey(run) === previous)) {
    const recorded = runs.find(run => run.symbol_counts && typeof run.symbol_counts === "object");
    if (recorded) get("symbol-eval").value = evaluationKey(recorded);
  }
  updateSymbols();
}

function ruleEvidence(run) {
  const region = get("symbol-rules");
  region.replaceChildren();
  region.hidden = !run;
  if (!run) return;
  const rules = Array.isArray(release.rules) ? release.rules.filter(rule => rule.run === run.id) : [];
  region.append(node("h4", "", "Held-out interpretation tests for this run"));
  if (!rules.length) {
    region.append(node("p", "", "No held-out interpretation test has been published for this run."));
    return;
  }
  for (const rule of rules) {
    if (rule.supported === true && typeof rule.description === "string" && rule.description.trim()) {
      region.append(node("p", "supported-rule", rule.description));
    } else {
      let status = "This test did not establish a symbol meaning.";
      if (rule.supported === true) status = "The rule met the evidence threshold. Its description is unavailable.";
      region.append(node("p", "", status));
    }
    const details = [];
    if (present(rule.held_out)) details.push("Evaluation " + rule.held_out);
    if (number(rule.state_n)) details.push(count(rule.state_n) + " state cases");
    if (number(rule.intervention_n)) details.push(count(rule.intervention_n) + " eligible interventions");
    if (details.length) region.append(node("p", "", details.join(" · ")));
  }
}

function symbolShare(occurrences, total) {
  if (!total) return "—";
  const pct = 100 * occurrences / total;
  return pct > 0 && pct < .01 ? "<0.01%" : pct.toLocaleString(undefined, {maximumFractionDigits: 2}) + "%";
}

function updateSymbols() {
  const run = filteredRuns().find(item => evaluationKey(item) === get("symbol-eval").value);
  ruleEvidence(run);
  const counts = run?.symbol_counts;
  const complete = counts && symbolNames.every(name => Number.isSafeInteger(counts[name]) && counts[name] >= 0);
  get("symbol-details").hidden = !complete;
  get("symbol-rows").replaceChildren();
  if (!complete) {
    message("symbol-distribution", run ? "A complete per-symbol count is unavailable for this evaluation." :
      release.runs.length ? "No evaluation matches these filters." : "Symbol counts will appear after an evaluation records its traces.");
    return;
  }
  const total = symbolNames.reduce((sum, name) => sum + counts[name], 0);
  const observed = symbolNames.filter(name => counts[name] > 0).sort((a, b) => counts[b] - counts[a]);
  const content = node("div", "symbol-content");
  const statistics = node("dl", "symbol-totals");
  const items = [["Novel emissions", count(total)], ["Symbols used", observed.length + " / " + symbolNames.length]];
  if (number(run.novel_rate)) items.push(["Novel share of all slots", percent(run.novel_rate)]);
  if (total && number(run.symbol_entropy_bits)) items.push(["Conditional entropy", run.symbol_entropy_bits.toFixed(2) + " bits"]);
  if (total && number(run.effective_symbols)) items.push(["Effective symbols", run.effective_symbols.toFixed(2)]);
  for (const [label, value] of items) {
    const item = node("div");
    item.append(node("dt", "", label), node("dd", "", value));
    statistics.append(item);
  }
  content.append(statistics);
  if (total) {
    const max = counts[observed[0]];
    const top = observed.slice(0, 6);
    content.append(node("p", "", "Most frequent symbols by share of novel-token emissions. Bar scale runs from 0% to " + symbolShare(max, total) + "."));
    const list = node("ol", "symbol-list");
    for (const name of top) {
      const item = node("li");
      const track = node("span", "symbol-track");
      track.setAttribute("aria-hidden", "true");
      const bar = node("i");
      bar.style.width = (100 * counts[name] / max) + "%";
      track.append(bar);
      item.append(node("code", "", name), track, node("span", "symbol-readout", count(counts[name]) + " · " + symbolShare(counts[name], total)));
      list.append(item);
    }
    content.append(list);
  } else content.append(node("p", "", "No novel tokens were emitted. Conditional shares and entropy are undefined."));
  get("symbol-distribution").replaceChildren(content);
  for (const name of symbolNames) {
    const row = node("tr");
    const label = node("th", "", name);
    label.scope = "row";
    row.append(label, node("td", "", count(counts[name])), node("td", "", symbolShare(counts[name], total)));
    get("symbol-rows").append(row);
  }
}

// When a training run has no evaluation row yet, its live curve is still visible by default.
function included(ids) {
  const active = ["task", "arm", "seed"].some(key => get(key).value);
  if (!active) return unique(ids);
  const matching = new Set(filteredRuns().map(run => String(run.id)));
  return unique(ids).filter(id => matching.has(id));
}

function lineValue(value, unit) {
  if (unit === "percent") return percent(value);
  if (unit === "points") return points(value) + " pp";
  return value.toLocaleString(undefined, {maximumFractionDigits: 4});
}

function svgElement(tag, attributes, content) {
  const element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, String(value));
  if (content !== undefined) element.textContent = content;
  return element;
}

function drawCurve(samples, metricKey) {
  const metric = metrics[metricKey];
  const small = window.matchMedia("(max-width: 540px)").matches;
  const width = small ? 430 : 920;
  const height = small ? 235 : 255;
  const left = small ? 63 : 75;
  const right = width - 18;
  const top = 14;
  const bottom = height - 49;
  const last = samples.at(-1);
  const maximumStep = Math.max(last.step, 1);
  const values = samples.map(point => point[metricKey]);
  let low = Math.min(0, ...values);
  let high = Math.max(0, ...values);
  if (metric.unit === "percent" || metric.unit === "reward") { low = 0; high = 1; }
  if (metric.unit === "points") { high = Math.max(Math.abs(low), high, threshold); low = -high; }
  if (high === low) high = low + 1;
  const x = step => left + step / maximumStep * (right - left);
  const y = value => bottom - (value - low) / (high - low) * (bottom - top);
  const svg = svgElement("svg", {viewBox: "0 0 " + width + " " + height, role: "img", "aria-labelledby": "plot-title plot-desc"});
  svg.append(svgElement("title", {id: "plot-title"}, metric.name + " by optimizer step"),
    svgElement("desc", {id: "plot-desc"}, samples.length + " recorded values. Final value " + lineValue(last[metricKey], metric.unit) + " at step " + last.step + ". The table gives every recorded value."));
  for (let i = 0; i <= 4; i++) {
    const value = low + i * (high - low) / 4;
    svg.append(svgElement("line", {x1: left, x2: right, y1: y(value), y2: y(value), stroke: "#d8e4e1"}),
      svgElement("text", {x: left - 8, y: y(value) + 4, "text-anchor": "end", "font-size": 13}, lineValue(value, metric.unit)));
  }
  const tickCount = Math.min(4, maximumStep);
  for (let i = 0; i <= tickCount; i++) {
    const step = Math.round(i * maximumStep / tickCount);
    svg.append(svgElement("text", {x: x(step), y: bottom + 19, "text-anchor": "middle", "font-size": 13}, count(step)));
  }
  const path = samples.map((sample, index) => (index ? "L" : "M") + x(sample.step) + "," + y(sample[metricKey])).join(" ");
  svg.append(svgElement("path", {d: path, fill: "none", stroke: "#0c625b", "stroke-width": 2.7, "stroke-linejoin": "round"}),
    svgElement("circle", {cx: x(last.step), cy: y(last[metricKey]), r: 4.2, fill: "#0c625b", stroke: "#fff"}),
    svgElement("text", {x: (left + right) / 2, y: height - 5, "text-anchor": "middle", "font-size": 14}, "Optimizer step"));
  const plot = node("div", "plot");
  plot.append(svg);
  get("curve").replaceChildren(plot);
}

function updateCurve() {
  const run = get("curve-run").value;
  const rows = release.curves.filter(row => String(row.id) === run && number(row.step));
  const available = Object.entries(metrics).filter(([key]) => rows.some(row => number(row[key])));
  options("curve-metric", available.map(([key, metric]) => [key, metric.name]));
  const key = get("curve-metric").value;
  const byStep = new Map(rows.filter(row => number(row[key])).map(row => [row.step, row]));
  const samples = [...byStep.values()].sort((a, b) => a.step - b.step);
  get("curve-details").hidden = !samples.length;
  if (!samples.length) {
    get("curve-last").textContent = "";
    get("curve-values").replaceChildren();
    message("curve", "No training measurements are available for this selection.");
    return;
  }
  const last = samples.at(-1);
  const metric = metrics[key];
  get("curve-last").textContent = "Step " + count(last.step) + " · " + lineValue(last[key], metric.unit);
  get("curve-value-head").textContent = metric.name;
  get("curve-values").replaceChildren(...samples.map(item => {
    const row = node("tr");
    row.append(node("td", "", count(item.step)), node("td", "", lineValue(item[key], metric.unit)));
    return row;
  }));
  drawCurve(samples, key);
}

function canonicalAnswer(value) {
  const text = String(value).trim();
  // Normalize ordinary signed decimals exactly, including values larger than a JavaScript integer.
  if (!/^[+-]?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(text)) return text;
  const [whole, fraction = ""] = text.replaceAll(",", "").replace(/^[+-]/, "").split(".");
  const digits = whole.replace(/^0+(?=\d)/, "") + ("." + fraction.replace(/0+$/, "")).replace(/^\.$/, "");
  return (text.startsWith("-") && digits !== "0" ? "-" : "") + digits;
}

function outcome(example) {
  if (typeof example.correct === "boolean") return example.correct ? "correct" : "incorrect";
  if (!present(example.gold) || !present(example.answer)) return "unscored";
  return canonicalAnswer(example.gold) === canonicalAnswer(example.answer) ? "correct" : "incorrect";
}

function updateExample() {
  const selected = get("example-run").value;
  const requested = get("outcome").value;
  const stages = unique(release.examples.filter(item => String(item.run) === selected).map(item => item.kind))
    .sort((a, b) => Number(a.startsWith("valid")) - Number(b.startsWith("valid")));
  options("example-stage", stages.map(stage => [stage, pretty(stage)]));
  const stage = get("example-stage").value;
  const eligible = release.examples.filter(item => String(item.run) === selected && String(item.kind) === stage && (!requested || outcome(item) === requested));
  page = Math.max(0, Math.min(page, eligible.length - 1));
  get("prev").disabled = page === 0;
  get("next").disabled = page + 1 >= eligible.length;
  get("page").textContent = eligible.length ? (page + 1) + " / " + eligible.length : "—";
  if (!eligible.length) {
    message("example", "No saved example matches this selection.");
    return;
  }
  const example = eligible[page];
  const result = outcome(example);
  const body = node("div", "example-body");
  const meta = node("div", "example-meta");
  meta.append(node("span", "state " + result, result[0].toUpperCase() + result.slice(1)));
  if (present(example.kind)) meta.append(node("span", "", pretty(example.kind)));
  body.append(meta, node("h3", "", "Question"), node("p", "prompt", example.prompt || "Question unavailable"));
  if (example.reader && example.reader !== example.prompt) {
    body.append(node("h3", "", "Question shown to the reader"), node("p", "prompt", example.reader));
  }
  if (Array.isArray(example.trace)) {
    body.append(node("h3", "", "Written trace"));
    if (example.trace.length) {
      const tokens = node("ol", "tokens");
      for (const token of example.trace) tokens.append(node("li", "", token));
      body.append(tokens);
    } else body.append(node("p", "prompt", "Empty trace"));
  }
  const answers = node("dl", "answer-grid");
  for (const [key, label] of [["gold", "Ground truth"], ["answer", "Own trace"], ["donor_answer", "Donor trace"],
    ["expected_counterfactual", "Expected after swap"], ["hybrid_answer", "Observed after swap"]]) {
    if (!present(example[key])) continue;
    const cell = node("div");
    cell.append(node("dt", "", label), node("dd", "", example[key]));
    answers.append(cell);
  }
  body.append(answers);
  if (example.outputs && example.intervention_ids) {
    const details = node("details");
    const scroll = node("div", "scroll");
    const table = node("table");
    const header = node("tr");
    for (const label of ["Condition", "Scratchpad IDs read", "Answer"]) header.append(node("th", "", label));
    const head = node("thead");
    head.append(header);
    table.append(head);
    const rows = node("tbody");
    for (const [condition, ids] of Object.entries(example.intervention_ids)) {
      const row = node("tr");
      row.append(node("td", "", pretty(condition)), node("td", "", ids.length ? ids.join(" ") : "Empty scratchpad"),
                 node("td", "", example.outputs[condition]));
      rows.append(row);
    }
    table.append(rows);
    scroll.append(table);
    details.append(node("summary", "", "Inspect each intervention"), scroll);
    body.append(details);
  }
  get("example").replaceChildren(body);
}

function updateViews() {
  updateResults();
  updateSymbolPicker();
  const curveIds = included(release.curves.map(row => row.id));
  const exampleIds = included(release.examples.map(row => row.run));
  options("curve-run", curveIds.map(id => [id, pretty(id)]));
  options("example-run", exampleIds.map(id => [id, pretty(id)]));
  updateCurve();
  updateExample();
}

async function refresh() {
  if (loading) return;
  loading = true;
  get("refresh").disabled = true;
  try {
    const response = await fetch("./data.json", {cache: "no-store"});
    if (!response.ok) throw new Error("HTTP " + response.status);
    const payload = await response.text();
    if (payload !== lastPayload) {
      const data = JSON.parse(payload);
      if (!data || !["runs", "curves", "examples"].every(key => Array.isArray(data[key]))) {
        throw new Error("Unexpected data format");
      }
      release = data;
      applyFilters();
      updateViews();
      lastPayload = payload;
    }
    const time = Date.parse(release.updated);
    const formatted = Number.isFinite(time) ? new Intl.DateTimeFormat(undefined, {dateStyle: "medium", timeStyle: "short"}).format(time) : "";
    get("release-time").textContent = formatted ? "Updated " + formatted : "Latest release";
    get("release-time").title = Number.isFinite(time) ? new Date(time).toISOString() : "";
    get("release-status").textContent = release.status || "";
  } catch (error) {
    get("release-time").textContent = lastPayload ? "Showing last loaded release" : "Data unavailable";
    get("release-status").textContent = "Could not load the release (" + error.message + "). Refresh to try again.";
  } finally {
    loading = false;
    get("refresh").disabled = false;
  }
}

for (const key of ["task", "arm", "seed"]) get(key).addEventListener("change", () => { page = 0; updateViews(); });
get("symbol-eval").addEventListener("change", updateSymbols);
for (const key of ["curve-run", "curve-metric"]) get(key).addEventListener("change", updateCurve);
for (const key of ["example-run", "example-stage", "outcome"]) get(key).addEventListener("change", () => { page = 0; updateExample(); });
get("prev").addEventListener("click", () => { page--; updateExample(); });
get("next").addEventListener("click", () => { page++; updateExample(); });
get("refresh").addEventListener("click", refresh);
window.matchMedia("(max-width: 540px)").addEventListener("change", updateCurve);
document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(); });
window.setInterval(() => { if (!document.hidden) refresh(); }, 30_000);
setTableHead();
applyFilters();
updateViews();
refresh();