File size: 5,050 Bytes
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c75e65
a2222d5
 
 
 
8c75e65
 
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c75e65
a2222d5
 
 
 
 
 
 
 
 
 
 
 
8c75e65
 
a2222d5
 
 
 
 
 
 
8c75e65
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.11"
# dependencies = ["huggingface_hub>=1.0"]
# ///
"""Build a per-agent time index and activity stats over the trace JSONL files.

Each file is cut into blocks of <=200 records or <=1 MiB. One row per block:
(agent, offset, length, records, min_ts, max_ts). The API range-reads only the
blocks that overlap a requested time window. Assistant messages also give each
agent's model calls, tool calls and token usage, in total and per hour.
Usage: index_traces.py SRC_DIR OUT_SQLITE [SPACE_REPO]
"""
import json, os, re, sqlite3, sys
from collections import defaultdict
from datetime import datetime
from multiprocessing import Pool

TS = re.compile(rb'"timestamp": ?"([^"]+)"')
DECODE = json.JSONDecoder().raw_decode
MAX_RECORDS, MAX_BYTES = 200, 1 << 20


def epoch(raw):
    return datetime.fromisoformat(raw.decode().replace("Z", "+00:00")).timestamp()


def index_file(args):
    lane, agent, path = args
    blocks, start, n, lo, hi, off = [], 0, 0, None, None, 0
    total, t, rebuilt = 0, None, False
    stats = [0, 0, 0, 0, 0]  # model calls, tool calls, input, output, reasoning tokens
    hours = defaultdict(lambda: [0, 0, 0, 0])  # hour -> model calls, tool calls, input, output tokens
    with open(path, "rb", buffering=8 << 20) as f:
        for line in f:
            if off == 0:  # traces rebuilt from the controller's event log say so in their session header
                rebuilt = b'"reconstructed_from"' in line
            m = TS.search(line, 0, 400)
            if m:
                t = epoch(m.group(1))
                lo = t if lo is None or t < lo else lo
                hi = t if hi is None or t > hi else hi
            if t is not None and b'"role": "assistant"' in line[:400]:
                u = line.find(b'"usage": ')
                usage = DECODE(line[u + 9:].decode("utf-8", "replace"))[0] if u > 0 else {}
                calls = line.count(b'"type": "toolCall"')  # escaped inside strings, so only real tool calls match
                row = (1, calls, usage.get("input", 0), usage.get("output", 0), usage.get("reasoning", 0))
                stats = [a + b for a, b in zip(stats, row)]
                h = hours[int(t // 3600)]
                for i, v in enumerate(row[:4]):
                    h[i] += v
            n += 1
            off += len(line)
            if n >= MAX_RECORDS or off - start >= MAX_BYTES:
                blocks.append((agent, start, off - start, n, lo, hi))
                total += n
                start, n, lo, hi = off, 0, None, None
    if n:
        blocks.append((agent, start, off - start, n, lo, hi))
        total += n
    los = [b[4] for b in blocks if b[4] is not None]
    his = [b[5] for b in blocks if b[5] is not None]
    meta = (agent, lane, off, total, min(los) if los else None, max(his) if his else None, int(rebuilt))
    return meta, blocks, (agent, *stats), [(agent, hr, *v) for hr, v in sorted(hours.items())]


def main(src, out, repo=None):
    jobs = []
    for lane in sorted(os.listdir(src)):
        d = os.path.join(src, lane)
        if os.path.isdir(d):
            jobs += [(lane, fn[:-6], os.path.join(d, fn)) for fn in sorted(os.listdir(d)) if fn.endswith(".jsonl")]
    print(f"{len(jobs)} files", flush=True)
    db = sqlite3.connect(out)
    db.executescript("""
      CREATE TABLE trace_files(agent TEXT PRIMARY KEY, lane TEXT, size INT, records INT, first_ts REAL, last_ts REAL,
                               reconstructed INT);
      CREATE TABLE trace_blocks(agent TEXT, offset INT, length INT, records INT, min_ts REAL, max_ts REAL);
      CREATE TABLE agent_stats(agent TEXT PRIMARY KEY, model_calls INT, tool_calls INT, input_tokens INT,
                               output_tokens INT, reasoning_tokens INT);
      CREATE TABLE agent_hours(agent TEXT, hour INT, model_calls INT, tool_calls INT, input_tokens INT, output_tokens INT);
    """)
    with Pool(int(os.environ.get("WORKERS", "16"))) as pool:
        for i, (meta, blocks, stats, hours) in enumerate(pool.imap_unordered(index_file, jobs), 1):
            db.execute("INSERT INTO trace_files VALUES (?,?,?,?,?,?,?)", meta)
            db.executemany("INSERT INTO trace_blocks VALUES (?,?,?,?,?,?)", blocks)
            db.execute("INSERT INTO agent_stats VALUES (?,?,?,?,?,?)", stats)
            db.executemany("INSERT INTO agent_hours VALUES (?,?,?,?,?,?)", hours)
            if i % 50 == 0:
                db.commit(); print(f"{i}/{len(jobs)}", flush=True)
    db.execute("CREATE INDEX blocks_agent ON trace_blocks(agent, offset)")
    db.execute("CREATE INDEX hours_agent ON agent_hours(agent, hour)")
    db.commit(); db.execute("VACUUM"); db.close()
    print("size", os.path.getsize(out), flush=True)
    if repo:
        from huggingface_hub import upload_file
        upload_file(path_or_fileobj=out, path_in_repo="data/traces.sqlite", repo_id=repo, repo_type="space",
                    commit_message="Add trace time index")
        print("uploaded", flush=True)


if __name__ == "__main__":
    main(*sys.argv[1:])