File size: 29,675 Bytes
9cd89ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Parallel, resource-bounded build for big sizes: python build_pool.py 1000M [options]

Same filters and safety nets as build.py (process, probe and the relaxation ladder come from there).
What is different:
  - Jobs. A source whose estimated time (from work/100M/stats.json) exceeds --job-hours is split into
    shards (whole dataset files, or every k-th row). Jobs run longest first in at most --workers
    processes, at below-normal priority and with one thread each, so the machine stays usable.
  - Memory. Dedup keeps 8-byte keys per document (the md5 key and the LSH band keys build.Dedup
    uses) instead of datasketch's index, and each job only holds its own. A global pass over the key
    files with numpy then drops documents that repeat across jobs; the first occurrence in MIX order
    wins, and a document that matches any earlier one is dropped (build.Dedup only compares against
    kept ones, so this is marginally stricter). Jobs collect --overshoot extra words so that pass
    rarely leaves a source short, and the excess is trimmed.
    The scheduler waits to start jobs while free RAM is below --min-free-gb and stops the youngest job
    when it falls below --kill-free-gb; a stopped job resumes later.
  - Robustness. Each job checkpoints every --ckpt-seconds, after flushing its data, so a hard kill
    loses at most that interval. On a network error it reopens the stream and skips the documents
    already seen (the streams are deterministic: fixed seed and shard). A job that crashes restarts
    from its checkpoint up to --retries times. Rerunning the same command resumes everything and
    skips finished jobs.
Output: work/<size>/<source>.jsonl and <source>.topup.jsonl plus stats.json, which assemble.py reads as
before. Per-job files (data, keys, checkpoints, logs) live in work/<size>/jobs/.

Testing: --scale 0.002 multiplies every quota (output in work/<size>_x0.002/); a small --job-hours
forces shards.
"""
import argparse
import hashlib
import itertools
import json
import math
import multiprocessing as mp
import os
import re
import shutil
import statistics
import sys
import time
import traceback
from collections import Counter
from pathlib import Path

# one thread per process for numpy, BLAS and Arrow; spawned workers inherit these
for _v in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ.setdefault(_v, "1")

import numpy as np
import psutil
from datasketch import MinHash, MinHashLSH
from wordfreq import top_n_list

import build
import mix
import sources

ROOT = build.ROOT
_LSH = MinHashLSH(threshold=0.8, num_perm=64)  # build.Dedup's parameters; only b and r are used
BANDS, ROWS = _LSH.b, _LSH.r
_MH = MinHash(num_perm=64)  # reused permutations; building them per document is most of MinHash's cost
PERMS, SCHEME = _MH.permutations, _MH.scheme
# odd 64-bit multipliers that fold the ROWS values of a band into one key
MIXER = np.random.RandomState(7).randint(1, 2**62, size=ROWS, dtype=np.int64).astype(np.uint64) | np.uint64(1)
REC = np.dtype([("x", "<u8"), ("b", "<u8", (BANDS,)), ("w", "<u4")])
# not streamed through sources._ds (so they cannot be sharded), or row order matters (poetry)
NO_SHARD = {"tinystories", "tinydialogues", "tinyhelen", "poetry"}
# Gutenberg rows are whole books in ~300 MB row groups: filling the shuffle buffer from datasets'
# default 10 files at once peaks at 6 GB, from one file at 1.7 GB (and is faster)
INPUT_SHARDS = {"gutenberg_books": 1}
# expected peak RAM per worker (GB), measured: a streamed parquet source with a 20k-row shuffle
# buffer sits near 1.4. The scheduler raises these to the peaks it observes during the run.
MEM_GB = {"gutenberg_books": 2.0}
MEM_DEFAULT_GB = 1.5


def doc_keys(text):
    """The md5 key and the LSH band keys build.Dedup would use for this text, as 64-bit ints."""
    x = int.from_bytes(hashlib.md5(re.sub(r"\W+", "", text.lower()).encode()).digest()[:8], "little")
    w = text.lower().split()
    mh = MinHash(num_perm=64, permutations=PERMS, scheme=SCHEME)
    mh.update_batch([" ".join(w[i:i + 5]).encode() for i in range(max(len(w) - 4, 1))])
    hv = mh.hashvalues[:BANDS * ROWS].astype(np.uint64).reshape(BANDS, ROWS)
    with np.errstate(over="ignore"):
        return x, (hv * MIXER).sum(axis=1, dtype=np.uint64)


class Keys:
    """build.Dedup on plain sets of 64-bit keys: same decisions, a fraction of the memory."""

    def __init__(self):
        self.exact, self.bands = set(), [set() for _ in range(BANDS)]

    def load(self, path):
        if path.exists():
            recs = np.fromfile(path, dtype=REC)
            self.exact.update(recs["x"].tolist())
            for i, s in enumerate(self.bands):
                s.update(recs["b"][:, i].tolist())

    def seen(self, x, bands):
        if x in self.exact:
            return True
        self.exact.add(x)
        b = bands.tolist()
        if any(k in s for s, k in zip(self.bands, b)):
            return True
        for s, k in zip(self.bands, b):
            s.add(k)
        return False


def write_json(path, obj):
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(json.dumps(obj), encoding="utf-8")
    for i in range(20):  # Windows refuses the replace while another process has the file open
        try:
            os.replace(tmp, path)
            return
        except PermissionError:
            time.sleep(0.5)
    os.replace(tmp, path)


def read_json(path):
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return None


def apply_scale(scale, size):
    """--scale: multiply this size's quotas in memory (parent and every worker), for test runs."""
    if scale == 1:
        return
    i = mix.SIZES[size]
    for k, (g, q) in list(mix.MIX.items()):
        mix.MIX[k] = (g, tuple(v * scale if j == i else v for j, v in enumerate(q)))


def paths(jobs_dir, job):
    return {ext: jobs_dir / f"{job['id']}.{ext}" for ext in ("jsonl", "keys", "ckpt", "done", "log")}


def is_done(jobs_dir, job):
    d = read_json(paths(jobs_dir, job)["done"])
    return bool(d) and abs(d["quota_M"] - job["quota"] / 1e6) < 1e-6


# ---------------------------------------------------------------- worker side

def robust_stream(name, size, start, st, tries=8):
    """Yield the source's documents from index `start`; on a stream error reopen the stream and skip
    what was already yielded."""
    pos, fails = start, 0
    while True:
        try:
            for doc in itertools.islice(sources.REGISTRY[name](size), pos, None):
                pos += 1
                fails = 0
                yield doc
            return
        except Exception as e:
            fails += 1
            st["retries"] = st.get("retries", 0) + 1
            if fails > tries:
                raise
            wait = min(600, 15 * 2 ** fails)
            print(f"stream error at doc {pos} ({e!r}); retry {fails}/{tries} in {wait}s", flush=True)
            time.sleep(wait)


def consumed_docs(job, jobs_dir):
    """Where a top-up starts: after what its source's primary job read, when both read the same stream."""
    if not job["tag"] or list(job["shard"]) != [0, 1]:
        return 0
    d = read_json(jobs_dir / f"{job['name']}.s0of1.done")
    return d["scanned_docs"] if d else 0


def run_job(job, size, jobs_dir, ckpt_seconds):
    """build.build_source for one job, with checkpoints and resume."""
    p = paths(jobs_dir, job)
    if is_done(jobs_dir, job):
        return
    name, quota = job["name"], job["quota"]
    genre = mix.MIX[name][0]
    base = mix.TIERS[size]
    vocab = set(top_n_list("en", base["vocab"]))
    dedup = Keys()
    for seed in job["seeds"]:  # a top-up must not repeat its own source's primary files
        dedup.load(Path(seed))
    st = read_json(p["ckpt"])
    # resuming skips documents by position, so it is only valid on the very same stream
    stream = [list(job["shard"]), INPUT_SHARDS.get(name)]
    if st and (abs(st["quota"] - quota) > 1 or st.get("stream") != stream):
        st = None  # options changed since the checkpoint: start over
    openers = Counter()
    if st:
        # drop whatever was written after the last checkpoint, then rebuild state from the rest
        with p["jsonl"].open("r+b") as f:
            f.truncate(st["bytes"])
        with p["keys"].open("r+b") as f:
            f.truncate(st["kept"] * REC.itemsize)
        dedup.load(p["keys"])
        for line in p["jsonl"].open(encoding="utf-8"):
            openers[" ".join(json.loads(line)["text"].lower().split()[:4])] += 1
        print(f"resume at doc {st['seen_docs']}, {st['got'] / 1e6:.2f}M/{quota / 1e6:.2f}M words", flush=True)
    else:
        step, probe_report = build.probe(name, size, genre, base, vocab, quota)
        print(f"probe: start at ladder step {step}; {probe_report[-1]}", flush=True)
        st = dict(quota=quota, stream=stream, step=step, probe=probe_report, relaxed=[dict(step=step, at_words=0)],
                  got=0, scanned=0, kept=0, seen_docs=consumed_docs(job, jobs_dir), rej={}, seconds=0, retries=0,
                  bytes=0)
        p["jsonl"].write_bytes(b"")
        p["keys"].write_bytes(b"")
    step = st["step"]
    tier, cov = build.at_step(base, step)
    got, scanned, kept, seen = st["got"], st["scanned"], st["kept"], st["seen_docs"]
    rej = Counter(st["rej"])
    win_scanned = win_kept = win_docs = 0
    abort, t0, last, elapsed0 = None, time.time(), time.time(), st["seconds"]
    with p["jsonl"].open("ab") as f, p["keys"].open("ab") as kf:

        def save():
            for h in (f, kf):
                h.flush()
                os.fsync(h.fileno())
            st.update(step=step, got=got, scanned=scanned, kept=kept, seen_docs=seen, rej=dict(rej),
                      seconds=round(elapsed0 + time.time() - t0), bytes=f.tell())
            write_json(p["ckpt"], st)

        stream = robust_stream(name, size, seen, st) if got < quota else ()
        for doc in stream:
            seen += 1
            win_docs += 1
            w = build.doc_words(doc)
            scanned += w
            win_scanned += w
            if scanned > quota * mix.MAX_SCAN:
                abort = "scan_cap"
                break
            docs, why = build.process(doc, genre, tier, vocab, name, cov)
            if why:
                rej[why] += 1
            for text in docs:
                op = " ".join(text.lower().split()[:4])
                if genre != "poetry" and openers[op] >= max(5, 0.005 * kept):
                    rej["opener_cap"] += 1
                    continue
                x, bands = doc_keys(text)
                if dedup.seen(x, bands):
                    rej["duplicate"] += 1
                    win_scanned -= len(text.split())  # says nothing about the yield of what is left
                    continue
                openers[op] += 1
                kept += 1
                n = len(text.split())
                got += n
                win_kept += n
                f.write((json.dumps({"text": text, "genre": genre, "src": name}) + "\n").encode("utf-8"))
                rec = np.zeros(1, REC)
                rec["x"], rec["b"], rec["w"] = x, bands, n
                kf.write(rec.tobytes())
            if got >= quota:
                break
            if time.time() - last >= ckpt_seconds:
                save()
                last = time.time()
                print(f"{seen} docs, kept {kept}, {got / 1e6:.2f}M/{quota / 1e6:.2f}M words, "
                      f"step {step}, top rejections {rej.most_common(3)}", flush=True)
            if win_docs >= mix.WINDOW:
                # same rule as build.py: climb a ladder step when the recent yield cannot finish
                # within the scan budget, give up at the top of the ladder
                recent = win_kept / win_scanned if win_scanned > 0 else 0
                need = (quota - got) / recent if recent else float("inf")
                if win_scanned > 0 and need > quota * mix.MAX_SCAN - scanned:
                    if step + 1 < len(mix.LADDER):
                        step += 1
                        tier, cov = build.at_step(base, step)
                        st["relaxed"].append(dict(step=step, at_words=got))
                        print(f"yield {100 * recent:.1f}% too low, relaxing to step {step}", flush=True)
                    else:
                        abort = "projected_shortfall"
                        break
                win_scanned = win_kept = win_docs = 0
        save()
    stats = dict(job=job["id"], source=name + job["tag"], genre=genre, target_M=job["target"] / 1e6,
                 quota_M=quota / 1e6, words_M=round(got / 1e6, 3), docs=kept, scanned_docs=seen,
                 scanned_words_M=round(scanned / 1e6, 1), seconds=st["seconds"],
                 stopped="quota" if got >= quota else (abort or "source_exhausted"),
                 relaxation=st["relaxed"], probe=st["probe"], rejections=dict(rej.most_common()),
                 stream_retries=st.get("retries", 0))
    write_json(p["done"], stats)
    p["ckpt"].unlink(missing_ok=True)
    print(f"done: {stats['words_M']}M words, stopped by {stats['stopped']}", flush=True)


def worker(job, size, scale, ckpt_seconds, jobs_dir):
    jobs_dir = Path(jobs_dir)
    sys.stdout = sys.stderr = paths(jobs_dir, job)["log"].open("a", encoding="utf-8", buffering=1)
    print(f"== {job['id']} pid {os.getpid()} {time.strftime('%Y-%m-%d %H:%M:%S')}", flush=True)
    psutil.Process().nice(psutil.BELOW_NORMAL_PRIORITY_CLASS if os.name == "nt" else 10)
    try:
        import pyarrow
        pyarrow.set_cpu_count(1)
        pyarrow.set_io_thread_count(2)
    except Exception:
        pass
    apply_scale(scale, size)
    sources.SHARD = tuple(job["shard"])
    sources.INPUT_SHARDS.update(INPUT_SHARDS)
    try:
        run_job(job, size, jobs_dir, ckpt_seconds)
    except Exception:
        traceback.print_exc()
        sys.exit(1)


# ---------------------------------------------------------------- parent side

class Log:
    def __init__(self, path):
        self.f = path.open("a", encoding="utf-8", buffering=1)

    def __call__(self, msg):
        line = f"{time.strftime('%H:%M:%S')} {msg}"
        print(line, flush=True)
        self.f.write(line + "\n")


def seconds_per_word():
    """Build seconds per target word for each source, measured on the 100M build."""
    s = read_json(ROOT / "work" / "100M" / "stats.json") or {}
    rates = {r["source"]: r["seconds"] / (r["target_M"] * 1e6)
             for r in s.get("sources", []) if r.get("target_M") and "seconds" in r}
    default = statistics.median(rates.values()) if rates else 1e-4
    return lambda name: rates.get(name, default)


def plan_jobs(targets, tag, args, seeds_for):
    """Split each (source, words) into shards of at most --job-hours estimated time."""
    rate, jobs = seconds_per_word(), []
    for name, target in targets:
        if target <= 0:
            continue
        est = rate(name) * target
        k = 1 if name in NO_SHARD else max(1, min(args.max_shards, math.ceil(est / (args.job_hours * 3600))))
        for i in range(k):
            jobs.append(dict(id=f"{name}{tag}.s{i}of{k}", name=name, tag=tag, shard=(i, k), target=target / k,
                             quota=target / k * (1 + args.overshoot), est=est / k, seeds=seeds_for(name)))
    return jobs


def run_pool(jobs, args, size, jobs_dir, log):
    """Run jobs in at most --workers processes, longest first, within the RAM and disk limits.
    Returns the jobs that failed more than --retries times."""
    pending = sorted((j for j in jobs if not is_done(jobs_dir, j)), key=lambda j: -j["est"])
    if not pending:
        return []
    total_est = sum(j["est"] for j in pending)
    log(f"{len(pending)} jobs to run ({len(jobs) - len(pending)} already done), about "
        f"{total_est / 3600:.1f} CPU hours by the 100M rates, {args.workers} workers")
    ctx = mp.get_context("spawn")
    running, attempts, failed = {}, Counter(), []
    # a job stopped twice for memory runs alone from then on, otherwise it could be stopped forever
    mem_stops, alone = Counter(), set()
    peak = Counter()  # observed peak RSS per source, GB
    hold = kill_hold = last_status = 0.0

    def need(job):
        return max(MEM_GB.get(job["name"], MEM_DEFAULT_GB), peak[job["name"]])

    def rss(proc):
        try:
            return psutil.Process(proc.pid).memory_info().rss / 1e9
        except psutil.Error:
            return 0.0

    def stop(jid, why):
        proc, job, _ = running.pop(jid)
        proc.terminate()
        proc.join()
        pending.insert(0, job)
        log(f"stopped {jid} ({why}); it resumes from its checkpoint")

    def pick(free, reserved):
        """First pending job whose expected peak leaves the stop threshold clear, so a big job that
        does not fit yet does not hold back smaller ones; a job marked to run alone waits for the rest."""
        if alone & set(running):
            return None
        for j in pending:
            if j["id"] in alone:
                return j if not running else None
            if not running or free - reserved - need(j) >= args.kill_free_gb + 0.5:
                return j
        return None

    try:
        while pending or running:
            now = time.time()
            for jid, (proc, job, _) in list(running.items()):
                if proc.is_alive():
                    continue
                proc.join()
                del running[jid]
                d = read_json(paths(jobs_dir, job)["done"])
                if d:
                    log(f"done {jid}: {d['words_M']}M words in {d['seconds'] / 60:.0f} min, stopped by {d['stopped']}")
                    continue
                attempts[jid] += 1
                if attempts[jid] > args.retries:
                    failed.append(job)
                    log(f"FAILED {jid} after {attempts[jid]} attempts, see {paths(jobs_dir, job)['log']}")
                else:
                    pending.insert(0, job)
                    hold = max(hold, now + 30)
                    log(f"{jid} exited with code {proc.exitcode}; restart {attempts[jid]}/{args.retries}")
            free = psutil.virtual_memory().available / 1e9
            # memory a running job is still expected to take (it grows while its buffers fill)
            reserved = 0.0
            for proc, job, _ in running.values():
                r = rss(proc)
                peak[job["name"]] = max(peak[job["name"]], r)
                reserved += max(0.0, need(job) - r)
            disk = shutil.disk_usage(jobs_dir).free / 1e9
            if disk < args.min_disk_gb:
                for jid in list(running):
                    stop(jid, f"only {disk:.1f} GB free on disk")
                raise SystemExit(f"stopped: {disk:.1f} GB free on disk, below --min-disk-gb {args.min_disk_gb}. "
                                 "Free space and rerun the same command to resume.")
            # the last running job is never stopped: that would only trade progress for nothing
            if free < args.kill_free_gb and len(running) > 1 and now >= kill_hold:
                # one job at a time, then give the OS time to reclaim its memory before judging again
                jid = max(running, key=lambda j: running[j][2])
                stop(jid, f"free RAM {free:.1f} GB < {args.kill_free_gb}")
                mem_stops[jid] += 1
                if mem_stops[jid] >= 2 and jid not in alone:
                    alone.add(jid)
                    log(f"{jid} will run alone: it was stopped {mem_stops[jid]} times for memory")
                hold, kill_hold = now + 120, now + 30
            elif (len(running) < args.workers and pending and now >= hold and free >= args.min_free_gb
                  and (job := pick(free, reserved))):
                pending.remove(job)
                proc = ctx.Process(target=worker, args=(job, size, args.scale, args.ckpt_seconds, str(jobs_dir)))
                proc.start()
                running[job["id"]] = (proc, job, now)
                hold = now + args.stagger
                log(f"start {job['id']} (est {job['est'] / 60:.0f} min, ~{need(job):.1f} GB)")
            if now - last_status >= args.status_seconds:
                last_status = now
                parts = []
                for jid, (proc, job, _) in running.items():
                    ck = read_json(paths(jobs_dir, job)["ckpt"])
                    prog = f"{100 * ck['got'] / job['quota']:.0f}%" if ck else "probe"
                    parts.append(f"{jid} {prog} {rss(proc):.1f}GB")
                log(f"status: {len(pending)} pending, free RAM {free:.1f} GB | " + " | ".join(parts))
            time.sleep(2)
    except KeyboardInterrupt:
        for proc, _, _ in running.values():
            proc.terminate()
        log("interrupted; rerun the same command to resume")
        raise SystemExit(130)
    return failed


def global_pass(groups, jobs_dir, out_dir, log, write):
    """groups: [(output file, [job, ...])] in priority order. Drops documents whose md5 key or any band
    key appeared in an earlier document, then keeps each job's documents in order until its target.
    With `write`, writes the output files. Returns {job id: report}."""
    jobs = [j for _, js in groups for j in js if is_done(jobs_dir, j)]
    recs = [np.fromfile(paths(jobs_dir, j)["keys"], dtype=REC) for j in jobs]
    allr = np.concatenate(recs) if recs else np.zeros(0, REC)
    order = np.arange(len(allr))
    dup = np.zeros(len(allr), bool)
    for col in [allr["x"]] + [allr["b"][:, i] for i in range(BANDS)]:
        _, first, inv = np.unique(col, return_index=True, return_inverse=True)
        dup |= first[inv.ravel()] != order
    avail, off = {}, 0
    for j, r in zip(jobs, recs):
        avail[j["id"]] = int(r["w"][~dup[off:off + len(r)]].sum(dtype=np.int64))
        off += len(r)
    # the shards of a source share its target: what one lost to duplicates, another with spare words fills
    budget = {}
    for _, js in groups:
        short = sum(max(0, j["target"] - avail[j["id"]]) for j in js if j["id"] in avail)
        for j in js:
            if j["id"] in avail:
                add = min(max(0, avail[j["id"]] - j["target"]), short)
                budget[j["id"]] = j["target"] + add
                short -= add
    report, masks, off = {}, {}, 0
    for j, r in zip(jobs, recs):
        d, w = dup[off:off + len(r)], r["w"].astype(np.int64)
        off += len(r)
        keep = ~d
        kw = np.where(keep, w, 0)
        before = np.cumsum(kw) - kw
        trimmed = keep & (before >= budget[j["id"]])
        keep &= ~trimmed
        masks[j["id"]] = keep
        report[j["id"]] = dict(docs=int(keep.sum()), words=int(w[keep].sum()), dup_docs=int(d.sum()),
                               dup_words=int(w[d].sum()), trimmed_words=int(w[trimmed].sum()))
    log(f"global dedup over {len(allr)} docs: {int(dup.sum())} duplicates across jobs, "
        f"{sum(r['trimmed_words'] for r in report.values()) / 1e6:.2f}M words trimmed to quota")
    if write:
        wanted = {fname for fname, _ in groups}
        for fname, js in groups:
            tmp = out_dir / (fname + ".tmp")
            with tmp.open("wb") as dst:
                for j in js:
                    if j["id"] not in masks:
                        continue
                    mask, n = masks[j["id"]], 0
                    with paths(jobs_dir, j)["jsonl"].open("rb") as src:
                        for line in src:
                            if n >= len(mask):
                                break
                            if mask[n]:
                                dst.write(line)
                            n += 1
                    if n != len(mask):
                        raise RuntimeError(f"{j['id']}: {n} lines but {len(mask)} keys; delete its files and rerun")
            os.replace(tmp, out_dir / fname)
        # a top-up file from an earlier run that this plan no longer has would still be read by assemble.py
        for stale in out_dir.glob("*.jsonl"):
            if stale.name not in wanted:
                stale.replace(stale.with_suffix(".jsonl.stale"))
                log(f"renamed stale {stale.name} to .stale")
    return report


def summarize(groups, jobs_dir, report):
    out = []
    for fname, js in groups:
        ds = [read_json(paths(jobs_dir, j)["done"]) for j in js]
        ds = [d for d in ds if d]
        rs = [report[j["id"]] for j in js if j["id"] in report]
        rej = Counter()
        for d in ds:
            rej.update(d["rejections"])
        out.append(dict(
            source=fname[:-len(".jsonl")], genre=mix.MIX[js[0]["name"]][0],
            target_M=round(sum(j["target"] for j in js) / 1e6, 3),
            words_M=round(sum(r["words"] for r in rs) / 1e6, 3), docs=sum(r["docs"] for r in rs),
            collected_M=round(sum(d["words_M"] for d in ds), 3),
            cross_job_duplicates_M=round(sum(r["dup_words"] for r in rs) / 1e6, 3),
            trimmed_M=round(sum(r["trimmed_words"] for r in rs) / 1e6, 3),
            scanned_words_M=round(sum(d["scanned_words_M"] for d in ds), 1),
            seconds=sum(d["seconds"] for d in ds), shards=len(js), jobs_done=len(ds),
            stopped=sorted({d["stopped"] for d in ds}), stream_retries=sum(d["stream_retries"] for d in ds),
            rejections=dict(rej.most_common()),
            jobs=[{k: d[k] for k in ("job", "words_M", "stopped", "relaxation", "probe")} for d in ds]))
    return out


def main():
    phys = psutil.cpu_count(logical=False) or 2
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("size", choices=list(mix.SIZES))
    ap.add_argument("--workers", type=int, default=max(1, phys // 2),
                    help=f"parallel jobs (default half the physical cores: {max(1, phys // 2)})")
    ap.add_argument("--min-free-gb", type=float, default=2.0, help="start a job only above this free RAM")
    ap.add_argument("--kill-free-gb", type=float, default=1.0, help="stop the youngest job below this free RAM")
    ap.add_argument("--min-disk-gb", type=float, default=10.0, help="stop everything below this free disk")
    ap.add_argument("--job-hours", type=float, default=1.5, help="split sources estimated above this")
    ap.add_argument("--max-shards", type=int, default=6)
    ap.add_argument("--overshoot", type=float, default=0.03, help="extra share collected before global dedup")
    ap.add_argument("--ckpt-seconds", type=int, default=120)
    ap.add_argument("--retries", type=int, default=3, help="restarts per job after a crash")
    ap.add_argument("--stagger", type=int, default=20, help="seconds between job starts")
    ap.add_argument("--status-seconds", type=int, default=300)
    ap.add_argument("--scale", type=float, default=1.0, help="multiply quotas, for test runs")
    ap.add_argument("--only", nargs="*", default=[], help="build only these sources (no fallbacks)")
    ap.add_argument("--allow-failed", action="store_true", help="go on to fallbacks even if a job failed")
    args = ap.parse_args()
    size = args.size
    apply_scale(args.scale, size)
    out_dir = ROOT / "work" / (size if args.scale == 1 else f"{size}_x{args.scale:g}")
    jobs_dir = out_dir / "jobs"
    jobs_dir.mkdir(parents=True, exist_ok=True)
    log = Log(out_dir / "pool.log")
    psutil.Process().nice(psutil.BELOW_NORMAL_PRIORITY_CLASS if os.name == "nt" else 10)
    t0, idx = time.time(), mix.SIZES[size]
    names = [n for n in mix.MIX if not args.only or n in args.only]
    log(f"== build {size} into {out_dir} ({' '.join(sys.argv[1:])})")

    prim = plan_jobs([(n, mix.MIX[n][1][idx] * 1e6) for n in names], "", args, lambda n: [])
    shards = Counter(j["name"] for j in prim)
    log("plan: " + ", ".join(f"{n} x{k}" for n, k in shards.items()))
    failed = run_pool(prim, args, size, jobs_dir, log)
    if failed and not args.allow_failed:
        raise SystemExit(f"{len(failed)} jobs failed: {[j['id'] for j in failed]}. Rerun the same command to "
                         "retry them, or add --allow-failed to fill their share from fallbacks.")
    groups = [(f"{n}.jsonl", [j for j in prim if j["name"] == n]) for n in names if shards[n]]

    fallback_log = []
    if not args.only:
        report = global_pass(groups, jobs_dir, out_dir, log, write=False)
        got = Counter()
        for j in prim:
            got[j["name"]] += report.get(j["id"], {}).get("words", 0)
        plan, fallback_log = build.plan_fallbacks(size, [dict(source=n, words_M=got[n] / 1e6) for n in names])
        log(f"fallback plan: {fallback_log}")
        topups = plan_jobs(list(plan.items()), ".topup", args,
                           lambda n: [str(paths(jobs_dir, j)["keys"]) for j in prim if j["name"] == n])
        failed = run_pool(topups, args, size, jobs_dir, log)
        if failed and not args.allow_failed:
            raise SystemExit(f"{len(failed)} top-up jobs failed: {[j['id'] for j in failed]}. Rerun to retry.")
        groups += [(f"{n}.topup.jsonl", [j for j in topups if j["name"] == n]) for n in plan]

    report = global_pass(groups, jobs_dir, out_dir, log, write=True)
    srcs = summarize(groups, jobs_dir, report)
    total = sum(s["words_M"] for s in srcs)
    stats = dict(total_M=round(total, 3), fallbacks=fallback_log, sources=srcs,
                 wall_seconds=round(time.time() - t0), options=vars(args))
    (out_dir / "stats.json").write_text(json.dumps(stats, indent=1))
    log(f"== total {total:.2f}M words in {(time.time() - t0) / 60:.0f} min wall")


if __name__ == "__main__":
    main()