#!/usr/bin/env python3 """Leased local-first OpenAlex work queue and reviewed-record publisher.""" from __future__ import annotations import argparse, csv, datetime as dt, hashlib, json, os, random, re, shutil, tempfile, time, uuid from pathlib import Path from urllib.parse import urlsplit ROOT = Path(__file__).resolve().parents[1] STATE = 'planning/workqueue_state.json' CSV = 'planning/openalex_workqueue.csv' SUMMARY = 'planning/workqueue_summary.json' FIELDS = ['record_id','work_id','collection','group','title','authors','year','work_type','pages','pdf_url','source_url','identifier','status','checked_at','sha256','verification_note','source_notes'] ACCEPT_TYPES = {'textbook','handbook','scholarly_book','edited_collection','book_chapter','doctoral_thesis','research_thesis','thesis_framing_text','habilitation_thesis','research_report'} def utcnow(): return dt.datetime.now(dt.timezone.utc) def stamp(t): return t.astimezone(dt.timezone.utc).isoformat(timespec='seconds').replace('+00:00','Z') def parse_time(s): if not s: return None return dt.datetime.fromisoformat(s.replace('Z','+00:00')).astimezone(dt.timezone.utc) def read_jsonl(p): return [json.loads(x) for x in Path(p).read_text().splitlines() if x.strip()] def atomic(path, data): path=Path(path); path.parent.mkdir(parents=True,exist_ok=True) fd,tmp=tempfile.mkstemp(prefix='.'+path.name+'.',dir=path.parent) try: with os.fdopen(fd,'w',encoding='utf-8',newline='') as f: f.write(data); f.flush(); os.fsync(f.fileno()) os.replace(tmp,path) finally: if os.path.exists(tmp): os.unlink(tmp) def json_dump(x): return json.dumps(x,ensure_ascii=False,indent=2)+'\n' def load_state(root): p=root/STATE if not p.exists(): return {'schema_version':1,'tasks':{}} s=json.loads(p.read_text()) if s.get('schema_version')!=1 or not isinstance(s.get('tasks'),dict): raise ValueError('Invalid workqueue state') return s def jobs(root): return {str(j['subfield_id']):j for j in read_jsonl(root/'planning/subfield_jobs.jsonl')} def mapping(root): p=root/'planning/collection_subfield_map.json' if not p.exists(): return {} x=json.loads(p.read_text()) return x.get('collections',{}) def refresh(root, state, now=None): atomic(root/STATE,json_dump(state)) from workqueue_counts import render render(root,now=now) def eligible_tasks(root, state, now): collmap=mapping(root); mixed_medical={str(sid) for name,ent in collmap.items() if name=='medical_sciences' for sid in ent.get('subfield_ids',[])}; rows=[] queue_counts={} cp=root/CSV if cp.exists(): with cp.open(newline='') as f: queue_counts={str(r['subfield_id']):r for r in csv.DictReader(f)} for sid,j in jobs(root).items(): # The mixed medical collection is intentionally outside this subfield-level queue. if str(sid) in mixed_medical or j.get('suggested_collection')=='medical_sciences': continue t=state['tasks'].get(str(sid),{}) expiry=parse_time(t.get('lease_expires_at','')) if expiry and expiry>now: continue cool=parse_time(t.get('cooldown_until','')) if cool and cool>now: continue row=queue_counts.get(str(sid),{}) if row.get('availability','available')!='available': continue count=int(row.get('valid_pdf_count',j.get('valid_pdf_count',0)) or 0) last=t.get('last_search_at','') or row.get('last_search_at','') rows.append((count,parse_time(last) or dt.datetime.min.replace(tzinfo=dt.timezone.utc),int(sid),sid,j)) return sorted(rows) def check_lease(state,sid,owner,lease_id,generation,now): t=state['tasks'].get(str(sid),{}) if t.get('owner')!=owner or t.get('lease_id')!=lease_id or t.get('generation')!=generation or not parse_time(t.get('lease_expires_at','')) or parse_time(t['lease_expires_at'])<=now: raise ValueError('Lease is stale, expired, or owned by another worker') return t def task_state(state,sid): t=state['tasks'].setdefault(str(sid),{}) defaults={'generation':0,'owner':'','lease_id':'','lease_expires_at':'','last_search_at':'','completed_rounds':0,'last_new_entries':0,'last_new_pdfs':0,'cooldown_until':''} for k,v in defaults.items(): t.setdefault(k,v) return t def do_claim(root, owner, now=None): now=now or utcnow(); s=load_state(root); choices=eligible_tasks(root,s,now) if not choices: return {'claimed':False,'reason':'no eligible task'} *_,sid,j=choices[0]; t=task_state(s,sid) gen=int(t.get('generation',0))+1; lid=str(uuid.uuid4()) t.update(generation=gen,owner=owner,lease_id=lid,lease_expires_at=stamp(now+dt.timedelta(minutes=30))) refresh(root,s,now) return {'claimed':True,'subfield_id':sid,'generation':gen,'owner':owner,'lease_id':lid,'lease_expires_at':t['lease_expires_at'],'job':j} def do_lease(root,action,sid,owner,lid,generation,now=None): now=now or utcnow(); s=load_state(root); t=check_lease(s,sid,owner,lid,int(generation),now) if action=='renew': t['lease_expires_at']=stamp(now+dt.timedelta(minutes=30)) else: t.update(owner='',lease_id='',lease_expires_at='') refresh(root,s,now); return {'action':action,'subfield_id':str(sid),'lease_expires_at':t.get('lease_expires_at','')} # Backend remains injectable to permit deterministic fake-CAS testing. class HFBackend: def __init__(self, repo, scratch): from huggingface_hub import HfApi self.api=HfApi(); self.repo=repo; self.scratch=Path(scratch) def head(self): return self.api.repo_info(self.repo,repo_type='dataset').sha def server_now(self): import requests r=requests.get('https://huggingface.co/api/datasets/'+self.repo+'?workqueue_nonce='+str(uuid.uuid4()),timeout=20,headers={'Cache-Control':'no-cache','Pragma':'no-cache'}); r.raise_for_status() value=r.headers.get('Date') if not value: raise RuntimeError('Hugging Face HTTP Date unavailable') return dt.datetime.strptime(value,'%a, %d %b %Y %H:%M:%S %Z').replace(tzinfo=dt.timezone.utc) def snapshot(self,revision,dest,allow_patterns=None): from huggingface_hub import snapshot_download snapshot_download(self.repo,repo_type='dataset',revision=revision,local_dir=str(dest),cache_dir=str(self.scratch/'hf-cache'),token=None,allow_patterns=allow_patterns) shutil.rmtree(Path(dest)/'.cache',ignore_errors=True) def lease_snapshot(self,revision,dest): # Lease heartbeats need only counts/state inputs, not every collection export. self.snapshot(revision,dest,allow_patterns=[ 'collections.json','data/verified_links.jsonl', 'planning/subfield_jobs.jsonl','taxonomy/openalex_subfields.csv', STATE,CSV,SUMMARY,'planning/collection_subfield_map.json', 'planning/*search_progress.jsonl']) def commit(self, base, files, message): from huggingface_hub import CommitOperationAdd ops=[CommitOperationAdd(path_in_repo=k,path_or_fileobj=str(v)) for k,v in sorted(files.items())] return self.api.create_commit(repo_id=self.repo,repo_type='dataset',operations=ops,commit_message=message,parent_commit=base) def sensitive(s): return bool(re.search(r'hf_[A-Za-z0-9]{20,}|/e/(?:home|fscratch)/|-----BEGIN .*PRIVATE KEY-----|[?&](?:token|access_token|api_key|x-amz-signature)=',str(s),re.I)) def has_secret(s): return bool(re.search(r'hf_[A-Za-z0-9]{20,}|-----BEGIN .*PRIVATE KEY-----|[?&](?:token|access_token|api_key|x-amz-signature)=',str(s),re.I)) def verify_record(record, proof, scratch): if set(record)!=set(FIELDS): raise ValueError('Record must contain exactly the 17 SCHEMA fields') if any(not isinstance(record[k],str) for k in FIELDS if k not in {'year','pages'}): raise ValueError('Public text fields must be strings') if record['status']!='downloaded_and_screened' or record['work_type'] not in ACCEPT_TYPES: raise ValueError('Only screened books, chapters, theses, and reports can be accepted') if not record['title'] or not record['pdf_url'] or not record['source_url'] or not record['verification_note'].strip(): raise ValueError('Missing title, public URLs, or editorial verification note') if record['year'] is not None and (type(record['year']) is not int or not 1000<=record['year']<=9999): raise ValueError('Invalid publication year') if type(record['pages']) is not int or record['pages']<1: raise ValueError('Invalid PDF page count') for k in ('pdf_url','source_url'): u=urlsplit(record[k]); if u.scheme not in {'http','https'} or not u.netloc or u.username or u.password or sensitive(record[k]): raise ValueError('Unsafe public URL') sha=record['sha256'] if not re.fullmatch('[0-9a-f]{64}',sha): raise ValueError('Invalid PDF SHA256') if record.get('work_id')!='sha256:'+sha or not record.get('record_id'): raise ValueError('New record identity must be sha256:') if any(sensitive(record[k]) for k in FIELDS if isinstance(record.get(k),str)): raise ValueError('Public record contains a private path, token, or secret pattern') p=proof if not isinstance(p,dict) or p.get('decision')!='accept' or p.get('complete') is not True or not (p.get('academic_context') is True or isinstance(p.get('academic_context'),str) and p['academic_context'].strip()): raise ValueError('Private proof must affirm academic context, completeness, and a positive decision') if p.get('public_access') is not True or p.get('source_verified') is not True or not isinstance(p.get('source_check_notes'),str) or not p['source_check_notes'].strip(): raise ValueError('Proof must record public access, source identity, and source-check notes') if p.get('pdf_url')!=record['pdf_url'] or p.get('source_url')!=record['source_url']: raise ValueError('Proof must bind the screened PDF and source URLs to the public record') if type(p.get('pages')) is not int or p['pages']!=record['pages']: raise ValueError('Proof page count mismatch') samples=p.get('reviewed_pages') if not isinstance(samples,list) or not samples or any(not isinstance(x,dict) for x in samples): raise ValueError('Reviewed first/middle/last page probes required') if any(type(x.get('page')) is not int or not 1<=x['page']<=record['pages'] for x in samples): raise ValueError('Reviewed page numbers must be valid one-based PDF pages') nums={x['page'] for x in samples} required={1,record['pages']//2+1,record['pages']} if not required.issubset(nums): raise ValueError('Proof must review the one-based first, middle, and last pages') if any(not isinstance(x.get('notes'),str) or not x['notes'].strip() for x in samples): raise ValueError('Each reviewed page needs actual screening notes') for k,v in p.items(): if k not in {'local_pdf','sample_file','evidence_file'} and isinstance(v,str) and has_secret(v): raise ValueError('Private evidence contains a credential or secret pattern') actual=Path(p.get('local_pdf','')) sr=Path(scratch).resolve(); actual=actual.resolve(strict=True) if sr not in actual.parents or actual.suffix.lower()!='.pdf': raise ValueError('Proof PDF must be a local PDF under --scratch-dir') if actual.stat().st_size<8: raise ValueError('Invalid PDF bytes or unsafe path') with actual.open('rb') as f: header=f.read(1024) if b'%PDF-' not in header: raise ValueError('Invalid PDF bytes or unsafe path') h=hashlib.sha256() with actual.open('rb') as f: for b in iter(lambda:f.read(1024*1024),b''): h.update(b) if h.hexdigest()!=sha or p.get('sha256')!=sha: raise ValueError('PDF hash mismatch') from pypdf import PdfReader reader=PdfReader(str(actual),strict=False) if reader.is_encrypted and reader.decrypt('')==0: raise ValueError('Encrypted PDF cannot be screened') if len(reader.pages)!=record['pages']: raise ValueError('Parsed PDF page count mismatch') def safe_rel(path): p=Path(path) if p.is_absolute() or '..' in p.parts or not p.parts or sensitive(str(path)): raise ValueError('Unsafe repository path') return p.as_posix() def cas_conflict(exc): status=getattr(exc,'status_code',None) or getattr(getattr(exc,'response',None),'status_code',None) return status in (409,412) def collection_def(root,j): coll=j.get('suggested_collection') if not coll: raise ValueError('Job has no suggested collection for this subfield') defs=json.loads((root/'collections.json').read_text()); existing=next((x for x in defs if x['collection']==coll),None) if existing: return existing group=j.get('suggested_group'); path=safe_rel(j.get('suggested_public_path','')) # The job supplies the prepared public definition; the mapped mixed medical folder is excluded above. if not all((coll,group,path)): raise ValueError('Mapped job lacks suggested group or path') return {'collection':coll,'group':group,'path':safe_rel(path),'display_name':j.get('subfield_name'),'verified_entries':0,'legacy_candidates':0,'openalex_subfield_id':str(j['subfield_id']),'openalex_field_id':str(j['field_id'])} def publish(root, backend, sid, owner, lid, generation, records, scratch, now_fn=None, attempts=5): scratch=Path(scratch).resolve() for r,p in records: verify_record(r,p,scratch) for attempt in range(attempts): base=backend.head(); now=backend.server_now() with tempfile.TemporaryDirectory(prefix='workqueue-snapshot-',dir=scratch) as td: snap=Path(td)/'repo'; backend.snapshot(base,snap) before={p.relative_to(snap).as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in snap.rglob('*') if p.is_file()} s=load_state(snap); t=check_lease(s,sid,owner,lid,generation,now) lease_guard=dict(t) # Recheck against latest snapshot canonical rows and make all output changes in this isolated tree. from catalog import read_rows, render as catalog_render, validate verified=read_rows(snap/'data/verified_links.jsonl'); legacy=read_rows(snap/'data/legacy_candidates.jsonl') from workqueue_counts import build as build_counts prior_rows,_=build_counts(snap,now=now) prior_sid_count=next((int(x['valid_pdf_count']) for x in prior_rows if str(x['subfield_id'])==str(sid)),0) j=jobs(snap)[str(sid)]; cdef=collection_def(snap,j) defs=json.loads((snap/'collections.json').read_text()) if not any(c['collection']==cdef['collection'] for c in defs): defs.append(cdef) keys={(x['collection'],x['sha256']) for x in verified} added=0 for rec,_ in records: key=(rec['collection'],rec['sha256']) if rec['collection']!=cdef['collection']: raise ValueError('Record collection does not match claimed subfield') if key in keys: continue verified.append(rec); keys.add(key); added+=1 atomic(snap/'data/verified_links.jsonl',''.join(json.dumps(x,ensure_ascii=False)+'\n' for x in verified)) atomic(snap/'collections.json',json_dump(defs)) # Round closes even with zero accepts. Coverage counters reflect actual accepted deltas. t['last_search_at']=stamp(now); t['completed_rounds']=int(t.get('completed_rounds',0))+1; t['last_new_entries']=added t['cooldown_until']=stamp(now+dt.timedelta(hours=24)); t.update(owner='',lease_id='',lease_expires_at='') atomic(snap/STATE,json_dump(s)) after_rows,_=build_counts(snap,now=now) after_sid_count=next((int(x['valid_pdf_count']) for x in after_rows if str(x['subfield_id'])==str(sid)),prior_sid_count) t['last_new_pdfs']=max(0,after_sid_count-prior_sid_count) atomic(snap/STATE,json_dump(s)) catalog_render(snap) from workqueue_counts import render as counts_render counts_render(snap,now=now) if hasattr(__import__('catalog'),'render_readme_counts'): __import__('catalog').render_readme_counts(snap) if not validate(snap): raise ValueError('Catalogue validation failed') changed={} allowed={'collections.json','README.md','data/verified_links.jsonl','data/verified_links.csv','data/release_summary.json',STATE,CSV,SUMMARY,cdef['group']+'/README.md'} folder=cdef['path'] allowed.update({folder+'/'+name for name in ('README.md','links.csv','links.jsonl','legacy_candidates.csv','legacy_candidates.jsonl','legacy_candidates.md')}) for f in snap.rglob('*'): if not f.is_file() or '.git' in f.parts: continue rel=f.relative_to(snap).as_posix() if rel not in allowed: continue digest=hashlib.sha256(f.read_bytes()).hexdigest() if before.get(rel)!=digest: changed[rel]=f # Restrict staged data to exact allowed outputs and commit from this HEAD. # Lease ownership and expiry are checked again against live server time immediately before CAS. if parse_time(lease_guard.get('lease_expires_at',''))<=backend.server_now(): raise ValueError('Lease expired before publish commit') try: commit_result=backend.commit(base,changed,'Publish reviewed OpenAlex workqueue records') return {'published':True,'new_entries':added,'round_closed':True,'base_commit':base,'commit':getattr(commit_result,'oid',None) or getattr(commit_result,'commit_id',None)} except Exception as exc: if not cas_conflict(exc): raise if attempt+1==attempts: raise # fresh-head retry on CAS races only time.sleep(min(2.0,0.15*(2**attempt))+random.random()*0.2) raise RuntimeError('CAS retries exhausted') def main(argv=None): ap=argparse.ArgumentParser(); ap.add_argument('action',choices=['status','claim','renew','release','publish']); ap.add_argument('--root',type=Path,default=ROOT); ap.add_argument('--repo',default='laion/academic-textbook-links'); ap.add_argument('--owner','--worker-id',dest='owner'); ap.add_argument('--subfield-id'); ap.add_argument('--lease-id'); ap.add_argument('--generation',type=int); ap.add_argument('--proofs',type=Path); ap.add_argument('--scratch-dir',type=Path,required=True); ap.add_argument('--apply',action='store_true'); args=ap.parse_args(argv) root=args.root.resolve() scratch=args.scratch_dir.resolve() if not scratch.is_dir() or scratch==root or root in scratch.parents: ap.error('--scratch-dir must be an existing private directory outside the checkout') if args.action=='status': print(json.dumps(json.loads((root/SUMMARY).read_text()) if (root/SUMMARY).exists() else {'state':load_state(root)},ensure_ascii=False,indent=2)); return owner=args.owner or str(uuid.uuid4()) try: if str(uuid.UUID(owner))!=owner.lower(): raise ValueError() except (ValueError,AttributeError): ap.error('--owner must be an opaque UUID (or omit it to generate one)') if args.action=='claim': if not args.apply: print(json.dumps({'dry_run':True,'candidate':eligible_tasks(root,load_state(root),utcnow())[0][3] if eligible_tasks(root,load_state(root),utcnow()) else None})); return result=remote_lease(args.repo,root,'claim',{'owner':owner},scratch=scratch) if result['claimed']: result['owner']=owner print(json.dumps(result,ensure_ascii=False)); return if not all((args.subfield_id,args.owner,args.lease_id,args.generation is not None)): ap.error('lease actions require --subfield-id --owner --lease-id --generation') if args.action in {'renew','release'}: if not args.apply: print(json.dumps({'dry_run':True,'action':args.action,'subfield_id':args.subfield_id})); return print(json.dumps(remote_lease(args.repo,root,args.action,vars(args),scratch=scratch))); return if not args.scratch_dir or not args.proofs: ap.error('publish requires --scratch-dir and --proofs') proof_path=args.proofs.resolve() if scratch not in proof_path.parents: ap.error('--proofs must be stored under --scratch-dir') items=json.loads(proof_path.read_text()); records=[(x['record'],x['proof']) for x in items] for record,proof in records: verify_record(record,proof,scratch) if not args.apply: print(json.dumps({'dry_run':True,'subfield_id':args.subfield_id,'reviewed_records':len(records),'unique_pdf_hashes':len({r['sha256'] for r,_ in records})})); return backend=HFBackend(args.repo,scratch); print(json.dumps(publish(root,backend,args.subfield_id,args.owner,args.lease_id,args.generation,records,scratch),ensure_ascii=False)) def remote_lease(repo,root,action,args,attempts=5,backend=None,scratch=None): if scratch is None: raise ValueError('Scratch directory is required for every network operation') scratch=Path(scratch).resolve(); backend=backend or HFBackend(repo,scratch) for attempt in range(attempts): base=backend.head(); now=backend.server_now() with tempfile.TemporaryDirectory(prefix='workqueue-lease-',dir=scratch) as td: snap=Path(td)/'repo' if hasattr(backend,'lease_snapshot'): backend.lease_snapshot(base,snap) else: backend.snapshot(base,snap) before={p.relative_to(snap).as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in snap.rglob('*') if p.is_file()} state=load_state(snap) if action=='claim': choices=eligible_tasks(snap,state,now) if not choices:return {'claimed':False,'reason':'no eligible task'} *_,sid,job=choices[0]; task=task_state(state,sid) generation=int(task.get('generation',0))+1; lease_id=str(uuid.uuid4()) task.update(generation=generation,owner=args['owner'],lease_id=lease_id,lease_expires_at=stamp(now+dt.timedelta(minutes=30))) result={'claimed':True,'subfield_id':sid,'generation':generation,'owner':args['owner'],'lease_id':lease_id,'lease_expires_at':task['lease_expires_at'],'job':job} else: task=check_lease(state,args['subfield_id'],args['owner'],args['lease_id'],args['generation'],now) lease_guard=dict(task) if action=='renew':task['lease_expires_at']=stamp(now+dt.timedelta(minutes=30)) else:task.update(owner='',lease_id='',lease_expires_at='') result={'action':action,'subfield_id':str(args['subfield_id']),'lease_expires_at':task.get('lease_expires_at','')} atomic(snap/STATE,json_dump(state)) from workqueue_counts import render render(snap,now=now) changed={p.relative_to(snap).as_posix():p for p in [snap/STATE,snap/CSV,snap/SUMMARY] if p.exists() and before.get(p.relative_to(snap).as_posix())!=hashlib.sha256(p.read_bytes()).hexdigest()} try: if action!='claim' and parse_time(lease_guard.get('lease_expires_at',''))<=backend.server_now(): raise ValueError('Lease expired before state commit') backend.commit(base,changed,'Update OpenAlex workqueue lease') return result except Exception as exc: if not cas_conflict(exc): raise if attempt+1==attempts:raise time.sleep(min(2,.15*2**attempt)+random.random()*.2) raise RuntimeError('CAS retries exhausted') if __name__=='__main__': main()