OmniDex / tools /parallel_transfer.py
willfny's picture
Add bounded parallel transfer, verified checkpoints and per-shard recovery
c11de1f verified
Raw History Blame Contribute Delete
11.5 kB
"""Bounded packaging/upload pipeline. Original source files are never modified."""
from pathlib import Path
from collections import deque,Counter
from concurrent.futures import ThreadPoolExecutor,wait,FIRST_COMPLETED
import datetime,hashlib,json,os,shutil,threading,time
def now():return datetime.datetime.now(datetime.timezone.utc).isoformat()
def fingerprint(job):
with job.mutex:
checkpoints=job.db.execute("SELECT component,complete,listed,retained,bytes FROM checkpoints ORDER BY component").fetchall()
if any(row[1]!=1 for row in checkpoints):return None
data={"schema":2,"source_root":job.c["source_root"],"bucket":job.c["bucket"],
"components":job.c["components"],"views":job.c.get("views_per_scene",5),
"anomalies":job.c.get("known_source_anomalies",[]),"checkpoints":checkpoints}
return hashlib.sha256(json.dumps(data,sort_keys=True).encode()).hexdigest()
def resources(job):
mem={}
for line in Path("/proc/meminfo").read_text().splitlines():
key,value=line.split(":",1);mem[key]=int(value.split()[0])*1024
values=[int(x) for x in Path("/proc/stat").read_text().splitlines()[0].split()[1:9]]
total=sum(values);idle=values[3]+values[4];previous=getattr(resources,"_cpu_previous",None)
busy=0.0
if previous and total>previous[0]:busy=100*(1-(idle-previous[1])/(total-previous[0]))
resources._cpu_previous=(total,idle)
disk=shutil.disk_usage(job.state)
staging=sum(p.stat().st_size for p in (job.state/"staging").glob("*") if p.is_file())
return {"memory_available_bytes":mem["MemAvailable"],"disk_free_bytes":disk.free,
"staging_bytes":staging,"load_1m":os.getloadavg()[0],"host_cpu_busy_percent":round(busy,2)}
def classify(error):
response=getattr(error,"response",None)
status=getattr(response,"status_code",None) or getattr(error,"code",None)
if isinstance(response,dict):status=response.get("ResponseMetadata",{}).get("HTTPStatusCode",status)
message=str(error).lower();kind=type(error).__name__.lower()
if status in [402,413] or any(s in message for s in ["storage quota","storage limit","quota exceeded"]):return "quota"
if status in [408,425,429,500,502,503,504] or any(s in kind for s in ["timeout","connection","endpoint"]) or any(s in message for s in ["timed out","network is unreachable","connection reset","connection refused"]):return "network"
return "requires_inspection"
def prepare(job,row):
sid,cid,path,*_=row
local=job.state/"staging"/(sid+(".tar" if path.endswith(".tar") else ".tar.zst"))
manifest=job.state/"staging"/(sid+".files.jsonl")
with job.mutex:current=job.db.execute("SELECT status FROM shards WHERE id=?",(sid,)).fetchone()[0]
if current=="packed" and local.is_file() and manifest.is_file():
job.event("packed_shard_resumed",shard=sid);return
job.package(row)
def send(job,row,commit_lock):
from huggingface_hub import CommitOperationAdd
sid,cid,path,*_=row
with job.mutex:
size,digest,blob,previous=job.db.execute("SELECT local_bytes,sha256,git_blob,commit_oid FROM shards WHERE id=?",(sid,)).fetchone()
local=job.state/"staging"/(sid+(".tar" if path.endswith(".tar") else ".tar.zst"))
manifest=job.state/"staging"/(sid+".files.jsonl")
data=manifest.read_bytes();sha=hashlib.sha256(data).hexdigest()
git=hashlib.sha1(b"blob "+str(len(data)).encode()+b"\0"+data).hexdigest()
job.repo_info();start=time.monotonic();operations=[]
for source,remote,nbytes,checksum,gitblob in [(local,path,size,digest,blob),(manifest,path+".files.jsonl",len(data),sha,git)]:
if not job.verified(remote,nbytes,checksum,gitblob):
operations.append(CommitOperationAdd(path_in_repo=remote,path_or_fileobj=source))
archive_needed=any(op.path_in_repo==path for op in operations)
job.event("uploading",shard=sid,hf_path=path,bytes=size)
revision="main";oid=previous
if operations:
# Network transfers run in parallel; only branch commits are serialized.
job.api.preupload_lfs_files(repo_id=job.c["repo_id"],repo_type="dataset",
revision="main",additions=operations,num_threads=1)
with commit_lock:
commit=job.api.create_commit(repo_id=job.c["repo_id"],repo_type="dataset",revision="main",
operations=operations,num_threads=1,commit_message="STD verified shard: "+path)
oid=revision=commit.oid
if not job.verified(path,size,digest,blob,revision):raise RuntimeError("Archive absent after commit")
if not job.verified(path+".files.jsonl",len(data),sha,git,revision):raise RuntimeError("Sidecar absent after commit")
if not oid:oid=job.api.repo_info(job.c["repo_id"],repo_type="dataset").sha
with job.mutex:
job.db.execute("UPDATE shards SET status='verified',commit_oid=? WHERE id=?",(oid,sid))
job.db.execute("DELETE FROM shard_failures WHERE id=?",(sid,));job.db.commit()
job.event("file_uploaded",shard=sid,hf_path=path,bytes=size if archive_needed else 0,
seconds=round(time.monotonic()-start,2),commit_oid=oid,parallel=True)
job.event("shard_verified",shard=sid,hf_path=path,bytes=size,sha256=digest)
local.unlink(missing_ok=True);manifest.unlink(missing_ok=True)
def transfer(job,ids):
packers=max(1,min(2,int(job.c.get("parallel_pack_workers",2))))
uploaders=max(1,min(2,int(job.c.get("parallel_upload_workers",2))))
slots=packers+uploaders;budget=int(job.c.get("max_staging_bytes",30*1024**3))
minfree=int(job.c.get("min_free_disk_bytes",100*1024**3))
minmem=int(job.c.get("min_available_memory_bytes",16*1024**3))
with job.mutex:
job.db.execute("CREATE TABLE IF NOT EXISTS shard_failures(id TEXT PRIMARY KEY,attempts INTEGER,next_retry REAL,kind TEXT,error TEXT)")
job.db.commit()
rows=[]
for cid in ids:rows.extend(job.db.execute("SELECT * FROM shards WHERE component=? AND status!='verified' ORDER BY id",(cid,)).fetchall())
failures={r[0]:r[1:] for r in job.db.execute("SELECT * FROM shard_failures")}
if not rows:return
todo=deque(rows);packing={};ready=deque();uploading={};commit_lock=threading.Lock()
last_report=0;pause_until=0;pause_reason="";error_window=deque()
job.event("parallel_transfer_started",pack_workers=packers,upload_workers=uploaders,max_inflight=slots,staging_budget_bytes=budget)
def failure(row,error):
nonlocal pause_until,pause_reason
sid=row[0];kind=classify(error);attempts=failures.get(sid,(0,))[0]+1
delay=min(900,max(0.1,float(job.c.get("retry_base_seconds",30)))*2**min(attempts,5)) if kind=="network" else (900 if kind=="quota" else 3600)
safe=job.safe(error);retry=time.time()+delay
failures[sid]=(attempts,retry,kind,safe)
with job.mutex:
job.db.execute("INSERT OR REPLACE INTO shard_failures VALUES(?,?,?,?,?)",(sid,attempts,retry,kind,safe));job.db.commit()
job.event("shard_retry_scheduled",shard=sid,attempts=attempts,kind=kind,retry_seconds=delay,error=safe)
todo.append(row)
if kind=="quota":pause_until=max(pause_until,retry);pause_reason="quota"
if kind=="requires_inspection":
stamp=time.time();error_window.append((stamp,type(error).__name__,safe))
while error_window and stamp-error_window[0][0]>300:error_window.popleft()
identical=sum(1 for _,name,detail in error_window if name==type(error).__name__ and detail==safe)
if identical>=3:
pause_until=max(pause_until,stamp+300);pause_reason="repeated_error"
with ThreadPoolExecutor(max_workers=packers,thread_name_prefix="pack") as pp,ThreadPoolExecutor(max_workers=uploaders,thread_name_prefix="upload") as up:
while todo or packing or ready or uploading:
for future in list(packing):
if not future.done():continue
row=packing.pop(future)
try:future.result();ready.append(row)
except Exception as error:failure(row,error)
for future in list(uploading):
if not future.done():continue
row=uploading.pop(future)
try:future.result();failures.pop(row[0],None)
except Exception as error:failure(row,error)
stat=resources(job);stamp=time.time()
gate=stamp<pause_until
# Existing uploads may drain the staging queue even when disk is low.
if not gate and stat["memory_available_bytes"]>=minmem:
while ready and len(uploading)<uploaders:
row=ready.popleft();uploading[up.submit(send,job,row,commit_lock)]=row
reason=""
if gate:reason=pause_reason
elif stat["memory_available_bytes"]<minmem:reason="low_available_memory"
elif stat["disk_free_bytes"]<minfree:reason="low_disk_space"
elif stat["host_cpu_busy_percent"]>float(job.c.get("max_host_cpu_percent",95)) and stat["load_1m"]>max(1,os.cpu_count() or 1)*0.95:reason="high_host_cpu_load"
if not reason:
scans=len(todo)
while todo and scans and len(packing)<packers and len(packing)+len(ready)+len(uploading)<slots:
scans-=1;row=todo.popleft();sid=row[0]
if failures.get(sid,(0,0))[1]>stamp:todo.append(row);continue
estimate=int(row[3]*1.15)+64*1024**2
active=list(packing.values())+list(ready)+list(uploading.values())
reserve=0
for other in active:
existing=sum(p.stat().st_size for p in (job.state/"staging").glob(other[0]+"*") if p.is_file())
reserve+=max(0,int(other[3]*1.15)+64*1024**2-existing)
existing=sum(p.stat().st_size for p in (job.state/"staging").glob(sid+"*") if p.is_file())
required=max(0,estimate-existing)
if stat["staging_bytes"]+reserve+required>budget or stat["disk_free_bytes"]-reserve-required<minfree:
todo.appendleft(row);reason="staging_budget";break
packing[pp.submit(prepare,job,row)]=row
if stamp-last_report>=20:
with job.mutex:
totals=job.db.execute("SELECT status,COUNT(*),COALESCE(SUM(source_bytes),0),COALESCE(SUM(local_bytes),0) FROM shards GROUP BY status").fetchall()
health={"updated_utc":now(),"pid":os.getpid(),"phase":"resource_paused" if reason else ("retry_wait" if todo and not(packing or ready or uploading) else "running"),
"pause_reason":reason,"pack_workers":packers,"upload_workers":uploaders,
"packing":[r[0] for r in packing.values()],"uploading":[r[0] for r in uploading.values()],
"ready":[r[0] for r in ready],"pending":len(todo),"failures":len(failures),
"failure_details":[{"shard":sid,"attempts":v[0],"retry_at_unix":v[1],"kind":v[2],"error":v[3]} for sid,v in list(failures.items())[:10]],
"shard_totals":totals,**stat}
temp=job.state/"health.tmp";temp.write_text(json.dumps(health,indent=2));temp.replace(job.state/"health.json")
last_report=stamp
current=list(packing)+list(uploading)
if current:wait(current,timeout=3,return_when=FIRST_COMPLETED)
else:time.sleep(5)
job.event("parallel_transfer_finished")