File size: 8,740 Bytes
e5a1dc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""All-file dataset mirroring with frozen completion scope and remote SHA-256."""
import base64, concurrent.futures, hashlib, json, os, shlex, subprocess
from datetime import datetime, timezone
from pathlib import Path

def ssh(command,stdin=None):
    return subprocess.run(['ssh','-o','BatchMode=yes','centre',command],input=stdin,
                          stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True).stdout

def snapshot(src):
    # Inventory only finalized run directories; do not race simulator/exporter writes.
    script='''
import base64,hashlib,json,os
from pathlib import Path
from datetime import datetime,timezone
src=json.loads(CONFIG)
root=Path(src['remote'])
completed={}
if src.get('snapshot_completed'):
    for f in sorted((root/'runs').glob('*/complete.json')):
        completed[f.parent.name]=json.loads(f.read_text())
exclude_root={x.strip('/') for x in src['exclude'] if x.startswith('/')}
exclude_names={x.strip('/') for x in src['exclude'] if not x.startswith('/')}
files={}; captured={}
for parent,dirs,names in os.walk(root):
    p=Path(parent);rel=p.relative_to(root)
    dirs[:]=sorted(d for d in dirs if d not in exclude_names and str(rel/d) not in exclude_root)
    for name in sorted(names):
        f=p/name
        if not f.is_file():continue
        r=f.relative_to(root).as_posix();parts=Path(r).parts
        selected=not (src.get('snapshot_completed') and parts[0]=='runs' and len(parts)>1 and parts[1] not in completed)
        st=f.stat()
        files[r]={'size':st.st_size,'mtime_ns':st.st_mtime_ns,'selected':selected}
        if src.get('snapshot_completed') and len(parts)==1:
            data=f.read_bytes()
            captured[r]={'data':base64.b64encode(data).decode(),'sha256':hashlib.sha256(data).hexdigest()}
            files[r]['size']=len(data)
print(json.dumps({'source':src['remote'],'frozen_at_utc':datetime.now(timezone.utc).isoformat(),
                  'files':files,'captured':captured,'completed_records':list(completed.values())}))
'''.replace('CONFIG',repr(json.dumps(src)))
    return json.loads(ssh('python3 -',script.encode()))

def sha_file(path):
    h=hashlib.sha256()
    with path.open('rb') as f:
        for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
    return h.hexdigest()

def remote_hashes(src,paths):
    result={}
    for i in range(0,len(paths),500):
        out=ssh('cd '+shlex.quote(src['remote'])+' && xargs -0 sha256sum --',
                b'\0'.join(p.encode() for p in paths[i:i+500])+b'\0')
        for line in out.decode().splitlines():
            digest,path=line.split('  ',1);result[path]=digest
    return result

def write_json(path,obj):
    tmp=path.with_suffix(path.suffix+'.tmp')
    tmp.write_text(json.dumps(obj,indent=2)+'\n');tmp.replace(path)

def sync_dataset_source(src,root,dry=False):
    started=datetime.now(timezone.utc).isoformat()
    snap=snapshot(src);inv=snap['files'];selected={p:r for p,r in inv.items() if r['selected']}
    dest=root/src['dest'];meta=dest/'_sync'
    print(json.dumps({'source':src['name'],'selected_files':len(selected),
                      'selected_bytes':sum(r['size'] for r in selected.values()),
                      'completed_cases':len(snap['completed_records']),'destination':str(dest)}),flush=True)
    if dry:return
    meta.mkdir(parents=True,exist_ok=True)
    write_json(meta/'REMOTE_SNAPSHOT.json',{k:v for k,v in snap.items() if k!='captured'})
    listing=meta/'files_selected.null'
    transfer=[p for p in selected if p not in snap['captured']]
    listing.write_bytes(b'\0'.join(p.encode() for p in transfer)+b'\0')
    cachepath=meta/'hash_cache.json'
    cache=json.loads(cachepath.read_text()) if cachepath.exists() else {}
    todo=[]
    for p,r in selected.items():
        f=dest/p;old=cache.get(p,{})
        if (p in snap['captured'] or not f.exists() or old.get('source_size')!=r['size']
            or old.get('source_mtime_ns')!=r['mtime_ns'] or f.stat().st_size!=r['size']
            or old.get('local_mtime_ns')!=f.stat().st_mtime_ns):todo.append(p)
    # Disjoint file lists permit concurrent SSH streams without concurrent writes
    # to any file. Balance by source byte size, and compress only useful formats.
    shards=[[] for _ in range(4)];weights=[0]*4
    for p in sorted(transfer,key=lambda p:selected[p]['size'],reverse=True):
        k=min(range(4),key=lambda j:weights[j]);shards[k].append(p);weights[k]+=selected[p]['size']
    def copy_shard(k):
        paths=sorted(shards[k]);lst=meta/f'files_selected_{k}.null'
        lst.write_bytes(b'\0'.join(p.encode() for p in paths)+b'\0')
        with (meta/f'transfer_{k}.log').open('w') as log:
            subprocess.run(['rsync','-a','--partial','-z','--compress-choice=zstd','--compress-level=3',
                            '--info=stats2,progress2','--from0','--files-from='+str(lst),
                            '-e','ssh -o BatchMode=yes -o Compression=no',
                            'centre:'+src['remote'].rstrip('/')+'/',str(dest)+'/'],check=True,stdout=log,stderr=subprocess.STDOUT)
        print('TRANSFER_SHARD_COMPLETE',k,flush=True)
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as pool:
        future=pool.submit(remote_hashes,src,[p for p in todo if p not in snap['captured']])
        copies=[pool.submit(copy_shard,k) for k in range(4)]
        for copy in copies:copy.result()
        expected=future.result()
    for p,v in snap['captured'].items():
        f=dest/p;f.parent.mkdir(parents=True,exist_ok=True)
        f.write_bytes(base64.b64decode(v['data']))
        os.utime(f,ns=(selected[p]['mtime_ns'],selected[p]['mtime_ns']))
        expected[p]=v['sha256']
    print('Verifying local SHA-256 for',len(todo),'new/changed files',flush=True)
    mismatches=[]
    for i,p in enumerate(todo):
        f=dest/p;digest=sha_file(f)
        if digest!=expected[p]:mismatches.append(p);continue
        cache[p]={'source_size':selected[p]['size'],'source_mtime_ns':selected[p]['mtime_ns'],
                  'local_mtime_ns':f.stat().st_mtime_ns,'sha256':digest}
        if (i+1)%1000==0:print('HASHED',i+1,'/',len(todo),flush=True)
    write_json(cachepath,cache)
    (meta/'SHA256SUMS').write_text(''.join(cache[p]['sha256']+'  '+p+'\n' for p in sorted(selected) if p in cache))
    inventory=['path\tsize\tremote_mtime_ns\tstatus']
    inventory.extend(f"{p}\t{r['size']}\t{r['mtime_ns']}\t"+('local_verified' if p in selected and p not in mismatches else 'remote_only(incomplete_run)' if p not in selected else 'sha256_mismatch') for p,r in sorted(inv.items()))
    (meta/'REMOTE_INVENTORY.tsv').write_text('\n'.join(inventory)+'\n')
    records=snap['completed_records']
    if records:
        (meta/'COMPLETED_CASES.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in records))
        rows=['case_id\tsuccess\tdataset_passed\tdataset_frames\tdataset_root']
        rows.extend('\t'.join(str(r.get(k,'')) for k in ['case_id','success','dataset_passed','dataset_frames','dataset_root']) for r in records)
        (meta/'RUNS_SUMMARY.tsv').write_text('\n'.join(rows)+'\n')
    report={'source':src['name'],'remote':'centre:'+src['remote'],'dest':src['dest'],
            'started_at':started,'finished_at':datetime.now(timezone.utc).isoformat(),'frozen_at_utc':snap['frozen_at_utc'],
            'local_files':len(selected),'local_bytes':sum(r['size'] for r in selected.values()),
            'hdf5_copied':sum(p.endswith('.hdf5') for p in selected),'newly_verified':len(todo)-len(mismatches),
            'sha256_mismatches':mismatches,'completed_cases':len(records),
            'successes':sum(bool(r.get('success')) for r in records),
            'datasets':sum(bool(r.get('dataset_passed')) for r in records),
            'frames':sum(r.get('dataset_frames') or 0 for r in records),
            'remote_only_files':sum(not r['selected'] for r in inv.values()),
            'note':'Original remote layout preserved; no deletions; active runs excluded; root campaign metadata captured at snapshot time.'}
    if not records and (dest/'dataset/meta/info.json').is_file():
        info=json.loads((dest/'dataset/meta/info.json').read_text())
        report.update(completed_cases=None,successes=None,datasets=1,
                      episodes=info['total_episodes'],frames=info['total_frames'],
                      note='Complete immutable dataset bundle; remote layout preserved; no deletions. Case-level success counters do not apply.')
    write_json(meta/'LAST_SYNC.json',report)
    with (root/'sync/SYNC_LOG.jsonl').open('a') as f:f.write(json.dumps(report)+'\n')
    print(json.dumps(report,indent=2),flush=True)
    if mismatches:raise RuntimeError('SHA-256 mismatches: '+repr(mismatches))