134 lines
12 KiB
Python
134 lines
12 KiB
Python
#!/usr/bin/env python3
|
||
"""Real production coordinator/playback with deterministic device/transport doubles. No sockets."""
|
||
from pathlib import Path
|
||
import subprocess
|
||
import tempfile
|
||
import argparse
|
||
import json
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
CACHE = Path('/home/ubuntu/android-build/gradle-home/caches/modules-2/files-2.1')
|
||
FALLBACK = Path('/tmp/lanvoice-gradle-home/caches/modules-2/files-2.1')
|
||
JAVA = '/home/ubuntu/android-build/jdk/temurin-17.0.20.1/bin/java'
|
||
|
||
def jar(group, artifact, version):
|
||
for base in (CACHE, FALLBACK):
|
||
result = list((base/group/artifact/version).glob('*/*.jar'))
|
||
if result: return str(result[0])
|
||
raise RuntimeError(f'Missing cached {group}:{artifact}:{version}')
|
||
|
||
stdlib = jar('org.jetbrains.kotlin','kotlin-stdlib','2.0.20')
|
||
compiler = ':'.join([jar('org.jetbrains.kotlin','kotlin-compiler-embeddable','2.0.20'), stdlib,
|
||
jar('org.jetbrains.kotlin','kotlin-reflect','1.6.10'), jar('org.jetbrains.kotlin','kotlin-script-runtime','2.0.20'),
|
||
jar('org.jetbrains.intellij.deps','trove4j','1.0.20200330'), jar('org.jetbrains','annotations','23.0.0'),
|
||
str(next((CACHE/'org.jetbrains.kotlinx/kotlinx-coroutines-core-jvm').glob('*/*/*.jar')))])
|
||
cp = ':'.join([stdlib, jar('com.squareup.okhttp3','okhttp','4.12.0'), jar('com.squareup.okio','okio-jvm','3.6.0')])
|
||
source = ROOT/'app/src/main/java/com/gorios/lanvoice'
|
||
suites = [
|
||
('session','ConnectionCheckKt', [source/'diag/DiagnosticLog.kt',source/'audio/PlaybackActivity.kt', source/'audio/VoiceSession.kt', source/'avatar/ActionController.kt', source/'dialogue/ReplyEmotion.kt', source/'net/DialogueClient.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt', source/'expression/FaceDiagnostics.kt']),
|
||
('playback','PlaybackCheckKt', [source/'audio/AudioPlayback.kt', source/'audio/PlaybackActivity.kt']),
|
||
('avatar','AvatarCheckKt', [source/'diag/DiagnosticLog.kt',source/'avatar/ConversationMediaDriver.kt',source/'avatar/AvatarMediaBinding.kt',source/'avatar/OfflineDancePreview.kt',source/'avatar/EmotionActionAvatarView.kt',source/'avatar/ContinuousAvatarView.kt',source/'avatar/ConversationPackagePlanner.kt', source/'avatar/EmotionActionManifest.kt', source/'avatar/ActionController.kt', source/'avatar/RoleVisualSelection.kt', source/'avatar/ContinuousAvatarManifest.kt', source/'avatar/ContinuousMouth.kt', source/'avatar/ContinuousFramePresenter.kt', source/'avatar/ContinuousBodyRenderer.kt', source/'avatar/EngineeringGraphAdmission.kt', source/'avatar/OfflineAvatarTrace.kt', source/'avatar/NeutralGraphContract.kt', source/'avatar/SafeVideoDriver.kt', source/'avatar/CodecAnchorVideoPort.kt', source/'avatar/AutoConversation.kt', source/'avatar/SafeAvatarGraph.kt', source/'avatar/SafeTransitionPlanner.kt', source/'avatar/SafeAvatarManifest.kt', source/'avatar/TransitionDiagnostics.kt', source/'avatar/AvatarController.kt', source/'avatar/CallIntent.kt', source/'avatar/AvatarVideoView.kt', source/'audio/PlaybackActivity.kt', source/'dialogue/ReplyEmotion.kt']),
|
||
('capture','CaptureCheckKt', [source/'audio/AudioCapture.kt']),
|
||
('protocol','ProtocolCheckKt', [source/'avatar/ActionController.kt', source/'net/DialogueProtocol.kt', source/'dialogue/ReplyEmotion.kt', source/'expression/FaceCueRules.kt', source/'expression/ExpressionRules.kt']),
|
||
]
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument('--suite', choices=[name for name, _, _ in suites])
|
||
parser.add_argument('--runtime-manifest',type=Path,help='Additionally exercise real continuous parser with actual offline manifest metadata')
|
||
parser.add_argument('--index-manifest',type=Path,help='Additionally admit an exact offline v2 index and each referenced runtime through production parsers; no activation')
|
||
parser.add_argument('--user-authorized-debug-sha',help='Explicit exact user-authorized parent index for debug candidate admission; not Pi publication or network actions')
|
||
parser.add_argument('--metadata-only',action='store_true',help='Only the actual manifest admission, without repeating fixtures')
|
||
parser.add_argument('--rejection-report',type=Path,help='New bounded structural field report; no raw values')
|
||
args = parser.parse_args()
|
||
if args.user_authorized_debug_sha and (not args.index_manifest or not any(
|
||
row.get('userAuthorizedDebug') is True and row['indexSha256']==args.user_authorized_debug_sha
|
||
for row in json.loads((ROOT/'manifests/character-build-profiles.json').read_bytes())['mediaBundles'].values())):
|
||
parser.error('Exact catalogued user-authorized index required')
|
||
if args.index_manifest and args.runtime_manifest: parser.error('Choose runtime or index manifest, not both')
|
||
if args.metadata_only and not (args.index_manifest or args.runtime_manifest): parser.error('Actual manifest required')
|
||
if args.rejection_report and (not args.index_manifest or args.rejection_report.exists()): parser.error('Index and new rejection report required')
|
||
for name, main, real in suites:
|
||
if args.suite and name != args.suite: continue
|
||
with tempfile.TemporaryDirectory(prefix=f'lan-voice-{name}-') as out:
|
||
files = list((ROOT/'tests'/name).glob('*.kt')) + real
|
||
if name in ('session','avatar'): files.append(source/'diag/StartupTrace.kt')
|
||
if name in ('session','protocol'): files.append(source/'expression/PresenceRules.kt')
|
||
if name=='avatar': files += [source/'avatar/StartupAvatarView.kt',source/'avatar/StartupLoadCache.kt']
|
||
if name == 'avatar' and (args.runtime_manifest or args.index_manifest):
|
||
definitions=[]
|
||
def kotlin(value):
|
||
if value is None: return 'null'
|
||
if isinstance(value,bool): return str(value).lower()
|
||
if isinstance(value,str): return json.dumps(value,ensure_ascii=False).replace('$',chr(92)+'$')
|
||
if isinstance(value,int): return str(value)+'L'
|
||
if isinstance(value,float): return repr(value)
|
||
if isinstance(value,(list,dict)):
|
||
result=('listOf<Any?>('+','.join(map(kotlin,value))+')' if isinstance(value,list) else
|
||
'mapOf<String,Any?>('+','.join(kotlin(k)+' to '+kotlin(v) for k,v in value.items())+')')
|
||
# Actual N×5 metadata can exceed a single JVM method. Preserve every
|
||
# field while splitting literal construction into bounded helpers.
|
||
method='metadata'+str(len(definitions))
|
||
kind='List<Any?>' if isinstance(value,list) else 'Map<String,Any?>'
|
||
definitions.append('private fun '+method+'(): '+kind+' = '+result+'\n')
|
||
return method+'()'
|
||
raise TypeError(type(value))
|
||
import hashlib
|
||
if args.runtime_manifest:
|
||
raw=args.runtime_manifest.read_bytes();digest=hashlib.sha256(raw).hexdigest()
|
||
extra=Path(out)/'ActualRuntimeCheck.kt'
|
||
literal=kotlin(json.loads(raw))
|
||
extra.write_text('import com.gorios.lanvoice.avatar.*\n'+''.join(definitions)+'fun main() {\nval root='+literal+'\n'+
|
||
'val pack=checkNotNull(ContinuousAvatarManifest.read(root,"'+digest+'","'+digest+'",true,"runtime/"))\n'+
|
||
'check(pack.patches.size==pack.body.frameCount && pack.curves.size==5)\n'+
|
||
('check(pack.apertureMode && pack.textureImages.size==pack.body.frameCount*5 && pack.patches.all { it.levels.size==5 })\n' if json.loads(raw)['packId'].endswith('runtime-04') else 'check(!pack.apertureMode && pack.textureImages.size==pack.body.frameCount)\n')+
|
||
'println("PASS: actual exported runtime manifest parsed by production Kotlin, exact hash '+digest+'; per-body actual frame count/PTS and five authored curves/routing")\n}\n')
|
||
else:
|
||
index_path=args.index_manifest.resolve(strict=True)
|
||
raw=index_path.read_bytes();digest=hashlib.sha256(raw).hexdigest()
|
||
if args.user_authorized_debug_sha and digest!=args.user_authorized_debug_sha: raise ValueError('User authorized index drift')
|
||
data=json.loads(raw);runtimes={};hashes={}
|
||
references=[row['runtimeManifest'] for row in data['conversationPackages']]
|
||
references += [edge['mouthRuntimeManifest'] for edge in data['edges'] if 'mouthRuntimeManifest' in edge]
|
||
for reference in references:
|
||
path=reference['path']
|
||
runtime_path=(index_path.parent/path).resolve(strict=True)
|
||
if not runtime_path.is_relative_to(index_path.parent): raise ValueError('Runtime path escape')
|
||
runtime_raw=runtime_path.read_bytes();runtime_hash=hashlib.sha256(runtime_raw).hexdigest()
|
||
if runtime_hash!=reference['sha256']: raise ValueError('Runtime hash drift')
|
||
runtimes[path]=json.loads(runtime_raw);hashes[path]=runtime_hash
|
||
index_literal=kotlin(data);runtime_literal=kotlin(runtimes);hash_literal=kotlin(hashes)
|
||
extra=Path(out)/'ActualIndexCheck.kt'
|
||
extra.write_text('import com.gorios.lanvoice.avatar.*\n'+''.join(definitions)+
|
||
'fun main() {\nval root='+index_literal+'\nval runtimes='+runtime_literal+'\nval hashes='+hash_literal+'\n'+
|
||
'val parsed=runtimes.mapValues { (path,value) ->\nval hash=hashes.getValue(path) as String\n'+
|
||
'@Suppress("UNCHECKED_CAST")\nContinuousAvatarManifest.read(value as Map<String,Any?>,hash,hash,true,"fixture/"+path.substringBeforeLast(47.toChar())+"/",'+
|
||
'onReject={ field -> println("REJECT_FIELD|"+path+"|"+field) },userAuthorizedDebug='+str(bool(args.user_authorized_debug_sha)).lower()+')\n}\n'+
|
||
'val index=checkNotNull(EmotionActionManifest.read(root,"'+digest+'","'+digest+'","fixture/",'+
|
||
'onReject={ field -> println("REJECT_FIELD|manifest.json|"+field) }) { path,hash ->\n'+
|
||
'check(hashes[path]==hash)\nparsed[path]\n})\n'+
|
||
'check(index.packages.values.all { it.textureImages.size==it.body.frameCount*5 })\n'+
|
||
('check(index.actionPack==null)\n' if not data['actions'] else 'check(index.actionPack?.assets?.size==2)\n')+
|
||
'println("PASS: actual exported v2 index parsed by production Kotlin, exact hash '+digest+'; packages="+index.packages.size+" rgbaBytes="+index.packages.values.sumOf { it.rgbaBytes }+" danceAvailable="+(index.actionPack!=null))\n}\n')
|
||
files.append(extra)
|
||
subprocess.run([JAVA,'-cp',compiler,'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler','-no-stdlib',
|
||
'-no-reflect','-jvm-target','17','-nowarn','-classpath',cp,'-d',out, *map(str,files)],check=True,cwd=ROOT)
|
||
if not args.metadata_only:
|
||
subprocess.run([JAVA,'-cp',out+':'+cp,main],check=True,cwd=ROOT,timeout=30)
|
||
if name == 'avatar' and args.runtime_manifest:
|
||
subprocess.run([JAVA,'-cp',out+':'+cp,'ActualRuntimeCheckKt'],check=True,cwd=ROOT,timeout=30)
|
||
if name == 'avatar' and args.index_manifest:
|
||
result=subprocess.run([JAVA,'-cp',out+':'+cp,'ActualIndexCheckKt'],capture_output=True,text=True,cwd=ROOT,timeout=30)
|
||
if args.rejection_report:
|
||
rejects=[]
|
||
for line in result.stdout.splitlines():
|
||
if line.startswith('REJECT_FIELD|'):
|
||
_,path,field=line.split('|',2)
|
||
if len(rejects)<128: rejects.append({'file':path,'field':field,'code':'production_metadata_rejected'})
|
||
args.rejection_report.parent.mkdir(parents=True,exist_ok=True)
|
||
with args.rejection_report.open('x') as f:
|
||
json.dump({'status':'passed' if result.returncode==0 else 'rejected','manifest_sha256':digest,
|
||
'scope':'production_metadata_only_no_media_admission_no_activation','rejects':rejects},f,indent=2)
|
||
f.write('\n')
|
||
print(result.stdout,end='')
|
||
if result.returncode: print('FAIL: production index admission; structural fields above, no raw metadata output',file=__import__('sys').stderr)
|
||
result.check_returncode()
|