File size: 5,248 Bytes
5599db4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Re-pack a Pass A store into the sharded Zarr layout.

Shards written before the 2026-09-04 fix hold one file per chunk (1.5 to 4.7 files per
calculation); the fixed writer groups 256 chunks per file. This copies every shard group of a
store array by array, keeping dtype, chunk shape and codecs and adding the sharding codec, and
verifies each copy element for element before marking it done. Groups already in the sharded
layout are copied unchanged. Safe to re-run: a destination group carrying the `repack_verified`
attribute is skipped.

    python repack_store.py --src $PSCRATCH/omol_store_100k --dst $PSCRATCH/omol_100k --workers 64
"""
from __future__ import annotations
import argparse, glob, os, shutil, sys, time, traceback
import multiprocessing as mp
import numpy as np
import zarr

# One thread per worker process: zarr's default pool (os.cpu_count() threads) times 64 to 96
# forked workers thrashed a 128-core node, cutting throughput several-fold.
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__)))
from omol_store import CHUNKS_PER_SHARD


def shard_paths(root):
    out = []
    for side in ("p1", "p2"):
        for depth in ("*", "*/*/*"):
            out += glob.glob(os.path.join(root, side, depth, "*.zarr"))
    return sorted(set(out))


def count_files(path):
    return sum(len(fs) for _, _, fs in os.walk(path))


def equal(a, b):
    if a.shape != b.shape or a.dtype != b.dtype:
        return False
    if a.dtype.kind == "f":
        return bool(np.array_equal(a, b, equal_nan=True))
    return bool(np.array_equal(a, b))


def repack_group(args):
    src, dst = args
    t0 = time.time()
    try:
        if os.path.isdir(dst):
            if zarr.open_group(dst, mode="r").attrs.get("repack_verified"):
                return dst, "skip", 0, 0, 0.0, ""
            shutil.rmtree(dst)
        gs = zarr.open_group(src, mode="r")
        attrs = dict(gs.attrs)
        gd = zarr.open_group(dst, mode="w")
        gd.attrs.update(attrs)
        for name in sorted(gs.array_keys()):
            zs = gs[name]
            data = np.asarray(zs[...])
            chunks = tuple(int(c) for c in zs.chunks)
            n_chunks = max(1, -(-zs.shape[0] // chunks[0]))
            shards = zs.shards or ((chunks[0] * min(CHUNKS_PER_SHARD, n_chunks),)
                                   + tuple(zs.shape[1:]))
            zd = gd.create_array(name=name, shape=zs.shape, chunks=chunks, shards=shards,
                                 dtype=zs.dtype, compressors=zs.compressors)
            if data.size:
                zd[...] = data
            if not equal(data, np.asarray(zd[...])):
                raise RuntimeError(f"read-back mismatch in {name}")
        gd = zarr.open_group(dst, mode="r+")
        if dict(gd.attrs) != attrs or sorted(gd.array_keys()) != sorted(gs.array_keys()):
            raise RuntimeError("attrs or array list differ after copy")
        gd.attrs["repack_verified"] = True
        return dst, "ok", count_files(src), count_files(dst), time.time() - t0, ""
    except Exception:
        return dst, "fail", 0, 0, time.time() - t0, traceback.format_exc(limit=3)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", required=True)
    ap.add_argument("--dst", required=True)
    ap.add_argument("--workers", type=int, default=64)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--pattern", default="", help="only shards whose basename contains this")
    args = ap.parse_args()
    src = os.path.abspath(args.src)
    dst = os.path.abspath(args.dst)
    shards = shard_paths(src)
    if args.pattern:
        shards = [s for s in shards if args.pattern in os.path.basename(s)]
    if args.limit:
        shards = shards[:args.limit]
    jobs = [(s, os.path.join(dst, os.path.relpath(s, src))) for s in shards]
    print(f"repack {len(jobs)} shard groups: {src} -> {dst}", flush=True)
    os.makedirs(dst, exist_ok=True)
    for f in glob.glob(os.path.join(src, "*.tsv")):
        shutil.copy2(f, dst)
    t0 = time.time()
    n_ok = n_skip = n_fail = 0
    files_in = files_out = 0
    with mp.Pool(min(args.workers, len(jobs))) as pool:
        for k, (path, status, fi, fo, dt, err) in enumerate(pool.imap_unordered(repack_group, jobs), 1):
            if status == "ok":
                n_ok += 1
                files_in += fi
                files_out += fo
            elif status == "skip":
                n_skip += 1
            else:
                n_fail += 1
                print(f"FAIL {path}\n{err}", flush=True)
            if k % 100 == 0 or k == len(jobs):
                el = time.time() - t0
                print(f"  {k}/{len(jobs)}  ok={n_ok} skip={n_skip} fail={n_fail}  "
                      f"files {files_in:,} -> {files_out:,}  {el/60:.1f} min", flush=True)
    print(f"\ndone: ok {n_ok}, skipped {n_skip}, failed {n_fail}, "
          f"files {files_in:,} -> {files_out:,}, wall {(time.time()-t0)/60:.1f} min")


if __name__ == "__main__":
    mp.set_start_method("fork", force=True)
    main()