midah commited on
Commit
df8a2a2
Β·
verified Β·
1 Parent(s): 1927bdd

feat: quick stats, larger cap (20k), readable hit rows, tighter copy

Browse files
__pycache__/app.cpython-313.pyc CHANGED
Binary files a/__pycache__/app.cpython-313.pyc and b/__pycache__/app.cpython-313.pyc differ
 
app.py CHANGED
@@ -29,11 +29,13 @@ Design decisions (benefit / price):
29
 
30
  from __future__ import annotations
31
 
 
32
  import re
33
  import time
34
  from collections import Counter, OrderedDict
35
  from dataclasses import dataclass
36
  from pathlib import Path
 
37
 
38
  from fastapi import FastAPI
39
  from fastapi.responses import FileResponse, JSONResponse
@@ -43,7 +45,7 @@ from pydantic import BaseModel
43
  from procgrep.ingest import ingest
44
 
45
  # ── configuration ────────────────────────────────────────────────────────────
46
- MAX_TRACES = 4000 # per-dataset ingest cap (design decision 3)
47
  MAX_DATASETS = 6 # cached datasets before LRU eviction (design decision 2)
48
  INGEST_TIMEOUT_S = 60.0
49
  HIT_SAMPLE = 50 # matched traces returned to the client
@@ -81,6 +83,7 @@ class CachedTrace:
81
  agent: str
82
  atoms: tuple[str, ...]
83
  spine: str # " ".join(atoms) + " ", so `(edit ){5,}` style regexes match
 
84
 
85
 
86
  # dataset id -> traces. OrderedDict gives us LRU order cheaply.
@@ -100,14 +103,17 @@ def _load(dataset: str) -> list[CachedTrace]:
100
 
101
  traces, plan = ingest(dataset, limit=MAX_TRACES, timeout=INGEST_TIMEOUT_S)
102
  cached = [
103
- CachedTrace(t.trace_id, t.agent, tuple(t.atoms), " ".join(t.atoms) + " ") for t in traces
 
 
 
104
  ]
105
  _CACHE[dataset] = cached
106
  _META[dataset] = {
107
  "adapter": plan.adapter,
108
  "n_traces": len(cached),
109
  "truncated": len(cached) >= MAX_TRACES,
110
- "n_models": len({t.agent for t in cached}),
111
  }
112
  while len(_CACHE) > MAX_DATASETS:
113
  evicted, _ = _CACHE.popitem(last=False)
@@ -115,6 +121,32 @@ def _load(dataset: str) -> list[CachedTrace]:
115
  return cached
116
 
117
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  def _action_mix(traces: list[CachedTrace]) -> dict[str, float]:
119
  """Normalized frequency of each atom across the given traces."""
120
  counts: Counter[str] = Counter(a for t in traces for a in t.atoms)
@@ -181,12 +213,27 @@ def query(req: QueryRequest) -> JSONResponse:
181
  "n_hits": len(hits),
182
  "elapsed_ms": round(elapsed_ms, 2),
183
  "truncated": _META.get(req.dataset, {}).get("truncated", False),
 
 
 
 
 
 
 
 
 
 
184
  "by_model": models,
185
  "mix_all": _action_mix(traces),
186
  "mix_hits": _action_mix(hits) if hits else {},
187
  "atom_color": ATOM_COLOR,
188
  "hits": [
189
- {"trace_id": t.trace_id, "model": t.agent, "atoms": list(t.atoms[:200])}
 
 
 
 
 
190
  for t in hits[:HIT_SAMPLE]
191
  ],
192
  }
 
29
 
30
  from __future__ import annotations
31
 
32
+ import math
33
  import re
34
  import time
35
  from collections import Counter, OrderedDict
36
  from dataclasses import dataclass
37
  from pathlib import Path
38
+ from statistics import median
39
 
40
  from fastapi import FastAPI
41
  from fastapi.responses import FileResponse, JSONResponse
 
45
  from procgrep.ingest import ingest
46
 
47
  # ── configuration ────────────────────────────────────────────────────────────
48
+ MAX_TRACES = 20000 # per-dataset ingest cap (design decision 3); raise as memory allows
49
  MAX_DATASETS = 6 # cached datasets before LRU eviction (design decision 2)
50
  INGEST_TIMEOUT_S = 60.0
51
  HIT_SAMPLE = 50 # matched traces returned to the client
 
83
  agent: str
84
  atoms: tuple[str, ...]
85
  spine: str # " ".join(atoms) + " ", so `(edit ){5,}` style regexes match
86
+ task: str = "" # the task/instance the trajectory solved (trace.group), if known
87
 
88
 
89
  # dataset id -> traces. OrderedDict gives us LRU order cheaply.
 
103
 
104
  traces, plan = ingest(dataset, limit=MAX_TRACES, timeout=INGEST_TIMEOUT_S)
105
  cached = [
106
+ CachedTrace(
107
+ t.trace_id, t.agent, tuple(t.atoms), " ".join(t.atoms) + " ", str(t.group or "")
108
+ )
109
+ for t in traces
110
  ]
111
  _CACHE[dataset] = cached
112
  _META[dataset] = {
113
  "adapter": plan.adapter,
114
  "n_traces": len(cached),
115
  "truncated": len(cached) >= MAX_TRACES,
116
+ **_stats(cached),
117
  }
118
  while len(_CACHE) > MAX_DATASETS:
119
  evicted, _ = _CACHE.popitem(last=False)
 
121
  return cached
122
 
123
 
124
+ def _stats(traces: list[CachedTrace]) -> dict[str, float | int]:
125
+ """Quick dataset stats: behavioral diversity, conciseness, CoT length, dups.
126
+
127
+ diversity_bits = mean per-trajectory action entropy (how varied each agent's
128
+ actions are); median_len = median trace length (conciseness); median_cot =
129
+ median count of `think` steps per trace (chain-of-thought length).
130
+ """
131
+ if not traces:
132
+ return {"n_models": 0}
133
+ lens = [len(t.atoms) for t in traces]
134
+ thinks = [sum(a == "think" for a in t.atoms) for t in traces]
135
+ ents: list[float] = []
136
+ for t in traces:
137
+ counts = Counter(t.atoms)
138
+ n = len(t.atoms) or 1
139
+ ents.append(-sum((k / n) * math.log2(k / n) for k in counts.values()))
140
+ uniq = len({t.spine for t in traces})
141
+ return {
142
+ "diversity_bits": round(sum(ents) / len(ents), 2),
143
+ "median_len": int(median(lens)),
144
+ "median_cot": int(median(thinks)),
145
+ "exact_dup_rate": round(1 - uniq / len(traces), 3),
146
+ "n_models": len({t.agent for t in traces}),
147
+ }
148
+
149
+
150
  def _action_mix(traces: list[CachedTrace]) -> dict[str, float]:
151
  """Normalized frequency of each atom across the given traces."""
152
  counts: Counter[str] = Counter(a for t in traces for a in t.atoms)
 
213
  "n_hits": len(hits),
214
  "elapsed_ms": round(elapsed_ms, 2),
215
  "truncated": _META.get(req.dataset, {}).get("truncated", False),
216
+ "stats": {
217
+ k: _META.get(req.dataset, {}).get(k)
218
+ for k in (
219
+ "diversity_bits",
220
+ "median_len",
221
+ "median_cot",
222
+ "exact_dup_rate",
223
+ "n_models",
224
+ )
225
+ },
226
  "by_model": models,
227
  "mix_all": _action_mix(traces),
228
  "mix_hits": _action_mix(hits) if hits else {},
229
  "atom_color": ATOM_COLOR,
230
  "hits": [
231
+ {
232
+ "trace_id": t.trace_id,
233
+ "model": t.agent,
234
+ "task": t.task,
235
+ "atoms": list(t.atoms[:200]),
236
+ }
237
  for t in hits[:HIT_SAMPLE]
238
  ],
239
  }
static/app.js CHANGED
@@ -57,16 +57,21 @@ async function run(pattern) {
57
  $("dsmeta").textContent = `Β· ${r.n_traces} traces${r.truncated ? " (capped)" : ""}`;
58
  const col = r.atom_color;
59
  const top = r.by_model[0];
 
 
 
 
60
  $("res").innerHTML =
61
  `<div style="font-size:15px;margin:4px 0"><b>${r.n_hits}</b> / ${r.n_traces} traces match <b>/${r.pattern}/</b></div>
62
- <div class="dim" style="margin-bottom:12px"><span class="speed">scanned in ${r.elapsed_ms} ms β€” no model call</span>${top ? ` Β· ${top.model.split("-").pop()} most affected (${(top.rate * 100).toFixed(0)}%)` : ""}</div>
 
63
  <div class="eyebrow">which models</div>
64
  ${r.by_model.map((m) => `<div class="rrow"><span class="rlab">${m.model.split("-").slice(-2).join("-")}</span><span class="barbg"><span class="fill" style="width:${(m.rate * 160).toFixed(0)}px"></span></span><span>${(m.rate * 100).toFixed(0)}%</span></div>`).join("")}
65
  <div class="eyebrow">action mix Β· matched vs. all</div>
66
  <div class="rrow"><span class="rlab">matched</span>${r.n_hits ? mixbar(r.mix_hits, col) : '<span class="dim">no matches</span>'}</div>
67
  <div class="rrow"><span class="rlab">all traces</span>${mixbar(r.mix_all, col)}</div>
68
  <div class="eyebrow">matching traces</div>
69
- ${r.hits.map((h) => `<div class="qhit"><span style="min-width:48px">${h.model.split("-").pop()}</span><span class="dim">${h.atoms.length} steps</span>${spine(h.atoms, col)}</div>`).join("")}
70
  ${r.n_hits > r.hits.length ? `<div class="note">showing ${r.hits.length} of ${r.n_hits} matches</div>` : ""}`;
71
  }
72
 
 
57
  $("dsmeta").textContent = `Β· ${r.n_traces} traces${r.truncated ? " (capped)" : ""}`;
58
  const col = r.atom_color;
59
  const top = r.by_model[0];
60
+ const s = r.stats || {};
61
+ const statline = s.n_models
62
+ ? `<div class="dim" style="margin-bottom:14px">diversity ${s.diversity_bits} bits Β· median ${s.median_len} steps Β· CoT ${s.median_cot} think-steps Β· ${(s.exact_dup_rate * 100).toFixed(0)}% exact-duplicate Β· ${s.n_models} models</div>`
63
+ : "";
64
  $("res").innerHTML =
65
  `<div style="font-size:15px;margin:4px 0"><b>${r.n_hits}</b> / ${r.n_traces} traces match <b>/${r.pattern}/</b></div>
66
+ <div class="dim" style="margin-bottom:6px"><span class="speed">scanned in ${r.elapsed_ms} ms, no model call</span>${top ? ` Β· ${top.model.split("-").slice(-2).join("-")} most affected at ${(top.rate * 100).toFixed(0)}%` : ""}</div>
67
+ ${statline}
68
  <div class="eyebrow">which models</div>
69
  ${r.by_model.map((m) => `<div class="rrow"><span class="rlab">${m.model.split("-").slice(-2).join("-")}</span><span class="barbg"><span class="fill" style="width:${(m.rate * 160).toFixed(0)}px"></span></span><span>${(m.rate * 100).toFixed(0)}%</span></div>`).join("")}
70
  <div class="eyebrow">action mix Β· matched vs. all</div>
71
  <div class="rrow"><span class="rlab">matched</span>${r.n_hits ? mixbar(r.mix_hits, col) : '<span class="dim">no matches</span>'}</div>
72
  <div class="rrow"><span class="rlab">all traces</span>${mixbar(r.mix_all, col)}</div>
73
  <div class="eyebrow">matching traces</div>
74
+ ${r.hits.map((h) => `<div class="qhit"><span class="hit-model">${h.model.split("-").slice(-2).join("-")}</span>${h.task ? `<span class="hit-task dim" title="${h.task}">${h.task}</span>` : ""}<span class="dim">${h.atoms.length} steps</span>${spine(h.atoms, col)}</div>`).join("")}
75
  ${r.n_hits > r.hits.length ? `<div class="note">showing ${r.hits.length} of ${r.n_hits} matches</div>` : ""}`;
76
  }
77
 
static/index.html CHANGED
@@ -5,9 +5,9 @@
5
  <link rel="stylesheet" href="static/style.css">
6
  </head><body><div class="wrap">
7
  <h1>Grep agent traces, live.</h1>
8
- <p class="sub">Ask a structural question about how an agent worked and get an exact answer over a
9
- whole trajectory dataset, not a sample. This runs ProcGrep on the server: it ingests the dataset,
10
- canonicalizes it into an action vocabulary, and scans every trace. No model call.</p>
11
 
12
  <div class="dsbar">dataset:
13
  <select id="ds"></select>
 
5
  <link rel="stylesheet" href="static/style.css">
6
  </head><body><div class="wrap">
7
  <h1>Grep agent traces, live.</h1>
8
+ <p class="sub">Ask a structural question about how an agent worked and get an exact answer over the whole
9
+ trajectory dataset, not a sample. ProcGrep runs server-side: it ingests the dataset, canonicalizes it
10
+ into an action vocabulary, and scans every trace. No model call.</p>
11
 
12
  <div class="dsbar">dataset:
13
  <select id="ds"></select>
static/style.css CHANGED
@@ -27,6 +27,8 @@ select,input{font-family:var(--mono);font-size:12px;padding:6px 8px;border:1px s
27
  .mix>span{height:100%}
28
  .speed{color:var(--copper)}
29
  .qhit{padding:5px 2px;border-bottom:1px solid var(--rule);display:flex;align-items:center;gap:8px}
 
 
30
  .spine{display:inline-flex;gap:1px;flex-wrap:wrap;flex:1}
31
  .spine i{display:inline-block;width:5px;height:12px;border-radius:1px}
32
  .spine i.nz{opacity:.26}
 
27
  .mix>span{height:100%}
28
  .speed{color:var(--copper)}
29
  .qhit{padding:5px 2px;border-bottom:1px solid var(--rule);display:flex;align-items:center;gap:8px}
30
+ .hit-model{min-width:96px}
31
+ .hit-task{min-width:130px;max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px}
32
  .spine{display:inline-flex;gap:1px;flex-wrap:wrap;flex:1}
33
  .spine i{display:inline-block;width:5px;height:12px;border-radius:1px}
34
  .spine i.nz{opacity:.26}