divsim-code / data /build_trajectories.py
anonymousfileupload's picture
Add divdata build scripts (build_divdata.py, build_trajectories.py); document consolidated dataset; replace absolute paths with $RUNS_DIR / OASIS_ROOT / SEED_DB env vars
327edac verified
Raw History Blame Contribute Delete
14.9 kB
"""Reconstruct per-agent, per-activation trajectories -- INCLUDING passive activations -- for
every run in divdata, and write `trajectories.parquet`.
Why this exists. `actions.parquet` only contains the two active actions the simulator logs
(create_post, create_comment). But every activation begins with a `refresh` row in `trace`
(the feed fetch) that carries a wall-clock timestamp whether or not the agent then acts, so
the *passive* side of the trajectory -- "agent was activated, looked at the feed, did
nothing" -- is fully recoverable from the database. Validated on the source runs: every
refresh window contains at most one action (1196/1200 windows have exactly one; the 4 with
zero are `status=exhausted` activations where all retries failed to parse).
Alignment to step. `step` is not in the database; it lives in `<run>_chats.jsonl`, one row
per activation. Step-0 rows have no refresh (the sign-up intro post is written directly), so
the k-th refresh of an agent is its k-th chats row with step > 0. Where that count matches,
step is EXACT; where an agent is off by one (seen in ~half the older sweeps) its steps are
NULL but its timestamps and actions are still emitted. Coverage is reported per run.
Reasoning. Some model families emit a free-text deliberation before the tool call; the
harness stored it in `<run>_reasoning.jsonl` keyed by (step, agent_id). It is joined on
where the step aligned. Absent for families that do not expose reasoning.
Decision record. Each activation's attempts in the chat sidecar carry the model's visible
output (`response_content` -- gemma and Magistral state their deliberation here ~95-99% of
the time, Qwen3 ~19%, gpt-oss/GLM-4 never), the tool call it chose (name + args, so the
target post is known even when the action later failed), and the parse error of each failed
attempt. All three are kept. The prompt is not: the feed it contained is `impressions`.
Row = one activation of one agent:
run_id, agent_id, model, activation_idx, step, refreshed_at, status, n_attempts,
action ('create_post' | 'create_comment' | 'none'), acted_at, latency_s,
post_id (own post for create_post; target post for create_comment), comment_id,
tool_name, tool_args (JSON), response_text, reasoning, finish_reason, errors,
extra_in_window (True for a 2nd+ action inside one refresh window; see below)
"""
import sqlite3, glob, os, json, argparse, collections, sys
import pandas as pd
ROOT = os.environ.get("OASIS_ROOT", ".") # directory holding runs/ (and attractor_rl/eval_runs*/)
sys.path.insert(0, os.path.dirname(__file__))
from build_divdata import agent_models
def decision(d):
"""The decision record of one activation, from its attempts list: the visible text the
model produced (its stated deliberation, where the family emits one), the tool call it
chose, and the parse errors of failed attempts. The prompt (user_message) is NOT kept --
the feed it contained is already in `impressions`, in slate order."""
atts = d.get("attempts") or []
last = next((a for a in reversed(atts) if "tool_calls" in a or "response_content" in a), None)
errs = [a.get("error") for a in atts if a.get("error")]
tc = (last or {}).get("tool_calls") or []
tc0 = tc[0] if tc else {}
return dict(n_attempts=len(atts),
response_text=((last or {}).get("response_content") or None),
finish_reason=((last or {}).get("finish_reason") or None),
tool_name=tc0.get("name"), tool_args=(json.dumps(tc0.get("args"), ensure_ascii=False) if tc0 else None),
errors=(" | ".join(str(e) for e in errs) or None))
def load_chats(path):
"""agent_id -> list of (step, status, decision) in file order, step>0 only; plus the
step-0 record per agent (the intro post, written without a refresh)."""
seq = collections.defaultdict(list); step0 = {}
for line in open(path):
try: d = json.loads(line)
except Exception: continue
try: st = int(d.get("step"))
except Exception: continue
ag = int(d.get("agent_id"))
if st == 0: step0[ag] = decision(d); continue
seq[ag].append((st, d.get("status"), decision(d)))
return seq, step0
def load_reasoning(path):
out = {}
if not os.path.exists(path): return out
for line in open(path):
try: d = json.loads(line)
except Exception: continue
try: out[(int(d["step"]), int(d["agent_id"]))] = d.get("reasoning")
except Exception: continue
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="divdata")
ap.add_argument("--runs", default="divdata/runs.parquet")
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--patch-steps", action="store_true",
help="fill NULL step in posts/comments/actions of --out from the trajectory alignment")
a = ap.parse_args()
runs = pd.read_parquet(a.runs, columns=["run_id", "source_path"])
if a.limit: runs = runs.head(a.limit)
T = []
log = dict(runs=0, no_chats=0, agents=0, agents_aligned=0, activations=0, passive=0,
windows_multi=0, agents_multi=0, with_reasoning=0, with_response_text=0, with_tool_call=0, status=collections.Counter())
from multiprocessing import Pool
with Pool(a.workers) as pool:
for i, (rows, plog) in enumerate(pool.imap_unordered(one_run, list(zip(runs.run_id, runs.source_path)), chunksize=4)):
T.extend(rows)
for k, v in plog.items():
if k == "status":
for kk, vv in v.items(): log["status"][kk] += vv
else: log[k] += v
if (i + 1) % 100 == 0:
print(f" ...{i+1}/{len(runs)} activations={len(T)}", flush=True)
finish(a, T, log)
def one_run(arg):
run_id, rel = arg
log = dict(runs=0, no_chats=0, agents=0, agents_aligned=0, activations=0, passive=0,
windows_multi=0, agents_multi=0, with_reasoning=0, with_response_text=0, with_tool_call=0, status=collections.Counter())
T = []
if True:
db = os.path.join(ROOT, rel)
meta_p = db.replace(".db", ".metadata.json")
_, am = agent_models(meta_p)
ch_p = db.replace(".db", "_chats.jsonl")
seq, step0 = load_chats(ch_p) if os.path.exists(ch_p) else (None, {})
if seq is None: log["no_chats"] += 1
reason = load_reasoning(db.replace(".db", "_reasoning.jsonl"))
try:
c = sqlite3.connect(db)
u2a = {u: g for u, g in c.execute("SELECT user_id, agent_id FROM user")}
# trace and post/comment timestamps differ by ~80 ms, so link by per-agent
# ordinal instead: the agent's k-th create_post in trace is its k-th post row.
posts_of = collections.defaultdict(list); coms_of = collections.defaultdict(list)
for pid, u in c.execute("SELECT post_id, user_id FROM post ORDER BY created_at, post_id"):
posts_of[u2a.get(u)].append(pid)
for cid, pid, u in c.execute("SELECT comment_id, post_id, user_id FROM comment ORDER BY created_at, comment_id"):
coms_of[u2a.get(u)].append((cid, pid))
tr = c.execute("SELECT user_id, created_at, action FROM trace WHERE action IN ('refresh','create_post','create_comment') "
"ORDER BY created_at, rowid").fetchall()
c.close()
except Exception:
return T, log
log["runs"] += 1
per = collections.defaultdict(list)
for u, ts, act in tr:
ag = u2a.get(u)
if ag is not None: per[ag].append((ts, act))
for ag, events in per.items():
model = am.get(ag, ("", None))[0] if am else None
s_ag = (seq or {}).get(ag, [])
n_ref = sum(1 for _, act in events if act == "refresh")
aligned = (seq is not None) and (len(s_ag) == n_ref)
log["agents"] += 1; log["agents_aligned"] += aligned
# walk windows
k = -1; cur = None; kp = kc = 0; multi = False
rows = []
for ts, act in events:
if act == "refresh":
if cur: rows.append(cur)
k += 1
st, status, dec = (s_ag[k] if aligned else (None, None, {}))
cur = dict(run_id=run_id, agent_id=ag, model=model, activation_idx=k, step=st,
refreshed_at=ts, status=status, action="none",
acted_at=None, post_id=None, comment_id=None, **dec,
reasoning=(reason.get((st, ag)) if st is not None else None))
else:
if cur is None:
# step-0 intro post: no refresh precedes it
rows.append(dict(run_id=run_id, agent_id=ag, model=model, activation_idx=-1, step=0,
refreshed_at=None, status="ok", action=act, **step0.get(ag, {}),
acted_at=ts, post_id=(posts_of[ag][kp] if kp < len(posts_of[ag]) else None),
comment_id=None, reasoning=reason.get((0, ag))))
kp += 1
continue
if cur["action"] != "none":
# A second action inside one refresh window. 16 runs (one old v9
# hetero_late archive run accounts for 2,468 of 3,247 such actions)
# violate the one-action-per-activation assumption, so the refresh
# alignment is not trustworthy for this agent: the extra action gets
# its own row (same activation_idx, extra_in_window=True) and the
# whole agent's step/decision fields are nulled below.
log["windows_multi"] += 1; multi = True
rows.append(cur)
cur = dict(cur, action="none", acted_at=None, post_id=None, comment_id=None, extra_in_window=True)
cur["action"] = act; cur["acted_at"] = ts
if act == "create_post":
cur["post_id"] = posts_of[ag][kp] if kp < len(posts_of[ag]) else None; kp += 1
else:
cid, pid = coms_of[ag][kc] if kc < len(coms_of[ag]) else (None, None); kc += 1
cur["comment_id"] = cid; cur["post_id"] = pid
if cur: rows.append(cur)
if multi:
log["agents_multi"] += 1
for r in rows:
if r["activation_idx"] >= 0:
for f in ("step", "status", "n_attempts", "response_text", "finish_reason",
"tool_name", "tool_args", "errors", "reasoning"):
r[f] = None
for r in rows:
r.setdefault("extra_in_window", False)
log["activations"] += 1
log["passive"] += (r["action"] == "none")
log["with_reasoning"] += (r["reasoning"] is not None)
log["with_response_text"] += bool(r.get("response_text"))
log["with_tool_call"] += bool(r.get("tool_name"))
log["status"][r["status"]] += 1
T.extend(rows)
return T, log
def finish(a, T, log):
df = pd.DataFrame(T)
# older runs wrote second-precision timestamps, newer ones microseconds
df["refreshed_at"] = pd.to_datetime(df.refreshed_at, format="mixed"); df["acted_at"] = pd.to_datetime(df.acted_at, format="mixed")
df["latency_s"] = (df.acted_at - df.refreshed_at).dt.total_seconds().round(3)
df["step"] = df.step.astype("Int64"); df["n_attempts"] = df.n_attempts.astype("Int64")
for col in ("response_text", "finish_reason", "tool_name", "tool_args", "errors", "reasoning"):
if col not in df: df[col] = None
df["post_id"] = df.post_id.astype("Int64"); df["comment_id"] = df.comment_id.astype("Int64")
df = df[["run_id", "agent_id", "model", "activation_idx", "step", "refreshed_at", "status", "n_attempts",
"action", "acted_at", "latency_s", "post_id", "comment_id",
"tool_name", "tool_args", "response_text", "reasoning", "finish_reason", "errors", "extra_in_window"]]
p = os.path.join(a.out, "trajectories.parquet")
df.to_parquet(p, index=False, compression="zstd")
log["status"] = dict(log["status"])
log["rows"] = len(df); log["size_mb"] = round(os.path.getsize(p) / 1e6, 1)
log["step_coverage"] = round(float(df.step.notna().mean()), 4)
log["action_counts"] = df.action.value_counts().to_dict()
print(json.dumps(log, indent=1, default=str))
if a.patch_steps:
patch_steps(a.out, df, log)
json.dump(log, open(os.path.join(a.out, "_trajectories_build_log.json"), "w"), indent=1, default=str)
def patch_steps(out, t, log):
"""The refresh-window alignment holds for every agent that has a chat sidecar, whereas
build_divdata's action-count alignment fails for an agent whose ok-activation and
action counts differ. Where the two agree they agree exactly (verified 100% on every
comparable row), so use the window alignment to fill step where build_divdata left NULL.
Existing non-null values are never overwritten."""
key = t[t.action != "none"].dropna(subset=["step"])
for name, on, sub in (("posts", ["run_id", "post_id"], key[key.action == "create_post"]),
("comments", ["run_id", "comment_id"], key[key.action == "create_comment"]),
("actions", ["run_id", "agent_id", "created_at"], key.assign(created_at=key.acted_at))):
p = os.path.join(out, f"{name}.parquet")
if not os.path.exists(p): continue
df = pd.read_parquet(p)
if name == "actions": df["created_at"] = pd.to_datetime(df.created_at, format="mixed")
m = df.merge(sub[on + ["step"]].rename(columns={"step": "_s"}), on=on, how="left")
before = df.step.isna().sum()
both = m.dropna(subset=["step", "_s"])
agree = float((both.step.astype(int) == both._s.astype(int)).mean()) if len(both) else 1.0
m["step"] = m.step.where(m.step.notna(), m._s).astype("Int64")
m = m.drop(columns="_s")
if name == "actions": m["created_at"] = m.created_at.astype(str)
m.to_parquet(p, index=False, compression="zstd")
log[f"patch_{name}"] = dict(null_before=int(before), null_after=int(m.step.isna().sum()),
rows=len(m), agreement_on_overlap=round(agree, 5))
print(f" patched {name}: step NULL {before} -> {int(m.step.isna().sum())} of {len(m)}; overlap agreement {agree:.5f}")
if __name__ == "__main__":
main()