Validate isolated public action followup calling path

This commit is contained in:
zenord
2026-10-13 05:50:20 +08:00
parent a113bd4bb3
commit 33b552473a
6 changed files with 475 additions and 0 deletions
+292
View File
@@ -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')
+37
View File
@@ -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()