"""Merge the many small Pass A/B1 shard groups of a store into a few large ones. Pass A flushed a shard group whenever a worker had buffered ~1.2 GB of Fock data, which bounds parser memory but leaves hundreds of groups per 100k calculations and tens of thousands of metadata files for a loader to touch. This rewrites a store as, per dataset, the smallest number of groups whose on-disk size stays under --group-bytes (measured on the p2 side, so p1 and p2 get the same row layout), and writes consolidated metadata so opening a group is one JSON read. Row order inside a merged group is the concatenation of the source groups in name order; every ragged array is concatenated and its offsets rebased; the per-calculation attrs lists are concatenated. Chunk shapes and codecs come from the source arrays; shard files hold --chunks-per-shard chunks. Writing is done in whole-shard blocks by a pool of workers (one task per destination array per block), so memory per worker stays around one shard. python merge_store.py --src $PSCRATCH/omol_100k --dst $PSCRATCH/omol_100k_m --group-bytes 32e9 """ from __future__ import annotations import argparse, glob, json, os, shutil, sys, time, traceback import multiprocessing as mp import numpy as np import zarr zarr.config.set({"threading.max_workers": 1, "async.concurrency": 2}) try: import numcodecs.blosc numcodecs.blosc.set_nthreads(1) numcodecs.blosc.use_threads = False except Exception: pass sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) DROP_ATTRS = {"repack_verified", "occ_derived_verified", "mo_gbw_root", "n_calc", "calc_id", "rel_path", "hftyp"} LIST_ATTRS = ("calc_id", "rel_path", "hftyp") def groups_by_dataset(root, side): out = {} for depth in ("*", "*/*/*"): for gp in glob.glob(os.path.join(root, side, depth, "*.zarr")): ds = os.path.relpath(os.path.dirname(gp), os.path.join(root, side)) out.setdefault(ds, []).append(gp) return {ds: sorted(v) for ds, v in out.items()} def dir_bytes(path): return sum(os.path.getsize(os.path.join(r, f)) for r, _, fs in os.walk(path) for f in fs) def plan_groups(src, group_bytes): """Split each dataset's shard list (sorted by name) into runs whose p2 bytes stay under budget.""" p2 = groups_by_dataset(src, "p2") plan = [] for ds, shards in sorted(p2.items()): run, run_b = [], 0 for gp in shards: b = dir_bytes(gp) if run and run_b + b > group_bytes: plan.append((ds, run)); run, run_b = [], 0 run.append(os.path.basename(gp)); run_b += b if run: plan.append((ds, run)) return plan def make_group(args): """Create one destination group (both sides): metadata, attrs, offsets. Returns write tasks.""" src, dst, side, ds, gname, members, cps = args try: srcs = [zarr.open_group(os.path.join(src, side, ds, m), mode="r") for m in members] out_path = os.path.join(dst, side, ds, gname) if os.path.isdir(out_path): shutil.rmtree(out_path) os.makedirs(os.path.dirname(out_path), exist_ok=True) gd = zarr.open_group(out_path, mode="w") attrs = {k: v for k, v in dict(srcs[0].attrs).items() if k not in DROP_ATTRS} for g in srcs[1:]: for k, v in attrs.items(): if g.attrs.get(k) != v: raise RuntimeError(f"attr {k} differs between source groups of {ds}") for k in LIST_ATTRS: attrs[k] = sum((list(g.attrs[k]) for g in srcs), []) attrs["n_calc"] = int(sum(int(g.attrs["n_calc"]) for g in srcs)) attrs["merged_from"] = members gd.attrs.update(attrs) names = sorted(srcs[0].array_keys()) for g in srcs[1:]: if sorted(g.array_keys()) != names: raise RuntimeError(f"array list differs between source groups of {ds}") tasks = [] for name in names: arrs = [g[name] for g in srcs] if name.endswith("_offsets"): parts, base = [np.asarray(arrs[0][...])], int(arrs[0][-1]) for a in arrs[1:]: o = np.asarray(a[...]) parts.append(o[1:] + base); base += int(o[-1]) offs = np.concatenate(parts) z = gd.create_array(name=name, shape=offs.shape, chunks=offs.shape, shards=offs.shape, dtype=offs.dtype, compressors=arrs[0].compressors) z[...] = offs continue lens = [int(a.shape[0]) for a in arrs] total = sum(lens) shape = (total,) + tuple(arrs[0].shape[1:]) chunk0 = int(arrs[0].chunks[0]) chunks = (max(1, min(total, chunk0)),) + tuple(arrs[0].shape[1:]) n_chunks = max(1, -(-total // chunks[0])) shard_len = chunks[0] * min(cps, n_chunks) shards = (shard_len,) + tuple(arrs[0].shape[1:]) gd.create_array(name=name, shape=shape, chunks=chunks, shards=shards, dtype=arrs[0].dtype, compressors=arrs[0].compressors) if total == 0: continue starts = np.concatenate([[0], np.cumsum(lens)[:-1]]) for a0 in range(0, total, shard_len): a1 = min(total, a0 + shard_len) pieces = [] for m, s0, n in zip(members, starts, lens): lo, hi = max(a0, s0), min(a1, s0 + n) if hi > lo: pieces.append((m, int(lo - s0), int(hi - s0))) tasks.append((src, side, ds, out_path, name, int(a0), int(a1), pieces)) return out_path, tasks, "" except Exception: return os.path.join(dst, side, ds, gname), [], traceback.format_exc(limit=4) def write_block(args): src, side, ds, out_path, name, a0, a1, pieces = args t0 = time.time() try: chunks = [np.asarray(zarr.open_group(os.path.join(src, side, ds, m), mode="r")[name][lo:hi]) for m, lo, hi in pieces] block = np.concatenate(chunks) if len(chunks) > 1 else chunks[0] z = zarr.open_array(out_path + "/" + name, mode="r+") z[a0:a1] = block return name, block.nbytes, time.time() - t0, "" except Exception: return name, 0, time.time() - t0, traceback.format_exc(limit=4) def verify_group(args): """Every array of the merged group equals the concatenation of its sources (full compare for arrays under 4 M elements, 3 random 200k windows otherwise); then consolidate metadata.""" src, dst, side, ds, gname = args try: gd = zarr.open_group(os.path.join(dst, side, ds, gname), mode="r+") members = gd.attrs["merged_from"] srcs = [zarr.open_group(os.path.join(src, side, ds, m), mode="r") for m in members] rng = np.random.default_rng(abs(hash(gname)) % (2**32)) for name in gd.array_keys(): if name.endswith("_offsets"): parts, base = [np.asarray(srcs[0][name][...])], int(srcs[0][name][-1]) for g in srcs[1:]: o = np.asarray(g[name][...]); parts.append(o[1:] + base); base += int(o[-1]) if not np.array_equal(np.asarray(gd[name][...]), np.concatenate(parts)): raise RuntimeError(f"{name} offsets differ") continue lens = [int(g[name].shape[0]) for g in srcs] starts = np.concatenate([[0], np.cumsum(lens)[:-1]]) total = int(gd[name].shape[0]) if total != sum(lens): raise RuntimeError(f"{name} length {total} != {sum(lens)}") if total == 0: continue if gd[name].size <= 4_000_000: windows = [(0, total)] else: windows = [(int(s), int(min(total, s + 200_000))) for s in rng.integers(0, total, 3)] for w0, w1 in windows: got = np.asarray(gd[name][w0:w1]) exp = [] for g, s0, n in zip(srcs, starts, lens): lo, hi = max(w0, s0), min(w1, s0 + n) if hi > lo: exp.append(np.asarray(g[name][lo - s0:hi - s0])) exp = np.concatenate(exp) ok = np.array_equal(got, exp, equal_nan=True) if got.dtype.kind == "f" else np.array_equal(got, exp) if not ok: raise RuntimeError(f"{name} content differs in [{w0},{w1})") n_ids = len(gd.attrs["calc_id"]) if n_ids != sum(len(g.attrs["calc_id"]) for g in srcs) or n_ids != int(gd.attrs["n_calc"]): raise RuntimeError("calc_id list length") zarr.consolidate_metadata(gd.store) return gname, side, ds, "ok", "" except Exception: return gname, side, ds, "fail", traceback.format_exc(limit=4) def main(): ap = argparse.ArgumentParser() ap.add_argument("--src", required=True) ap.add_argument("--dst", required=True) ap.add_argument("--group-bytes", type=float, default=32e9) ap.add_argument("--chunks-per-shard", type=int, default=64) ap.add_argument("--workers", type=int, default=96) ap.add_argument("--datasets", default="", help="comma list to restrict (smoke tests)") args = ap.parse_args() src, dst = os.path.abspath(args.src), os.path.abspath(args.dst) t0 = time.time() plan = plan_groups(src, args.group_bytes) if args.datasets: keep = set(args.datasets.split(",")) plan = [p for p in plan if p[0] in keep] counter = {} named = [] for ds, members in plan: k = counter.get(ds, 0); counter[ds] = k + 1 named.append((ds, f"group_{k:03d}.zarr", members)) print(f"plan: {sum(len(m) for _, _, m in named)} source groups -> {len(named)} merged groups " f"over {len(counter)} datasets ({(time.time()-t0)/60:.1f} min)", flush=True) for ds, n in sorted(counter.items(), key=lambda kv: -kv[1])[:8]: print(f" {ds}: {n} groups", flush=True) # phase 1: create groups and gather write tasks (parallel over groups) jobs = [(src, dst, side, ds, g, m, args.chunks_per_shard) for ds, g, m in named for side in ("p1", "p2")] tasks = [] with mp.Pool(min(32, len(jobs))) as pool: for out_path, t, err in pool.imap_unordered(make_group, jobs): if err: print(f"FAIL creating {out_path}\n{err}", flush=True); sys.exit(1) tasks.extend(t) # biggest blocks first so the tail is short tasks.sort(key=lambda t: -(t[6] - t[5])) print(f"phase 1 done: {len(jobs)} groups created, {len(tasks)} write blocks " f"({(time.time()-t0)/60:.1f} min)", flush=True) # phase 2: write blocks n_ok = n_fail = 0; nbytes = 0 with mp.Pool(min(args.workers, max(1, len(tasks)))) as pool: for k, (name, nb, dt, err) in enumerate(pool.imap_unordered(write_block, tasks), 1): if err: n_fail += 1; print(f"FAIL block {name}\n{err}", flush=True) else: n_ok += 1; nbytes += nb if k % 500 == 0 or k == len(tasks): el = time.time() - t0 print(f" blocks {k}/{len(tasks)} ok={n_ok} fail={n_fail} {nbytes/1e12:.3f} TB " f"{el/60:.1f} min", flush=True) if n_fail: print("write failures, stopping before verification"); sys.exit(1) # phase 3: verify and consolidate vjobs = [(src, dst, side, ds, g) for ds, g, _ in named for side in ("p1", "p2")] v_ok = v_fail = 0 with mp.Pool(min(args.workers, len(vjobs))) as pool: for gname, side, ds, status, err in pool.imap_unordered(verify_group, vjobs): if status == "ok": v_ok += 1 else: v_fail += 1; print(f"VERIFY FAIL {side}/{ds}/{gname}\n{err}", flush=True) for f in glob.glob(os.path.join(src, "*")): if os.path.isfile(f): shutil.copy2(f, dst) if os.path.isdir(os.path.join(src, "code")): shutil.copytree(os.path.join(src, "code"), os.path.join(dst, "code"), dirs_exist_ok=True) print(f"\ndone: {len(named)} merged groups per side, verify ok {v_ok} fail {v_fail}, " f"{nbytes/1e12:.3f} TB written, wall {(time.time()-t0)/60:.1f} min") if __name__ == "__main__": mp.set_start_method("fork", force=True) main()