Prepare pinned partial emotion bundle gate and safe candidate packaging
This commit is contained in:
@@ -0,0 +1,240 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only partial v2 emotion gate by default; import/publish needs an external Pi pin."""
|
||||
from pathlib import Path, PurePosixPath
|
||||
from decimal import Decimal
|
||||
from fractions import Fraction
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
import zipfile
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
ASSET_ROOT='avatar/a01-expression-action-v1/'
|
||||
TOOLS=Path('/home/ubuntu/android-build/sdk/build-tools/34.0.0')
|
||||
CERT='b9608336bc1ed1de3269bb4594f9fe718daaa5439511c5187aa385d2b799dcf1'
|
||||
LEGACY_PIN='0a3c4918ba746019cf1df885bec66e5858a8950997dac4f64e7d37094be64dad'
|
||||
ROLLBACK=ROOT/'artifacts/lan-voice-v070-stage-candidate-code16-arm64-debug.apk'
|
||||
ROLLBACK_SHA='687c350ec64d693dd8a0bc6e8f1e249816842631119f17a4cbdd38b0cb1e7336'
|
||||
spec=importlib.util.spec_from_file_location('runtime_gate',ROOT/'scripts/check-avatar-runtime.py')
|
||||
runtime_gate=importlib.util.module_from_spec(spec);spec.loader.exec_module(runtime_gate)
|
||||
require=runtime_gate.require
|
||||
sha=lambda b:hashlib.sha256(b).hexdigest()
|
||||
|
||||
|
||||
def file_sha(path):
|
||||
with Path(path).open('rb') as f: return hashlib.file_digest(f,'sha256').hexdigest()
|
||||
|
||||
|
||||
def relative(name):
|
||||
require(isinstance(name,str) and re.fullmatch(r'[A-Za-z0-9_./-]+',name),'asset path shape')
|
||||
p=PurePosixPath(name)
|
||||
require(not p.is_absolute() and str(p)==name and all(x not in ('.','..','') for x in name.split('/')),'asset path escape')
|
||||
return name
|
||||
|
||||
|
||||
def locate(root,name):
|
||||
p=(root/relative(name)).resolve(strict=True)
|
||||
require(p.is_relative_to(root.resolve()) and p.is_file(),'asset path escape/missing')
|
||||
return p
|
||||
|
||||
|
||||
def unique(pairs):
|
||||
result={}
|
||||
for k,v in pairs:
|
||||
require(k not in result,'duplicate manifest key');result[k]=v
|
||||
return result
|
||||
|
||||
|
||||
def read_json(path):
|
||||
require(path.stat().st_size<=2_000_000,'manifest byte bound')
|
||||
return json.loads(path.read_bytes(),object_pairs_hook=unique)
|
||||
|
||||
|
||||
def probe_clip(path):
|
||||
result=subprocess.run(['/home/ubuntu/miniconda3/envs/gori-speech/bin/ffprobe','-v','error','-show_streams','-show_frames','-of','json',str(path)],capture_output=True,check=True,timeout=60)
|
||||
data=json.loads(result.stdout)
|
||||
require(len(data['streams'])==1,'conversation/bridge must be silent video')
|
||||
v=data['streams'][0]
|
||||
require(v['codec_type']=='video' and v['codec_name']=='h264' and (v['width'],v['height'])==(480,848),'clip codec/shape')
|
||||
us=lambda value:int((Decimal(value)*1_000_000).to_integral_value())
|
||||
measured={'ptsUs':[us(f['best_effort_timestamp_time']) for f in data['frames']],
|
||||
'durationUs':us(v['duration']),'fps':Fraction(v['r_frame_rate'])}
|
||||
subprocess.run(['/home/ubuntu/gori-bin/ffmpeg','-v','error','-xerror','-i',str(path),'-map','0:v:0','-f','null','-'],capture_output=True,check=True,timeout=60)
|
||||
return measured
|
||||
|
||||
|
||||
def check_bundle(manifest,expected,output):
|
||||
manifest=manifest.resolve(strict=True);root=manifest.parent
|
||||
require(re.fullmatch('[0-9a-f]{64}',expected) and file_sha(manifest)==expected,'candidate index drift')
|
||||
index=read_json(manifest)
|
||||
require(index['schemaVersion']==2 and index['identityId']=='a01' and index['packId']=='a01-expression-action-v1','index identity/schema')
|
||||
require(index['actions']==[],'this partial-emotion packer requires actions:[]; dance needs its separate audio gate')
|
||||
rows=index['conversationPackages'];require(1<=len(rows)<=12,'package count')
|
||||
files={};measurements={};runtimes=[]
|
||||
def add(name,digest,bound):
|
||||
p=locate(root,name)
|
||||
require(re.fullmatch('[0-9a-f]{64}',digest) and p.stat().st_size<=bound and file_sha(p)==digest,'file hash/byte bound: '+name)
|
||||
row={'sha256':digest,'bytes':p.stat().st_size}
|
||||
require(name not in files or files[name]==row,'conflicting file reference')
|
||||
files[name]=row
|
||||
require(sum(f['bytes'] for f in files.values())<=512_000_000,'bundle byte bound')
|
||||
return p
|
||||
for row in rows:
|
||||
ref=row['runtimeManifest'];path=add(ref['path'],ref['sha256'],2_000_000)
|
||||
evidence,verified=runtime_gate.check_runtime(path,ref['sha256'],kotlin=False)
|
||||
m=read_json(path);prefix=PurePosixPath(ref['path']).parent
|
||||
for name,digest in verified.items(): add(str(prefix/name),digest,64_000_000 if name.endswith('.mp4') else 256_000)
|
||||
body=m['body'];measurements[str(prefix/body['path'])]={'ptsUs':body['ptsUs'] if m['schemaVersion']==2 else [i*1_000_000//24 for i in range(body['frameCount'])],
|
||||
'durationUs':body['durationUs'],'fps':Fraction(body['fpsNumerator'],body['fpsDenominator'])}
|
||||
runtimes.append({'package_id':row['id'],**evidence})
|
||||
rgba=sum(r['rgba_cache_bytes'] for r in runtimes);require(rgba<=32_000_000,'combined runtime cache bound')
|
||||
require(len(index['edges'])<=100,'edge count bound')
|
||||
for edge in index['edges']:
|
||||
clip=edge['clip'];name=relative(clip['path']);path=add(name,clip['sha256'],64_000_000)
|
||||
require(clip['hasAudio'] is False,'conversation edge cannot have audio')
|
||||
measured=measurements.get(name)
|
||||
if measured is None: measured=measurements[name]=probe_clip(path)
|
||||
require(len(measured['ptsUs'])==clip['frameCount'] and len(clip['ptsUs'])==clip['frameCount'],'decoded clip N mismatch: '+name)
|
||||
require(all(abs(a-b)<=2 for a,b in zip(measured['ptsUs'],clip['ptsUs'])),'decoded clip PTS mismatch: '+name)
|
||||
require(abs(measured['durationUs']-clip['durationUs'])<=2 and measured['fps']==Fraction(clip['fpsNumerator'],clip['fpsDenominator']),'decoded clip timing mismatch: '+name)
|
||||
# Preview inventory is checked too, but only runtime-referenced files enter APK.
|
||||
declared=index['files']
|
||||
if isinstance(declared,dict): declared=[dict(v,path=k) for k,v in declared.items()]
|
||||
require(isinstance(declared,list) and len(declared)<=20000,'file inventory shape/bound')
|
||||
table={}
|
||||
for row in declared:
|
||||
name=relative(row['path']);require(name not in table,'duplicate inventory path')
|
||||
p=locate(root,name)
|
||||
require(p.stat().st_size==row['bytes'] and p.stat().st_size<=128_000_000 and file_sha(p)==row['sha256'],'declared file mismatch: '+name)
|
||||
table[name]={'sha256':row['sha256'],'bytes':row['bytes']}
|
||||
require(all(table.get(name)==row for name,row in files.items()),'inventory missing/mismatching referenced file')
|
||||
log=output/'production-index-tests.txt'
|
||||
with log.open('x') as f:
|
||||
result=subprocess.run([sys.executable,str(ROOT/'scripts/check-reply-regressions.py'),'--suite','avatar','--index-manifest',str(manifest)],stdout=f,stderr=subprocess.STDOUT,timeout=180)
|
||||
require(result.returncode==0 and 'PASS: actual exported v2 index parsed' in log.read_text(),'production index admission failed; see '+str(log))
|
||||
files['manifest.json']={'sha256':expected,'bytes':manifest.stat().st_size}
|
||||
for name,row in files.items(): require(file_sha(locate(root,name))==row['sha256'],'bundle changed during gate')
|
||||
report={'status':'passed','scope':'read_only_machine_gate_no_approval_no_activation','manifest_sha256':expected,
|
||||
'runtime_packages':runtimes,'combined_rgba_bytes':rgba,'referenced_files':len(files),'preview_files_not_packaged':len(table.keys()-files.keys()),
|
||||
'edge_count':len(index['edges']),'action_count':0,'dance_available':False,'production_kotlin_index':'passed',
|
||||
'naturalness':'not_certified','real_device':'not_run','files':files}
|
||||
(output/'bundle-gate.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
return report
|
||||
|
||||
|
||||
def import_files(root,files,target):
|
||||
require(not target.is_symlink(),'import target symlink')
|
||||
# Preflight every destination before writing; preserve unknown existing bytes.
|
||||
for name,row in files.items():
|
||||
dest=target/relative(name)
|
||||
require(not dest.exists() or (not dest.is_symlink() and dest.is_file() and file_sha(dest)==row['sha256']),'unknown destination preserved: '+name)
|
||||
require(dest.resolve().is_relative_to(target.resolve()),'import destination escape')
|
||||
require(file_sha(locate(root,name))==row['sha256'],'source drift before import')
|
||||
for name,row in files.items():
|
||||
dest=target/name;dest.parent.mkdir(parents=True,exist_ok=True)
|
||||
if dest.exists(): continue
|
||||
fd,tmp=tempfile.mkstemp(prefix='.emotion-import-',dir=dest.parent)
|
||||
try:
|
||||
with os.fdopen(fd,'wb') as out,locate(root,name).open('rb') as source: shutil.copyfileobj(source,out)
|
||||
require(file_sha(tmp)==row['sha256'],'source drift during import')
|
||||
os.link(tmp,dest) # Exclusive creation, never replacement.
|
||||
finally: os.unlink(tmp)
|
||||
|
||||
|
||||
def badging(path):
|
||||
return subprocess.check_output([str(TOOLS/'aapt'),'dump','badging',str(path)],text=True,stderr=subprocess.STDOUT)
|
||||
|
||||
|
||||
def next_version(paths):
|
||||
codes=[int(re.search(r"versionCode='(\d+)'",badging(p))[1]) for p in paths]
|
||||
return max([16,*codes])+1
|
||||
|
||||
|
||||
def tested_source():
|
||||
client=json.loads((ROOT/'logs/avatar-safe-061/client-tests.json').read_text())
|
||||
require(client['status']=='passed' and client['jvm_entry_points']==9,'client regression evidence')
|
||||
for name,digest in client['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested source: '+name)
|
||||
evidence=json.loads((ROOT/'logs/action-emotion/media-wiring/delivery.json').read_text())
|
||||
require(evidence['gateway_passed']==97 and evidence['gateway_skipped']==1 and evidence['offline_gles_goldens']==40,'gateway/GLES evidence')
|
||||
for name,digest in evidence['source_hashes'].items():
|
||||
if name.startswith('app/'): require(file_sha(ROOT/name)==digest,'media evidence drift: '+name)
|
||||
|
||||
|
||||
def packaging_tests_current():
|
||||
evidence=json.loads((ROOT/'logs/action-emotion/partial-pack/packaging-tests.json').read_text())
|
||||
require(evidence['status']=='passed','packaging regression evidence')
|
||||
for name,digest in evidence['hashes'].items(): require(file_sha(ROOT/name)==digest,'untested packaging source: '+name)
|
||||
|
||||
|
||||
def publish(report,output,requested):
|
||||
tested_source();packaging_tests_current();require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback drift')
|
||||
version=next_version((ROOT/'artifacts').glob('*.apk'))
|
||||
if requested is not None:
|
||||
require(requested>=version,'version code occupied');version=requested
|
||||
subprocess.run([str(ROOT/'scripts/build.sh'),'assembleDebug','compileDebugAndroidTestKotlin','-PavatarActionCandidate=true',
|
||||
'-PavatarNatural=true','-PavatarMouthCandidate=true','-PnaturalManifestSha='+LEGACY_PIN,
|
||||
'-PemotionManifestSha='+report['manifest_sha256'],'-PactionVersionCode='+str(version)],check=True,cwd=ROOT)
|
||||
built=ROOT/'app/build/outputs/apk/debug/app-debug.apk';badge=badging(built)
|
||||
for text in ("name='com.gorios.lanvoice'",f"versionCode='{version}'","versionName='0.7.0-stage-dev'","sdkVersion:'26'","targetSdkVersion:'34'"):
|
||||
require(text in badge,'APK metadata: '+text)
|
||||
require(re.search(r'^native-code: (.+)$',badge,re.M)[1].strip()=="'arm64-v8a'",'APK ABI')
|
||||
cert=subprocess.check_output([str(TOOLS/'apksigner'),'verify','--verbose','--print-certs',str(built)],text=True)
|
||||
require(re.search(r'Signer #1 certificate SHA-256 digest: (\w+)',cert)[1]==CERT,'APK certificate')
|
||||
with zipfile.ZipFile(ROLLBACK) as old,zipfile.ZipFile(built) as new:
|
||||
paths=lambda z:{n for n in z.namelist() if n.startswith('assets/avatar/') and not n.endswith('/')}
|
||||
extra={'assets/'+ASSET_ROOT+n for n in report['files']}
|
||||
require(paths(new)==paths(old)|extra,'APK unreferenced/missing avatar assets')
|
||||
for name in paths(old): require(new.read(name)==old.read(name),'rollback asset changed')
|
||||
for name,row in report['files'].items(): require(sha(new.read('assets/'+ASSET_ROOT+name))==row['sha256'],'APK pack hash')
|
||||
for name in paths(new):
|
||||
if name.endswith('.mp4'): require(new.getinfo(name).compress_type==zipfile.ZIP_STORED,'compressed media')
|
||||
config=ROOT/'app/build/generated/source/buildConfig/debug/com/gorios/lanvoice/BuildConfig.java'
|
||||
require('EMOTION_MANIFEST_SHA = "'+report['manifest_sha256']+'"' in config.read_text(),'compiled index pin mismatch')
|
||||
require(version>=next_version((ROOT/'artifacts').glob('*.apk')),'version became occupied during build')
|
||||
artifact=ROOT/f'artifacts/lan-voice-v070-emotion-candidate-code{version}-arm64-debug.apk'
|
||||
with artifact.open('xb') as f,built.open('rb') as source: shutil.copyfileobj(source,f)
|
||||
digest=file_sha(artifact);checksum=f'{digest} {artifact.name}\n'.encode()
|
||||
with artifact.with_suffix('.apk.sha256').open('xb') as f: f.write(checksum)
|
||||
url='http://192.168.31.124:8080/'+artifact.name
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(url,timeout=30) as response: require(response.status==200 and sha(response.read())==digest,'HTTP APK bytes mismatch')
|
||||
with opener.open(url+'.sha256',timeout=15) as response: require(response.status==200 and response.read()==checksum,'HTTP checksum mismatch')
|
||||
require(file_sha(ROLLBACK)==ROLLBACK_SHA,'rollback modified')
|
||||
delivery={'status':'partial_emotion_candidate','version_code':version,'url':url,'sha256':digest,
|
||||
'certificate_sha256':CERT,'manifest_sha256':report['manifest_sha256'],'dance_available':False,'action_count':0,
|
||||
'http_bytes_verified':True,'device':'not_run','naturalness':'not_certified','paid_calls':0,'gateway_deployed':False}
|
||||
(output/'delivery.json').write_text(json.dumps(delivery,indent=2)+'\n')
|
||||
return delivery
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--manifest',type=Path,required=True);parser.add_argument('--sha256',required=True)
|
||||
parser.add_argument('--output',type=Path,required=True,help='New evidence directory outside owner storage')
|
||||
parser.add_argument('--pi-pin',help='External exact Pi pin, required for import/publish')
|
||||
mode=parser.add_mutually_exclusive_group();mode.add_argument('--import-only',action='store_true');mode.add_argument('--publish',action='store_true')
|
||||
parser.add_argument('--version-code',type=int,help='Default max existing APK code+1, minimum17')
|
||||
args=parser.parse_args();manifest=args.manifest.resolve(strict=True);output=args.output.resolve()
|
||||
require(not output.exists() and not output.is_relative_to(manifest.parent),'new evidence outside owner root required')
|
||||
if args.import_only or args.publish: require(args.pi_pin==args.sha256 and re.fullmatch('[0-9a-f]{64}',args.pi_pin or ''),'external Pi pin required')
|
||||
output.mkdir(parents=True)
|
||||
report=check_bundle(manifest,args.sha256,output)
|
||||
if args.import_only or args.publish:
|
||||
import_files(manifest.parent,report['files'],ROOT/'app/src/main/assets'/ASSET_ROOT)
|
||||
(output/'import.json').write_text(json.dumps({'externally_pinned_sha256':args.pi_pin,'files':len(report['files']),'naturalness':'not_certified'})+'\n')
|
||||
result=publish(report,output,args.version_code) if args.publish else {k:v for k,v in report.items() if k!='files'}
|
||||
print(json.dumps(result,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
try: main()
|
||||
except (ValueError,KeyError,TypeError,OSError,subprocess.SubprocessError) as error:
|
||||
print('FAIL: emotion pack: '+str(error),file=sys.stderr);raise SystemExit(1)
|
||||
Reference in New Issue
Block a user