File size: 25,904 Bytes
c5f5de4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compile verified OpenRCA and RCABench observations to compact case snapshots."""
import argparse
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
import fcntl
import json
import math
import os
from pathlib import Path
import random
import re
import shutil
import tempfile

import duckdb
import pyarrow as pa
import pyarrow.parquet as pq

from adapters import (epoch, group_files, logs_sql, metric_sql, normalize_pack, pack_batches,
                      sql_str, traces_sql, v1_batches)

DATASETS = ("openrca_v1", "propagation_bench", "openrca_v2")
FORBIDDEN = r"root[_. -]*cause|ground[_. -]*truth|label|inject|pave"
DROP_LOG = (FORBIDDEN + r"|chaos[_. -]*mesh|chaosdaemon|chaos[-_. ]?operator|"
            r"networkchaos|podchaos|stresschaos|jvmchaos|httpchaos|timechaos|"
            r"kubectl[[:space:]]|tc[[:space:]]+qdisc|iptables[[:space:]]+-|"
            r"stress-ng|\bkill[[:space:]]+-[0-9]|experiment controller|fault[_. -]*script")
ALERT = r"\b(error|fatal|warn(?:ing)?|exception|oom(?:killed)?|crash(?:ed|loopbackoff)?|timeout|timed out|out of memory)\b"
TS = pa.timestamp("us", tz="UTC")
SCHEMAS = {
    "metrics_1m.parquet": pa.schema([
        ("entity_id", pa.string()), ("timestamp", TS), ("metric_group", pa.string()),
        ("raw_metric_name", pa.string()), ("value", pa.float64()),
    ]),
    "metric_stats.parquet": pa.schema([
        ("entity_id", pa.string()), ("raw_metric_name", pa.string()),
        ("median_base", pa.float64()), ("mad_base", pa.float64()),
        ("mean_detect", pa.float64()), ("robust_z", pa.float64()), ("onset_ts", TS),
    ]),
    "traces_edge_stats.parquet": pa.schema([
        ("caller_id", pa.string()), ("callee_id", pa.string()), ("minute_ts", TS),
        ("call_count", pa.int64()), ("err_count", pa.int64()),
        ("caller_p99_ms", pa.float64()), ("callee_p99_ms", pa.float64()),
        ("span_gap_ms", pa.float64()),
    ]),
    "logs_events.parquet": pa.schema([
        ("entity_id", pa.string()), ("minute_ts", TS), ("event_template", pa.string()),
        ("count", pa.int64()), ("sample_message", pa.string()),
    ]),
}
SNAPSHOT_FILES = frozenset(("topology.json", *SCHEMAS))
FILTER = re.compile(FORBIDDEN, re.I)


def clean(expr):
    return f"({expr} is not null and not regexp_matches({expr}, {sql_str('(?i)' + FORBIDDEN)}))"


def make_table(conn, name, queries, select, empty):
    statements = list(queries)
    sql = select.format(source=" union all ".join(statements)) if statements else empty
    conn.execute(f"create temp table {name} as {sql}")


def compile_metrics(conn, batch, groups):
    make_table(
        conn, "obs", metric_sql(conn, batch, groups),
        f"""
        select w.case_id, r.entity, r.layer, r.svc, r.host, r.metric,
               floor((r.t-w.boundary)/60)*60+w.boundary bucket,
               avg(r.val) val, count(*) n
        from ({{source}}) r join windows w on r.t between w.lo and w.hi
        where {clean('r.entity')} and {clean('r.metric')} and isfinite(r.val)
        group by all
        """,
        """select ''::varchar case_id, ''::varchar entity, ''::varchar layer, ''::varchar svc,
                  ''::varchar host, ''::varchar metric, 0::double bucket, 0::double val, 0::bigint n where false""",
    )
    conn.execute("""
        create temp table series as
        select case_id, entity, metric, bucket, sum(val*n)/sum(n) val
        from obs group by all
    """)
    conn.execute("""
        create temp table summaries as
        with base as (
            select s.case_id, entity, metric, median(val) median_base
            from series s join windows w using (case_id)
            where bucket < w.boundary group by all
        ), spread as (
            select s.case_id, s.entity, s.metric, b.median_base,
                   median(abs(s.val-b.median_base)) mad_base
            from series s join base b using(case_id,entity,metric)
            join windows w using(case_id)
            where s.bucket < w.boundary group by all
        ), detect as (
            select s.case_id, s.entity, s.metric, avg(s.val) mean_detect
            from series s join windows w using (case_id)
            where bucket >= w.boundary group by all
        ), stats as (
            select case_id, entity, metric, median_base, mad_base, mean_detect
            from spread full outer join detect using(case_id,entity,metric)
        )
        select st.case_id, st.entity entity_id, st.metric raw_metric_name, median_base,
               mad_base, mean_detect,
               (mean_detect-median_base)/(1.4826*mad_base+1e-6) robust_z,
               to_timestamp(min(s.bucket) filter (
                   where s.bucket >= w.boundary and
                   (s.val-st.median_base)/(1.4826*st.mad_base+1e-6) >= 3.0
               )) onset_ts
        from stats st join series s on (st.case_id, st.entity, st.metric) = (s.case_id, s.entity, s.metric)
        join windows w on w.case_id=st.case_id
        group by all
    """)


def compile_traces(conn, batch, groups):
    query = traces_sql(conn, batch, groups)
    make_table(
        conn, "spans", [query] if query else [],
        f"""
        select w.case_id, r.* from ({{source}}) r
        join windows w on r.t between w.lo and w.hi
        where {clean('r.service')} and isfinite(r.duration) and r.duration >= 0
          and r.trace_id is not null and r.span_id is not null
        qualify row_number() over (partition by w.case_id, trace_id, span_id order by t, duration) = 1
        """,
        """select ''::varchar case_id, 0::double t, ''::varchar service, ''::varchar entity,
                  ''::varchar pod, 0::double duration, ''::varchar kind, 0::int failed,
                  ''::varchar trace_id, ''::varchar span_id, ''::varchar parent_id, ''::varchar span_name,
                  ''::varchar destination where false""",
    )
    conn.execute("""
        create temp table edge_stats as
        with paired as (
            select s.case_id, p.service caller_id, s.service callee_id,
                   floor(s.t/60)*60 minute_bucket,
                   greatest(p.failed, s.failed) failed,
                   case when p.kind in ('client','span_kind_client','3') or p.destination=s.service
                        then p.duration end caller_duration,
                   s.duration callee_duration
            from spans s join spans p on p.case_id=s.case_id and p.trace_id=s.trace_id
              and p.span_id=s.parent_id
            where s.service != p.service
            union all
            select p.case_id, p.service, p.destination, floor(p.t/60)*60, p.failed, p.duration, null
            from spans p
            where p.destination != p.service and
                  regexp_full_match(p.destination, '[A-Za-z0-9_.-]{1,100}')
                  and not regexp_matches(p.destination, '(?i)root[_. -]*cause|ground[_. -]*truth|label|inject|pave')
                  and not exists (select 1 from spans s where s.case_id=p.case_id
                      and s.trace_id=p.trace_id and s.parent_id=p.span_id and s.service != p.service)
        ), agg as (
            select case_id, caller_id, callee_id, to_timestamp(minute_bucket) minute_ts,
                   count(*) call_count, sum(failed)::bigint err_count,
                   quantile_cont(caller_duration, 0.99) caller_p99_ms,
                   quantile_cont(callee_duration, 0.99) callee_p99_ms
            from paired group by all
        )
        select *, case when caller_p99_ms is not null and callee_p99_ms is not null
                       then greatest(0, caller_p99_ms-callee_p99_ms) end span_gap_ms
        from agg
    """)


def compile_logs(conn, batch, groups):
    pattern = sql_str("(?i)" + DROP_LOG)
    alert = sql_str("(?i)" + ALERT)
    make_table(
        conn, "events", logs_sql(conn, batch, groups),
        f"""
        with obs as (
            select w.case_id, r.entity entity_id, r.pod, r.svc,
                   to_timestamp(floor(t/60)*60) minute_ts,
                   regexp_replace(
                     regexp_replace(
                       regexp_replace(substr(msg,1,200),
                         '(?i)[0-9a-f]{{{{8}}}}-[0-9a-f-]{{{{27,}}}}|\\b[0-9a-f]{{{{16,}}}}\\b', '<id>', 'g'),
                       '\\b[0-9]{{{{1,3}}}}(?:\\.[0-9]{{{{1,3}}}}){{{{3}}}}\\b', '<ip>', 'g'),
                     '[[:space:]]+', ' ', 'g') sample_message
            from ({{source}}) r join windows w on r.t between w.lo and w.hi
            where {clean('r.entity')} and not regexp_matches(msg, {pattern})
              and (regexp_matches(msg, {alert}) or regexp_matches(severity, {alert}))
        ), templates as (
            select *, left(regexp_replace(sample_message,
                '[-+]?[0-9]+(?:\\.[0-9]+)?', '<num>', 'g'), 200) event_template
            from obs
        )
        select case_id, entity_id, pod, svc, minute_ts, event_template,
               count(*) count, min(sample_message) sample_message
        from templates group by all
        """,
        """select ''::varchar case_id, ''::varchar entity_id, ''::varchar pod, ''::varchar svc,
                  now() minute_ts, ''::varchar event_template, 0::bigint count,
                  ''::varchar sample_message where false""",
    )


METRIC_GROUPS = (
    ("latency_p99", ("p99", "0.99", "quantile_99")),
    ("latency_avg", ("latency", "duration.mean", "response_time", "avg_time", "mrt")),
    ("error_rate", ("error_rate", "error.rate", "fail_rate", "failure_rate")),
    ("request_rate", ("request_rate", "requests_per", "requests.rate", "throughput", "qps", "rps")),
    ("cpu_usage", ("cpu", "loadavg")),
    ("mem_usage", ("memory", "mem_", "mem.", "heap", "bufferpool", "rss")),
    ("network_usage", ("network", "net.", "net_", "bytes_sent", "bytes_recv", "packets", "tcp")),
    ("io_usage", ("disk", "filesystem", "io.", "io_", "iops")),
)


def register_metric_groups(conn):
    branches = []
    for group, matches in METRIC_GROUPS:
        pattern = "|".join(map(re.escape, matches))
        branches.append(f"when regexp_matches(lower(name), {sql_str(pattern)}) then {sql_str(group)}")
    conn.execute(f"create macro metric_group(name) as case {' '.join(branches)} else 'other' end")


def topology(conn, case, batch):
    spans = conn.execute("""
        select distinct entity, service, pod from spans where case_id=?
    """, [case.case_id]).fetchall()
    observations = conn.execute("""
        select distinct entity, layer, svc, host from obs where case_id=?
        union select distinct entity_id,
            case when pod is null then 'service' else 'instance' end, svc, null
        from events where case_id=?
    """, [case.case_id] * 2).fetchall()
    edge_data = conn.execute("""
        select distinct caller_id, callee_id from edge_stats where case_id=?
    """, [case.case_id]).fetchall()
    nodes, edges = {}, set()

    def add(entity, layer, service=None, host=None):
        if not entity or FILTER.search(entity):
            return
        old = nodes.get(entity)
        if old and old["layer"] != "service" and layer == "service":
            layer = old["layer"]
        service = service if service and service != entity and not FILTER.search(service) else None
        host = host if host and host != entity and not FILTER.search(host) else None
        if old and layer == old["layer"]:
            service = service or old["parent_service"]
            host = host or old["host_node"]
        nodes[entity] = {
            "id": entity, "layer": layer,
            "parent_service": service if layer == "instance" else None, "host_node": host,
        }
        if service and layer == "instance":
            nodes.setdefault(service, {"id": service, "layer": "service", "parent_service": None, "host_node": None})
            edges.add((service, entity, "own"))
        if host:
            nodes[host] = {"id": host, "layer": "host", "parent_service": None, "host_node": None}
            edges.add((entity, host, "host"))

    def infer(entity, layer, service, host):
        if not entity:
            return
        match = re.fullmatch(r"(node-\d+)\.(.+)", entity) if batch.systems.startswith("Market") else None
        if match:
            host, pod = match.groups()
            service = re.sub(r"-\d+$", "", pod)
            layer = "instance"
        elif batch.systems.startswith("Market") and layer == "service" and re.search(r"(?<!^node)-\d+$", entity):
            service, layer = re.sub(r"-\d+$", "", entity), "instance"
        if batch.systems == "Telecom" and batch.deployment:
            host = host or batch.deployment.get(entity)
            if host:
                layer = "instance"
        if re.fullmatch(r"(?:node|os)[_-]\d+", entity):
            layer, service = "host", None
        add(entity, layer, service, host)

    for entity, layer, service, host in sorted(observations, key=lambda row: tuple(x or "" for x in row)):
        infer(entity, layer, service, host)
    for entity, service, pod in sorted(spans, key=lambda row: tuple(x or "" for x in row)):
        infer(pod or entity, "instance" if pod or entity != service else "service", service, None)
        add(service, "service")
    for src, dst in edge_data:
        add(src, "service")
        add(dst, "service")
        if src in nodes and dst in nodes and src != dst:
            edges.add((src, dst, "call"))
    nodes = sorted(nodes.values(), key=lambda row: row["id"])
    edges = [{"src": src, "dst": dst, "edge_type": kind} for src, dst, kind in sorted(edges)]
    return {"nodes": nodes, "edges": edges}


QUERIES = {
    "metrics_1m.parquet": """
        select entity entity_id, to_timestamp(bucket) as "timestamp",
               metric_group(metric) metric_group, metric raw_metric_name, val as "value"
        from series where case_id=? order by entity, metric, bucket
    """,
    "metric_stats.parquet": """
        select * exclude(case_id) from summaries where case_id=?
        order by entity_id, robust_z desc nulls last, raw_metric_name
    """,
    "traces_edge_stats.parquet": """
        select * exclude(case_id) from edge_stats where case_id=? order by caller_id, callee_id, minute_ts
    """,
    "logs_events.parquet": """
        select entity_id, minute_ts, event_template, sum(count)::bigint count, min(sample_message) sample_message
        from events where case_id=? group by all order by entity_id, minute_ts, event_template
    """,
}


def publish_case(conn, case, batch, runtime, staging):
    destination = runtime / batch.source / case.case_id
    destination.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(dir=staging, prefix="case-") as tmp:
        shadow = Path(tmp) / "new"
        shadow.mkdir()
        graph = topology(conn, case, batch)
        (shadow / "topology.json").write_text(json.dumps(graph, ensure_ascii=False, separators=(",", ":")))
        counts = {}
        for name, sql in QUERIES.items():
            table = conn.execute(sql, [case.case_id]).to_arrow_table().cast(SCHEMAS[name])
            counts[name] = table.num_rows
            pq.write_table(table, shadow / name, compression="zstd", compression_level=3,
                           row_group_size=16384, write_page_checksum=True)
        if not graph["nodes"] or not any(counts.values()):
            raise ValueError("No telemetry in case window")
        backup = Path(tmp) / "old"
        if destination.exists():
            destination.rename(backup)
        try:
            shadow.rename(destination)
        except OSError:
            if backup.exists():
                backup.rename(destination)
            raise
    return counts


def observed_path(conn, case, postmortem):
    # Only the vault writer consumes the publisher's per-span postmortem.
    # Report a direction from affected callee to affected upstream caller.
    if case.truth["ground_truth_causal_path"] is not None or postmortem is None:
        return case.truth["ground_truth_causal_path"]
    try:
        rows = pq.ParquetFile(postmortem).read(columns=["SpanName", "Issues"], use_threads=False)
        abnormal = {
            row["SpanName"] for row in rows.to_pylist()
            if row["Issues"] and str(row["Issues"]).strip() not in ("{}", "[]", "null")
        }
    except (KeyError, OSError, pa.ArrowInvalid):
        abnormal = set()
    impacted = {
        service for service, name in conn.execute(
            "select distinct service, span_name from spans where case_id=?", [case.case_id]
        ).fetchall() if name in abnormal
    }
    t0 = epoch(case.truth["fault_timestamp"])
    impact_rows = conn.execute("""
        with evidence as (
            select service, count(*) filter (where t < $t0) n_before,
                   count(*) filter (where t >= $t0) n_after,
                   avg(failed) filter (where t < $t0) err_before,
                   avg(failed) filter (where t >= $t0) err_after,
                   sum(failed) filter (where t >= $t0) errors,
                   quantile_cont(duration,.99) filter (where t < $t0) p99_before,
                   quantile_cont(duration,.99) filter (where t >= $t0) p99_after
            from spans where case_id=$case group by service
        )
        select service from evidence where n_before >= 10 and n_after >= 10
        and ((errors >= 3 and err_after-err_before >= .10) or
             (p99_after >= 2*p99_before and p99_after-p99_before >= 5))
    """, {"t0": t0, "case": case.case_id}).fetchall()
    impacted.update(row[0] for row in impact_rows)
    upstream = defaultdict(set)
    for caller, callee in conn.execute(
        "select distinct caller_id, callee_id from edge_stats where case_id=?", [case.case_id]
    ).fetchall():
        if caller in impacted:
            upstream[callee].add(caller)
    seen = set(case.truth["root_cause_entities"])
    frontier = sorted(seen)
    edges = []
    while frontier:
        next_frontier = set()
        for src in frontier:
            for dst in sorted(upstream[src] - seen):
                edges.append({"src": src, "dst": dst})
                next_frontier.add(dst)
        seen.update(next_frontier)
        frontier = sorted(next_frontier)
    return edges or None


def compile_batch(batch, runtime, staging, threads):
    groups = group_files(batch.files)
    if not groups:
        raise ValueError("No telemetry inputs for batch")
    with tempfile.TemporaryDirectory(dir=staging, prefix="db-") as db_dir, duckdb.connect(
        config={"threads": str(threads), "memory_limit": "6GB", "temp_directory": db_dir}
    ) as conn:
        conn.execute("set timezone='UTC'")
        conn.execute("set enable_progress_bar=false")
        register_metric_groups(conn)
        conn.execute("create temp table windows(case_id varchar, lo double, boundary double, hi double)")
        conn.executemany("insert into windows values (?, ?, ?, ?)",
                         [(case.case_id, case.start, case.boundary, case.end) for case in batch.cases])
        compile_metrics(conn, batch, groups)
        compile_traces(conn, batch, groups)
        compile_logs(conn, batch, groups)
        stats = Counter()
        done, failed = [], []
        for case in batch.cases:
            try:
                stats.update(publish_case(conn, case, batch, runtime, staging))
                record = dict(case.truth)
                record["ground_truth_causal_path"] = observed_path(conn, case, batch.postmortem)
                done.append(record)
            except Exception as error:
                failed.append((case.case_id, type(error).__name__, str(error)))
        rejects = (conn.execute("select count(*) from reject_errors").fetchone()[0]
                   if conn.execute("select count(*) from duckdb_tables() where table_name='reject_errors'").fetchone()[0]
                   else 0)
    return done, failed, stats, rejects


def assign_splits(records):
    rng = random.Random(42)
    systems = defaultdict(list)
    for record in records:
        systems[record["system_name"].split("/", 1)[0]].append(record)
    for group in sorted(systems):
        records = sorted(systems[group], key=lambda row: (row["fault_timestamp"], row["case_id"]))
        rng.shuffle(records)
        targets = [len(records) * ratio for ratio in (0.60, 0.15, 0.25)]
        counts = list(map(math.floor, targets))
        residual = len(records) - sum(counts)
        for index in sorted(range(3), key=lambda i: (targets[i] - counts[i], -i), reverse=True)[:residual]:
            counts[index] += 1
        index = 0
        for split, count in zip(("train", "val", "test"), counts):
            for row in records[index:index + count]:
                row["split"] = split
            index += count


def write_vault(records, path):
    assign_splits(records)
    with tempfile.NamedTemporaryFile(dir=path.parent, mode="w", encoding="utf-8", delete=False) as handle:
        for record in sorted(records, key=lambda row: row["case_id"]):
            handle.write(json.dumps(record, ensure_ascii=False) + "\n")
    Path(handle.name).chmod(0o444)
    os.replace(handle.name, path)


def collect_batches(raw, dataset, limit):
    if dataset == "openrca_v1":
        groups = list(v1_batches(raw))
        return groups[:limit], []
    groups, errors = [], []
    for directory, manifest, base in list(pack_batches(raw, dataset))[:limit]:
        try:
            groups.append(normalize_pack(dataset, base, directory, manifest))
        except Exception as error:
            errors.append((directory.name, type(error).__name__, str(error)))
    return groups, errors


def compile_dataset(args, dataset, runtime, vault, scratch):
    raw = args.raw_root / dataset
    if not (raw / ".verified.json").is_file() and not args.preview:
        raise RuntimeError(f"Source integrity receipt missing for {dataset}")
    batches, errors = collect_batches(raw, dataset, args.limit)
    if not batches:
        raise ValueError(f"No batches discovered for {dataset}")
    expected = sum(len(batch.cases) for batch in batches) + len(errors)
    records, stats = [], Counter()
    rejects = 0
    with ThreadPoolExecutor(max_workers=args.jobs) as executor:
        jobs = [(batch, executor.submit(compile_batch, batch, runtime, scratch, args.threads))
                for batch in batches]
        for index, (batch, job) in enumerate(jobs, 1):
            try:
                done, failed, counts, bad_rows = job.result()
                records.extend(done)
                errors.extend(failed)
                stats.update(counts)
                rejects += bad_rows
                if failed:
                    print(f"{dataset} batch {index}: {failed[:2]}", flush=True)
            except Exception as error:
                errors.append((batch.key, type(error).__name__, str(error)))
                print(f"{dataset} batch {index} failed: {error}", flush=True)
            if index % 25 == 0 or index == len(jobs):
                print(f"{dataset}: {index}/{len(jobs)} batches, {len(records)}/{expected} cases", flush=True)
    if not records:
        raise RuntimeError(f"No cases compiled for {dataset}")
    write_vault(records, vault / f"{dataset}.jsonl")
    summary = {
        "total_cases": len(records), "source_cases_discovered": expected,
        "systems_breakdown": dict(Counter(row["system_name"].split("/", 1)[0] for row in records)),
        "cases_with_causal_path": sum(bool(row["ground_truth_causal_path"]) for row in records),
        "train_val_test_counts": [sum(row["split"] == name for row in records) for name in ("train", "val", "test")],
        "snapshot_rows": dict(stats), "rejected_csv_rows": rejects, "failed_batches_or_cases": len(errors),
    }
    return summary, errors


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--storage-root", type=Path, required=True)
    parser.add_argument("--raw-root", type=Path)
    parser.add_argument("--dataset", choices=DATASETS, action="append")
    parser.add_argument("--jobs", type=int, default=6)
    parser.add_argument("--threads", type=int, default=3)
    parser.add_argument("--preview", action="store_true", help="Allow unverified inputs for development validation")
    parser.add_argument("--limit", type=int, help="Maximum batches in preview mode")
    args = parser.parse_args()
    if args.limit is not None and not args.preview:
        parser.error("--limit requires --preview")
    args.raw_root = args.raw_root or args.storage_root / "datasets_raw"
    runtime = args.storage_root / "runtime_snapshots"
    vault = args.storage_root / "ground_truth_vault"
    reports = args.storage_root / "reports"
    scratch = args.storage_root / ".snapshot_build"
    for directory in (runtime, reports, scratch, vault):
        directory.mkdir(parents=True, exist_ok=True)
    vault.chmod(0o700)
    status = 0
    for dataset in args.dataset or DATASETS[:2]:
        with (scratch / f".{dataset}.build.lock").open("w") as guard:
            fcntl.flock(guard, fcntl.LOCK_EX)
            result = reports / f"{dataset}.build.json"
            try:
                summary, errors = compile_dataset(args, dataset, runtime, vault, scratch)
                summary["preview"] = args.preview
                temp = result.with_suffix(".tmp")
                temp.write_text(json.dumps(summary, indent=2) + "\n")
                temp.replace(result)
                error_path = vault / f".{dataset}.errors.json"
                if errors:
                    status = 1
                    error_path.write_text(json.dumps(errors, indent=2))
                else:
                    error_path.unlink(missing_ok=True)
            except Exception as error:
                print(f"{dataset}: {error}", flush=True)
                status = 1
    return status


if __name__ == "__main__":
    raise SystemExit(main())