#!/usr/bin/env python3 """Fixed owner-authorized Stage acceptance. No automatic retry or cost reconciliation.""" import hashlib import json import os from pathlib import Path import subprocess import sys import time import urllib.request import uuid SHA='860324e3a91b31c2b6d4e784e458f6d120582cb8' SESSION='v4-ci-resume-1a00-20261024' TASK='1a00bc08-3ca4-4519-ae1e-9eec7b098756' def renew_existing(a): route='tasks/'+TASK row=a(route) if row['id']!=TASK or row['state']!='READY' or row['runs'] or row['budgetLedger'] or row['budgetLimitCents']!=20 or row['metadata']['commitSha']!=SHA: raise ValueError('Only exact unstarted zero-reservation READY task allowed') approved=a(route+'/gates/1/decide',{'decision':'APPROVED','expectedVersion':row['version'],'idempotencyKey':SESSION+':renew-gate1','expiresAt':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime(time.time()+450)),'notes':'Owner-authorized continuation of existing unstarted task only; max20 existing budget; no QA/publication/Production authority.'}) if approved['state']!='READY': raise ValueError('Gate1 must enqueue READY') refreshed=a(route) if refreshed['state']!='READY' or refreshed['version']!=approved['version'] or refreshed['runs'] or refreshed['budgetLedger']: raise ValueError('Renewal refresh mismatch') return TASK def command(args,timeout=15): return subprocess.check_output(args,stderr=subprocess.DEVNULL,timeout=timeout) def http(base,token,route,body=None,method=None): req=urllib.request.Request(base+'/'+route,data=None if body is None else json.dumps(body).encode(),headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'},method=method or ('GET' if body is None else 'POST')) opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),NoRedirect()) with opener.open(req,timeout=10) as r: raw=r.read(262145) if len(raw)>262144: raise ValueError('Response bound') return json.loads(raw) class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self,req,fp,code,msg,headers,newurl): return None def ci_success(log): return SHA in log and 'Deployment for develop completed successfully!' in log and '🏁 Job succeeded' in log def verify_artifact(status,task): artifact=status.get('artifact') if status['state']!='VERIFYING' or not artifact: raise ValueError('Acceptance incomplete') if hashlib.sha256(artifact['bytes'].encode()).hexdigest()!=artifact['sha256']: raise ValueError('Digest mismatch') binding=json.loads(artifact['bytes']) if binding['taskId']!=task or binding['commitSha']!=SHA or status['qaStatus']!='PENDING_INDEPENDENT_QA': raise ValueError('Artifact binding mismatch') return artifact def main(): if os.getuid()!=0 or Path('/.dockerenv').exists(): raise ValueError('Host only') logs=Path('/opt/services/git/gitea/gitea/gitea/actions_log/parsa/canina') if not any(ci_success(p.read_text()) for p in logs.glob('*/*.log')): raise ValueError('Exact deployed SHA CI success required') actual=command(['docker','exec','canino_backend_stage','cat','/app/STAGE_TEST_ARTIFACT_SHA']).decode().strip() deployed=json.loads(command(['docker','exec','canina-hermes','cat','/opt/data/editorial-v4/deployment.json'])) if actual!=SHA or deployed.get('commitSha')!=SHA: raise ValueError('Deployment mismatch') # Strict private backend IP; no public bootstrap endpoint or direct DB writes. networks=json.loads(command(['docker','inspect','--format','{{json .NetworkSettings.Networks}}','canino_backend_stage'])) ip=networks['stage_hermes_inventory_backend']['IPAddress'] import ipaddress if not ipaddress.ip_address(ip).is_private: raise ValueError('Private backend required') base='http://'+ip+':3000/api' handle=json.loads(command(['docker','exec','canino_backend_stage','cat','/app/private-stage-test/'+SESSION+'.json'])) if handle['user']['role']!='SUPER_ADMIN' or handle['user']['id']=='pmo': raise ValueError('Independent reviewer required') admin=handle['accessToken']; del handle worker=command(['docker','exec','--user','hermes','canina-hermes','cat','/opt/data/editorial-v4/credentials/editorial-pmo-token']).decode().strip() a=lambda route,body=None,method=None:http(base,admin,'admin/orchestration/'+route,body,method) w=lambda route,body=None:http(base,worker,'internal/prepare-worker/'+route,body) tasks=a('tasks') # Preserve all old unknown costs and fence previous failed attempts. failed=[t for t in tasks if t.get('key','').startswith('editorial-v1:') and t['state']=='FAILED'] frozen={t['id']:a('tasks/'+t['id'])['budgetLedger'] for t in failed} unknown=sum(sum(x['amountCents'] for x in ledger) for ledger in frozen.values()) if unknown!=60: raise ValueError('Prior unknown reservation must be 60') task=renew_existing(a); route='tasks/'+task # Existing Gate1 renewal atomically retains READY; no queue or proposal request. # Exactly one process, as hermes. Installed runner has 120-second profile cap, # CLI headroom30 and allowlisted timing evidence. Total330 fits window480. code="import sys,json;sys.path.insert(0,'/opt/data/editorial-v4/runtime-package');import runner;from pathlib import Path;runner.run(Path('/opt/data'),sys.argv[1],total_seconds=330)" try: rc=subprocess.run(['docker','exec','--user','hermes','canina-hermes','python3','-c',code,task],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=430).returncode except subprocess.TimeoutExpired: # No second runner; read persisted state and fence only after its lease expires. rc=1 status=w('editorial-proposals/'+task) if status['state']=='RUNNING': # Let last heartbeat lease expire, then fence the artifact-free unknown attempt. time.sleep(31) row=a(route) runs=[r for r in row['runs'] if r['status']=='RUNNING'] if len(runs)!=1: raise ValueError('Ambiguous recovery') a(route+'/editorial-failure',{'runId':runs[0]['id'],'expectedVersion':row['version'],'idempotencyKey':SESSION+':stopped','reason':'Bounded acceptance stopped; cost unknown and reservation retained; no retry.'}) status=w('editorial-proposals/'+task) for old,ledger in frozen.items(): row=a('tasks/'+old) if row['state']!='FAILED' or row['budgetLedger']!=ledger: raise ValueError('Prior fence changed') row=a(route) if sum(x['amountCents'] for x in row['budgetLedger'])!=20 or any(x['kind']=='RECONCILE' for x in row['budgetLedger']): raise ValueError('Reservation changed') if rc: raise ValueError('Acceptance incomplete; fenced unknown20') artifact=verify_artifact(status,task) print(json.dumps({'taskId':task,'state':status['state'],'artifactSha256':artifact['sha256'],'qaStatus':status['qaStatus'],'priorUnknownReservedCents':60,'freshReservedCents':20,'commitSha':SHA})) if __name__=='__main__': try: main() except Exception: print('Stage acceptance stopped; no retry or cost reconciliation; read authenticated status',file=sys.stderr) sys.exit(1)