File size: 34,754 Bytes
dbe304f
 
 
3c45056
 
 
cfa6ce6
dbe304f
 
 
3c45056
 
dbe304f
 
 
 
3c45056
 
 
dbe304f
 
 
 
 
3c45056
 
 
 
 
dbe304f
 
 
 
 
 
 
 
3c45056
 
dbe304f
 
 
3c45056
 
 
dbe304f
cfa6ce6
dbe304f
 
 
 
3c45056
 
 
 
 
dbe304f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78b2e7f
 
dbe304f
 
 
 
 
 
 
 
 
cfa6ce6
 
 
 
dbe304f
cfa6ce6
 
 
 
dbe304f
cfa6ce6
 
dbe304f
 
 
 
 
 
 
cfa6ce6
dbe304f
cfa6ce6
 
 
 
 
dbe304f
 
 
 
 
 
 
 
78b2e7f
dbe304f
 
78b2e7f
dbe304f
 
78b2e7f
dbe304f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c45056
 
 
 
 
dbe304f
 
 
3c45056
 
 
 
 
dbe304f
 
 
 
 
 
 
 
 
 
cfa6ce6
 
dbe304f
 
3c45056
 
dbe304f
 
 
3c45056
dbe304f
 
 
 
 
 
 
 
3c45056
 
dbe304f
 
 
 
 
3c45056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe304f
 
3c45056
dbe304f
 
3c45056
 
 
dbe304f
3c45056
dbe304f
 
 
3c45056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe304f
3c45056
dbe304f
3c45056
cfa6ce6
3c45056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe304f
3c45056
dbe304f
 
3c45056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa6ce6
3c45056
cfa6ce6
3c45056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfa6ce6
 
3c45056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe304f
3c45056
 
 
dbe304f
 
 
 
 
3c45056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbe304f
 
 
 
 
 
 
 
 
3c45056
 
 
 
dbe304f
 
 
cfa6ce6
 
dbe304f
 
 
cfa6ce6
3c45056
 
 
 
 
 
 
 
cfa6ce6
 
 
 
3c45056
 
 
 
dbe304f
 
 
 
 
 
 
 
3c45056
dbe304f
 
 
 
 
 
 
 
 
3c45056
dbe304f
 
 
 
 
 
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
"""Build the mid-training candidate pool (Hub dataset MINZIK77/midtraining-pool), one config per source.

usage:
  python build_pool.py probe NAME [--rows 40]          # parse a few rows of one file, print a normalized row and counts
  python build_pool.py build NAME [NAME ...] [--upload] [--workers N]
                                                       # all files -> OUT/data/NAME/train-*.parquet + OUT/stats/NAME.json
  python build_pool.py upload [NAME ...]               # data + stats + this script -> the Hub repo (README: make_card.py)

Each row is one agent trajectory in one schema for all sources:
  id, source, task_id, repo, scaffold, outcome, group, messages[{role, content, reasoning, tool_calls, tool_call_id,
  name}], tools, n_messages, n_chars, n_tokens_sigdig, n_tokens_smollm3, content_hash
- id: source/file/row for parquet sources, source/file@byte_offset for jsonl sources.
- messages keep the source text. Roles are mapped to system / user / assistant / tool. tool_calls is a JSON list of
  {id, name, arguments}; tools is the source's tool definitions as JSON text.
- outcome: "resolved" / "failed" when the source labels the run (verified, resolved, reward), "incomplete" when the
  source records that the run stopped with an error (for example a timeout), else "unlabeled".
- n_chars, n_tokens_*: characters and tokens of a ChatML rendering (tools as one system turn; reasoning, content and
  tool calls of each turn), with allenai/dolma2-tokenizer-sigdig @86d32e8 and HuggingFaceTB/SmolLM3-3B, no special
  tokens added.
- content_hash: blake2b-64 of that rendering, for deduplication inside and across sources.
Filters (light; the training mix selects further):
- rows with no assistant turn or that do not parse;
- rows of the 12 SWE-bench repositories, also forks with the same name (matched on the repository basename);
- exact duplicates of the rendering inside a source (the first one stays, in file order).
Sources are read at a pinned commit. Files are downloaded and cut into work units (parquet row groups of at most
SLICE_ROWS rows, after re-chunking larger ones in one streaming pass; jsonl byte ranges), converted in parallel
processes, then deduplicated and written as shards of about 1.5 GB of text.
Shared hosts: every process sets oom_score_adj 1000 (the kernel kills these first), new units wait while the
cgroup's anonymous memory is above MEMORY_SHARE of its limit, and each downloaded file is deleted when its units end.
"""
import argparse
import hashlib
import json
import os
import shutil
import sys
import time
from collections import deque
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, ThreadPoolExecutor, wait
from pathlib import Path

HERE = Path(__file__).resolve().parent
TOKDIR = Path(os.environ.get("POOL_TOK", HERE.parent / "datasize" / "tok"))
OUT = Path(os.environ["POOL_OUT"]) if "POOL_OUT" in os.environ else HERE.parents[3] / "build" / "pool_repo"
TMP = Path(os.environ["POOL_TMP"]) if "POOL_TMP" in os.environ else HERE.parents[3] / "build" / "pool_tmp"
REPO = "MINZIK77/midtraining-pool"
CATEGORY = "trajectory"  # data/CATEGORY/NAME/ and config CATEGORY-NAME (this script builds the trajectory category)
SWEB = {"astropy", "django", "matplotlib", "seaborn", "flask", "requests", "xarray", "pylint",
        "pytest", "scikit-learn", "sphinx", "sympy"}
ROLE = {"gpt": "assistant", "human": "user", "model": "assistant", "function": "tool", "observation": "tool",
        "ipython": "tool", "tool_response": "tool"}
SLICE_ROWS = 512  # parquet work unit: one row group of at most this many rows (larger row groups are re-chunked)
CHUNK_BYTES = 32 << 20  # jsonl work unit: lines that start in this many bytes
TOKEN_BATCH = 32  # rows per tokenizer call (only the lengths are kept)
SHARD_CHARS = 1_500_000_000  # output shard: about this much rendered text
MEMORY_SHARE = 0.4  # do not start new work units while the cgroup's anonymous memory is above this share of its limit


def repo_base(s):
    if not s:
        return None
    s = str(s).lower()
    if "__" in s:  # owner__repo-123 / owner__repo.hash.task
        s = s.split("__", 1)[1]
        for sep in (".", "-"):
            head = s.split(sep)[0]
            if head in SWEB:
                return head
        return s.split(".")[0]
    return s.rstrip("/").split("/")[-1]


def is_sweb(*names):
    for n in names:
        b = repo_base(n)
        if b and (b in SWEB or any(b.startswith(x + "-") for x in SWEB if x not in ("requests", "flask"))):
            return True
    return False


def flag(v, true_values=(1, True)):
    return "resolved" if v in true_values else "failed"


def trove_outcome(r, p):
    v = r.get("result")
    if v in (None, "None", ""):
        return "unlabeled"
    try:
        return "resolved" if float(v) >= 1.0 else "failed"
    except ValueError:
        return "incomplete"  # AgentTimeoutError, DaytonaError, ...


# name -> spec. kind pq | jsonl. msgs: field with the turns. outcome/task/repo/group: functions of (row, path).
SOURCES = {
    "nanoswe": dict(ds="nanoswe/nanoswe-trajs-261002", kind="pq", glob="train-*.parquet", license="mit",
                    cols=["messages", "verified", "instance_id"], msgs="messages",
                    scaffold="not named (tools: bash, file_editor)",
                    outcome=lambda r, p: flag(bool(r["verified"])), task=lambda r, p: r["instance_id"]),
    "minicoder": dict(ds="ricdomolm/mini-coder-trajs-400k", kind="pq", glob="data/*.parquet", license="mit",
                      cols=["messages", "verified", "instance_id"], msgs="messages", scaffold="mini-swe-agent",
                      outcome=lambda r, p: flag(bool(r["verified"])), task=lambda r, p: r["instance_id"]),
    "klear": dict(ds="Kwai-Klear/SWE-smith-mini_swe_agent_plus-trajectories-66k", kind="pq", glob="data/*.parquet",
                  license="mit", cols=["messages", "instance_id"], msgs="messages", scaffold="mini-swe-agent-plus",
                  task=lambda r, p: r["instance_id"]),
    "openswe": dict(ds="nvidia/Open-SWE-Traces", kind="pq", glob="data/**/*.parquet", license="cc-by-4.0",
                    cols=["messages", "tools", "resolved", "repo", "instance_id"], msgs="messages", tools="tools",
                    # resolved: 1 solved, 0 not solved, -1 information unavailable (card)
                    scaffold="see group",
                    outcome=lambda r, p: {1: "resolved", 0: "failed"}.get(r["resolved"], "unlabeled"),
                    task=lambda r, p: r["instance_id"],
                    repo=lambda r, p: r["repo"], group=lambda r, p: "/".join(p.split("/")[1:-1])),
    # filtered_reward1-* is a second copy of the reward-1 runs (its own split on the card), so it is not read.
    "coderforge": dict(ds="togethercomputer/CoderForge-Preview", kind="pq",
                       glob=["trajectories/R2E_Gym-*.parquet", "trajectories/SWE_Rebench-*.parquet",
                             "trajectories/SWE_Smith-*.parquet"],
                       license="none stated", cols=["messages", "tools", "reward", "image"], msgs="messages",
                       tools="tools", scaffold="single scaffold (not named on the card)",
                       group=lambda r, p: p.split("/")[-1].split("-")[0],
                       outcome=lambda r, p: "resolved" if (r["reward"] or 0) >= 1.0 else "failed",
                       task=lambda r, p: (r["image"] or "").split("/")[-1] or None,
                       repo=lambda r, p: (r["image"] or "").split("/")[-1].split(":")[0].replace("_1776_", "__") or None),
    "nemoswe_v1": dict(ds="nvidia/Nemotron-SWE-v1", kind="jsonl", glob="data/r2e_gym.jsonl", license="cc-by-4.0",
                       msgs="messages", tools="tools", scaffold="openhands", repo=lambda r, p: r.get("repo")),
    "nemoswe_v2_oh": dict(ds="nvidia/Nemotron-SFT-SWE-v2", kind="jsonl", glob="data/swe.jsonl",
                          license="cc-by-4.0 (+ code licenses)", msgs="messages", tools="tools", scaffold="openhands"),
    # exit_status is 'submit' when the agent ended with its terminating action, else an OpenHands error message.
    "nebius_oh": dict(ds="nebius/SWE-rebench-openhands-trajectories", kind="pq", glob="*.parquet", license="cc-by-4.0",
                      cols=["trajectory", "tools", "resolved", "repo", "instance_id", "exit_status"], msgs="trajectory",
                      tools="tools", scaffold="openhands",
                      outcome=lambda r, p: "resolved" if r["resolved"] == 1 else
                      ("failed" if r.get("exit_status") == "submit" else "incomplete"),
                      task=lambda r, p: r["instance_id"],
                      repo=lambda r, p: r["repo"]),
    "swezero": dict(ds="nvidia/SWE-Zero-openhands-trajectories", kind="pq", glob="data/*.parquet", license="cc-by-4.0",
                    cols=["trajectory", "repo"], msgs="trajectory", scaffold="openhands", repo=lambda r, p: r["repo"]),
    "scaleswe": dict(ds="AweAI-Team/Scale-SWE-Distilled", kind="pq", glob="data/*.parquet", license="none stated",
                     cols=["messages", "system"], msgs="messages", system="system", scaffold="unspecified"),
    "sera": dict(ds="allenai/SERA-4.6-Lite-Best-Subset", kind="jsonl", glob="*.jsonl", license="apache-2.0",
                 msgs="messages", scaffold="unspecified", task=lambda r, p: r.get("instance_id")),
    "terminal": dict(ds="nvidia/Nemotron-Terminal-Corpus", kind="pq", glob="**/*.parquet", license="cc-by-4.0",
                     cols=["conversations"], msgs="conversations", scaffold="not named",
                     group=lambda r, p: "/".join(p.split("/")[:-1]) or None),
    "otagent": dict(ds="open-thoughts/OpenThoughts-Agent-SFT-100K", kind="pq", glob="data/*.parquet",
                    license="apache-2.0", cols=["conversations"], msgs="conversations", scaffold="terminus-2"),
    "agenttrove": dict(ds="open-thoughts/AgentTrove", kind="pq", glob="data/*.parquet", license="apache-2.0",
                       cols=["conversations", "result", "original_source", "trace_source"], msgs="conversations",
                       scaffold="terminus-2 (Harbor)", outcome=trove_outcome,
                       group=lambda r, p: "/".join(str(x) for x in (r.get("original_source"), r.get("trace_source")) if x)),
    "opencode": dict(ds="nvidia/Nemotron-SFT-OpenCode-v1", kind="jsonl", glob="*/data.jsonl", license="cc-by-4.0",
                     msgs="messages", tools="tools", scaffold="opencode", group=lambda r, p: p.split("/")[-2]),
}


def text_of(c):
    if c is None:
        return ""
    if isinstance(c, str):
        return c
    if isinstance(c, list):
        return "".join(x.get("text", "") if isinstance(x, dict) else str(x) for x in c)
    if isinstance(c, dict):
        return c.get("text") if isinstance(c.get("text"), str) else json.dumps(c, ensure_ascii=False, default=str)
    return str(c)


def opt(v):
    return None if v is None or v == "" else str(v)


def norm_messages(msgs, system=None):
    if isinstance(msgs, str):
        msgs = json.loads(msgs)
    out = []
    if system and not any(isinstance(m, dict) and (m.get("role") or m.get("from")) == "system" for m in msgs or []):
        out.append(dict(role="system", content=str(system), reasoning=None, tool_calls=None, tool_call_id=None, name=None))
    for m in msgs or []:
        if not isinstance(m, dict):
            continue
        role = m.get("role") or m.get("from") or ""
        role = ROLE.get(role, role)
        content = text_of(m.get("content", m.get("value")))
        for part in m.get("parts") or []:
            content += part.get("text", "") if isinstance(part, dict) else str(part)
        calls = m.get("tool_calls")
        if isinstance(calls, str):
            calls = json.loads(calls) if calls.strip() else None
        norm = []
        for tc in calls or []:
            fn = tc.get("function", tc) if isinstance(tc, dict) else {}
            args = fn.get("arguments")
            norm.append({"id": tc.get("id") if isinstance(tc, dict) else None, "name": fn.get("name"),
                         "arguments": args if isinstance(args, str) or args is None else json.dumps(args, ensure_ascii=False, default=str)})
        out.append(dict(role=str(role), content=content, reasoning=opt(m.get("reasoning_content") or m.get("reasoning")),
                        tool_calls=json.dumps(norm, ensure_ascii=False) if norm else None,
                        tool_call_id=opt(m.get("tool_call_id")), name=opt(m.get("name"))))
    return out


def norm_tools(t):
    if t is None:
        return None
    if isinstance(t, str):
        return t or None
    if isinstance(t, (list, tuple)):
        if not t:
            return None
        if all(isinstance(x, str) for x in t):
            try:
                return json.dumps([json.loads(x) for x in t], ensure_ascii=False)
            except ValueError:
                return "\n".join(t)
    return json.dumps(t, ensure_ascii=False, default=str)


def render(messages, tools):
    s = [f"<|im_start|>system\n# Tools\n{tools}<|im_end|>\n"] if tools else []
    for m in messages:
        parts = [p for p in (m["reasoning"], m["content"]) if p]
        for c in json.loads(m["tool_calls"]) if m["tool_calls"] else []:
            parts.append(json.dumps({"name": c["name"], "arguments": c["arguments"]}, ensure_ascii=False))
        s.append(f"<|im_start|>{m['role']}\n" + "\n".join(parts) + "<|im_end|>\n")
    return "".join(s)


def schema():
    import pyarrow as pa
    msg = pa.struct([("role", pa.string()), ("content", pa.string()), ("reasoning", pa.string()),
                     ("tool_calls", pa.string()), ("tool_call_id", pa.string()), ("name", pa.string())])
    return pa.schema([("id", pa.string()), ("source", pa.string()), ("task_id", pa.string()), ("repo", pa.string()),
                      ("scaffold", pa.string()), ("outcome", pa.string()), ("group", pa.string()),
                      ("messages", pa.list_(msg)), ("tools", pa.string()), ("n_messages", pa.int32()),
                      ("n_chars", pa.int64()), ("n_tokens_sigdig", pa.int32()), ("n_tokens_smollm3", pa.int32()),
                      ("content_hash", pa.string())])


_TOK = None


def tokenizers():
    global _TOK
    if _TOK is None:
        from tokenizers import Tokenizer
        _TOK = Tokenizer.from_file(str(TOKDIR / "sigdig.json")), Tokenizer.from_file(str(TOKDIR / "smollm3.json"))
    return _TOK


def revision(ds):
    from huggingface_hub import HfApi
    return HfApi().dataset_info(ds).sha


def list_files(spec, rev):
    from huggingface_hub import HfFileSystem
    base = f"datasets/{spec['ds']}@{rev}"
    globs = spec["glob"] if isinstance(spec["glob"], list) else [spec["glob"]]
    return sorted({p[len(base) + 1:] for g in globs for p in HfFileSystem().glob(f"{base}/{g}")})


def convert(name, spec, rel, key, r):
    """One source row -> one pool row (without the rendering columns), or the drop reason."""
    try:
        messages = norm_messages(r[spec["msgs"]], r.get(spec["system"]) if spec.get("system") else None)
        tools = norm_tools(r.get(spec["tools"])) if spec.get("tools") else None
    except (ValueError, TypeError, AttributeError, KeyError):
        return "parse_error"
    if not any(m["role"] == "assistant" for m in messages):
        return "no_assistant"
    task = opt(spec["task"](r, rel)) if spec.get("task") else None
    repo = opt(spec["repo"](r, rel)) if spec.get("repo") else None
    if is_sweb(repo, task):
        return "swebench"
    group = opt(spec["group"](r, rel)) if spec.get("group") else None
    sep = "@" if spec["kind"] == "jsonl" else "/"
    return dict(id=f"{name}/{rel}{sep}{key}", source=name, task_id=task, repo=repo,
                scaffold=group.split("/")[0] if spec["scaffold"] == "see group" and group else spec["scaffold"],
                outcome=spec["outcome"](r, rel) if spec.get("outcome") else "unlabeled", group=group,
                messages=messages, tools=tools, n_messages=len(messages))


# ---------------------------------------------------------------- shared-host guards
def low_priority():
    """Ask the kernel to kill these processes first if memory runs out (other jobs share the host)."""
    try:
        with open("/proc/self/oom_score_adj", "w") as f:
            f.write("1000")
    except OSError:
        pass


def memory_ok():
    """False while the cgroup's anonymous memory is above MEMORY_SHARE of its limit (cgroup v2; else True)."""
    try:
        limit = open("/sys/fs/cgroup/memory.max").read().strip()
        if limit == "max":
            limit = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
        anon = next(int(line.split()[1]) for line in open("/sys/fs/cgroup/memory.stat") if line.startswith("anon "))
        return anon < MEMORY_SHARE * int(limit)
    except (OSError, StopIteration, ValueError):
        return True


# ---------------------------------------------------------------- work units
def fetch(spec, rev, rel):
    from huggingface_hub import hf_hub_download
    for attempt in range(5):
        try:
            return hf_hub_download(spec["ds"], rel, repo_type="dataset", revision=rev,
                                   local_dir=str(TMP / spec["ds"].replace("/", "__")))
        except Exception as error:  # network or Hub errors
            if attempt == 4:
                raise
            print(f"download {rel} failed ({type(error).__name__}), retry", flush=True)
            time.sleep(30 * (attempt + 1))


def units_of(spec, path):
    """Work units of a file: ("pq", row group, first row) or ("jsonl", start, end); None if it needs re-chunking."""
    if spec["kind"] == "pq":
        import pyarrow.parquet as pq
        meta = pq.ParquetFile(path).metadata
        sizes = [meta.row_group(rg).num_rows for rg in range(meta.num_row_groups)]
        if any(n > SLICE_ROWS for n in sizes):
            return None
        bases = [sum(sizes[:rg]) for rg in range(len(sizes))]
        return [("pq", rg, base) for rg, base in enumerate(bases) if sizes[rg]]
    size = os.path.getsize(path)
    return [("jsonl", s, min(size, s + CHUNK_BYTES)) for s in range(0, size, CHUNK_BYTES)]


def rechunk(name, path):
    """Stream a parquet file (only the needed columns) into files of SLICE_ROWS rows, one row group each.
    Returns [(chunk path, first row in the source file)]. Memory stays at a few batches."""
    import pyarrow as pa
    import pyarrow.parquet as pq
    low_priority()
    spec = SOURCES[name]
    out = Path(f"{path}.chunks")
    shutil.rmtree(out, ignore_errors=True)
    out.mkdir()
    pf = pq.ParquetFile(path, pre_buffer=False, buffer_size=8 << 20)
    chunks, buf, rows, first = [], [], 0, 0
    for batch in pf.iter_batches(batch_size=64, columns=spec["cols"]):
        buf.append(batch)
        rows += batch.num_rows
        if rows >= SLICE_ROWS:
            table = pa.Table.from_batches(buf)
            head, rest = table.slice(0, SLICE_ROWS), table.slice(SLICE_ROWS)
            p = out / f"{len(chunks):06d}.parquet"
            pq.write_table(head, p, compression="lz4", row_group_size=SLICE_ROWS)
            chunks.append((str(p), first))
            first += SLICE_ROWS
            buf, rows = (rest.to_batches() if rest.num_rows else []), rest.num_rows
    if rows:
        p = out / f"{len(chunks):06d}.parquet"
        pq.write_table(pa.Table.from_batches(buf), p, compression="lz4", row_group_size=SLICE_ROWS)
        chunks.append((str(p), first))
    os.remove(path)
    return chunks


def read_unit(spec, path, unit):
    """(key, row) pairs of one unit. A jsonl line belongs to the unit in which its first byte lies."""
    if unit[0] == "pq":
        import pyarrow.parquet as pq
        _, rg, base = unit
        cols = spec["cols"] if not path.endswith(".chunks") and ".chunks/" not in path else None
        table = pq.ParquetFile(path).read_row_group(rg, columns=cols)
        for i, r in enumerate(table.to_pylist()):
            yield base + i, r
        return
    _, start, end = unit
    with open(path, "rb") as f:
        if start:
            f.seek(start - 1)
            f.readline()  # skip the line that started before this unit
        while True:
            pos = f.tell()
            if pos >= end:
                return
            line = f.readline()
            if not line:
                return
            if line.strip():
                yield pos, json.loads(line)


def run_unit(name, rel, path, unit, order):
    """Convert one unit into OUT/parts/NAME/ORDER.parquet. ORDER sorts the parts in file order."""
    import pyarrow as pa
    import pyarrow.parquet as pq
    low_priority()
    spec = SOURCES[name]
    sig, smol = tokenizers()
    counts = dict(rows=0, kept=0, parse_error=0, no_assistant=0, swebench=0)
    rows = []
    for key, r in read_unit(spec, path, unit):
        counts["rows"] += 1
        row = convert(name, spec, rel, key, r)
        if isinstance(row, str):
            counts[row] += 1
            continue
        rows.append(row)
    counts["kept"] = len(rows)
    if rows:
        for i in range(0, len(rows), TOKEN_BATCH):
            batch = rows[i:i + TOKEN_BATCH]
            texts = [render(x["messages"], x["tools"]) for x in batch]
            a = [len(e.ids) for e in sig.encode_batch_fast(texts, add_special_tokens=False)]
            b = [len(e.ids) for e in smol.encode_batch_fast(texts, add_special_tokens=False)]
            for x, t, na, nb in zip(batch, texts, a, b, strict=True):
                x.update(n_chars=len(t), n_tokens_sigdig=na, n_tokens_smollm3=nb,
                         content_hash=hashlib.blake2b(t.encode("utf-8"), digest_size=8).hexdigest())
        out = OUT / "parts" / name
        out.mkdir(parents=True, exist_ok=True)
        pq.write_table(pa.Table.from_pylist(rows, schema=schema()), out / f"{order:012d}.parquet",
                       compression="zstd", compression_level=6, row_group_size=256)
    return counts


def compact(name, shard, parts, keeps):
    """Write the kept rows of consecutive parts as OUT/data/NAME/train-SHARD.parquet. Returns sums of the kept rows."""
    import pyarrow as pa
    import pyarrow.compute as pc
    import pyarrow.parquet as pq
    low_priority()
    out = OUT / "data" / CATEGORY / name / f"train-{shard:05d}.parquet"
    sums = dict(rows=0, chars=0, tokens_sigdig=0, tokens_smollm3=0, outcomes={})
    with pq.ParquetWriter(out, schema(), compression="zstd", compression_level=6) as writer:
        for part, keep in zip(parts, keeps, strict=True):
            table = pq.read_table(part).filter(pa.array(keep))
            writer.write_table(table, row_group_size=256)
            sums["rows"] += table.num_rows
            sums["chars"] += pc.sum(table["n_chars"]).as_py() or 0
            sums["tokens_sigdig"] += pc.sum(table["n_tokens_sigdig"]).as_py() or 0
            sums["tokens_smollm3"] += pc.sum(table["n_tokens_smollm3"]).as_py() or 0
            for k, v in zip(*pc.value_counts(table["outcome"]).flatten(), strict=True):
                sums["outcomes"][k.as_py()] = sums["outcomes"].get(k.as_py(), 0) + v.as_py()
    return sums


def plan_shards(name):
    """Keep masks (first copy of each content_hash in part order) and the parts of each shard."""
    import pyarrow.parquet as pq
    parts = sorted((OUT / "parts" / name).glob("*.parquet"))
    seen, shards, cur, size, dropped = set(), [], [], 0, 0
    for part in parts:
        t = pq.read_table(part, columns=["content_hash", "n_chars"])
        keep = []
        for h in t["content_hash"].to_pylist():
            keep.append(h not in seen)
            seen.add(h)
        dropped += keep.count(False)
        cur.append((part, keep))
        size += sum(c for c, k in zip(t["n_chars"].to_pylist(), keep, strict=True) if k)
        if size >= SHARD_CHARS:
            shards.append(cur)
            cur, size = [], 0
    if cur:
        shards.append(cur)
    return shards, dropped


# ---------------------------------------------------------------- driver
def build(names, workers, do_upload):
    """Download, convert, deduplicate, shard (and upload) every source in `names`, all through one process pool.
    At most `workers` process tasks run at a time, and no new unit starts while memory_ok() is False."""
    import multiprocessing
    low_priority()
    os.environ["RAYON_NUM_THREADS"] = "1"  # parallelism comes from the processes
    TMP.mkdir(parents=True, exist_ok=True)
    t0 = time.time()
    # spawn, not fork: the driver also runs download and upload threads
    procs = ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context("spawn"),
                                initializer=low_priority)
    downloads = ThreadPoolExecutor(max_workers=16)
    uploads = ThreadPoolExecutor(max_workers=1)
    state, pending, ready, file_left = {}, {}, deque(), {}
    busy = 0  # process tasks submitted and not done
    for name in names:
        spec = SOURCES[name]
        rev = revision(spec["ds"])
        files = list_files(spec, rev)
        for d in (OUT / "parts" / name, OUT / "data" / CATEGORY / name):
            shutil.rmtree(d, ignore_errors=True)
        (OUT / "data" / CATEGORY / name).mkdir(parents=True, exist_ok=True)
        state[name] = dict(spec=spec, rev=rev, files=files, open=len(files), units=0, done_units=0,
                           counts=dict(rows=0, kept=0, parse_error=0, no_assistant=0, swebench=0), shards=0, sums=[])
        print(f"[{name}] {spec['ds']}@{rev[:10]}: {len(files)} files", flush=True)
        for i, rel in enumerate(files):
            pending[downloads.submit(fetch, spec, rev, rel)] = ("download", name, (i, rel))

    def add_units(name, i, rel, path, units, base_order=0):
        file_left[path] = len(units)
        state[name]["units"] += len(units)
        for j, unit in enumerate(units):
            ready.append((name, rel, path, unit, i * 1_000_000 + base_order + j))
        if not units:
            os.remove(path)

    def finish(name):
        st = state[name]
        tot = {k: sum(s[k] for s in st["sums"]) for k in ("rows", "chars", "tokens_sigdig", "tokens_smollm3")}
        outcomes = {}
        for s in st["sums"]:
            for k, v in s["outcomes"].items():
                outcomes[k] = outcomes.get(k, 0) + v
        stats = dict(name=name, dataset=st["spec"]["ds"], revision=st["rev"], license=st["spec"]["license"],
                     scaffold=st["spec"]["scaffold"], files=len(st["files"]), built=time.strftime("%Y-%m-%d"),
                     rows=st["counts"]["rows"], kept=tot["rows"], parse_error=st["counts"]["parse_error"],
                     no_assistant=st["counts"]["no_assistant"], swebench=st["counts"]["swebench"],
                     duplicate=st["dropped"], outcomes=outcomes, chars=tot["chars"],
                     tokens_sigdig=tot["tokens_sigdig"], tokens_smollm3=tot["tokens_smollm3"], shards=st["shards"])
        (OUT / "stats" / CATEGORY).mkdir(parents=True, exist_ok=True)
        (OUT / "stats" / CATEGORY / f"{name}.json").write_text(json.dumps(stats, indent=1))
        shutil.rmtree(OUT / "parts" / name, ignore_errors=True)
        shutil.rmtree(TMP / st["spec"]["ds"].replace("/", "__"), ignore_errors=True)
        print(f"[{name}] done in {time.time() - t0:.0f}s: {json.dumps(stats)}", flush=True)
        if do_upload:
            pending[uploads.submit(upload, [name])] = ("upload", name, None)

    waited = 0.0
    while pending or ready:
        while ready and busy < workers:
            if not memory_ok():
                break
            name, rel, path, unit, order = ready.popleft()
            pending[procs.submit(run_unit, name, rel, path, unit, order)] = ("unit", name, path)
            busy += 1
        if not pending:  # only units left, held back by memory_ok()
            time.sleep(5)
            waited += 5
            continue
        done, _ = wait(list(pending), timeout=10, return_when=FIRST_COMPLETED)
        if not done and ready and not memory_ok():
            waited += 10
        for fut in done:
            kind, name, extra = pending.pop(fut)
            st = state[name]
            result = fut.result()  # an error stops the build
            if kind == "download":
                i, rel = extra
                units = units_of(st["spec"], result)
                if units is None:
                    pending[procs.submit(rechunk, name, result)] = ("rechunk", name, (i, rel))
                    busy += 1
                else:
                    st["open"] -= 1
                    add_units(name, i, rel, result, units)
            elif kind == "rechunk":
                busy -= 1
                i, rel = extra
                st["open"] -= 1
                for k, (chunk, first) in enumerate(result):
                    add_units(name, i, rel, chunk, [("pq", 0, first)], base_order=k * 1000)
            elif kind == "unit":
                busy -= 1
                st["done_units"] += 1
                for k in st["counts"]:
                    st["counts"][k] += result[k]
                file_left[extra] -= 1
                if file_left[extra] == 0:
                    os.remove(extra)
                    del file_left[extra]
                if st["done_units"] % 500 == 0:
                    print(f"[{name}] {st['done_units']}/{st['units']} units ({st['open']} files open), "
                          f"{st['counts']['kept']} rows, {time.time() - t0:.0f}s, memory waits {waited:.0f}s", flush=True)
            elif kind == "shard":
                busy -= 1
                st["sums"].append(result)
                if len(st["sums"]) == st["shards"]:
                    finish(name)
            elif kind == "upload":
                print(f"[{name}] uploaded", flush=True)
            if kind in ("download", "rechunk", "unit") and st["open"] == 0 and st["done_units"] == st["units"] \
                    and "dropped" not in st:
                shards, st["dropped"] = plan_shards(name)
                st["shards"] = len(shards)
                print(f"[{name}] {st['units']} units converted; {st['dropped']} duplicates; {len(shards)} shards",
                      flush=True)
                if not shards:
                    finish(name)
                for k, shard in enumerate(shards):
                    parts, keeps = zip(*shard, strict=True)
                    pending[procs.submit(compact, name, k, list(parts), list(keeps))] = ("shard", name, None)
                    busy += 1
    procs.shutdown()
    downloads.shutdown()
    uploads.shutdown()


# ---------------------------------------------------------------- probe, card, upload
def probe(name, rows):
    """Parse a few rows of the middle file by range requests and print one normalized row."""
    import pyarrow.parquet as pq
    from huggingface_hub import HfFileSystem
    spec = SOURCES[name]
    rev = revision(spec["ds"])
    files = list_files(spec, rev)
    rel = files[len(files) // 2]
    print(f"[{name}] {spec['ds']}@{rev[:10]} {len(files)} files; probing {rel}")
    path = f"datasets/{spec['ds']}@{rev}/{rel}"
    raw = []
    if spec["kind"] == "pq":
        with HfFileSystem().open(path, "rb", block_size=32 << 20) as f:
            for batch in pq.ParquetFile(f).iter_batches(batch_size=rows, columns=spec["cols"]):
                raw = batch.to_pylist()[:rows]
                break
    else:
        with HfFileSystem().open(path, "r", encoding="utf-8", block_size=8 << 20) as f:
            for i, line in enumerate(f):
                if i >= rows:
                    break
                if line.strip():
                    raw.append(json.loads(line))
    kept, reasons, outcomes = [], {}, {}
    for i, r in enumerate(raw):
        row = convert(name, spec, rel, i, r)
        if isinstance(row, str):
            reasons[row] = reasons.get(row, 0) + 1
            continue
        kept.append(row)
        outcomes[row["outcome"]] = outcomes.get(row["outcome"], 0) + 1
    if not kept:
        print("no row kept", reasons)
        return
    sig, _ = tokenizers()
    toks = [len(e.ids) for e in sig.encode_batch_fast([render(x["messages"], x["tools"]) for x in kept],
                                                      add_special_tokens=False)]
    print(f"kept {len(kept)} dropped {reasons} outcomes {outcomes}; tokens median {sorted(toks)[len(toks) // 2]}")


def upload(names):
    """Upload the built configs (data, stats) and this script. README.md and LICENSE.md are written by make_card.py
    from the cross-checked source facts, so this function does not touch them."""
    import fcntl
    from huggingface_hub import HfApi
    api = HfApi()
    names = names or sorted(p.stem for p in (OUT / "stats" / CATEGORY).glob("*.json"))
    with open(OUT / ".upload.lock", "w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        api.create_repo(REPO, repo_type="dataset", private=False, exist_ok=True)
        (OUT / "scripts").mkdir(exist_ok=True)
        shutil.copy(__file__, OUT / "scripts" / "build_pool.py")
        for attempt in range(3):  # one commit per call; the Hub skips content it already has on a retry
            try:
                api.upload_folder(repo_id=REPO, repo_type="dataset", folder_path=str(OUT),
                                  commit_message=f"Add {CATEGORY}: {', '.join(names)}",
                                  allow_patterns=["scripts/build_pool.py", *[f"stats/{CATEGORY}/{n}.json" for n in names],
                                                  *[f"data/{CATEGORY}/{n}/*" for n in names]],
                                  delete_patterns=[f"data/{CATEGORY}/{n}/*" for n in names])
                return
            except Exception as error:  # network or Hub errors
                print(f"upload attempt {attempt + 1} failed: {type(error).__name__}: {error}", flush=True)
                time.sleep(60)
    raise SystemExit(f"upload of {names} failed")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["probe", "build", "upload"])
    ap.add_argument("names", nargs="*")
    ap.add_argument("--rows", type=int, default=40)
    ap.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 4) - 2))
    ap.add_argument("--upload", action="store_true", help="build: upload each source after it is built")
    a = ap.parse_args()
    for n in a.names:
        if n not in SOURCES:
            sys.exit(f"unknown source {n}; known: {sorted(SOURCES)}")
    if a.cmd == "probe":
        for n in a.names or sorted(SOURCES):
            probe(n, a.rows)
    elif a.cmd == "build":
        build(a.names or sorted(SOURCES), a.workers, a.upload)
    else:
        upload(a.names)


if __name__ == "__main__":
    main()