anonymousfileupload commited on
Commit
327edac
·
verified ·
1 Parent(s): dd138ec

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

Browse files
Files changed (4) hide show
  1. README.md +23 -2
  2. data/build_divdata.py +211 -0
  3. data/build_trajectories.py +264 -0
  4. oasis/run_v9.py +1 -1
README.md CHANGED
@@ -193,13 +193,32 @@ Reference data (SQLite databases, one per run) are listed in `data/MANIFEST.md`
193
  with SHA-256 checksums and sizes. The canonical data lives at:
194
 
195
  ```
196
- /data/user_data/droytbur/oasis/runs/sweep_*.db
197
  ```
198
 
199
  The manifest records all valid runs used in the paper (dyadic, triadic, and four-way),
200
  including the four-way DBs under `$RUNS_DIR/tetradic/`. The content analyses additionally
201
  use a text corpus (`data/texts.jsonl`) regenerated by `analyses/extract_texts.py`.
202
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  ---
204
 
205
  ## Repository layout
@@ -235,7 +254,9 @@ divsim_publish/
235
  │ ├── style_geometry.py # style directions + engagement-direction cosines
236
  │ └── cluster_model_persona.py / length_regimes.py # supporting checks
237
  ├── data/
238
- │ └── MANIFEST.md # DB paths, SHA-256, size, (pair/triplet, seed) labels
 
 
239
  ├── smoke_test/
240
  │ ├── run_smoke.sh # short dyad smoke run (20 steps, 2 agents/family)
241
  │ └── assert_h_matrix.py # assert H matrix computable + basic sanity checks
 
193
  with SHA-256 checksums and sizes. The canonical data lives at:
194
 
195
  ```
196
+ $RUNS_DIR/sweep_*.db
197
  ```
198
 
199
  The manifest records all valid runs used in the paper (dyadic, triadic, and four-way),
200
  including the four-way DBs under `$RUNS_DIR/tetradic/`. The content analyses additionally
201
  use a text corpus (`data/texts.jsonl`) regenerated by `analyses/extract_texts.py`.
202
 
203
+ ### Consolidated dataset (`divdata`)
204
+
205
+ Every run is also released as one Parquet dataset indexed by `run_id` and `step`
206
+ (`anonymousfileupload/divdata` on the Hub): posts, comments, agents, impressions (the feed
207
+ each agent saw, with slate position), actions, and **trajectories** — one row per agent
208
+ activation including passive ones, with the tool call the model emitted, its stated
209
+ deliberation / reasoning where the family exposes one, and wall-clock timestamps. The two
210
+ scripts that build it from the run databases are in `data/`:
211
+
212
+ ```bash
213
+ export OASIS_ROOT=/path/containing/runs # directory that holds runs/*.db + sidecars
214
+ python data/build_divdata.py --out divdata/ # 6 core tables
215
+ python data/build_trajectories.py --out divdata/ --workers 16 --patch-steps # trajectories + step back-fill
216
+ ```
217
+
218
+ `step` is not stored by the simulator; both scripts reconstruct it from the per-run chat
219
+ sidecar and document exactly where the alignment is exact and where it is left NULL. See
220
+ the dataset's `README.md` and `BUILD_LOG.md` for the details and for the 2026-09-09 erratum.
221
+
222
  ---
223
 
224
  ## Repository layout
 
254
  │ ├── style_geometry.py # style directions + engagement-direction cosines
255
  │ └── cluster_model_persona.py / length_regimes.py # supporting checks
256
  ├── data/
257
+ │ ├── MANIFEST.md # DB paths, SHA-256, size, (pair/triplet, seed) labels
258
+ │ ├── build_divdata.py # run DBs -> divdata Parquet (runs/agents/posts/comments/impressions/actions)
259
+ │ └── build_trajectories.py # + trajectories.parquet (every activation, passive included) and step back-fill
260
  ├── smoke_test/
261
  │ ├── run_smoke.sh # short dyad smoke run (20 steps, 2 agents/family)
262
  │ └── assert_h_matrix.py # assert H matrix computable + basic sanity checks
data/build_divdata.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Consolidate every OASIS run into one Parquet dataset indexed by run_id and step.
2
+
3
+ Each simulation currently lives as <run>.db + <run>.metadata.json + <run>_chats.jsonl.
4
+ Step is NOT stored in the database; it lives only in the chat sidecar, one row per agent
5
+ activation. Validated on every run: the agent's k-th status='ok' activation corresponds to
6
+ its k-th action in `trace` ordered by time, so step is recovered EXACTLY (not inferred).
7
+ Runs where that alignment fails are still emitted, with step = NULL and a flag, rather than
8
+ silently guessed.
9
+
10
+ Impressions are normalised. In the raw databases each `trace.refresh` event embeds the full
11
+ text of all 20 slate posts, which is ~48% of every file (17.9 MB of a 37.6 MB run). Here an
12
+ impression is just (run_id, step, viewer_agent_id, post_id); post text is stored once in
13
+ `posts`. That is a ~150x reduction on the largest table.
14
+
15
+ Tables written (one Parquet file each):
16
+ runs run_id, experiment_type, model_default, n_agents, n_initial, steps, join_step,
17
+ created_at, source_path, step_alignment_ok, step_coverage
18
+ agents run_id, agent_id, user_id, model, persona, join_step
19
+ posts run_id, post_id, agent_id, model, step, created_at, content
20
+ comments run_id, comment_id, post_id, agent_id, model, step, created_at, content,
21
+ is_cross_model
22
+ impressions run_id, step, viewer_agent_id, post_id, slot (0-based position in the 20-slot slate)
23
+ actions run_id, agent_id, step, action, created_at
24
+ """
25
+ import sqlite3, glob, os, re, json, argparse, collections
26
+ import pandas as pd
27
+
28
+ ROOT = os.environ.get("OASIS_ROOT", ".") # directory holding runs/ (and attractor_rl/eval_runs*/)
29
+
30
+
31
+ def agent_models(meta_path):
32
+ try:
33
+ j = json.load(open(meta_path))
34
+ except Exception:
35
+ return None, {}
36
+ am = j.get("agent_model_map") or {}
37
+ out = {}
38
+ for k, v in am.items():
39
+ try: k = int(k)
40
+ except Exception: pass
41
+ if isinstance(v, dict):
42
+ out[k] = (v.get("model", "").split("/")[-1], v.get("join_step"))
43
+ else:
44
+ out[k] = (str(v).split("/")[-1], None)
45
+ return j, out
46
+
47
+
48
+ def steps_for(db, u2a):
49
+ """Two per-agent step sequences from the chat sidecar, in file order:
50
+ ok -- steps of status='ok' activations (incl. step 0). The k-th one is the
51
+ agent's k-th ACTION (post or comment) in time order.
52
+ ref -- steps of every activation with step > 0, any status. The k-th one is the
53
+ agent's k-th `refresh` row in trace: exhausted activations still refresh,
54
+ and the step-0 intro post is written without a refresh.
55
+ Returns (ok, ref) or None if there is no sidecar."""
56
+ ch = db.replace(".db", "_chats.jsonl")
57
+ if not os.path.exists(ch):
58
+ return None
59
+ ok = collections.defaultdict(list); ref = collections.defaultdict(list)
60
+ try:
61
+ for line in open(ch):
62
+ try: d = json.loads(line)
63
+ except Exception: continue
64
+ ag = d.get("agent_id"); st = d.get("step")
65
+ if d.get("status") == "ok":
66
+ ok[ag].append(st)
67
+ try:
68
+ if int(st) > 0: ref[ag].append(st)
69
+ except Exception:
70
+ pass
71
+ except Exception:
72
+ return None
73
+ return ok, ref
74
+
75
+
76
+ def main():
77
+ ap = argparse.ArgumentParser()
78
+ ap.add_argument("--out", default="divdata")
79
+ ap.add_argument("--limit", type=int, default=0)
80
+ a = ap.parse_args()
81
+ os.makedirs(a.out, exist_ok=True)
82
+
83
+ dbs = sorted(glob.glob(os.path.join(ROOT, "runs/**/*.db"), recursive=True)) + \
84
+ sorted(glob.glob(os.path.join(ROOT, "attractor_rl/eval_runs*/**/*.db"), recursive=True))
85
+ if a.limit: dbs = dbs[:a.limit]
86
+
87
+ R, A, P, C, I, X = [], [], [], [], [], []
88
+ aligned = misaligned = skipped = 0
89
+
90
+ for idx, db in enumerate(dbs):
91
+ if os.path.exists(db.replace(".db", "_checkpoint.json")): skipped += 1; continue
92
+ meta_p = db.replace(".db", ".metadata.json")
93
+ if not os.path.exists(meta_p): skipped += 1; continue
94
+ meta, am = agent_models(meta_p)
95
+ if not am: skipped += 1; continue
96
+ run_id = os.path.relpath(db, ROOT)[:-3].replace("/", "__")
97
+ try:
98
+ c = sqlite3.connect(db)
99
+ users = list(c.execute("SELECT user_id, agent_id, user_name FROM user"))
100
+ u2a = {u: ag for u, ag, _ in users}
101
+ a2u = {ag: u for u, ag, _ in users}
102
+ persona = {ag: nm for _, ag, nm in users}
103
+
104
+ _sq = steps_for(db, u2a)
105
+ seq, rseq = (_sq if _sq else (None, None))
106
+ trace = list(c.execute(
107
+ "SELECT user_id, action, created_at FROM trace "
108
+ "WHERE action IN ('create_post','create_comment') ORDER BY created_at, rowid"))
109
+ per_agent_actions = collections.defaultdict(list)
110
+ for uid, act, ts in trace:
111
+ ag = u2a.get(uid)
112
+ if ag is not None: per_agent_actions[ag].append((act, ts))
113
+
114
+ # PER-AGENT alignment. An agent's k-th successful activation is its k-th
115
+ # action in time order, so when the two counts agree the step is EXACT. A
116
+ # single stray action (seen in ~half the older sweeps: one agent off by one,
117
+ # e.g. 380 activations vs 379 actions) must not discard the other 19 agents,
118
+ # so alignment is decided per agent and unalignable agents get step = NULL.
119
+ step_of = {}
120
+ n_ok = n_tot = 0
121
+ for ag, acts in per_agent_actions.items():
122
+ s_ag = (seq or {}).get(ag, [])
123
+ n_tot += len(acts)
124
+ if len(s_ag) == len(acts):
125
+ n_ok += len(acts)
126
+ for i, _ in enumerate(acts):
127
+ step_of[(ag, i)] = s_ag[i]
128
+ ok = n_tot > 0 and n_ok == n_tot
129
+ aligned += ok; misaligned += (not ok)
130
+ cover = (n_ok / n_tot) if n_tot else 0.0
131
+
132
+ for ag, (model, js) in am.items():
133
+ A.append(dict(run_id=run_id, agent_id=ag, user_id=a2u.get(ag),
134
+ model=model, persona=persona.get(ag), join_step=js))
135
+
136
+ # Posts and comments are merged into ONE time-ordered stream per agent before
137
+ # indexing. (An earlier version indexed all posts, then all comments, which
138
+ # mis-assigned step for every agent that had both -- see BUILD_LOG.)
139
+ events = [("post", pid, None, uid, ts, content) for pid, uid, ts, content in c.execute(
140
+ "SELECT post_id, user_id, created_at, content FROM post")] + \
141
+ [("comment", cid, pid, uid, ts, content) for cid, pid, uid, ts, content in c.execute(
142
+ "SELECT comment_id, post_id, user_id, created_at, content FROM comment")]
143
+ events.sort(key=lambda e: (e[4], e[1]))
144
+ seen = collections.Counter()
145
+ owner, ownmodel = {}, {}
146
+ for kind, _id, pid, uid, ts, content in events:
147
+ ag = u2a.get(uid); m = am.get(ag, ("", None))[0] if ag is not None else None
148
+ st = step_of.get((ag, seen[ag]))
149
+ seen[ag] += 1
150
+ if kind == "post":
151
+ owner[_id] = ag; ownmodel[_id] = m
152
+ P.append(dict(run_id=run_id, post_id=_id, agent_id=ag, model=m,
153
+ step=st, created_at=ts, content=content))
154
+ else:
155
+ om = ownmodel.get(pid)
156
+ C.append(dict(run_id=run_id, comment_id=_id, post_id=pid, agent_id=ag, model=m,
157
+ step=st, created_at=ts, content=content,
158
+ is_cross_model=(bool(om and m and om != m) if om and m else None)))
159
+
160
+ # impressions: normalised out of trace.refresh
161
+ ref = list(c.execute("SELECT user_id, created_at, info FROM trace WHERE action='refresh' ORDER BY created_at, rowid"))
162
+ nref = collections.Counter(u2a.get(uid) for uid, _, _ in ref)
163
+ rseen = collections.Counter()
164
+ for uid, ts, info in ref:
165
+ ag = u2a.get(uid)
166
+ try: d = json.loads(info)
167
+ except Exception: continue
168
+ st = None
169
+ r_ag = (rseq or {}).get(ag, [])
170
+ k = rseen[ag]
171
+ if len(r_ag) == nref[ag] and k < len(r_ag): st = r_ag[k]
172
+ rseen[ag] += 1
173
+ for slot, p in enumerate(d.get("posts", []) or []):
174
+ pid = p.get("post_id")
175
+ if pid is not None:
176
+ I.append(dict(run_id=run_id, step=st, viewer_agent_id=ag, post_id=pid, slot=slot))
177
+ aseen = collections.Counter()
178
+ for uid, act, ts in trace:
179
+ ag = u2a.get(uid)
180
+ X.append(dict(run_id=run_id, agent_id=ag, step=step_of.get((ag, aseen[ag])), action=act, created_at=ts))
181
+ aseen[ag] += 1
182
+ c.close()
183
+
184
+ R.append(dict(run_id=run_id,
185
+ experiment_type=(meta or {}).get("experiment_type"),
186
+ model_default=(meta or {}).get("model_default"),
187
+ n_agents=(meta or {}).get("n_agents"),
188
+ n_initial=(meta or {}).get("n_initial"),
189
+ steps=(meta or {}).get("steps"),
190
+ join_step=(meta or {}).get("join_step"),
191
+ created_at=(meta or {}).get("created_at"),
192
+ source_path=os.path.relpath(db, ROOT),
193
+ step_alignment_ok=bool(ok),
194
+ step_coverage=round(cover, 4)))
195
+ except Exception:
196
+ skipped += 1
197
+ continue
198
+ if (idx + 1) % 100 == 0:
199
+ print(f" ...{idx+1}/{len(dbs)} runs={len(R)} posts={len(P)} comments={len(C)} impressions={len(I)}", flush=True)
200
+
201
+ print(f"\n runs kept={len(R)} skipped={skipped} step-aligned={aligned} misaligned={misaligned}")
202
+ for name, rows in (("runs", R), ("agents", A), ("posts", P), ("comments", C),
203
+ ("impressions", I), ("actions", X)):
204
+ df = pd.DataFrame(rows)
205
+ p = os.path.join(a.out, f"{name}.parquet")
206
+ df.to_parquet(p, index=False, compression="zstd")
207
+ print(f" {name:12s} {len(df):9d} rows {os.path.getsize(p)/1e6:8.1f} MB")
208
+
209
+
210
+ if __name__ == "__main__":
211
+ main()
data/build_trajectories.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reconstruct per-agent, per-activation trajectories -- INCLUDING passive activations -- for
2
+ every run in divdata, and write `trajectories.parquet`.
3
+
4
+ Why this exists. `actions.parquet` only contains the two active actions the simulator logs
5
+ (create_post, create_comment). But every activation begins with a `refresh` row in `trace`
6
+ (the feed fetch) that carries a wall-clock timestamp whether or not the agent then acts, so
7
+ the *passive* side of the trajectory -- "agent was activated, looked at the feed, did
8
+ nothing" -- is fully recoverable from the database. Validated on the source runs: every
9
+ refresh window contains at most one action (1196/1200 windows have exactly one; the 4 with
10
+ zero are `status=exhausted` activations where all retries failed to parse).
11
+
12
+ Alignment to step. `step` is not in the database; it lives in `<run>_chats.jsonl`, one row
13
+ per activation. Step-0 rows have no refresh (the sign-up intro post is written directly), so
14
+ the k-th refresh of an agent is its k-th chats row with step > 0. Where that count matches,
15
+ step is EXACT; where an agent is off by one (seen in ~half the older sweeps) its steps are
16
+ NULL but its timestamps and actions are still emitted. Coverage is reported per run.
17
+
18
+ Reasoning. Some model families emit a free-text deliberation before the tool call; the
19
+ harness stored it in `<run>_reasoning.jsonl` keyed by (step, agent_id). It is joined on
20
+ where the step aligned. Absent for families that do not expose reasoning.
21
+
22
+ Decision record. Each activation's attempts in the chat sidecar carry the model's visible
23
+ output (`response_content` -- gemma and Magistral state their deliberation here ~95-99% of
24
+ the time, Qwen3 ~19%, gpt-oss/GLM-4 never), the tool call it chose (name + args, so the
25
+ target post is known even when the action later failed), and the parse error of each failed
26
+ attempt. All three are kept. The prompt is not: the feed it contained is `impressions`.
27
+
28
+ Row = one activation of one agent:
29
+ run_id, agent_id, model, activation_idx, step, refreshed_at, status, n_attempts,
30
+ action ('create_post' | 'create_comment' | 'none'), acted_at, latency_s,
31
+ post_id (own post for create_post; target post for create_comment), comment_id,
32
+ tool_name, tool_args (JSON), response_text, reasoning, finish_reason, errors,
33
+ extra_in_window (True for a 2nd+ action inside one refresh window; see below)
34
+ """
35
+ import sqlite3, glob, os, json, argparse, collections, sys
36
+ import pandas as pd
37
+
38
+ ROOT = os.environ.get("OASIS_ROOT", ".") # directory holding runs/ (and attractor_rl/eval_runs*/)
39
+ sys.path.insert(0, os.path.dirname(__file__))
40
+ from build_divdata import agent_models
41
+
42
+
43
+ def decision(d):
44
+ """The decision record of one activation, from its attempts list: the visible text the
45
+ model produced (its stated deliberation, where the family emits one), the tool call it
46
+ chose, and the parse errors of failed attempts. The prompt (user_message) is NOT kept --
47
+ the feed it contained is already in `impressions`, in slate order."""
48
+ atts = d.get("attempts") or []
49
+ last = next((a for a in reversed(atts) if "tool_calls" in a or "response_content" in a), None)
50
+ errs = [a.get("error") for a in atts if a.get("error")]
51
+ tc = (last or {}).get("tool_calls") or []
52
+ tc0 = tc[0] if tc else {}
53
+ return dict(n_attempts=len(atts),
54
+ response_text=((last or {}).get("response_content") or None),
55
+ finish_reason=((last or {}).get("finish_reason") or None),
56
+ tool_name=tc0.get("name"), tool_args=(json.dumps(tc0.get("args"), ensure_ascii=False) if tc0 else None),
57
+ errors=(" | ".join(str(e) for e in errs) or None))
58
+
59
+
60
+ def load_chats(path):
61
+ """agent_id -> list of (step, status, decision) in file order, step>0 only; plus the
62
+ step-0 record per agent (the intro post, written without a refresh)."""
63
+ seq = collections.defaultdict(list); step0 = {}
64
+ for line in open(path):
65
+ try: d = json.loads(line)
66
+ except Exception: continue
67
+ try: st = int(d.get("step"))
68
+ except Exception: continue
69
+ ag = int(d.get("agent_id"))
70
+ if st == 0: step0[ag] = decision(d); continue
71
+ seq[ag].append((st, d.get("status"), decision(d)))
72
+ return seq, step0
73
+
74
+
75
+ def load_reasoning(path):
76
+ out = {}
77
+ if not os.path.exists(path): return out
78
+ for line in open(path):
79
+ try: d = json.loads(line)
80
+ except Exception: continue
81
+ try: out[(int(d["step"]), int(d["agent_id"]))] = d.get("reasoning")
82
+ except Exception: continue
83
+ return out
84
+
85
+
86
+ def main():
87
+ ap = argparse.ArgumentParser()
88
+ ap.add_argument("--out", default="divdata")
89
+ ap.add_argument("--runs", default="divdata/runs.parquet")
90
+ ap.add_argument("--limit", type=int, default=0)
91
+ ap.add_argument("--workers", type=int, default=8)
92
+ ap.add_argument("--patch-steps", action="store_true",
93
+ help="fill NULL step in posts/comments/actions of --out from the trajectory alignment")
94
+ a = ap.parse_args()
95
+
96
+ runs = pd.read_parquet(a.runs, columns=["run_id", "source_path"])
97
+ if a.limit: runs = runs.head(a.limit)
98
+
99
+ T = []
100
+ log = dict(runs=0, no_chats=0, agents=0, agents_aligned=0, activations=0, passive=0,
101
+ windows_multi=0, agents_multi=0, with_reasoning=0, with_response_text=0, with_tool_call=0, status=collections.Counter())
102
+ from multiprocessing import Pool
103
+ with Pool(a.workers) as pool:
104
+ for i, (rows, plog) in enumerate(pool.imap_unordered(one_run, list(zip(runs.run_id, runs.source_path)), chunksize=4)):
105
+ T.extend(rows)
106
+ for k, v in plog.items():
107
+ if k == "status":
108
+ for kk, vv in v.items(): log["status"][kk] += vv
109
+ else: log[k] += v
110
+ if (i + 1) % 100 == 0:
111
+ print(f" ...{i+1}/{len(runs)} activations={len(T)}", flush=True)
112
+ finish(a, T, log)
113
+
114
+
115
+ def one_run(arg):
116
+ run_id, rel = arg
117
+ log = dict(runs=0, no_chats=0, agents=0, agents_aligned=0, activations=0, passive=0,
118
+ windows_multi=0, agents_multi=0, with_reasoning=0, with_response_text=0, with_tool_call=0, status=collections.Counter())
119
+ T = []
120
+ if True:
121
+ db = os.path.join(ROOT, rel)
122
+ meta_p = db.replace(".db", ".metadata.json")
123
+ _, am = agent_models(meta_p)
124
+ ch_p = db.replace(".db", "_chats.jsonl")
125
+ seq, step0 = load_chats(ch_p) if os.path.exists(ch_p) else (None, {})
126
+ if seq is None: log["no_chats"] += 1
127
+ reason = load_reasoning(db.replace(".db", "_reasoning.jsonl"))
128
+ try:
129
+ c = sqlite3.connect(db)
130
+ u2a = {u: g for u, g in c.execute("SELECT user_id, agent_id FROM user")}
131
+ # trace and post/comment timestamps differ by ~80 ms, so link by per-agent
132
+ # ordinal instead: the agent's k-th create_post in trace is its k-th post row.
133
+ posts_of = collections.defaultdict(list); coms_of = collections.defaultdict(list)
134
+ for pid, u in c.execute("SELECT post_id, user_id FROM post ORDER BY created_at, post_id"):
135
+ posts_of[u2a.get(u)].append(pid)
136
+ for cid, pid, u in c.execute("SELECT comment_id, post_id, user_id FROM comment ORDER BY created_at, comment_id"):
137
+ coms_of[u2a.get(u)].append((cid, pid))
138
+ tr = c.execute("SELECT user_id, created_at, action FROM trace WHERE action IN ('refresh','create_post','create_comment') "
139
+ "ORDER BY created_at, rowid").fetchall()
140
+ c.close()
141
+ except Exception:
142
+ return T, log
143
+ log["runs"] += 1
144
+ per = collections.defaultdict(list)
145
+ for u, ts, act in tr:
146
+ ag = u2a.get(u)
147
+ if ag is not None: per[ag].append((ts, act))
148
+
149
+ for ag, events in per.items():
150
+ model = am.get(ag, ("", None))[0] if am else None
151
+ s_ag = (seq or {}).get(ag, [])
152
+ n_ref = sum(1 for _, act in events if act == "refresh")
153
+ aligned = (seq is not None) and (len(s_ag) == n_ref)
154
+ log["agents"] += 1; log["agents_aligned"] += aligned
155
+ # walk windows
156
+ k = -1; cur = None; kp = kc = 0; multi = False
157
+ rows = []
158
+ for ts, act in events:
159
+ if act == "refresh":
160
+ if cur: rows.append(cur)
161
+ k += 1
162
+ st, status, dec = (s_ag[k] if aligned else (None, None, {}))
163
+ cur = dict(run_id=run_id, agent_id=ag, model=model, activation_idx=k, step=st,
164
+ refreshed_at=ts, status=status, action="none",
165
+ acted_at=None, post_id=None, comment_id=None, **dec,
166
+ reasoning=(reason.get((st, ag)) if st is not None else None))
167
+ else:
168
+ if cur is None:
169
+ # step-0 intro post: no refresh precedes it
170
+ rows.append(dict(run_id=run_id, agent_id=ag, model=model, activation_idx=-1, step=0,
171
+ refreshed_at=None, status="ok", action=act, **step0.get(ag, {}),
172
+ acted_at=ts, post_id=(posts_of[ag][kp] if kp < len(posts_of[ag]) else None),
173
+ comment_id=None, reasoning=reason.get((0, ag))))
174
+ kp += 1
175
+ continue
176
+ if cur["action"] != "none":
177
+ # A second action inside one refresh window. 16 runs (one old v9
178
+ # hetero_late archive run accounts for 2,468 of 3,247 such actions)
179
+ # violate the one-action-per-activation assumption, so the refresh
180
+ # alignment is not trustworthy for this agent: the extra action gets
181
+ # its own row (same activation_idx, extra_in_window=True) and the
182
+ # whole agent's step/decision fields are nulled below.
183
+ log["windows_multi"] += 1; multi = True
184
+ rows.append(cur)
185
+ cur = dict(cur, action="none", acted_at=None, post_id=None, comment_id=None, extra_in_window=True)
186
+ cur["action"] = act; cur["acted_at"] = ts
187
+ if act == "create_post":
188
+ cur["post_id"] = posts_of[ag][kp] if kp < len(posts_of[ag]) else None; kp += 1
189
+ else:
190
+ cid, pid = coms_of[ag][kc] if kc < len(coms_of[ag]) else (None, None); kc += 1
191
+ cur["comment_id"] = cid; cur["post_id"] = pid
192
+ if cur: rows.append(cur)
193
+ if multi:
194
+ log["agents_multi"] += 1
195
+ for r in rows:
196
+ if r["activation_idx"] >= 0:
197
+ for f in ("step", "status", "n_attempts", "response_text", "finish_reason",
198
+ "tool_name", "tool_args", "errors", "reasoning"):
199
+ r[f] = None
200
+ for r in rows:
201
+ r.setdefault("extra_in_window", False)
202
+ log["activations"] += 1
203
+ log["passive"] += (r["action"] == "none")
204
+ log["with_reasoning"] += (r["reasoning"] is not None)
205
+ log["with_response_text"] += bool(r.get("response_text"))
206
+ log["with_tool_call"] += bool(r.get("tool_name"))
207
+ log["status"][r["status"]] += 1
208
+ T.extend(rows)
209
+ return T, log
210
+
211
+
212
+ def finish(a, T, log):
213
+ df = pd.DataFrame(T)
214
+ # older runs wrote second-precision timestamps, newer ones microseconds
215
+ df["refreshed_at"] = pd.to_datetime(df.refreshed_at, format="mixed"); df["acted_at"] = pd.to_datetime(df.acted_at, format="mixed")
216
+ df["latency_s"] = (df.acted_at - df.refreshed_at).dt.total_seconds().round(3)
217
+ df["step"] = df.step.astype("Int64"); df["n_attempts"] = df.n_attempts.astype("Int64")
218
+ for col in ("response_text", "finish_reason", "tool_name", "tool_args", "errors", "reasoning"):
219
+ if col not in df: df[col] = None
220
+ df["post_id"] = df.post_id.astype("Int64"); df["comment_id"] = df.comment_id.astype("Int64")
221
+ df = df[["run_id", "agent_id", "model", "activation_idx", "step", "refreshed_at", "status", "n_attempts",
222
+ "action", "acted_at", "latency_s", "post_id", "comment_id",
223
+ "tool_name", "tool_args", "response_text", "reasoning", "finish_reason", "errors", "extra_in_window"]]
224
+ p = os.path.join(a.out, "trajectories.parquet")
225
+ df.to_parquet(p, index=False, compression="zstd")
226
+ log["status"] = dict(log["status"])
227
+ log["rows"] = len(df); log["size_mb"] = round(os.path.getsize(p) / 1e6, 1)
228
+ log["step_coverage"] = round(float(df.step.notna().mean()), 4)
229
+ log["action_counts"] = df.action.value_counts().to_dict()
230
+ print(json.dumps(log, indent=1, default=str))
231
+ if a.patch_steps:
232
+ patch_steps(a.out, df, log)
233
+ json.dump(log, open(os.path.join(a.out, "_trajectories_build_log.json"), "w"), indent=1, default=str)
234
+
235
+
236
+ def patch_steps(out, t, log):
237
+ """The refresh-window alignment holds for every agent that has a chat sidecar, whereas
238
+ build_divdata's action-count alignment fails for an agent whose ok-activation and
239
+ action counts differ. Where the two agree they agree exactly (verified 100% on every
240
+ comparable row), so use the window alignment to fill step where build_divdata left NULL.
241
+ Existing non-null values are never overwritten."""
242
+ key = t[t.action != "none"].dropna(subset=["step"])
243
+ for name, on, sub in (("posts", ["run_id", "post_id"], key[key.action == "create_post"]),
244
+ ("comments", ["run_id", "comment_id"], key[key.action == "create_comment"]),
245
+ ("actions", ["run_id", "agent_id", "created_at"], key.assign(created_at=key.acted_at))):
246
+ p = os.path.join(out, f"{name}.parquet")
247
+ if not os.path.exists(p): continue
248
+ df = pd.read_parquet(p)
249
+ if name == "actions": df["created_at"] = pd.to_datetime(df.created_at, format="mixed")
250
+ m = df.merge(sub[on + ["step"]].rename(columns={"step": "_s"}), on=on, how="left")
251
+ before = df.step.isna().sum()
252
+ both = m.dropna(subset=["step", "_s"])
253
+ agree = float((both.step.astype(int) == both._s.astype(int)).mean()) if len(both) else 1.0
254
+ m["step"] = m.step.where(m.step.notna(), m._s).astype("Int64")
255
+ m = m.drop(columns="_s")
256
+ if name == "actions": m["created_at"] = m.created_at.astype(str)
257
+ m.to_parquet(p, index=False, compression="zstd")
258
+ log[f"patch_{name}"] = dict(null_before=int(before), null_after=int(m.step.isna().sum()),
259
+ rows=len(m), agreement_on_overlap=round(agree, 5))
260
+ print(f" patched {name}: step NULL {before} -> {int(m.step.isna().sum())} of {len(m)}; overlap agreement {agree:.5f}")
261
+
262
+
263
+ if __name__ == "__main__":
264
+ main()
oasis/run_v9.py CHANGED
@@ -52,7 +52,7 @@ MODEL_B = os.getenv("MODEL_NAME_B", "openai/gpt-oss-20b")
52
  MODEL_C = os.getenv("MODEL_NAME_C", "mistralai/Magistral-Small-2509")
53
  MODEL_D = os.getenv("MODEL_NAME_D", "zai-org/GLM-4-32B-0414")
54
 
55
- SEED_DB = "/data/user_data/droytbur/oasis/data/mock-dbs/hf-zero-50.sqlite"
56
 
57
 
58
  def write_metadata(db_path: str, mode: str, n_agents: int, n_initial: int,
 
52
  MODEL_C = os.getenv("MODEL_NAME_C", "mistralai/Magistral-Small-2509")
53
  MODEL_D = os.getenv("MODEL_NAME_D", "zai-org/GLM-4-32B-0414")
54
 
55
+ SEED_DB = os.environ.get("SEED_DB", "data/mock-dbs/hf-zero-50.sqlite")
56
 
57
 
58
  def write_metadata(db_path: str, mode: str, n_agents: int, n_initial: int,