junidude14 commited on
Commit
6008029
·
verified ·
1 Parent(s): 3f6049e

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20260928T141133Z-catalog-cache-fix/diffusion/dataset/server_1/maintenance/ca21c3874df84b79/catalog.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Current paper catalogs derived only from the immutable baseline and latest chain."""
2
+ from __future__ import annotations
3
+ import base64,csv,datetime,hashlib,io,json,os,re,shlex,subprocess,tempfile
4
+ from pathlib import Path
5
+ from typing import Any
6
+ PROJECT='pbisc-diffusion'
7
+ ID=re.compile(r'[0-9]{8}T[0-9]{6}Z-[a-z0-9-]+\Z')
8
+ NAMES=('CURRENT_MODEL_INDEX.csv','CURRENT_INFERENCE_LOCATIONS.csv','CURRENT_CATALOG.json')
9
+ HF_PREFIX='paper-releases/pbisc-diffusion/'
10
+
11
+ def read(path: Path) -> Any:
12
+ if path.is_symlink():raise ValueError('catalog_symlink_refused')
13
+ return json.loads(path.read_text())
14
+ def sha(data: bytes) -> str:return hashlib.sha256(data).hexdigest()
15
+ def atomic(path: Path,data: bytes) -> None:
16
+ if path.is_symlink():raise ValueError('catalog_symlink_refused')
17
+ with tempfile.NamedTemporaryFile(dir=path.parent,prefix='.catalog-',delete=False) as f:
18
+ tmp=Path(f.name);f.write(data);f.flush();os.fsync(f.fileno())
19
+ try:os.replace(tmp,path)
20
+ finally:tmp.unlink(missing_ok=True)
21
+ def encoded(value: Any) -> bytes:return (json.dumps(value,indent=2,sort_keys=True,ensure_ascii=False)+'\n').encode()
22
+ def csv_bytes(rows: list[dict[str,Any]], first: list[str]) -> bytes:
23
+ fields=first+sorted({k for row in rows for k in row}-set(first))
24
+ stream=io.StringIO(newline='');w=csv.DictWriter(stream,fieldnames=fields);w.writeheader()
25
+ for row in rows:w.writerow({k:json.dumps(v,sort_keys=True) if isinstance(v,(dict,list)) else v for k,v in row.items()})
26
+ return stream.getvalue().encode()
27
+ def chain(root: Path,pointer: dict[str,Any]|None) -> list[tuple[Path,dict[str,Any]]]:
28
+ result=[];seen=set()
29
+ while pointer is not None:
30
+ identifier=pointer.get('id')
31
+ if pointer.get('project_id',PROJECT)!=PROJECT or not isinstance(identifier,str) or not ID.fullmatch(identifier) or identifier in seen:raise ValueError('invalid_catalog_history')
32
+ seen.add(identifier);folder=root/'maintenance/updates'/identifier
33
+ if folder.is_symlink():raise ValueError('catalog_symlink_refused')
34
+ path=folder/'UPDATE_VERIFIED.json';proof=read(path)
35
+ if sha(path.read_bytes())!=pointer.get('verified_receipt_sha256'):raise ValueError('catalog_proof_digest_mismatch')
36
+ if proof.get('status')!='PASS' or proof.get('project_id')!=PROJECT or proof.get('update_id')!=identifier:raise ValueError('catalog_wrong_project_or_state')
37
+ manifest=folder/'manifest.json'
38
+ if proof.get('schema')!='pbisc.diffusion.update-verified.v1' or not proof.get('manifest_sha256'):raise ValueError('catalog_unbound_proof')
39
+ if manifest.is_symlink() or sha(manifest.read_bytes())!=proof['manifest_sha256']:raise ValueError('catalog_manifest_digest_mismatch')
40
+ result.append((folder,proof));pointer=proof.get('parent_latest')
41
+ return list(reversed(result))
42
+ def checked_metadata(folder: Path,proof: dict[str,Any],name: str,required: bool=True) -> dict[str,Any]:
43
+ path=folder/name
44
+ matches=[r for r in proof['assets'] if r.get('category')=='update_metadata' and r.get('source')==str(path)]
45
+ if not matches:
46
+ if required:raise ValueError('catalog_metadata_not_verified')
47
+ return {}
48
+ if len(matches)!=1 or path.is_symlink() or sha(path.read_bytes())!=matches[0]['sha256']:raise ValueError('catalog_metadata_digest_mismatch')
49
+ return read(path)
50
+ def build(root: Path) -> tuple[dict[str,bytes],dict[str,Any]]:
51
+ reference=root/'maintenance/BASELINE_REFERENCE.json'
52
+ if reference.exists():
53
+ for name,digest in read(reference)['immutable_files'].items():
54
+ path=root/name
55
+ if Path(name).is_absolute() or '..' in Path(name).parts or path.is_symlink() or sha(path.read_bytes())!=digest:raise ValueError('frozen_baseline_changed')
56
+ latest=read(root/'LATEST.json') if (root/'LATEST.json').exists() else None
57
+ verified=chain(root,latest)
58
+ with (root/'MODEL_INDEX.csv').open(newline='') as f:models={(x['host'],x['source']):dict(x,project_id=PROJECT,catalog_version='paper-20260928') for x in csv.DictReader(f)}
59
+ locations={}
60
+ for filename in ['inference-locations.json','legacy-inference-locations.json']:
61
+ for row in read(root/filename)['entries']:
62
+ locations[row['host'],row['path']]=dict(row,project_id=PROJECT,catalog_version='paper-20260928',source_catalog=filename,sha256_basis='existing_receipt_not_fresh_output_hash')
63
+ for folder,proof in verified:
64
+ request=checked_metadata(folder,proof,'request.json',False)
65
+ details={(x['host'],x['source']):x for x in request.get('assets',[])}
66
+ for row in proof['assets']:
67
+ if row.get('category')!='checkpoint':continue
68
+ key=(row['host'],row['source']);old=models.get(key,{})
69
+ extra=details.get(key,{})
70
+ m=dict(old,host=row['host'],source=row['source'],sha256=row['sha256'],bytes=row['bytes'],category='checkpoint',state=row.get('state',''),bundle_path=row['bundle_path'],hf_repo=row['repo_id'],hf_path=row['remote_path'],hf_revision=row['hf_revision'],project_id=PROJECT,catalog_version=proof['update_id'])
71
+ for key2 in ['cohort','protocol','mode','parent_sha256']:m[key2]=extra.get(key2,m.get(key2,''))
72
+ m['hf_release_tag']='';m['hf_url']=f"https://huggingface.co/{row['repo_id']}/resolve/{row['hf_revision']}/{row['remote_path']}";models[key]=m
73
+ doc=checked_metadata(folder,proof,'inference_locations.json')
74
+ if doc.get('project_id')!=PROJECT or doc.get('update_id')!=proof['update_id']:raise ValueError('catalog_locator_identity_mismatch')
75
+ for row in doc['locations']:
76
+ key=row['host'],row['path'];entry=dict(locations.get(key,{}));entry.update(row)
77
+ entry.update(project_id=PROJECT,catalog_version=proof['update_id'],source_catalog=f'updates/{proof["update_id"]}/inference_locations.json',status=row['state'],sha256_basis=row.get('sha256_basis','existing_receipt_not_fresh_output_hash'))
78
+ locations[key]=entry
79
+ outputs={NAMES[0]:csv_bytes(sorted(models.values(),key=lambda x:(x.get('cohort',''),x['host'],x['source'])),['project_id','catalog_version','category','cohort','protocol','mode','state','host','source','sha256','hf_repo','hf_path','hf_revision','hf_url']),NAMES[1]:csv_bytes(sorted(locations.values(),key=lambda x:(x.get('cohort',''),x['host'],x['path'])),['project_id','catalog_version','cohort','experiment','host','path','status','sha256_basis','output_sha256','checkpoint_sha256','condition_sha256','generation_log','receipt'])}
80
+ meta={'schema':'pbisc-diffusion.current-catalog.v1','project_id':PROJECT,'generated_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'latest_id':latest.get('id') if latest else None,'baseline':'paper-20260928','models':len(models),'inference_locations':len(locations),'applied_updates':[proof['update_id'] for _,proof in verified],'files':{name:{'sha256':sha(data),'bytes':len(data)} for name,data in outputs.items()},'evidence_boundary':'Location states and output hashes come from recorded receipts/observations, not a new inference run or fresh hashing of large generated outputs.'}
81
+ outputs[NAMES[2]]=encoded(meta);return outputs,meta
82
+
83
+ def mirror(outputs: dict[str,bytes],latest_id: str|None) -> None:
84
+ code='''import base64,hashlib,json,os,sys,tempfile
85
+ from pathlib import Path
86
+ r=Path('/home/sj_server_2/PBISC/paper-release-20260928');d=json.load(sys.stdin)
87
+ assert d['project_id']=='pbisc-diffusion' and r.is_dir() and not r.is_symlink()
88
+ p=r/'LATEST.json';current=json.loads(p.read_text()) if p.exists() else None
89
+ assert (current.get('id') if current else None)==d['latest_id']
90
+ allowed=['CURRENT_MODEL_INDEX.csv','CURRENT_INFERENCE_LOCATIONS.csv','CURRENT_CATALOG.json'];data={}
91
+ assert sorted(d['files'])==sorted(allowed)
92
+ for n,x in d['files'].items():
93
+ assert not (r/n).is_symlink();b=base64.b64decode(x['data']);assert hashlib.sha256(b).hexdigest()==x['sha256'];data[n]=b
94
+ for n in allowed:
95
+ with tempfile.NamedTemporaryFile(dir=r,prefix='.catalog-',delete=False) as f:
96
+ f.write(data[n]);f.flush();os.fsync(f.fileno());tmp=f.name
97
+ os.replace(tmp,r/n)
98
+ print(json.dumps({'files':len(data),'latest_id':d['latest_id']}))'''
99
+ request={'project_id':PROJECT,'latest_id':latest_id,'files':{n:{'data':base64.b64encode(b).decode(),'sha256':sha(b)} for n,b in outputs.items()}}
100
+ result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=10','spark-0110',shlex.join(['python3','-B','-c',code])],input=json.dumps(request),text=True,capture_output=True)
101
+ if result.returncode:raise ValueError('catalog_remote_sync_failed')
102
+ reply=json.loads(result.stdout)
103
+ if reply.get('files')!=3 or reply.get('latest_id')!=latest_id:raise ValueError('catalog_remote_verification_failed')
104
+ def publish_views(outputs: dict[str,bytes],latest: dict[str,Any]|None) -> str:
105
+ os.environ['HF_HUB_DISABLE_XET']='1';os.environ['HF_HUB_ENABLE_HF_TRANSFER']='0'
106
+ from huggingface_hub import HfApi,CommitOperationAdd,hf_hub_download,constants
107
+ constants.HF_HUB_ENABLE_HF_TRANSFER=False
108
+ api=HfApi(token=True);info=api.repo_info('junidude14/PBISC-data',repo_type='dataset',files_metadata=True)
109
+ if info.private is not True:raise ValueError('catalog_dataset_not_private')
110
+ current={x.rfilename:x for x in info.siblings}
111
+ if HF_PREFIX+'LATEST.json' in current:
112
+ p=hf_hub_download('junidude14/PBISC-data',HF_PREFIX+'LATEST.json',repo_type='dataset',revision=info.sha,token=True)
113
+ # HF's pinned download cache uses snapshot-to-blob symlinks. This is an SDK
114
+ # download, not a project source path; project reads retain the strict guard.
115
+ if json.loads(Path(p).read_text())!=latest:raise ValueError('catalog_hf_latest_changed')
116
+ elif latest is not None:raise ValueError('catalog_hf_latest_missing')
117
+ operations=[CommitOperationAdd(path_in_repo=HF_PREFIX+n,path_or_fileobj=io.BytesIO(b)) for n,b in outputs.items()]
118
+ result=api.create_commit('junidude14/PBISC-data',repo_type='dataset',parent_commit=info.sha,operations=operations,commit_message='Refresh PBISC-diffusion current model and inference catalogs',num_threads=2)
119
+ verified=api.repo_info('junidude14/PBISC-data',repo_type='dataset',revision=result.oid,files_metadata=True)
120
+ entries={x.rfilename:x for x in verified.siblings}
121
+ for name,data in outputs.items():
122
+ item=entries.get(HF_PREFIX+name)
123
+ if item is None or item.size!=len(data):raise ValueError('catalog_hf_size_mismatch')
124
+ if item.lfs:
125
+ if item.lfs.sha256!=sha(data):raise ValueError('catalog_hf_digest_mismatch')
126
+ elif item.blob_id!=hashlib.sha1(f'blob {len(data)}\0'.encode()+data).hexdigest():raise ValueError('catalog_hf_digest_mismatch')
127
+ return result.oid
128
+
129
+ def refresh(root: Path,*,sync: bool=True) -> None:
130
+ outputs,meta=build(root)
131
+ # All source/proof checks finish before any live catalog is replaced.
132
+ for name in NAMES:atomic(root/name,outputs[name])
133
+ if sync:
134
+ latest=read(root/'LATEST.json') if (root/'LATEST.json').exists() else None
135
+ mirror(outputs,meta['latest_id']);revision=publish_views(outputs,latest)
136
+ atomic(root/'maintenance/CATALOG_SYNC.json',encoded({'project_id':PROJECT,'status':'PASS','latest_id':meta['latest_id'],'dataset_revision':revision,'files':meta['files']}))
137
+
138
+ if __name__=='__main__':
139
+ import fcntl
140
+ root=Path(__file__).resolve().parent.parent
141
+ with (root/'maintenance/.writer.lock').open('a') as lock:
142
+ fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);refresh(root)
143
+ print('PBISC-diffusion current catalogs verified and synchronized')
paper-releases/pbisc-diffusion/updates/20260928T141133Z-catalog-cache-fix/diffusion/dataset/server_1/maintenance/eaf90a878c5f3647/test_catalog.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv,hashlib,importlib.util,json,tempfile,unittest
2
+ from pathlib import Path
3
+
4
+ PATH=Path(__file__).with_name('catalog.py')
5
+
6
+ class CatalogTests(unittest.TestCase):
7
+ def setUp(self):
8
+ self.tmp=tempfile.TemporaryDirectory();self.root=Path(self.tmp.name)
9
+ self.addCleanup(self.tmp.cleanup)
10
+ with (self.root/'MODEL_INDEX.csv').open('w') as f:
11
+ f.write('host,source,sha256,category,hf_path\nserver_1,/m/base.pt,'+'a'*64+',checkpoint,old/base.pt\n')
12
+ for name,rows in [('inference-locations.json',[{'host':'server_1','path':'/m/out.npz','status':'completed_receipt_present'}]),('legacy-inference-locations.json',[{'host':'server_2','path':'/m/old.npz','status':'present_without_receipt'}])]:
13
+ (self.root/name).write_text(json.dumps({'entries':rows}))
14
+ def module(self):
15
+ self.assertTrue(PATH.is_file(),'catalog implementation is missing')
16
+ spec=importlib.util.spec_from_file_location('catalog_test_module',PATH);m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m
17
+ def add_update(self,identifier,*,parent=None,foreign=False):
18
+ folder=self.root/'maintenance/updates'/identifier;folder.mkdir(parents=True)
19
+ locations={'project_id':'pbisc-diffusion','update_id':identifier,'locations':[{'host':'server_1','path':'/m/new.npz','state':'running','presence':'present'}]}
20
+ p=folder/'inference_locations.json';p.write_text(json.dumps(locations))
21
+ assets=[{'host':'server_1','source':'/m/base.pt','category':'checkpoint','state':'final','sha256':'b'*64,'bytes':50,'repo_id':'junidude14/PBISC','remote_path':'updates/new/base.pt','bundle_path':'updates/new/base.pt','hf_revision':'c'*40}, {'host':'server_1','source':str(p),'category':'update_metadata','sha256':hashlib.sha256(p.read_bytes()).hexdigest()}]
22
+ manifest=folder/'manifest.json';manifest.write_text(json.dumps({'project_id':'pbisc-diffusion','update_id':identifier,'assets':assets}))
23
+ proof={'schema':'pbisc.diffusion.update-verified.v1','manifest_sha256':hashlib.sha256(manifest.read_bytes()).hexdigest(),'status':'PASS','project_id':'other-paper' if foreign else 'pbisc-diffusion','update_id':identifier,'parent_latest':parent,'assets':assets}
24
+ p=folder/'UPDATE_VERIFIED.json';p.write_text(json.dumps(proof));return {'id':identifier,'project_id':'pbisc-diffusion','verified_receipt_sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'parent':parent}
25
+ def test_baseline_projection_preserves_frozen_sources(self):
26
+ before=(self.root/'MODEL_INDEX.csv').read_bytes();self.module().refresh(self.root,sync=False)
27
+ d=json.loads((self.root/'CURRENT_CATALOG.json').read_text());self.assertEqual(d['models'],1);self.assertEqual(d['inference_locations'],2);self.assertEqual((self.root/'MODEL_INDEX.csv').read_bytes(),before)
28
+ def test_only_reachable_verified_update_changes_latest_model_and_adds_locator(self):
29
+ self.add_update('20260928T010000Z-orphan')
30
+ pointer=self.add_update('20260928T020000Z-current');(self.root/'LATEST.json').write_text(json.dumps(pointer))
31
+ self.module().refresh(self.root,sync=False)
32
+ with (self.root/'CURRENT_MODEL_INDEX.csv').open() as f:rows=list(csv.DictReader(f))
33
+ self.assertEqual(len(rows),1);self.assertEqual(rows[0]['sha256'],'b'*64)
34
+ d=json.loads((self.root/'CURRENT_CATALOG.json').read_text());self.assertEqual(d['applied_updates'],[pointer['id']]);self.assertEqual(d['inference_locations'],3)
35
+ with (self.root/'CURRENT_INFERENCE_LOCATIONS.csv').open() as f:rows=list(csv.DictReader(f))
36
+ self.assertEqual(next(x for x in rows if x['path']=='/m/new.npz')['status'],'running')
37
+ def test_orphan_pass_is_not_promoted(self):
38
+ self.add_update('20260928T010000Z-orphan');self.module().refresh(self.root,sync=False)
39
+ d=json.loads((self.root/'CURRENT_CATALOG.json').read_text());self.assertEqual(d['applied_updates'],[]);self.assertEqual(d['inference_locations'],2)
40
+ def test_foreign_or_tampered_proof_refused_before_replacing_catalogs(self):
41
+ m=self.module();m.refresh(self.root,sync=False);before=(self.root/'CURRENT_CATALOG.json').read_bytes()
42
+ p=self.add_update('20260928T030000Z-foreign',foreign=True);(self.root/'LATEST.json').write_text(json.dumps(p))
43
+ with self.assertRaises(ValueError):m.refresh(self.root,sync=False)
44
+ self.assertEqual((self.root/'CURRENT_CATALOG.json').read_bytes(),before)
45
+ def test_hf_managed_cache_symlink_is_readable_without_relaxing_source_guard(self):
46
+ from types import SimpleNamespace
47
+ from unittest.mock import patch
48
+ import huggingface_hub
49
+ m=self.module();latest={'id':'20260928T020000Z-current','project_id':'pbisc-diffusion'}
50
+ blob=self.root/'blob';blob.write_text(json.dumps(latest));cache=self.root/'download-cache.json';cache.symlink_to(blob)
51
+ outputs={name:b'catalog content\n' for name in m.NAMES}
52
+ class Api:
53
+ def repo_info(self,*args,**kw):
54
+ if kw.get('revision')=='b'*40:
55
+ siblings=[SimpleNamespace(rfilename=m.HF_PREFIX+n,size=len(b),lfs=None,blob_id=hashlib.sha1(f'blob {len(b)}\0'.encode()+b).hexdigest()) for n,b in outputs.items()]
56
+ else:siblings=[SimpleNamespace(rfilename=m.HF_PREFIX+'LATEST.json')]
57
+ return SimpleNamespace(private=True,sha='a'*40,siblings=siblings)
58
+ def create_commit(self,*args,**kw):return SimpleNamespace(oid='b'*40)
59
+ with patch.object(huggingface_hub,'HfApi',return_value=Api()),patch.object(huggingface_hub,'hf_hub_download',return_value=str(cache)):
60
+ self.assertEqual(m.publish_views(outputs,latest),'b'*40)
61
+ with self.assertRaises(ValueError):m.read(cache)
62
+ def test_tampered_manifest_refused(self):
63
+ p=self.add_update('20260928T020000Z-current');(self.root/'LATEST.json').write_text(json.dumps(p))
64
+ (self.root/'maintenance/updates'/p['id']/'manifest.json').write_text('{}')
65
+ with self.assertRaises(ValueError):self.module().refresh(self.root,sync=False)
66
+ def test_tampered_locator_refused(self):
67
+ p=self.add_update('20260928T020000Z-current');(self.root/'LATEST.json').write_text(json.dumps(p))
68
+ (self.root/'maintenance/updates'/p['id']/'inference_locations.json').write_text('{}')
69
+ with self.assertRaises(ValueError):self.module().refresh(self.root,sync=False)
70
+
71
+ if __name__=='__main__':unittest.main()
paper-releases/pbisc-diffusion/updates/20260928T141133Z-catalog-cache-fix/diffusion/metadata/inference_locations.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "locations": [],
3
+ "project_id": "pbisc-diffusion",
4
+ "update_id": "20260928T141133Z-catalog-cache-fix"
5
+ }
paper-releases/pbisc-diffusion/updates/20260928T141133Z-catalog-cache-fix/diffusion/metadata/request.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "assets": [
3
+ {
4
+ "host": "server_1",
5
+ "kind": "maintenance",
6
+ "source": "/home/sj_server_1/PBISC/paper-release-20260928/maintenance/catalog.py",
7
+ "state": "completed"
8
+ },
9
+ {
10
+ "host": "server_1",
11
+ "kind": "maintenance",
12
+ "source": "/home/sj_server_1/PBISC/paper-release-20260928/maintenance/test_catalog.py",
13
+ "state": "completed"
14
+ }
15
+ ],
16
+ "inference_locations": [],
17
+ "project_id": "pbisc-diffusion",
18
+ "summary": "Fix current-catalog publication for Hugging Face managed cache symlinks while retaining local source symlink rejection. Completes the catalog refresh deferred by 20260928T140457Z-maintenance-bootstrap. No scientific artifact changes."
19
+ }