Spaces:
Sleeping
Sleeping
Pilot r2: replace four cases, causal tutorial and durable bucket ingest
Browse files- app.py +20 -7
- bucket_selftest.py +43 -0
- bucket_storage.py +145 -0
- requirements.txt +1 -1
- study_r2_assets.zip +3 -0
app.py
CHANGED
|
@@ -14,12 +14,14 @@ from pydantic import BaseModel, Field
|
|
| 14 |
|
| 15 |
ROOT = Path(__file__).parent
|
| 16 |
import zipfile
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
DATA = ROOT / 'data'
|
| 24 |
DEMO = os.getenv('DEMO_MODE', 'true').lower() == 'true'
|
| 25 |
SECRET = os.getenv('ASSIGNMENT_SECRET', 'demo-only-secret')
|
|
@@ -108,13 +110,24 @@ def submit(body: Response):
|
|
| 108 |
def save_payload(payload, path):
|
| 109 |
from storage_writer import save_payload as save_batched
|
| 110 |
try:
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
except Exception:
|
| 113 |
raise HTTPException(503, 'Storage unavailable. Retry the same response.') from None
|
| 114 |
|
| 115 |
|
| 116 |
@app.on_event('startup')
|
| 117 |
async def check_live_storage():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
if os.getenv('LIVE_STORAGE_SELFTEST', 'false').lower() == 'true':
|
| 119 |
if DEMO:
|
| 120 |
raise RuntimeError('Storage self-test requires live storage configuration')
|
|
|
|
| 14 |
|
| 15 |
ROOT = Path(__file__).parent
|
| 16 |
import zipfile
|
| 17 |
+
for bundle in ('assets.zip', 'study_r2_assets.zip'):
|
| 18 |
+
if not (ROOT / bundle).is_file(): continue
|
| 19 |
+
with zipfile.ZipFile(ROOT / bundle) as archive:
|
| 20 |
+
for member in archive.infolist():
|
| 21 |
+
target = (ROOT / member.filename).resolve()
|
| 22 |
+
if not target.is_relative_to(ROOT.resolve()):
|
| 23 |
+
raise RuntimeError('Invalid packaged asset path')
|
| 24 |
+
archive.extractall(ROOT)
|
| 25 |
DATA = ROOT / 'data'
|
| 26 |
DEMO = os.getenv('DEMO_MODE', 'true').lower() == 'true'
|
| 27 |
SECRET = os.getenv('ASSIGNMENT_SECRET', 'demo-only-secret')
|
|
|
|
| 110 |
def save_payload(payload, path):
|
| 111 |
from storage_writer import save_payload as save_batched
|
| 112 |
try:
|
| 113 |
+
if os.getenv('HF_RESPONSE_BUCKET'):
|
| 114 |
+
from bucket_storage import save_payload as save_durable
|
| 115 |
+
save_durable(payload, path)
|
| 116 |
+
else:
|
| 117 |
+
save_batched(payload, path, REPO)
|
| 118 |
except Exception:
|
| 119 |
raise HTTPException(503, 'Storage unavailable. Retry the same response.') from None
|
| 120 |
|
| 121 |
|
| 122 |
@app.on_event('startup')
|
| 123 |
async def check_live_storage():
|
| 124 |
+
if os.getenv('HF_RESPONSE_BUCKET'):
|
| 125 |
+
from starlette.concurrency import run_in_threadpool
|
| 126 |
+
from bucket_storage import initialize
|
| 127 |
+
if os.getenv('BUCKET_STORAGE_SELFTEST', 'false').lower() == 'true':
|
| 128 |
+
from bucket_selftest import run_selftest
|
| 129 |
+
app.state.bucket_storage_test = await run_in_threadpool(run_selftest)
|
| 130 |
+
await run_in_threadpool(initialize)
|
| 131 |
if os.getenv('LIVE_STORAGE_SELFTEST', 'false').lower() == 'true':
|
| 132 |
if DEMO:
|
| 133 |
raise RuntimeError('Storage self-test requires live storage configuration')
|
bucket_selftest.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Opt-in live probe: synthetic immutable events only; never deletes data."""
|
| 2 |
+
import hashlib, json, os, time, uuid
|
| 3 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from statistics import median
|
| 6 |
+
from bucket_storage import HubStore, DurableIngest
|
| 7 |
+
|
| 8 |
+
def run_selftest():
|
| 9 |
+
store = HubStore(os.environ['HF_RESPONSE_BUCKET'], os.environ['HF_DATASET_REPO'],
|
| 10 |
+
os.environ['BUCKET_TOKEN'], os.environ['HF_TOKEN'])
|
| 11 |
+
run = str(uuid.uuid4())
|
| 12 |
+
records = []
|
| 13 |
+
for i in range(12):
|
| 14 |
+
payload = json.dumps({'synthetic':True,'test':'bucket-durability','run':run,'item':i}, sort_keys=True).encode()
|
| 15 |
+
path = 'responses/storage-selftest-bucket/' + run + '/' + hashlib.sha256(payload).hexdigest()+'.json'
|
| 16 |
+
records.append((payload,path))
|
| 17 |
+
first = DurableIngest(store, background=False)
|
| 18 |
+
def save(item):
|
| 19 |
+
start = time.monotonic()
|
| 20 |
+
first.save(*item)
|
| 21 |
+
return time.monotonic()-start
|
| 22 |
+
with ThreadPoolExecutor(max_workers=12) as pool:
|
| 23 |
+
durations=list(pool.map(save, records + records[:6]))
|
| 24 |
+
first.close()
|
| 25 |
+
# New writer with no in-memory cache/queue: emulate a process restart before
|
| 26 |
+
# mirror. All source objects must be discoverable and recoverable remotely.
|
| 27 |
+
restored = dict(store.get_many([p for _,p in records]))
|
| 28 |
+
if any(restored.get(p)!=b for b,p in records):
|
| 29 |
+
raise RuntimeError('Bucket readback mismatch')
|
| 30 |
+
second = DurableIngest(store, background=False)
|
| 31 |
+
second.recover_once()
|
| 32 |
+
second.close()
|
| 33 |
+
from huggingface_hub import hf_hub_download
|
| 34 |
+
for body,path in records:
|
| 35 |
+
local=hf_hub_download(repo_id=store.repo, repo_type='dataset', filename=path,
|
| 36 |
+
token=os.environ['HF_TOKEN'], force_download=True)
|
| 37 |
+
if Path(local).read_bytes()!=body:
|
| 38 |
+
raise RuntimeError('Dataset mirror readback mismatch')
|
| 39 |
+
result={'passed':True,'unique':12,'requests':18,'remote_bucket_readback':12,
|
| 40 |
+
'restart_recovery_dataset_readback':12,'seconds_median':round(median(durations),3),
|
| 41 |
+
'seconds_max':round(max(durations),3)}
|
| 42 |
+
print('BUCKET_SELFTEST '+json.dumps(result,sort_keys=True),flush=True)
|
| 43 |
+
return result
|
bucket_storage.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional durable ingest in a PRIVATE HF bucket, then async Dataset mirroring.
|
| 2 |
+
|
| 3 |
+
Never enable without owner-approved bucket and scoped token. A browser may close
|
| 4 |
+
after save() returns, not before its request reaches the server. No local disk is
|
| 5 |
+
treated as durable. Bucket objects are retained; there is no delete operation.
|
| 6 |
+
"""
|
| 7 |
+
import hashlib
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import tempfile
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
from collections import OrderedDict
|
| 14 |
+
from concurrent.futures import Future
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
_PATH = re.compile(r"responses/[A-Za-z0-9_.-]{1,80}/[0-9a-f-]{36}/[0-9a-f]{64}\.json\Z")
|
| 18 |
+
|
| 19 |
+
def valid_payload(path, payload):
|
| 20 |
+
if not _PATH.fullmatch(path) or len(payload) > 65536:
|
| 21 |
+
raise ValueError('Invalid response object')
|
| 22 |
+
if path.rsplit('/', 1)[-1] != hashlib.sha256(payload).hexdigest() + '.json':
|
| 23 |
+
raise ValueError('Response digest mismatch')
|
| 24 |
+
|
| 25 |
+
class HubStore:
|
| 26 |
+
def __init__(self, bucket, repo, bucket_token, dataset_token):
|
| 27 |
+
from huggingface_hub import HfApi
|
| 28 |
+
self.bucket, self.repo = bucket, repo
|
| 29 |
+
self.bapi = HfApi(token=bucket_token)
|
| 30 |
+
self.dapi = HfApi(token=dataset_token)
|
| 31 |
+
if not self.bapi.bucket_info(bucket).private:
|
| 32 |
+
raise RuntimeError('Response bucket must be private')
|
| 33 |
+
if not self.dapi.repo_info(repo, repo_type='dataset').private:
|
| 34 |
+
raise RuntimeError('Response Dataset must be private')
|
| 35 |
+
|
| 36 |
+
def put(self, path, payload):
|
| 37 |
+
# One immutable object per call: batch API is not transactional.
|
| 38 |
+
# A successful return is remote storage confirmation, not a RAM enqueue.
|
| 39 |
+
self.bapi.batch_bucket_files(self.bucket, add=[(payload, path)])
|
| 40 |
+
|
| 41 |
+
def source_paths(self):
|
| 42 |
+
return [o.path for o in self.bapi.list_bucket_tree(self.bucket, prefix='responses', recursive=True)
|
| 43 |
+
if getattr(o, 'type', None) == 'file' and _PATH.fullmatch(o.path)]
|
| 44 |
+
|
| 45 |
+
def mirrored_paths(self):
|
| 46 |
+
return set(self.dapi.list_repo_files(self.repo, repo_type='dataset'))
|
| 47 |
+
|
| 48 |
+
def get_many(self, paths):
|
| 49 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 50 |
+
files = [(p, str(Path(tmp) / str(i))) for i, p in enumerate(paths)]
|
| 51 |
+
self.bapi.download_bucket_files(self.bucket, files=files, raise_on_missing_files=True)
|
| 52 |
+
result = [(p, Path(local).read_bytes()) for p, local in files]
|
| 53 |
+
for path, data in result:
|
| 54 |
+
valid_payload(path, data)
|
| 55 |
+
return result
|
| 56 |
+
|
| 57 |
+
def mirror(self, records):
|
| 58 |
+
from huggingface_hub import CommitOperationAdd
|
| 59 |
+
self.dapi.create_commit(repo_id=self.repo, repo_type='dataset',
|
| 60 |
+
operations=[CommitOperationAdd(path_in_repo=p, path_or_fileobj=b) for p,b in records],
|
| 61 |
+
commit_message='Mirror durably received study responses')
|
| 62 |
+
|
| 63 |
+
class DurableIngest:
|
| 64 |
+
def __init__(self, store, *, interval=30, max_batch=64, max_parallel=8, background=True):
|
| 65 |
+
self.store, self.interval, self.max_batch = store, interval, max_batch
|
| 66 |
+
self.lock, self.mirror_lock = threading.Lock(), threading.Lock()
|
| 67 |
+
self.slots = threading.BoundedSemaphore(max_parallel)
|
| 68 |
+
self.pending, self.confirmed = {}, OrderedDict()
|
| 69 |
+
self.stop, self.wake = threading.Event(), threading.Event()
|
| 70 |
+
self.thread = None
|
| 71 |
+
if background:
|
| 72 |
+
self.thread = threading.Thread(target=self._loop, name='durable-response-mirror', daemon=True)
|
| 73 |
+
self.thread.start()
|
| 74 |
+
|
| 75 |
+
def save(self, payload, path):
|
| 76 |
+
valid_payload(path, payload)
|
| 77 |
+
with self.lock:
|
| 78 |
+
if path in self.confirmed:
|
| 79 |
+
return
|
| 80 |
+
owner = path not in self.pending
|
| 81 |
+
if owner:
|
| 82 |
+
self.pending[path] = Future()
|
| 83 |
+
future = self.pending[path]
|
| 84 |
+
if not owner:
|
| 85 |
+
return future.result()
|
| 86 |
+
try:
|
| 87 |
+
with self.slots:
|
| 88 |
+
self.store.put(path, payload)
|
| 89 |
+
with self.lock:
|
| 90 |
+
self.confirmed[path] = True
|
| 91 |
+
while len(self.confirmed) > 10000:
|
| 92 |
+
self.confirmed.popitem(last=False)
|
| 93 |
+
future.set_result(None)
|
| 94 |
+
self.wake.set()
|
| 95 |
+
except Exception:
|
| 96 |
+
with self.lock:
|
| 97 |
+
future.set_exception(RuntimeError('Durable storage unavailable'))
|
| 98 |
+
raise RuntimeError('Durable storage unavailable') from None
|
| 99 |
+
finally:
|
| 100 |
+
with self.lock:
|
| 101 |
+
self.pending.pop(path, None)
|
| 102 |
+
|
| 103 |
+
def recover_once(self):
|
| 104 |
+
# Scan remote state, never a local pending queue. This reconstructs all
|
| 105 |
+
# unfinished work after a crash, rebuild, idle shutdown, or deployment.
|
| 106 |
+
with self.mirror_lock:
|
| 107 |
+
existing = self.store.mirrored_paths()
|
| 108 |
+
waiting = [p for p in self.store.source_paths() if p not in existing]
|
| 109 |
+
for i in range(0, len(waiting), self.max_batch):
|
| 110 |
+
records = self.store.get_many(waiting[i:i+self.max_batch])
|
| 111 |
+
self.store.mirror(records)
|
| 112 |
+
return len(waiting)
|
| 113 |
+
|
| 114 |
+
def _loop(self):
|
| 115 |
+
while not self.stop.is_set():
|
| 116 |
+
try:
|
| 117 |
+
self.recover_once()
|
| 118 |
+
except Exception:
|
| 119 |
+
# Do not leak token, paths, participant IDs, or responses.
|
| 120 |
+
print('Dataset mirror deferred; durable source retained', flush=True)
|
| 121 |
+
self.wake.wait(self.interval)
|
| 122 |
+
self.wake.clear()
|
| 123 |
+
# Coalesce burst submissions without delaying durable receipt.
|
| 124 |
+
self.stop.wait(1.0)
|
| 125 |
+
|
| 126 |
+
def close(self):
|
| 127 |
+
self.stop.set()
|
| 128 |
+
self.wake.set()
|
| 129 |
+
if self.thread:
|
| 130 |
+
self.thread.join(timeout=2)
|
| 131 |
+
|
| 132 |
+
_instance = None
|
| 133 |
+
_init_lock = threading.Lock()
|
| 134 |
+
|
| 135 |
+
def initialize():
|
| 136 |
+
global _instance
|
| 137 |
+
with _init_lock:
|
| 138 |
+
if _instance is None:
|
| 139 |
+
store = HubStore(os.environ['HF_RESPONSE_BUCKET'], os.environ['HF_DATASET_REPO'],
|
| 140 |
+
os.environ['BUCKET_TOKEN'], os.environ['HF_TOKEN'])
|
| 141 |
+
_instance = DurableIngest(store)
|
| 142 |
+
return _instance
|
| 143 |
+
|
| 144 |
+
def save_payload(payload, path):
|
| 145 |
+
initialize().save(payload, path)
|
requirements.txt
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
fastapi>=0.115,<1
|
| 2 |
uvicorn>=0.30,<1
|
| 3 |
-
huggingface_hub
|
| 4 |
Pillow>=10,<13
|
| 5 |
httpx>=0.27,<1
|
|
|
|
| 1 |
fastapi>=0.115,<1
|
| 2 |
uvicorn>=0.30,<1
|
| 3 |
+
huggingface_hub==1.19.0
|
| 4 |
Pillow>=10,<13
|
| 5 |
httpx>=0.27,<1
|
study_r2_assets.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:82f234ebf590cce661b26ba1f30a60615acdfb9f3bfc1156bfce6143eaa38769
|
| 3 |
+
size 38183219
|