feat(voice): implement local S2S responsiveness candidate and direct TTS routing

Add local S2S responsiveness candidate pinning ASR options and sentence-at-a-time generation. Route speech synthesis directly to OpenAI API for fluent Persian phonetics with gpt-4o-mini-tts-2025-12-15. Add responsiveness, budget carry, and browser watch unit tests along with acceptance benchmarks and evaluation evidence.
This commit is contained in:
amirhosein mazaheri
2026-10-17 13:02:41 +03:30
parent a94b8cd3ea
commit 628aec8def
40 changed files with 1568 additions and 70 deletions
+4 -3
View File
@@ -1,4 +1,4 @@
"""Real DB local profiles retain replay/owner/revocation authority."""
"""Real DB local profiles retain replay/owner/revocation authority."""
from uuid import UUID, uuid4
from sqlalchemy import text
import pytest
@@ -6,11 +6,12 @@ from tests.integration.test_phase2_postgres import seeded_env
from tests.unit.test_local_s2s_phase2 import local_config
def test_local_profile_replay_never_rewrites_frozen_components(seeded_env):
@pytest.mark.parametrize('responsive',[False, True])
def test_local_profile_replay_never_rewrites_frozen_components(seeded_env,responsive):
e = seeded_env
cid = UUID(e.lifecycle.create_conversation(e.user, uuid4())['id'])
request = uuid4()
config = local_config()
config = local_config(local_s2s_responsive=responsive)
first = e.lifecycle.create_live_session(e.user, cid, request, provider='local_s2s',
model=config.selected_model, execution_profile=config.profile())
sid = UUID(first['session_id'])
+109
View File
@@ -0,0 +1,109 @@
"""Documentary carry must preserve prior exposure and exclusive live admission."""
import asyncio
import importlib.util
import json
from pathlib import Path
import httpx
import pytest
spec=importlib.util.spec_from_file_location('phase4_guard',Path(__file__).parents[2]/'docs/evaluation/local-s2s/phase4-browser-budget.py')
guard=importlib.util.module_from_spec(spec);spec.loader.exec_module(guard)
@pytest.fixture
def evidence(tmp_path):
checkpoint=dict(prior_conservative_exposure_usd='0.704504399',total_cap_usd='1',paid_calls_on_this_host=0,prior_private_ledgers_available=False,source='docs/evaluation/local-s2s/phase-04-interruption-incident.md',status='preparation_only_not_a_live_admission_ledger')
(tmp_path/'carried-budget-preparation.json').write_text(json.dumps(checkpoint))
endpoints=[dict(tag=tag,max_prompt_tokens=8192,max_completion_tokens=16384,pricing=dict(prompt='0.0000005',completion='0.000006')) for tag in ('google-ai-studio','google-vertex/global')]
(tmp_path/'endpoints-google-gemini-3.8-flash-lite-tts.json').write_text(json.dumps(dict(data=dict(endpoints=endpoints))))
(tmp_path/'endpoints-openai-whisper-large-v3.json').write_text(json.dumps(dict(data=dict(endpoints=[dict(pricing=dict(prompt='0.000001'))]))))
return tmp_path
def test_failures_remain_reserved_and_limit_precedes_provider(evidence):
async def run():
calls=[]
def upstream(request):
calls.append(request)
return httpx.Response(503)
transport=guard.BrowserBudget(evidence,upstream=httpx.MockTransport(upstream))
assert transport.state['maximum_cumulative_usd']=='0.940504399'
assert transport.state['carry_basis']=='documentary_checkpoint'
request=httpx.Request('POST','https://openrouter.ai/api/v1/audio/speech',json=dict(model='google/gemini-3.8-flash-lite-tts',voice='Kore',input='test',response_format='pcm'))
try:
for _ in range(4):await transport.handle_async_request(request)
with pytest.raises(guard.EvaluationBudgetExhausted):await transport.handle_async_request(request)
assert len(calls)==4
assert transport.state['reserved_usd']=='0.844504399'
assert len(transport.state['attempts'])==4
with pytest.raises(FileExistsError):guard.BrowserBudget(evidence,upstream=httpx.MockTransport(upstream))
finally:await transport.close_owned()
asyncio.run(run())
@pytest.mark.parametrize('field,value',[('prior_conservative_exposure_usd','0'),('total_cap_usd','5'),('paid_calls_on_this_host',1),('prior_private_ledgers_available',True)])
def test_changed_carry_rejected_before_ledger_creation(evidence,field,value):
p=evidence/'carried-budget-preparation.json';data=json.loads(p.read_text());data[field]=value;p.write_text(json.dumps(data))
with pytest.raises(ValueError):guard.BrowserBudget(evidence)
assert not (evidence/'browser-paid-ledger.json').exists()
def test_mixed_carry_evidence_rejected(evidence):
(evidence/'previous-phase4-ledger.json').write_text('{}')
with pytest.raises(ValueError):guard.BrowserBudget(evidence)
assert not (evidence/'browser-paid-ledger.json').exists()
@pytest.fixture
def billed_evidence(evidence):
attempts=[];bills=[]
for stage,reserve,cost in [('transcriptions','.004','0.0000075'),('completions','.02','0.0000228'),('speech','.035','0.0001635')]:
attempts.append(dict(stage=stage,reserved_usd=reserve,status='headers_received',http_status=200,generation_id='fixture-'+stage))
bills.append(dict(stage=stage,generation_id='fixture-'+stage,http_status=200,billing=dict(total_cost=cost)))
(evidence/'previous-windows-ledger.json').write_text(json.dumps(dict(previous_reserved_and_billed_usd='0.704504399',reserved_usd='0.763504399',carry_basis='documentary_checkpoint',attempts=attempts)))
(evidence/'previous-windows-billing.json').write_text(json.dumps(bills))
return evidence
def test_only_exact_billed_attempts_release_reserves(billed_evidence):
async def run():
transport=guard.BrowserBudget(billed_evidence,upstream=httpx.MockTransport(lambda r:httpx.Response(503)))
try:
assert transport.state['reserved_usd']=='0.704698199'
assert transport.state['maximum_cumulative_usd']=='0.940698199'
assert transport.state['carry_basis']=='documentary_checkpoint_with_local_bills'
finally:await transport.close_owned()
asyncio.run(run())
@pytest.mark.parametrize('change',['wrong_id','negative_cost','missing_receipt'])
def test_unverified_billing_cannot_release_reserves(billed_evidence,change):
path=billed_evidence/'previous-windows-billing.json';bills=json.loads(path.read_text())
if change=='wrong_id':bills[0]['generation_id']='unrelated'
elif change=='negative_cost':bills[0]['billing']['total_cost']='-1'
else:bills.pop()
path.write_text(json.dumps(bills))
with pytest.raises(ValueError):guard.BrowserBudget(billed_evidence)
assert not (billed_evidence/'browser-paid-ledger.json').exists()
@pytest.fixture
def chained_evidence(billed_evidence):
first=json.loads((billed_evidence/'previous-windows-ledger.json').read_text());bills=json.loads((billed_evidence/'previous-windows-billing.json').read_text())
second=json.loads(json.dumps(first));second['previous_reserved_and_billed_usd']='0.704698199';second['reserved_usd']='0.763698199'
for row in second['attempts']:row['generation_id']='second-'+row['generation_id']
second_bills=json.loads(json.dumps(bills))
for row in second_bills:row['generation_id']='second-'+row['generation_id']
(billed_evidence/'one-ledger.json').write_text(json.dumps(first));(billed_evidence/'one-bills.json').write_text(json.dumps(bills))
(billed_evidence/'two-ledger.json').write_text(json.dumps(second));(billed_evidence/'two-bills.json').write_text(json.dumps(second_bills))
(billed_evidence/'previous-windows-ledger.json').unlink();(billed_evidence/'previous-windows-billing.json').unlink()
(billed_evidence/'previous-windows-runs.json').write_text(json.dumps([dict(ledger='one-ledger.json',billing='one-bills.json'),dict(ledger='two-ledger.json',billing='two-bills.json')]))
return billed_evidence
def test_chained_receipts_carry_all_previous_calls(chained_evidence):
async def run():
g=guard.BrowserBudget(chained_evidence,upstream=httpx.MockTransport(lambda r:httpx.Response(503)))
try:
assert g.state['reserved_usd']=='0.704891999'
assert g.state['maximum_cumulative_usd']=='0.975891999'
finally:await g.close_owned()
asyncio.run(run())
def test_chain_cannot_skip_prior_cost(chained_evidence):
p=chained_evidence/'two-ledger.json';data=json.loads(p.read_text());data['previous_reserved_and_billed_usd']='0.704504399';p.write_text(json.dumps(data))
with pytest.raises(ValueError):guard.BrowserBudget(chained_evidence)
assert not (chained_evidence/'browser-paid-ledger.json').exists()
+151
View File
@@ -0,0 +1,151 @@
"""Opt-in policy must reach real wire bytes and remain frozen/attested."""
import asyncio
import base64
from io import BytesIO
import importlib.util
import json
from pathlib import Path
from threading import Thread
from types import SimpleNamespace
import wave
import httpx
import pytest
from app.modules.voice.local_s2s import RESPONSIVE_ASR_PROMPT
from services.local_s2s.responsiveness import install_stt_policy,transcription_request
from services.local_s2s.extension import active_components
from services.local_s2s.components import ComponentServer
from services.local_s2s.request_policy import install_client_policy
from tests.unit.test_local_s2s_phase2 import local_config,confirmed
from tests.unit.test_local_s2s_engine import handlers
from app.infrastructure.local_s2s import LocalS2SAdapter
from app.modules.voice.settings import RuntimeSettings
def audio():
out=BytesIO()
with wave.open(out,'wb') as w:
w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(bytes(3200))
return out.getvalue()
def request():
r=httpx.Request('POST','https://openrouter.ai/api/v1/audio/transcriptions',data=dict(model='openai/whisper-large-v3',language='fa',response_format='json',temperature='0',prompt=RESPONSIVE_ASR_PROMPT),files={'file':('audio.wav',audio(),'audio/wav')})
r.read();return r
def test_profile_changes_identity_and_requires_applied_settings():
baseline=local_config();responsive=local_config(local_s2s_responsive=True)
assert baseline.profile()!=responsive.profile()
assert not LocalS2SAdapter(None,config=baseline,settings=RuntimeSettings(_env_file=None)).acknowledged(confirmed(LocalS2SAdapter(None,config=responsive,settings=RuntimeSettings(_env_file=None))))
unit=handlers(responsive);unit.handlers[1].gen_kwargs=dict(temperature=0,prompt=RESPONSIVE_ASR_PROMPT);unit.handlers[2].stream_batch_sentences=1
assert active_components(unit,responsive.components())==responsive.components()
unit.handlers[2].stream_batch_sentences=3
with pytest.raises(ValueError):active_components(unit,responsive.components())
def test_transcription_policy_preserves_audio_and_uses_supported_options():
r=transcription_request(request());d=json.loads(r.content)
assert base64.b64decode(d['input_audio']['data'])==audio()
assert d['temperature']==0 and d['language']=='fa'
assert d['provider']=={'options':{'groq':{'prompt':RESPONSIVE_ASR_PROMPT}}}
assert 'prompt' not in d
spec=importlib.util.spec_from_file_location('admission',Path(__file__).parents[2]/'docs/evaluation/local-s2s/native-budget-transport.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
assert m.validate_request(r)[0]=='transcriptions'
d['temperature']=1
with pytest.raises(ValueError):m.validate_request(httpx.Request(r.method,r.url,json=d))
def test_stt_settings_apply_before_native_setup_and_warmup():
calls=[]
class Handler:
def setup(self,**kwargs):calls.append(kwargs)
module=SimpleNamespace(OpenAICompatibleSTTHandler=Handler)
install_stt_policy(module);Handler().setup(gen_kwargs={'response_style':'plain'})
assert calls==[{'gen_kwargs':{'response_style':'plain','temperature':0,'prompt':RESPONSIVE_ASR_PROMPT}}]
def test_sentence_policy_applies_before_llm_warmup():
calls=[]
class Base:
def setup(self,**kwargs):calls.append(kwargs)
module=SimpleNamespace(OpenAI=lambda **kwargs:None,BaseOpenAICompatibleHandler=Base)
install_client_policy(module,local_config(local_s2s_responsive=True));Base().setup()
assert calls[0]['stream_batch_sentences']==1
def test_actual_gateway_transforms_request_without_rewriting_transcript(capsys):
observed=[]
def upstream(r):
observed.append(json.loads(r.content))
return httpx.Response(200,headers={'content-type':'application/json'},json={'text':'unchanged transcript'})
server=ComponentServer('fixture-key',port=0,transport=httpx.MockTransport(upstream),responsive=True)
thread=Thread(target=server.serve_forever,daemon=True);thread.start();assert server.ready.wait(3)
try:
r=request()
with httpx.Client(trust_env=False,timeout=5) as client:
result=client.post('http://127.0.0.1:'+str(server.server_port)+'/v1/audio/transcriptions',content=r.content,headers={'content-type':r.headers['content-type'],'authorization':'Bearer local-components'})
assert result.status_code==200 and result.json()['text']=='unchanged transcript'
assert observed[0]['provider']['options']['groq']['prompt']==RESPONSIVE_ASR_PROMPT
finally:
server.shutdown();server.server_close();thread.join(3)
output=capsys.readouterr().out
assert 'component_first_byte' in output
assert RESPONSIVE_ASR_PROMPT not in output and 'unchanged transcript' not in output
@pytest.mark.parametrize('component', ['transcriptions', 'speech'])
@pytest.mark.parametrize('has_key', [True, False])
def test_direct_openai_audio_routes_and_never_uses_router_key(monkeypatch, component, has_key):
if has_key:
monkeypatch.setenv('OPENAI_API_KEY', 'openai-fixture')
else:
monkeypatch.delenv('OPENAI_API_KEY', raising=False)
observed = []
def upstream(r):
observed.append(r)
return httpx.Response(200, headers={'content-type': 'application/json' if component == 'transcriptions' else 'audio/pcm'},
content=b'{"text":"unchanged"}' if component == 'transcriptions' else bytes(100))
if component == 'transcriptions':
r = httpx.Request('POST', 'http://fixture', data=dict(model='gpt-4o-transcribe', language='fa', response_format='json', temperature='0', prompt=RESPONSIVE_ASR_PROMPT), files={'file': ('audio.wav', audio(), 'audio/wav')})
r.read()
else:
r = httpx.Request('POST', 'http://fixture', json=dict(model='openai/gpt-4o-mini-tts', input='fixture', voice='alloy', response_format='pcm'))
server = ComponentServer('router-fixture', port=0, transport=httpx.MockTransport(upstream), responsive=True)
thread = Thread(target=server.serve_forever, daemon=True); thread.start(); assert server.ready.wait(3)
try:
with httpx.Client(trust_env=False, timeout=5) as client:
try:
result = client.post(f'http://127.0.0.1:{server.server_port}/v1/audio/{component}', content=r.content,
headers={'content-type': r.headers['content-type'], 'authorization': 'Bearer local-components'})
except httpx.RemoteProtocolError:
assert not has_key
else:
assert has_key and result.status_code == 200
if has_key:
sent = observed[0]
assert str(sent.url) == f'https://api.openai.com/v1/audio/{component}'
assert sent.headers['authorization'] == 'Bearer openai-fixture'
if component == 'transcriptions':
assert sent.content == r.content
assert sent.headers['content-type'].startswith('multipart/form-data;')
else:
assert json.loads(sent.content)['model'] == 'gpt-4o-mini-tts'
else:
assert observed == []
finally:
server.shutdown(); server.server_close(); thread.join(3)
def test_faster_tts_applies_before_warmup_and_is_attested():
from services.local_s2s.request_policy import install_tts_speed
from app.modules.voice.local_s2s import setup_session
calls = []
class Handler:
def setup(self, **kwargs):
self.speed = kwargs['speed']; calls.append(kwargs)
module = SimpleNamespace(OpenAICompatibleTTSHandler=Handler)
install_tts_speed(module, 1.3); handler = Handler(); handler.setup()
assert calls == [{'speed': 1.3}]
config = local_config(local_s2s_tts_speed=1.3)
assert setup_session(config)['audio']['output']['speed'] == 1.3
assert config.profile() != local_config().profile()
unit = handlers(config); unit.handlers[-1].speed = handler.speed
assert active_components(unit, config.components())['tts']['speed'] == 1.3
unit.handlers[-1].speed = 1.0
with pytest.raises(ValueError): active_components(unit, config.components())
+58
View File
@@ -0,0 +1,58 @@
"""The Windows handoff supervisor must fail closed and stop only its engine."""
import importlib.util
import json
from pathlib import Path
import pytest
@pytest.fixture
def watcher(tmp_path,monkeypatch):
spec=importlib.util.spec_from_file_location('windows_watch',Path(__file__).parents[2]/'docs/evaluation/local-s2s/watch-windows-browser.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
monkeypatch.setattr(m,'EVIDENCE',tmp_path)
monkeypatch.setattr(m,'REPORT',tmp_path/'report.json')
monkeypatch.setattr(m,'available',lambda:4*1024**3)
monkeypatch.setattr(m,'vm_available',lambda:6*1024**3)
monkeypatch.setattr(m.signal,'signal',lambda *args:None)
calls=[]
monkeypatch.setattr(m.subprocess,'run',lambda command,**kwargs:calls.append(command))
return m,calls
def test_existing_ledger_never_restarts(watcher):
m,calls=watcher;(m.EVIDENCE/'browser-paid-ledger.json').write_text('{}')
with pytest.raises(SystemExit):m.main()
assert calls==[]
def test_low_memory_makes_no_launch(watcher,monkeypatch):
m,calls=watcher;monkeypatch.setattr(m,'available',lambda:1024**3)
with pytest.raises(SystemExit):m.main(enforce_memory=True)
assert calls==[]
assert json.loads(m.REPORT.read_text())['reason']=='prestart_memory'
@pytest.mark.parametrize('reason',['memory_floor','handoff_expired_30_minutes'])
def test_runtime_guard_stops_only_owned_engine(watcher,monkeypatch,reason):
m,calls=watcher
if reason=='memory_floor':
readings=iter([4*1024**3,2*1024**3]);monkeypatch.setattr(m,'available',lambda:next(readings))
monkeypatch.setattr(m.time,'monotonic',lambda:0)
else:
times=iter([0,1801,1801]);monkeypatch.setattr(m.time,'monotonic',lambda:next(times))
m.main(enforce_memory=True)
assert len(calls)==2
assert calls[0][-5:]==['--pull','never','--no-deps','-d','local-s2s-engine']
assert calls[1][-4:]==['stop','--timeout','5','local-s2s-engine']
assert json.loads(m.REPORT.read_text())['reason']==reason
def test_default_observes_low_memory_without_blocking_or_stopping(watcher,monkeypatch):
m,calls=watcher
monkeypatch.setattr(m,'available',lambda:1024**3)
monkeypatch.setattr(m,'vm_available',lambda:1024**3)
times=iter([0,1801,1801]);monkeypatch.setattr(m.time,'monotonic',lambda:next(times))
m.main()
report=json.loads(m.REPORT.read_text())
assert report['memory_enforcement'] is False
assert report['reason']=='handoff_expired_30_minutes'
assert report['minimum_windows_available_bytes']==1024**3
assert len(calls)==2
assert calls[0][-1]=='local-s2s-engine'
assert calls[1][-4:]==['stop','--timeout','5','local-s2s-engine']