Validate isolated public action followup calling path
This commit is contained in:
@@ -390,3 +390,42 @@ hashes matched. Evidence: `logs/action-emotion/idle-dance-preflight-01/`.
|
||||
Paid calls/cost0; no model probes, gateway deployment/restart/provider/TTS change.
|
||||
Physical device, real music listening/full-speed dance review and naturalness remain
|
||||
not_run/not_certified. Handoff: **IDLE_DANCE_SOURCE_PREFLIGHT_READY_FOR_NEW_INDEX_SHA**.
|
||||
|
||||
### Public action calling-path validation (2026-10-13)
|
||||
|
||||
Clean remote-matched baseline `a113bd4bb3fc25f19a76f4854c3acc3b9830ae6c`.
|
||||
One actual loopback WebSocket run reused the unchanged production0.8 routes with
|
||||
temporary history, manual-VAD double and a process-only fixture allowlist. Lifespan
|
||||
model loading was disabled; no deployed source/config/service or live action
|
||||
allowlist changed. Backends were actual ASR/Qwen/TTS. Input was newly synthesized
|
||||
public text, kept in memory; no user recording/chat/face report was read.
|
||||
|
||||
Real socket sequence passed: ASR→one LLM→pre full-text single TTS→simulated drain→
|
||||
plan→simulated mic-stop/music→early completion rejected→1s fixture elapsed→video/
|
||||
audio-stop/return-A confirmations→duplicate completion→new server turn2→3→after
|
||||
single TTS→drain→confirmed history. Pre/after PCM230400/276480 bytes, peaks11924/
|
||||
13760. After expression appeared only in its new turn; after history absent before
|
||||
drain,3 rows after. Duplicate completion produced no further speech; stale ACTION
|
||||
PCM produced no second ASR. These are received service events; mic/media/drain are
|
||||
explicit fixtures, not AudioRecord, real video/music or human-hearing evidence.
|
||||
|
||||
Exactly5 local Qwen requests: the chain plus4 fixed semantic samples (different dance
|
||||
request, negation, quotation, unavailable legacy). All finished stop at max_tokens160;
|
||||
negation/quotation/unavailable returned none, no after object. The second dance after
|
||||
text differed from the chain's; no raw model text/hash/audio saved. Chain prepare924ms
|
||||
versus full reply2961ms; four direct headers597–797ms versus full replies1217–2840ms.
|
||||
Prepare is speculative preload, final authoritative; no general ordering/≤1s SLA.
|
||||
Each actual request had one system and fresh explicit Asia/Shanghai clock.160 retained.
|
||||
Total real backend calls:1 ASR/5 LLM/3 TTS (1 input generator+2 reply generators),
|
||||
no retries/cloud/paid calls. NTP=yes/NTPSynchronized=yes, read only. Source/env/unit/
|
||||
PID stayed unchanged. Numeric bounded evidence: `logs/action-emotion/calling-path-public-01/probe.json`.
|
||||
|
||||
Fresh9 JVM/UI and gateway98 (97 pass/1 excluded Silero skip) passed. New client
|
||||
fixture verifies action-followup abort/speech/new-turn, future-expression rejection,
|
||||
retired PCM/emotion/drain and duplicate completion.17 full-graph fixture assertions
|
||||
cover5 own bodies+8 own-mouth bridges+5 loops (13edges)+two241-frame dances,96/4s
|
||||
action source binding and combined32MB rejection; fixture RGBA11,211,200 bytes.
|
||||
Runtime Android/backend source and published code17 APK are unchanged; no new APK
|
||||
or deployment needed. Exact new P4b/P5 index SHA/files, every idle bridge's own runtime,
|
||||
independent Pi pin and server duration allowlist remain required for actual activation.
|
||||
Handoff: **PUBLIC_ACTION_CALLING_PATH_PASSED_AWAIT_REAL_INDEX_AND_EXACT_PI_PIN**.
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
"""SSH stdin payload body. sources/expected are supplied by the bounded launcher.
|
||||
|
||||
No production history, recordings, debug reports or model output is read/persisted.
|
||||
Real services supply ASR/LLM/TTS; manual VAD and all media confirmations are fixtures.
|
||||
"""
|
||||
import asyncio
|
||||
import base64
|
||||
from contextlib import suppress
|
||||
import hashlib
|
||||
import inspect
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
import wave
|
||||
|
||||
import httpx
|
||||
|
||||
LIVE=Path('/home/gorios-spark-2/lan-voice')
|
||||
report={'status':'failed','scope':'isolated actual WebSocket/ASR/Qwen/TTS; simulated mic/media/drain',
|
||||
'paid_calls':0,'max_tokens':160,'device':'not_run','naturalness':'not_certified','semantic_rows':[],
|
||||
'llm_requests':0,'tts_requests':0,'asr_requests':0,'events':[]}
|
||||
digest=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def live_health():
|
||||
ctx=ssl.create_default_context(cafile=str(LIVE/'.runtime/gateway-cert.pem'))
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
||||
with opener.open('https://192.168.31.61:5011/health',timeout=5) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
async def main(stage):
|
||||
import websockets
|
||||
import uvicorn
|
||||
import gateway as g
|
||||
from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply
|
||||
from guest_sessions import GuestSessions
|
||||
from history import History
|
||||
from llm_provider import LLMProvider
|
||||
from protocol import pack,unpack
|
||||
from reply_emotion import SYSTEM_FRAGMENT
|
||||
from tests_fake import FakeModel
|
||||
provider=LLMProvider()
|
||||
assert (provider.base_url,provider.model,provider.structured_output,provider.clock.zone.key)==(
|
||||
'http://127.0.0.1:8888/v1','qwen3.8-27b','json_schema','Asia/Shanghai')
|
||||
report.update(provider=provider.model,zone=provider.clock.zone.key,mode=provider.structured_output)
|
||||
fixture_sha=hashlib.sha256(b'isolated-public-action-calling-path-fixture-not-an-asset').hexdigest()
|
||||
os.environ['LAN_ACTION_PACKS']=json.dumps({fixture_sha:{'asset_01':1000,'asset_02':1000}})
|
||||
token=secrets.token_urlsafe(32) # Ephemeral fixture token, never output.
|
||||
history=History(stage/'fixture-history.sqlite3');await history.initialize()
|
||||
clocks=[]
|
||||
async def request_hook(request):
|
||||
if live_health().get('busy'): raise RuntimeError('busy_no_probe')
|
||||
port=request.url.port
|
||||
if port==8888:
|
||||
report['llm_requests']+=1
|
||||
assert report['llm_requests']<=5
|
||||
body=json.loads(request.content);systems=[m['content'] for m in body['messages'] if m['role']=='system']
|
||||
assert len(systems)==1 and systems[0].count('当前服务器时间:')==1 and body['max_tokens']==160
|
||||
assert '时区:Asia/Shanghai' in systems[0]
|
||||
reference=re.search(r'当前服务器时间:([^\n]+)',systems[0])[1]
|
||||
clocks.append(reference)
|
||||
report.setdefault('request_metadata',[]).append({'request':report['llm_requests'],'system_count':1,
|
||||
'clock':reference,'zone':'Asia/Shanghai','max_tokens':160,'nested_nullable_schema':
|
||||
body['response_format']['json_schema']['schema']['properties']['after_action'].get('anyOf') is not None})
|
||||
elif port==5002:
|
||||
report['tts_requests']+=1;assert report['tts_requests']<=3
|
||||
elif port==5001:
|
||||
report['asr_requests']+=1;assert report['asr_requests']==1
|
||||
else: raise ValueError('unexpected_backend')
|
||||
async with httpx.AsyncClient(timeout=40,trust_env=False,event_hooks={'request':[request_hook]}) as client:
|
||||
# New public synthetic phrase; no prior/user audio files are accessed.
|
||||
response=await client.post('http://192.168.31.61:5002/v1/audio/speech',json={
|
||||
'model':'openbmb/VoxCPM2','voice':g.DEFAULT_VOICE_ID,'input':'请跳一段舞,结束后自然问我一个问题。','stream':True})
|
||||
response.raise_for_status()
|
||||
with wave.open(io.BytesIO(response.content),'rb') as audio:
|
||||
assert (audio.getframerate(),audio.getnchannels(),audio.getsampwidth())==(48000,1,2)
|
||||
generated=audio.readframes(audio.getnframes());assert 0<len(generated)<=48000*15*2
|
||||
import numpy as np
|
||||
values=np.frombuffer(generated,dtype='<i2');pcm=np.round(values.reshape(-1,3).mean(axis=1)).astype('<i2').tobytes() if len(values)%3==0 else values[::3].astype('<i2').tobytes()
|
||||
assert 0<len(pcm)<=16000*15*2
|
||||
report['synthetic_input_samples']=len(pcm)//2
|
||||
state=g.app.state
|
||||
state.busy=False;state.model=FakeModel();state.client=client;state.history=history
|
||||
state.token=token;state.guest_enabled=False;state.lan_open=False;state.guests=GuestSessions()
|
||||
state.debug=None;state.voices=[{'id':g.DEFAULT_VOICE_ID,'source':'registered_reference','default':True}]
|
||||
# Reuse unmodified production routes while explicitly bypassing startup/model loading.
|
||||
config=uvicorn.Config(g.app,host='127.0.0.1',port=0,lifespan='off',log_level='critical',access_log=False)
|
||||
server=uvicorn.Server(config);sock=socket.socket();sock.bind(('127.0.0.1',0));sock.listen();sock.setblocking(False)
|
||||
port=sock.getsockname()[1];task=asyncio.create_task(server.serve(sockets=[sock]))
|
||||
try:
|
||||
async with asyncio.timeout(5):
|
||||
while not server.started:
|
||||
if task.done(): await task;raise ValueError('fixture_server_not_started')
|
||||
await asyncio.sleep(.01)
|
||||
kwargs={'origin':'https://192.168.31.61:5011','open_timeout':5,'close_timeout':2}
|
||||
if 'proxy' in inspect.signature(websockets.connect).parameters: kwargs['proxy']=None
|
||||
async def hello(ws,cap):
|
||||
await ws.send(json.dumps({'type':'auth','token':token}))
|
||||
auth=json.loads(await ws.recv());assert auth['type']=='auth' and auth['state']=='ok'
|
||||
await ws.send(json.dumps({'type':'hello','codec':'pcm16','sample_rate':16000,'frame_duration':20,
|
||||
'persona':'default','voice_mode':'continuous_voice','tts_debug':False,**cap}))
|
||||
event=json.loads(await ws.recv());assert event['type']=='hello'
|
||||
return event
|
||||
availability=[]
|
||||
for cap in ({},{'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':'b'*64}):
|
||||
async with websockets.connect(f'ws://127.0.0.1:{port}/ws/dialogue',**kwargs) as ws:
|
||||
event=await hello(ws,cap);availability.append(event['action_available']);assert not event['action_available']
|
||||
async with asyncio.timeout(5):
|
||||
while state.busy: await asyncio.sleep(.01)
|
||||
report['legacy_unknown_hello_availability']=availability
|
||||
async with websockets.connect(f'ws://127.0.0.1:{port}/ws/dialogue',**kwargs) as ws:
|
||||
event=await hello(ws,{'action_protocol':1,'action_kinds':['dance'],'action_pack_sha256':fixture_sha})
|
||||
assert event['action_available']
|
||||
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'start','barge_in':False}))
|
||||
while True:
|
||||
event=json.loads(await ws.recv())
|
||||
if event['type']=='listen' and event.get('state')=='start': input_turn=event['turn_id'];break
|
||||
for offset in range(0,len(pcm),640):
|
||||
await ws.send(pack(1,input_turn,offset//640+1,pcm[offset:offset+640].ljust(640,b'\0')))
|
||||
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'stop'}))
|
||||
start=time.monotonic();pre_turn=None;after_turn=None;last_event_seq=0;plan=None;started_at=None
|
||||
bodies={};emotions={};pcm_stats={};metrics={};sentence_counts={};history_counts=[];after_text=None
|
||||
def trace(event):
|
||||
row={k:event[k] for k in ('type','turn_id','seq','server_ms','state','emotion','intensity','source',
|
||||
'finish_reason','preload_only','origin','reason') if k in event}
|
||||
row['received_ms']=round((time.monotonic()-start)*1000,2)
|
||||
if event['type']=='history': row['row_count']=len(event['messages'])
|
||||
assert len(report['events'])<256;report['events'].append(row)
|
||||
async with asyncio.timeout(90):
|
||||
while True:
|
||||
raw=await ws.recv()
|
||||
if isinstance(raw,bytes):
|
||||
turn,seq,audio=unpack(raw,2);assert turn in emotions and 0<len(audio)<=1920
|
||||
row=pcm_stats.setdefault(turn,{'frames':0,'bytes':0,'peak':0,'square':0,'first_received_ms':round((time.monotonic()-start)*1000,2)})
|
||||
assert seq==row['frames']+1;row['frames']+=1;row['bytes']+=len(audio)
|
||||
samples=struct.unpack('<'+'h'*(len(audio)//2),audio);row['peak']=max(row['peak'],max(map(abs,samples)))
|
||||
row['square']+=sum(x*x for x in samples);continue
|
||||
event=json.loads(raw);kind=event['type'];turn=event.get('turn_id')
|
||||
assert event['seq']>last_event_seq;last_event_seq=event['seq'];trace(event)
|
||||
if kind=='error': raise ValueError('isolated_gateway_backend_error')
|
||||
if kind=='capture.end': pre_turn=turn
|
||||
if kind=='llm':
|
||||
assert event['text'].strip() and not event['text'].lstrip().startswith(('{','[','```'))
|
||||
bodies[turn]=event['text']
|
||||
if kind=='reply.emotion':
|
||||
assert turn in bodies and turn not in emotions and turn not in pcm_stats
|
||||
assert event['source']=='model';emotions[turn]=(event['emotion'],event['intensity'])
|
||||
if turn==pre_turn: assert event['finish_reason']=='stop'
|
||||
if kind=='metrics': metrics[turn]=event['values']
|
||||
if kind=='tts' and event.get('state')=='sentence_start':
|
||||
assert event['text']==bodies[turn]
|
||||
sentence_counts[turn]=sentence_counts.get(turn,0)+1
|
||||
if kind=='tts' and event.get('state')=='stop':
|
||||
assert turn in pcm_stats and pcm_stats[turn]['peak']>327
|
||||
if turn==after_turn:
|
||||
rows=await history.rows(event_conversation)
|
||||
assert len(rows)==2
|
||||
report['after_history_before_drain']=False;after_text=bodies[turn]
|
||||
await ws.send(json.dumps({'type':'playback.drained','turn_id':turn}))
|
||||
trace({'type':'fixture.playback.drained.sent','turn_id':turn})
|
||||
if kind=='history':
|
||||
event_conversation=event['conversation_id'];history_counts.append(len(event['messages']))
|
||||
if kind=='action.plan':
|
||||
assert plan is None and after_turn is None and report['tts_requests']==2
|
||||
assert len(emotions)==1 and len(pcm_stats)==1
|
||||
plan=event
|
||||
# This is a simulated media acknowledgement, not physical AudioRecord/video evidence.
|
||||
status={'type':'action.status','turn_id':pre_turn,'action_id':plan['action_id'],
|
||||
'status':'started','asset_id':'asset_01','mic_stopped':True}
|
||||
await ws.send(json.dumps(status));started_at=time.monotonic()
|
||||
trace({'type':'fixture.mic_stop_and_music_started','turn_id':pre_turn})
|
||||
# Delayed pre-recorded PCM during ACTION must be dropped before capture/ASR.
|
||||
await ws.send(pack(1,pre_turn,999,bytes(640)))
|
||||
complete={**status,'status':'completed','video_ended':True,'audio_stopped':True,'idle_restored':True}
|
||||
await ws.send(json.dumps(complete)) # Deliberate premature event.
|
||||
await ws.send(json.dumps({'type':'ping'}))
|
||||
if kind=='pong' and plan is not None and after_turn is None:
|
||||
assert report['tts_requests']==2 and len(emotions)==1
|
||||
await asyncio.sleep(max(0,1.05-(time.monotonic()-started_at)))
|
||||
await ws.send(json.dumps(complete));await ws.send(json.dumps(complete))
|
||||
trace({'type':'fixture.audio_video_end_returnA_completed_twice','turn_id':pre_turn})
|
||||
if kind=='speech.start':
|
||||
assert plan is not None and event['origin']=='after_action' and turn>pre_turn and after_turn is None
|
||||
after_turn=turn
|
||||
assert len(emotions)==1 # Future after expression was not sent with the plan.
|
||||
if kind=='listen' and event.get('state')=='resumed' and turn==after_turn:
|
||||
rows=await history.rows(event_conversation)
|
||||
assert len(rows)==3 and rows[-1]['text']==bodies[after_turn] and rows[-1]['playback']=='confirmed'
|
||||
assert metrics[pre_turn]['llm_request_count']==1 and metrics[after_turn]['llm_request_count']==0
|
||||
assert metrics[pre_turn]['tts_request_count']==metrics[after_turn]['tts_request_count']==1
|
||||
assert sentence_counts=={pre_turn:1,after_turn:1} and report['asr_requests']==1
|
||||
assert report['llm_requests']==1 and report['tts_requests']==3
|
||||
await ws.send(json.dumps(complete));await ws.send(json.dumps({'type':'ping'}))
|
||||
break
|
||||
while True:
|
||||
event=json.loads(await asyncio.wait_for(ws.recv(),5));trace(event)
|
||||
assert event['type']!='speech.start'
|
||||
if event['type']=='pong':break
|
||||
assert report['tts_requests']==3
|
||||
for row in pcm_stats.values(): row['rms']=round(math.sqrt(row.pop('square')/(row['bytes']//2)),2)
|
||||
report['chain']={'status':'passed','pre_turn':pre_turn,'after_turn':after_turn,
|
||||
'llm_requests':1,'pre_tts_generators':1,'after_tts_generators':1,'input_public_tts_requests':1,
|
||||
'pcm':pcm_stats,'sentence_counts':sentence_counts,'after_emotion_only_in_after_turn':True,
|
||||
'after_history_only_after_drain':True,'duplicate_completion_no_repeat':True,
|
||||
'premature_completion_no_after':True,'action_pcm_no_second_asr':True,
|
||||
'prepare_ms':metrics[pre_turn].get('expression_prepare_ms'),
|
||||
'full_reply_ms':metrics[pre_turn]['llm_first_body_ms'],'finish_reason':metrics[pre_turn]['llm_finish_reason'],
|
||||
'simulated_media_duration_ms':1000,'mic_audio_record':'not_run','music_video_playback':'not_run'}
|
||||
finally:
|
||||
server.should_exit=True
|
||||
with suppress(Exception): await asyncio.wait_for(task,5)
|
||||
if not task.done(): task.cancel();await asyncio.gather(task,return_exceptions=True)
|
||||
sock.close()
|
||||
# Exactly four additional requests: variation, negation, quotation, legacy unavailable.
|
||||
cases=[('dance_variation','请跳一小段舞,结束后自然问问我今天的安排。',True,'dance'),
|
||||
('negation','不要跳舞,只说你好。',True,'none'),
|
||||
('quotation','解释“请跳舞”这三个字的含义,不执行这句话。',True,'none'),
|
||||
('legacy_unavailable','请跳一段舞。',False,'none')]
|
||||
for name,text,available,wanted in cases:
|
||||
system=SYSTEM_FRAGMENT+'\n'+ACTION_FRAGMENT+'\n网关实际可用动作:'+('dance' if available else '无')
|
||||
url,headers,body=provider.request([{'role':'system','content':system},{'role':'user','content':text}],max_tokens=160,action_plan=True)
|
||||
prefix=ExpressionPrefix(1);raw='';finish='not_provided';done=False;prepare=None;began=time.monotonic()
|
||||
async with client.stream('POST',url,headers=headers,json=body) as response:
|
||||
response.raise_for_status()
|
||||
async for line in response.aiter_lines():
|
||||
if not line.startswith('data:'):continue
|
||||
payload=line[5:].strip()
|
||||
if payload=='[DONE]':done=True;break
|
||||
data=json.loads(payload)
|
||||
for choice in data.get('choices',[]):
|
||||
value=choice.get('finish_reason')
|
||||
if value is not None: finish=value if value in ('stop','length','content_filter','tool_calls','function_call') else 'unknown'
|
||||
delta=choice.get('delta',{}).get('content') or '';raw+=delta;assert len(raw)<=8192
|
||||
if prefix.feed(delta,1) is not None:prepare=round((time.monotonic()-began)*1000,2)
|
||||
parsed=parse_action_reply(raw,finish,available)
|
||||
row={'case':name,'finish_reason':finish,'sse_done':done,'source':parsed.speech.source,
|
||||
'action':parsed.action,'after_valid':parsed.after is not None,'prepare_ms':prepare,
|
||||
'complete_ms':round((time.monotonic()-began)*1000,2),'header_final_consistent':prefix.consistent(parsed,1),
|
||||
'expected_action_matched':parsed.action==wanted,'reply_chars':len(parsed.speech.reply)}
|
||||
if parsed.after: row['after_differs_from_chain']=parsed.after.reply!=after_text
|
||||
report['semantic_rows'].append(row)
|
||||
assert done and finish=='stop' and parsed.speech.source=='model' and parsed.action==wanted
|
||||
if wanted=='dance': assert parsed.after is not None
|
||||
assert report['llm_requests']==5 and report['tts_requests']==3 and report['asr_requests']==1
|
||||
assert len(set(clocks))>=2
|
||||
report['clock_refreshed_each_request']=True
|
||||
|
||||
|
||||
try:
|
||||
health=live_health()
|
||||
assert health.get('status')=='ok' and not health.get('busy'), 'busy_no_probe'
|
||||
report['live_health_before']={k:health.get(k) for k in ('version','busy','llm_model','llm_time_zone','llm_structured_output')}
|
||||
actual={name:digest(LIVE/name) for name in expected}
|
||||
assert actual==expected, 'live_source_drift_no_probe'
|
||||
pid=subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip()
|
||||
private=LIVE/'.runtime'
|
||||
private_hashes={str(p):digest(p) for p in private.glob('*.env')}
|
||||
unit=subprocess.check_output(['systemctl','--user','cat','lan-voice-gateway.service'])
|
||||
env=dict(item.split('=',1) for item in Path('/proc/'+pid+'/environ').read_bytes().decode().split('\0') if '=' in item)
|
||||
# Private provider settings stay in this process; no env file/service is written.
|
||||
os.environ.update({k:v for k,v in env.items() if k.startswith('LAN_LLM_')})
|
||||
with tempfile.TemporaryDirectory(prefix='action-public-calling-path-') as folder:
|
||||
stage=Path(folder)
|
||||
for name,content in sources.items(): (stage/name).write_bytes(base64.b64decode(content))
|
||||
(stage/'web').mkdir()
|
||||
sys.path.insert(0,folder)
|
||||
asyncio.run(main(stage))
|
||||
assert {name:digest(LIVE/name) for name in expected}==actual
|
||||
assert all(digest(Path(p))==value for p,value in private_hashes.items())
|
||||
assert subprocess.check_output(['systemctl','--user','cat','lan-voice-gateway.service'])==unit
|
||||
assert subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip()==pid
|
||||
report['live_source_env_unit_pid_unchanged']=True
|
||||
report['status']='passed'
|
||||
except Exception as error:
|
||||
report['error_type']=type(error).__name__
|
||||
if isinstance(error,(AssertionError,RuntimeError)) and str(error) in ('busy_no_probe','live_source_drift_no_probe'): report['reason']=str(error)
|
||||
if isinstance(error,httpx.HTTPStatusError):report['http_status']=error.response.status_code
|
||||
print(json.dumps(report,ensure_ascii=False))
|
||||
raise SystemExit(report['status']!='passed')
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One isolated socket chain + four fixed local-Qwen samples; never a live pack approval."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output',type=Path,required=True,help='New ignored numeric evidence file')
|
||||
args=parser.parse_args()
|
||||
output=args.output.resolve()
|
||||
if output.exists() or not output.is_relative_to(ROOT/'logs'): raise ValueError('new logs evidence required')
|
||||
source={p.name:base64.b64encode(p.read_bytes()).decode() for p in (ROOT/'gateway').glob('*.py')}
|
||||
baseline=json.loads((ROOT/'gateway/SOURCE_MANIFEST.json').read_text())['deployment_baseline']['files']
|
||||
expected={name:digest for name,digest in baseline.items() if name in source and name!='tests_fake.py'}
|
||||
payload='sources='+repr(source)+'\nexpected='+repr(expected)+'\n'+(ROOT/'scripts/action-calling-path-remote.py').read_text()
|
||||
run=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5',
|
||||
'gorios-spark-2@192.168.31.61','cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],
|
||||
input=payload.encode(),capture_output=True,timeout=210)
|
||||
if run.stdout:
|
||||
report=json.loads(run.stdout)
|
||||
report['workspace_source_hashes']={str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in [ROOT/'scripts/probe-action-calling-path.py',ROOT/'scripts/action-calling-path-remote.py',*(ROOT/'gateway').glob('*.py')]}
|
||||
output.parent.mkdir(parents=True,exist_ok=True)
|
||||
output.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
print(json.dumps({k:report.get(k) for k in ('status','scope','reason','error_type','llm_requests','tts_requests','chain','semantic_rows')},ensure_ascii=False,indent=2))
|
||||
if run.stderr: print('Remote stderr present; content suppressed.')
|
||||
raise SystemExit(run.returncode)
|
||||
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -13,6 +13,7 @@ fun main() {
|
||||
actualMediaViewCheck()
|
||||
mediaBoundaryCheck()
|
||||
idleVariantCheck()
|
||||
fullActionGraphCheck()
|
||||
checkContinuous()
|
||||
checkEngineering()
|
||||
checkSafeDriver()
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import com.gorios.lanvoice.avatar.*
|
||||
|
||||
/** Expected five bodies/eight TALK bridges/two dances, synthetic metadata only. */
|
||||
fun fullActionGraphCheck() {
|
||||
val pin="b".repeat(64)
|
||||
val bodies=listOf("neutral","happy","sad","idle-breathe","idle-shift").associateWith { id->
|
||||
val sha=java.security.MessageDigest.getInstance("SHA-256").digest(id.toByteArray()).joinToString("") { "%02x".format(it) }
|
||||
dynamicPack(if(id=="sad") 49 else 97,24,sha)
|
||||
}
|
||||
fun clip(pack: ContinuousAvatarPack,path: String,audio: Boolean=false)=mapOf<String,Any?>(
|
||||
"path" to path,"sha256" to pack.body.sha256,"width" to 480,"height" to 848,"hasAudio" to audio,
|
||||
"frameCount" to pack.body.frameCount,"ptsUs" to pack.body.ptsUs,"durationUs" to pack.body.durationUs,
|
||||
"fpsNumerator" to pack.body.fpsNumerator,"fpsDenominator" to pack.body.fpsDenominator)
|
||||
val rows=bodies.map { (id,body)->mapOf<String,Any?>("id" to id,
|
||||
"emotion" to if(id.startsWith("idle")) "neutral" else id,"visualIntensity" to if(id in setOf("happy","sad")) 1 else 0,
|
||||
"mouthBodySha256" to body.body.sha256,"runtimeManifest" to mapOf("path" to "$id/manifest.json","sha256" to body.manifestSha),
|
||||
"entryAnchor" to "A","exitAnchor" to "A","legalExitFrames" to listOf(body.body.frameCount-1),"loopEdge" to "$id-loop") }
|
||||
val mouths=linkedMapOf<String,ContinuousAvatarPack>()
|
||||
val loops=bodies.map { (id,body)->mapOf<String,Any?>("id" to "$id-loop","from" to id,"to" to id,
|
||||
"fromFrame" to body.body.frameCount-1,"fromPtsUs" to body.body.ptsUs.last(),"toFrame" to 0,"toPtsUs" to 0L,
|
||||
"fromAnchor" to "A","toAnchor" to "A","nativeLoop" to true,"clip" to clip(body,"$id/body.mp4")) }
|
||||
val bridges=bodies.keys.filter { it!="neutral" }.flatMap { id->listOf("neutral" to id,id to "neutral").map { (from,to)->
|
||||
val name="$from-$to";val sha=java.security.MessageDigest.getInstance("SHA-256").digest(name.toByteArray()).joinToString("") { "%02x".format(it) }
|
||||
val own=dynamicPack(25,24,sha);mouths[name]=own
|
||||
mapOf<String,Any?>("id" to name,"from" to from,"to" to to,"fromFrame" to bodies.getValue(from).body.frameCount-1,
|
||||
"fromPtsUs" to bodies.getValue(from).body.ptsUs.last(),"toFrame" to 0,"toPtsUs" to 0L,"fromAnchor" to "A","toAnchor" to "A",
|
||||
"mouthAllowed" to true,"mouthRuntimeManifest" to mapOf("path" to "$name/manifest.json","sha256" to own.manifestSha),
|
||||
"clip" to clip(own,"$name/body.mp4"))
|
||||
} }
|
||||
val dance=dynamicPack(241,24,"f".repeat(64))
|
||||
val actions=listOf("asset_01","asset_02").map { id->mapOf<String,Any?>("id" to id,"kind" to "dance",
|
||||
"mouthAllowed" to false,"disallowTALK" to true,"entryAnchor" to "A","returnAnchor" to "A",
|
||||
"sourcePackageId" to "neutral","sourceFrame" to 96,"sourcePtsUs" to 4_000_000L,
|
||||
"returnPackageId" to "neutral","returnFrame" to 0,"returnPtsUs" to 0L,
|
||||
"clip" to clip(dance,"$id.mp4",true),"audioEndUs" to 10_000_000L) }
|
||||
val root=mapOf<String,Any?>("schemaVersion" to 2,"identityId" to "a01","packId" to "a01-expression-action-v1",
|
||||
"fallbackPackageId" to "neutral","conversationPackages" to rows,"edges" to loops+bridges,"actions" to actions)
|
||||
fun read(meta: Map<String,Any?> = root,bodyData: Map<String,ContinuousAvatarPack> = bodies,
|
||||
bridgeData: Map<String,ContinuousAvatarPack> = mouths)=EmotionActionManifest.read(meta,pin,pin) { path,hash->
|
||||
(bodyData[path.substringBefore('/')] ?: bridgeData[path.substringBefore('/')])?.takeIf { it.manifestSha==hash }
|
||||
}
|
||||
val index=checkNotNull(read());var assertions=0
|
||||
check(index.packages.size==5 && index.edges.size==13 && index.edges.count { it.mouthRuntime!=null }==8);assertions++
|
||||
check(index.actionPack?.assets?.size==2 && index.actionPack.assets.all { it.media?.ptsUs?.size==241 });assertions++
|
||||
val bytes=index.packages.values.sumOf { it.rgbaBytes }+index.edges.mapNotNull { it.mouthRuntime }.sumOf { it.rgbaBytes }
|
||||
check(bytes==bodies.values.sumOf { it.rgbaBytes }+mouths.values.sumOf { it.rgbaBytes } && bytes<=BodyTimeline.MAX_PACK_CACHE_BYTES);assertions++
|
||||
for(change in listOf(mapOf("sourceFrame" to 0),mapOf("sourcePtsUs" to 0L),mapOf("returnPtsUs" to 1L),
|
||||
mapOf("sourcePackageId" to "idle-breathe"),mapOf("returnPackageId" to "idle-shift"))) {
|
||||
check(read(root+("actions" to listOf(actions[0]+change,actions[1])))==null);assertions++
|
||||
}
|
||||
for(name in mouths.keys) {
|
||||
val wrong=mouths.getValue(name).copy(body=mouths.getValue(name).body.copy(sha256=bodies.getValue("neutral").body.sha256))
|
||||
check(read(bridgeData=mouths+(name to wrong))==null);assertions++
|
||||
}
|
||||
val inflated=bodies.mapValues { (_,body)->body.copy(patches=body.patches.map { it.copy(width=80,height=44) }) }
|
||||
check(inflated.values.all { it.rgbaBytes<=BodyTimeline.MAX_RGBA_BYTES } && read(bodyData=inflated)==null);assertions++
|
||||
println("PASS: $assertions full5-body/13-edge/8-own-bridge/two241-frame-action parser assertions; RGBA=$bytes bytes, source96/4s/return binding and total-cache rejection; fixtures only")
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.gorios.lanvoice.avatar.*
|
||||
import com.gorios.lanvoice.net.*
|
||||
|
||||
fun checkActionSession() {
|
||||
checkActionFollowupSession()
|
||||
val sha="a".repeat(64);val states=mutableListOf<VoiceUiState>()
|
||||
val prepared=mutableListOf<com.gorios.lanvoice.dialogue.ReplyEmotion?>()
|
||||
var plays=0;var stopped=0;var ended: ((ActionEnd)->Unit)?=null
|
||||
@@ -54,3 +55,50 @@ fun checkActionSession() {
|
||||
session.release();AudioCapture.confirmStopsAutomatically=true
|
||||
println("PASS: actual VoiceSession action plan→capture cleanup fence→player, queued mic/downlink dropped, prepare-only/old-turn, no voice barge, background cancel; doubles only")
|
||||
}
|
||||
|
||||
/** Client consumes the same pre-turn→action→new after-turn order as the socket probe. */
|
||||
fun checkActionFollowupSession() {
|
||||
val sha="a".repeat(64);val states=mutableListOf<VoiceUiState>();var finish: ((ActionEnd)->Unit)?=null
|
||||
val player=object: ActionPlayer {
|
||||
override fun play(asset: ActionAsset,finished: (ActionEnd)->Unit,failed: ()->Unit) { finish=finished }
|
||||
override fun stop(released: ()->Unit) { released() }
|
||||
}
|
||||
val session=VoiceSession("localhost",5011,states::add,
|
||||
reviewedActionPack=ReviewedActionPack(sha,listOf(ActionAsset("asset_01",1000),ActionAsset("asset_02",1000))),actionPlayer=player)
|
||||
fun field(name: String)=session.javaClass.getDeclaredField(name).apply { isAccessible=true }
|
||||
val dialogue=field("dialogue").get(session) as DialogueClient
|
||||
val socket=FakeSocket();dialogue.setField("socket",socket);dialogue.setField("ready",true)
|
||||
field("foreground").set(session,true);field("state").set(session,VoiceUiState(connection=ConnectionStatus.CONNECTED))
|
||||
val method=session.javaClass.getDeclaredMethod("onEvent",ServerEvent::class.java).apply { isAccessible=true }
|
||||
fun event(type: String,kind: EventKind,turn: Long,fields: Map<String,Any> = emptyMap()) {
|
||||
method.invoke(session,ServerEvent(type,kind,Payload(turn=turn,state=fields["state"] as? String ?: "",
|
||||
reason=fields["reason"] as? String ?: "",fields=fields)))
|
||||
}
|
||||
val frame=session.javaClass.getDeclaredMethod("onFrame",DownlinkFrame::class.java).apply { isAccessible=true }
|
||||
session.startVoice();event("listen",EventKind.LISTEN,7,mapOf("state" to "start"))
|
||||
frame.invoke(session,DownlinkFrame(7));checkNotNull(AudioPlayback.lastDrained)(7,0);Handler.drain()
|
||||
event("action.plan",EventKind.ACTION,7,mapOf("action_id" to "y".repeat(24),"pack_sha256" to sha,"ttl_ms" to 10000L))
|
||||
Handler.drain();check(states.last().actionActive && finish!=null)
|
||||
event("reply.emotion",EventKind.REPLY_EMOTION,8,mapOf("seq" to 30L,"emotion" to "sad","intensity" to 2,"source" to "model"))
|
||||
check(states.last().replyEmotion.turnId==null) // No future after expression during ACTION.
|
||||
val controller=field("actions").get(session) as ActionController
|
||||
controller.javaClass.getDeclaredField("started").apply { isAccessible=true }.setLong(controller,android.os.SystemClock.elapsedRealtime()-1001)
|
||||
finish!!(ActionEnd(true,true,true));Handler.drain();check(!states.last().actionActive)
|
||||
event("abort",EventKind.ABORT,8,mapOf("reason" to "action_followup"))
|
||||
event("speech.start",EventKind.SPEECH,8,mapOf("origin" to "after_action"))
|
||||
event("tts",EventKind.TTS,8,mapOf("state" to "start"))
|
||||
event("reply.emotion",EventKind.REPLY_EMOTION,8,mapOf("seq" to 33L,"emotion" to "sad","intensity" to 2,"source" to "model"))
|
||||
check(states.last().replyEmotion.turnId==8L && states.last().replyEmotion.intensity==2)
|
||||
val before=AudioPlayback.enqueued;frame.invoke(session,DownlinkFrame(8))
|
||||
check(AudioPlayback.enqueued==before+1 && states.last().phase==VoicePhase.ANSWERING)
|
||||
frame.invoke(session,DownlinkFrame(7))
|
||||
event("reply.emotion",EventKind.REPLY_EMOTION,7,mapOf("seq" to 99L,"emotion" to "happy","intensity" to 1,"source" to "model"))
|
||||
check(AudioPlayback.enqueued==before+1 && states.last().replyEmotion.turnId==8L)
|
||||
AudioPlayback.activityFence={turn,_->turn==8L}
|
||||
checkNotNull(AudioPlayback.lastDrained)(7,0);Handler.drain();check(states.last().replyEmotion.turnId==8L)
|
||||
checkNotNull(AudioPlayback.lastDrained)(8,0);Handler.drain()
|
||||
check(states.last().replyEmotion.turnId==null && states.last().phase==VoicePhase.LISTENING)
|
||||
val messages=socket.sent.size;finish!!(ActionEnd(true,true,true));Handler.drain();check(socket.sent.size==messages)
|
||||
session.release();AudioPlayback.activityFence=null
|
||||
println("PASS: client normal action completion/new server speech turn accepted, future after emotion hidden, retired pre audio/emotion/drain rejected, independent after drain and duplicate completion fence; deterministic doubles only")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user