feat(voice): add isolated Local S2S v3 candidate and acceptance evidence
Extract the provider boundary while retaining OpenAI/Gemini contracts. Add an opt-in isolated Local S2S adapter, pinned engine extension, bounded component gateway and frozen effective configuration profiles. Enforce request token limits, zero retries, local asset validation, connection deadlines, disconnect ownership, bounded cleanup and signals. Include regression coverage, pinned source fixtures, operator guidance, asset fingerprints and guarded disposable PostgreSQL acceptance tooling. Preserve immutable fixture bytes across Git line-ending conversion. Validation recorded in the reports: - 74 repair, 107 combined and 242 preservation checks passed. - Fresh PostgreSQL local checks: 2 passed. - Expanded PostgreSQL: 57 passed, 6 documented baseline failures. - Compose configurations, staged whitespace and fixture hashes passed. Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component audio and Persian browser acceptance remain pending. No operational switch, paid call, model download or Phase 3 implementation is included.
This commit is contained in:
@@ -145,3 +145,26 @@ INGEST_OCR_REVIEW_REQUIRED=true
|
|||||||
OPENAI_REALTIME_MAX_OUTPUT_TOKENS=2048
|
OPENAI_REALTIME_MAX_OUTPUT_TOKENS=2048
|
||||||
# Provider-side speech speed (0.25..1.5); frozen for each new Live session.
|
# Provider-side speech speed (0.25..1.5); frozen for each new Live session.
|
||||||
OPENAI_REALTIME_SPEED=1.30
|
OPENAI_REALTIME_SPEED=1.30
|
||||||
|
|
||||||
|
# Local S2S Phase 2 candidate (off by default; isolated development only).
|
||||||
|
# See services/local_s2s/README.md. Do not change the operational VOICE_PROVIDER.
|
||||||
|
LOCAL_S2S_ENABLED=false
|
||||||
|
LOCAL_S2S_ENDPOINT=ws://local-s2s-engine:8765/v1/realtime
|
||||||
|
LOCAL_S2S_ENGINE_REVISION=619e3fe4f71d1c6f35c15870d588a3638de34722
|
||||||
|
LOCAL_S2S_STT_MODEL=openai/whisper-large-v3
|
||||||
|
LOCAL_S2S_LLM_MODEL=openai/gpt-4.1-mini
|
||||||
|
# Candidate only: actual voice/rate/Persian compatibility is not accepted yet.
|
||||||
|
LOCAL_S2S_TTS_MODEL=google/gemini-3.8-flash-lite-tts
|
||||||
|
LOCAL_S2S_TTS_VOICE=Kore
|
||||||
|
LOCAL_S2S_MAX_OUTPUT_TOKENS=256
|
||||||
|
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS=30
|
||||||
|
LOCAL_S2S_TOKEN=
|
||||||
|
# Engine-only OpenRouter key: set at launch, never forward it to the API/browser.
|
||||||
|
# OPENROUTER_API_KEY=
|
||||||
|
|
||||||
|
# Local engine v2: provision these local bundles separately, never at startup.
|
||||||
|
# Compose host paths (see services/local_s2s/README.md):
|
||||||
|
# LOCAL_S2S_VAD_SOURCE=<local-silero-source-and-jit-bundle>
|
||||||
|
# LOCAL_S2S_NLTK_SOURCE=<local-unpacked-nltk-data>
|
||||||
|
# LOCAL_S2S_ASSET_MANIFEST_SOURCE=<local-assets.json>
|
||||||
|
# LOCAL_S2S_ASSET_MANIFEST_SHA256=<reviewed-manifest-sha256>
|
||||||
|
|||||||
@@ -4,3 +4,7 @@
|
|||||||
# Preserve calibration original bytes used by independently annotated hashes.
|
# Preserve calibration original bytes used by independently annotated hashes.
|
||||||
/data/calibration/phase2-source.md -text
|
/data/calibration/phase2-source.md -text
|
||||||
/docs/calibration/phase2-cases.json text eol=lf
|
/docs/calibration/phase2-cases.json text eol=lf
|
||||||
|
|
||||||
|
# Pinned upstream fixtures and historical repair patch have byte fingerprints.
|
||||||
|
/tests/fixtures/local_s2s_upstream/* -text whitespace=cr-at-eol
|
||||||
|
/docs/evaluation/local-s2s/phase-02-remaining-repairs.patch -text whitespace=-blank-at-eol,-blank-at-eof
|
||||||
|
|||||||
@@ -86,3 +86,6 @@ temp/
|
|||||||
|
|
||||||
# Immutable ingestion originals (may contain private uploaded content)
|
# Immutable ingestion originals (may contain private uploaded content)
|
||||||
data/originals/
|
data/originals/
|
||||||
|
|
||||||
|
# Isolated local S2S generated source and dependency inputs
|
||||||
|
.local-s2s-build/
|
||||||
|
|||||||
@@ -102,6 +102,9 @@ def create_voice_session(req: CreateLiveSessionRequest, response: Response,
|
|||||||
response.status_code = 201 if result['status'] == 'connected' else 202
|
response.status_code = 201 if result['status'] == 'connected' else 202
|
||||||
response.headers['Idempotency-Replayed'] = 'true'
|
response.headers['Idempotency-Replayed'] = 'true'
|
||||||
return result
|
return result
|
||||||
|
if config.provider == 'local_s2s':
|
||||||
|
from app.modules.voice.local_s2s import require_isolated_candidate
|
||||||
|
require_isolated_candidate(config, IngestionSettings(), database_url=engine.url)
|
||||||
cutoff = capability(config)
|
cutoff = capability(config)
|
||||||
profile = config.profile()
|
profile = config.profile()
|
||||||
# Construct configured embedding transport only after replay recovery.
|
# Construct configured embedding transport only after replay recovery.
|
||||||
@@ -166,6 +169,9 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
|||||||
try:
|
try:
|
||||||
user = await blocking(auth_service.get_current_user, websocket.cookies.get(COOKIE_NAME))
|
user = await blocking(auth_service.get_current_user, websocket.cookies.get(COOKIE_NAME))
|
||||||
info = await blocking(lifecycle_service.validate_stream, user, session_id, initial=True)
|
info = await blocking(lifecycle_service.validate_stream, user, session_id, initial=True)
|
||||||
|
if config.provider == 'local_s2s':
|
||||||
|
from app.modules.voice.local_s2s import require_isolated_candidate
|
||||||
|
require_isolated_candidate(config, search_service.settings, database_url=engine.url)
|
||||||
config.require_voice()
|
config.require_voice()
|
||||||
if search_service.cutoff is None and not config.voice_transport_testing:
|
if search_service.cutoff is None and not config.voice_transport_testing:
|
||||||
raise ValueError('CALIBRATION_REQUIRED')
|
raise ValueError('CALIBRATION_REQUIRED')
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ from uuid import uuid4
|
|||||||
from app.modules.knowledge.service import SearchInput
|
from app.modules.knowledge.service import SearchInput
|
||||||
from app.modules.voice.settings import RuntimeSettings
|
from app.modules.voice.settings import RuntimeSettings
|
||||||
from app.modules.voice.serialization import bounded_json
|
from app.modules.voice.serialization import bounded_json
|
||||||
from app.infrastructure.realtime import POLICY, strict_json, ProviderProtocolError
|
from app.infrastructure.realtime import POLICY
|
||||||
|
from app.modules.voice.provider import strict_json, ProviderProtocolError
|
||||||
|
|
||||||
class GeminiContextError(ProviderProtocolError):
|
class GeminiContextError(ProviderProtocolError):
|
||||||
context_sync = True
|
context_sync = True
|
||||||
@@ -102,6 +103,21 @@ class GeminiLiveAdapter:
|
|||||||
self._sent_samples = 0
|
self._sent_samples = 0
|
||||||
self._resampler = PCM24To16()
|
self._resampler = PCM24To16()
|
||||||
|
|
||||||
|
def cancellation_request(self, response_id, operation_id=None):
|
||||||
|
event = dict(type="response.cancel", response_id=response_id)
|
||||||
|
if operation_id is not None:
|
||||||
|
event["event_id"] = operation_id
|
||||||
|
return event
|
||||||
|
|
||||||
|
def history_repair_request(self, repair):
|
||||||
|
# Preserve the existing send-path failure and its bounded cleanup.
|
||||||
|
return dict(type="conversation.item.truncate", event_id=repair.operation_id,
|
||||||
|
item_id=repair.item_id, content_index=repair.content_index,
|
||||||
|
audio_end_ms=repair.played_ms)
|
||||||
|
|
||||||
|
def confirm_history_repair(self, repair, event):
|
||||||
|
raise GeminiContextError('Gemini context cannot be safely truncated')
|
||||||
|
|
||||||
def setup(self):
|
def setup(self):
|
||||||
return dict(type='session.update', session={'provider':'gemini'})
|
return dict(type='session.update', session={'provider':'gemini'})
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""Pinned local engine GA transport; no invented native input/history receipts."""
|
||||||
|
from app.infrastructure.realtime import RealtimeAdapter
|
||||||
|
from app.modules.voice.provider import ProviderProtocolError
|
||||||
|
from app.modules.voice.local_s2s import setup_session, effective_identity
|
||||||
|
|
||||||
|
|
||||||
|
class LocalS2SContextError(ProviderProtocolError):
|
||||||
|
context_sync = True
|
||||||
|
|
||||||
|
|
||||||
|
class LocalS2SAdapter(RealtimeAdapter):
|
||||||
|
def __init__(self, transport, *, config, settings):
|
||||||
|
# The local text model is not an OpenAI Realtime model. Keep its config
|
||||||
|
# independent of OpenAI reasoning/transcription settings.
|
||||||
|
self.transport, self.config, self.settings = transport, config, settings
|
||||||
|
self.model, self.voice = config.selected_model, config.selected_voice
|
||||||
|
self._setup = setup_session(config)
|
||||||
|
self._identity = effective_identity(config.components(), self._setup)
|
||||||
|
self._confirmed = False
|
||||||
|
|
||||||
|
def setup(self):
|
||||||
|
from copy import deepcopy
|
||||||
|
return dict(type='session.update', session=deepcopy(self._setup))
|
||||||
|
|
||||||
|
def acknowledged(self, session):
|
||||||
|
# A session echo cannot certify a fixed global engine's real components.
|
||||||
|
# The versioned engine extension derives this from initialized handlers.
|
||||||
|
if not isinstance(session, dict) or session.get('s2s_effective') != self._identity:
|
||||||
|
return False
|
||||||
|
def matches(actual, expected):
|
||||||
|
if isinstance(expected, dict):
|
||||||
|
return isinstance(actual, dict) and all(k in actual and matches(actual[k], v) for k, v in expected.items())
|
||||||
|
if isinstance(expected, list):
|
||||||
|
return isinstance(actual, list) and len(actual) == len(expected) and all(matches(a, b) for a, b in zip(actual, expected))
|
||||||
|
return type(actual) is type(expected) and actual == expected
|
||||||
|
self._confirmed = matches(session, self._setup)
|
||||||
|
return self._confirmed
|
||||||
|
|
||||||
|
def token_limited(self, response):
|
||||||
|
# No unverified local terminal signature is accepted as a successful answer.
|
||||||
|
return False
|
||||||
|
|
||||||
|
def is_no_active(self, error):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def confirm_history_repair(self, repair, event):
|
||||||
|
raise LocalS2SContextError('Local history repair is not available in Phase 2')
|
||||||
|
|
||||||
|
async def send_serialized(self, wire):
|
||||||
|
from app.modules.voice.provider import strict_json
|
||||||
|
event = strict_json(wire)
|
||||||
|
if event.get('type') in ('response.cancel', 'conversation.item.truncate'):
|
||||||
|
raise LocalS2SContextError('Local interruption requires Phase 3 history repair')
|
||||||
|
await self.transport.send(wire)
|
||||||
|
|
||||||
|
|
||||||
|
async def connect_local(config, limits):
|
||||||
|
from websockets.asyncio.client import connect
|
||||||
|
token = config.local_s2s_token.get_secret_value()
|
||||||
|
return await connect(config.local_s2s_endpoint,
|
||||||
|
additional_headers={'Authorization': 'Bearer ' + token} if token else {},
|
||||||
|
proxy=None, compression=None, max_size=limits.max_provider_message_bytes, max_queue=16,
|
||||||
|
open_timeout=limits.connect_timeout_seconds, close_timeout=limits.send_timeout_seconds,
|
||||||
|
ping_interval=20, ping_timeout=20)
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
"""Private OpenAI Realtime wire adapter; no application/provider IDs cross to clients."""
|
"""Private OpenAI Realtime wire adapter; no application/provider IDs cross to clients."""
|
||||||
import json
|
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
|
|
||||||
from app.modules.knowledge.service import SearchInput
|
from app.modules.knowledge.service import SearchInput
|
||||||
@@ -8,8 +7,9 @@ from app.modules.voice.configuration import OpenAIInputSettings
|
|||||||
from app.modules.voice.serialization import bounded_json
|
from app.modules.voice.serialization import bounded_json
|
||||||
from app.modules.voice.openai_style import effective_instructions
|
from app.modules.voice.openai_style import effective_instructions
|
||||||
|
|
||||||
class ProviderProtocolError(ValueError):
|
from app.modules.voice.provider import (
|
||||||
pass
|
ProviderProtocolError, canonical_json, strict_json, HistoryRepair, HistoryRepairReceipt,
|
||||||
|
)
|
||||||
|
|
||||||
POLICY = """You are the official voice assistant for «شرکت شهرکهای صنعتی اصفهان».
|
POLICY = """You are the official voice assistant for «شرکت شهرکهای صنعتی اصفهان».
|
||||||
Your scope is strictly limited to answering questions regarding «شرکت شهرکهای صنعتی اصفهان», including its regulations, industrial parks in Isfahan province, land allocations, contracts, permits, circulars, and official procedures.
|
Your scope is strictly limited to answering questions regarding «شرکت شهرکهای صنعتی اصفهان», including its regulations, industrial parks in Isfahan province, land allocations, contracts, permits, circulars, and official procedures.
|
||||||
@@ -52,21 +52,6 @@ When calling search_knowledge:
|
|||||||
- Preserve the user's explicitly stated place names, person names, document titles and identifiers in query. Shortening the question must not replace them with different entities. If a name is unclear, ask for clarification rather than guessing.
|
- Preserve the user's explicitly stated place names, person names, document titles and identifiers in query. Shortening the question must not replace them with different entities. If a name is unclear, ask for clarification rather than guessing.
|
||||||
- Set 'context' to null. Never write explanations or user intent in 'context'."""
|
- Set 'context' to null. Never write explanations or user intent in 'context'."""
|
||||||
|
|
||||||
def canonical_json(value):
|
|
||||||
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
|
||||||
separators=(",", ":"), sort_keys=True)
|
|
||||||
|
|
||||||
def strict_json(raw):
|
|
||||||
def pairs(items):
|
|
||||||
value = {}
|
|
||||||
for key, item in items:
|
|
||||||
if key in value:
|
|
||||||
raise ValueError("Duplicate JSON key")
|
|
||||||
value[key] = item
|
|
||||||
return value
|
|
||||||
return json.loads(raw, object_pairs_hook=pairs,
|
|
||||||
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")))
|
|
||||||
|
|
||||||
class RealtimeAdapter:
|
class RealtimeAdapter:
|
||||||
# Argument-done can precede a cut-off tool call: wait for terminal success.
|
# Argument-done can precede a cut-off tool call: wait for terminal success.
|
||||||
defer_tool_execution = True
|
defer_tool_execution = True
|
||||||
@@ -146,6 +131,30 @@ class RealtimeAdapter:
|
|||||||
for key in empty_defaults
|
for key in empty_defaults
|
||||||
if key not in expected['audio']['input']['transcription'])
|
if key not in expected['audio']['input']['transcription'])
|
||||||
|
|
||||||
|
def cancellation_request(self, response_id, operation_id=None):
|
||||||
|
event = dict(type="response.cancel", response_id=response_id)
|
||||||
|
if operation_id is not None:
|
||||||
|
event["event_id"] = operation_id
|
||||||
|
return event
|
||||||
|
|
||||||
|
def history_repair_request(self, repair: HistoryRepair):
|
||||||
|
return dict(type="conversation.item.truncate", event_id=repair.operation_id,
|
||||||
|
item_id=repair.item_id, content_index=repair.content_index,
|
||||||
|
audio_end_ms=repair.played_ms)
|
||||||
|
|
||||||
|
def confirm_history_repair(self, repair: HistoryRepair, event):
|
||||||
|
# Native OpenAI ack has no request event_id/response_id. Runtime first
|
||||||
|
# matches exactly one dispatched item/part in this session; never invent
|
||||||
|
# additional upstream confirmation or infer a heard transcript prefix.
|
||||||
|
if (event.get("type") != "conversation.item.truncated"
|
||||||
|
or event.get("item_id") != repair.item_id
|
||||||
|
or type(event.get("content_index")) is not int
|
||||||
|
or event["content_index"] != repair.content_index
|
||||||
|
or type(event.get("audio_end_ms")) is not int
|
||||||
|
or event["audio_end_ms"] != repair.played_ms):
|
||||||
|
raise ProviderProtocolError("History repair acknowledgement mismatch")
|
||||||
|
return HistoryRepairReceipt(repair, event.get("event_id"), "openai.item_truncated")
|
||||||
|
|
||||||
def interrupted_tool_output(self, call_id):
|
def interrupted_tool_output(self, call_id):
|
||||||
# Resolve abandoned private tool calls without publishing stale evidence.
|
# Resolve abandoned private tool calls without publishing stale evidence.
|
||||||
return dict(type="conversation.item.create", item=dict(
|
return dict(type="conversation.item.create", item=dict(
|
||||||
|
|||||||
@@ -1,11 +1,22 @@
|
|||||||
"""Selected voice transport construction shared by the API and operator smoke."""
|
"""Selected voice transport construction shared by the API and operator smoke."""
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from app.modules.voice.provider import VoiceProvider
|
||||||
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
|
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
|
||||||
from app.infrastructure.realtime import RealtimeAdapter, connect as connect_openai
|
from app.infrastructure.realtime import RealtimeAdapter, connect as connect_openai
|
||||||
|
|
||||||
|
|
||||||
async def create_adapter(config, limits):
|
async def create_adapter(config, limits) -> VoiceProvider:
|
||||||
config.require_voice()
|
config.require_voice()
|
||||||
|
if config.provider == 'local_s2s':
|
||||||
|
from app.infrastructure.local_s2s import LocalS2SAdapter, connect_local
|
||||||
|
if limits.output_capacity_profile != 'standard':
|
||||||
|
raise ValueError('OpenAI output capacity cannot be used for local S2S')
|
||||||
|
transport = await asyncio.wait_for(connect_local(config, limits), limits.connect_timeout_seconds)
|
||||||
|
try:
|
||||||
|
return LocalS2SAdapter(transport, config=config, settings=limits)
|
||||||
|
except BaseException:
|
||||||
|
await asyncio.wait_for(transport.close(), limits.send_timeout_seconds)
|
||||||
|
raise
|
||||||
if config.provider == 'gemini' and limits.output_capacity_profile != 'standard':
|
if config.provider == 'gemini' and limits.output_capacity_profile != 'standard':
|
||||||
raise ValueError('OpenAI output capacity cannot be used for Gemini')
|
raise ValueError('OpenAI output capacity cannot be used for Gemini')
|
||||||
input_settings = None
|
input_settings = None
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
"""Explicit offline stage demonstration or bounded opt-in OpenRouter smoke.
|
||||||
|
|
||||||
|
Default stub output is a labelled test tone, never evidence of Persian speech.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
from io import BytesIO
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import struct
|
||||||
|
import wave
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from app.modules.voice.configuration import VoiceSettings
|
||||||
|
from app.modules.voice.provider import strict_json
|
||||||
|
|
||||||
|
MAX_PCM = 480000 # 10 seconds at 24 kHz, also bounds saved evaluation audio.
|
||||||
|
|
||||||
|
|
||||||
|
def wav_bytes(pcm):
|
||||||
|
output = BytesIO()
|
||||||
|
with wave.open(output, 'wb') as audio:
|
||||||
|
audio.setnchannels(1)
|
||||||
|
audio.setsampwidth(2)
|
||||||
|
audio.setframerate(24000)
|
||||||
|
audio.writeframes(pcm)
|
||||||
|
return output.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def tone():
|
||||||
|
return b''.join(struct.pack('<h', round(1800 * math.sin(2 * math.pi * 440 * i / 24000)))
|
||||||
|
for i in range(9600))
|
||||||
|
|
||||||
|
|
||||||
|
async def bounded_response(client, endpoint, *, max_bytes, **kwargs):
|
||||||
|
async with asyncio.timeout(30):
|
||||||
|
async with client.stream('POST', 'https://openrouter.ai/api/v1/' + endpoint, **kwargs) as response:
|
||||||
|
if response.status_code != 200:
|
||||||
|
raise ValueError('LOCAL_STAGE_HTTP_FAILURE')
|
||||||
|
body = bytearray()
|
||||||
|
async for part in response.aiter_bytes(8192):
|
||||||
|
if len(body) + len(part) > max_bytes:
|
||||||
|
raise ValueError('LOCAL_STAGE_RESPONSE_CAPACITY')
|
||||||
|
body.extend(part)
|
||||||
|
return bytes(body), response.headers.get('content-type', '').split(';')[0]
|
||||||
|
|
||||||
|
|
||||||
|
async def stages(config, pcm, client, key, *, stt_format='multipart'):
|
||||||
|
if not pcm or len(pcm) % 2 or len(pcm) > MAX_PCM:
|
||||||
|
raise ValueError('LOCAL_STAGE_INPUT_CAPACITY')
|
||||||
|
headers = {'Authorization': 'Bearer ' + key}
|
||||||
|
audio = wav_bytes(pcm)
|
||||||
|
if stt_format == 'multipart':
|
||||||
|
payload = dict(files={'file': ('fixture.wav', audio, 'audio/wav')},
|
||||||
|
data={'model': config.local_s2s_stt_model, 'language': 'fa', 'response_format': 'json'})
|
||||||
|
elif stt_format == 'json':
|
||||||
|
payload = dict(json=dict(model=config.local_s2s_stt_model, language='fa', response_format='json',
|
||||||
|
input_audio=dict(data=base64.b64encode(audio).decode('ascii'), format='wav')))
|
||||||
|
else:
|
||||||
|
raise ValueError('LOCAL_STAGE_STT_FORMAT')
|
||||||
|
raw, media = await bounded_response(client, 'audio/transcriptions', headers=headers, max_bytes=65536, **payload)
|
||||||
|
if media != 'application/json':
|
||||||
|
raise ValueError('LOCAL_STAGE_STT_FORMAT')
|
||||||
|
text = strict_json(raw).get('text')
|
||||||
|
if not isinstance(text, str) or not text.strip() or len(text) > 1024:
|
||||||
|
raise ValueError('LOCAL_STAGE_STT_RESULT')
|
||||||
|
raw, media = await bounded_response(client, 'chat/completions', headers=headers, max_bytes=65536,
|
||||||
|
json=dict(model=config.local_s2s_llm_model, stream=False, max_tokens=128,
|
||||||
|
messages=[dict(role='system', content='Reply briefly in Persian. A greeting only; no document claims.'),
|
||||||
|
dict(role='user', content=text)]))
|
||||||
|
if media != 'application/json':
|
||||||
|
raise ValueError('LOCAL_STAGE_LLM_FORMAT')
|
||||||
|
result = strict_json(raw)
|
||||||
|
choices = result.get('choices')
|
||||||
|
if not isinstance(choices, list) or len(choices) != 1 or choices[0].get('finish_reason') != 'stop':
|
||||||
|
raise ValueError('LOCAL_STAGE_LLM_TERMINAL')
|
||||||
|
answer = choices[0].get('message', {}).get('content')
|
||||||
|
if not isinstance(answer, str) or not answer.strip() or len(answer) > 300:
|
||||||
|
raise ValueError('LOCAL_STAGE_LLM_RESULT')
|
||||||
|
raw, media = await bounded_response(client, 'audio/speech', headers=headers, max_bytes=MAX_PCM,
|
||||||
|
json=dict(model=config.local_s2s_tts_model, voice=config.local_s2s_tts_voice,
|
||||||
|
input=answer, response_format='pcm'))
|
||||||
|
if media != 'audio/pcm' or not raw or len(raw) % 2:
|
||||||
|
raise ValueError('LOCAL_STAGE_TTS_FORMAT')
|
||||||
|
return raw
|
||||||
|
|
||||||
|
|
||||||
|
def stub_response(request):
|
||||||
|
if request.url.path.endswith('/audio/transcriptions'):
|
||||||
|
return httpx.Response(200, json={'text': '\u0633\u0644\u0627\u0645'})
|
||||||
|
if request.url.path.endswith('/chat/completions'):
|
||||||
|
return httpx.Response(200, json={'choices': [{'finish_reason': 'stop', 'message': {'content': '\u0633\u0644\u0627\u0645'}}]})
|
||||||
|
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=tone())
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--live', action='store_true', help='Makes exactly 3 paid requests; no retries or startup probes.')
|
||||||
|
parser.add_argument('--input', type=Path, help='Consented PCM16 mono 24k WAV, at most 10 seconds.')
|
||||||
|
parser.add_argument('--output', type=Path, required=True)
|
||||||
|
parser.add_argument('--save-evaluation-audio', action='store_true', help='Consent to saving actual provider speech.')
|
||||||
|
parser.add_argument('--stt-format', choices=['multipart', 'json'], default='multipart')
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.output.exists():
|
||||||
|
parser.error('Output already exists; choose a new filename.')
|
||||||
|
if args.live and (not args.input or not args.save_evaluation_audio):
|
||||||
|
parser.error('--live requires consented --input and --save-evaluation-audio')
|
||||||
|
if args.live:
|
||||||
|
config = VoiceSettings(provider='local_s2s')
|
||||||
|
if not all((config.local_s2s_stt_model, config.local_s2s_llm_model, config.local_s2s_tts_model, config.local_s2s_tts_voice)):
|
||||||
|
parser.error('Explicit local model/voice settings are required.')
|
||||||
|
key = os.environ.get('OPENROUTER_API_KEY', '')
|
||||||
|
if not key:
|
||||||
|
parser.error('OPENROUTER_API_KEY is required.')
|
||||||
|
# Check size before reading/decompressing input.
|
||||||
|
if args.input.stat().st_size > MAX_PCM + 4096:
|
||||||
|
parser.error('Input is too large.')
|
||||||
|
with wave.open(str(args.input), 'rb') as audio:
|
||||||
|
if (audio.getnchannels(), audio.getsampwidth(), audio.getframerate(), audio.getcomptype()) != (1, 2, 24000, 'NONE'):
|
||||||
|
parser.error('Expected mono PCM16 24kHz WAV.')
|
||||||
|
pcm = audio.readframes(240001)
|
||||||
|
transport = httpx.AsyncHTTPTransport(retries=0)
|
||||||
|
else:
|
||||||
|
config = VoiceSettings(_env_file=None, provider='local_s2s',
|
||||||
|
local_s2s_stt_model='stub/stt', local_s2s_llm_model='stub/llm',
|
||||||
|
local_s2s_tts_model='stub/tts', local_s2s_tts_voice='stub')
|
||||||
|
key, pcm, transport = 'stub-only', tone(), httpx.MockTransport(stub_response)
|
||||||
|
async def run():
|
||||||
|
async with httpx.AsyncClient(transport=transport, timeout=30, follow_redirects=False) as client:
|
||||||
|
async with asyncio.timeout(90):
|
||||||
|
return await stages(config, pcm, client, key, stt_format=args.stt_format)
|
||||||
|
try:
|
||||||
|
output = asyncio.run(run())
|
||||||
|
with args.output.open('xb') as target:
|
||||||
|
target.write(wav_bytes(output))
|
||||||
|
except (ValueError, KeyError, TypeError, OSError, httpx.HTTPError, TimeoutError):
|
||||||
|
print(json.dumps(dict(status='failed', mode='live' if args.live else 'stub')))
|
||||||
|
return 1
|
||||||
|
print(json.dumps(dict(status='ok', mode='live' if args.live else 'stub-test-tone',
|
||||||
|
requests=3, paid_requests=3 if args.live else 0,
|
||||||
|
sample_rate=24000, samples=len(output)//2)))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -32,6 +32,10 @@ async def lifespan(app):
|
|||||||
engine = None
|
engine = None
|
||||||
startup_error = None
|
startup_error = None
|
||||||
try:
|
try:
|
||||||
|
from app.modules.voice.local_s2s import require_isolated_candidate
|
||||||
|
candidate_config = dependencies.get_voice_settings()
|
||||||
|
if candidate_config.provider == 'local_s2s':
|
||||||
|
require_isolated_candidate(candidate_config, dependencies.get_ingestion_settings())
|
||||||
engine = dependencies.get_engine()
|
engine = dependencies.get_engine()
|
||||||
lifecycle = dependencies.get_lifecycle_service(engine)
|
lifecycle = dependencies.get_lifecycle_service(engine)
|
||||||
await blocking(dependencies.prepare_search_tools)
|
await blocking(dependencies.prepare_search_tools)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from typing import Literal
|
|||||||
from urllib.parse import urlsplit
|
from urllib.parse import urlsplit
|
||||||
from pydantic import AliasChoices, BaseModel, Field, SecretStr, field_validator, model_validator
|
from pydantic import AliasChoices, BaseModel, Field, SecretStr, field_validator, model_validator
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
from app.modules.voice.local_s2s import LocalS2SSettings
|
||||||
|
|
||||||
|
|
||||||
class OpenAIInputSettings(BaseModel):
|
class OpenAIInputSettings(BaseModel):
|
||||||
@@ -87,9 +88,9 @@ class OpenAIInputSettings(BaseModel):
|
|||||||
dict(type=self.openai_realtime_noise_reduction))
|
dict(type=self.openai_realtime_noise_reduction))
|
||||||
|
|
||||||
|
|
||||||
class VoiceSettings(OpenAIInputSettings, BaseSettings):
|
class VoiceSettings(LocalS2SSettings, OpenAIInputSettings, BaseSettings):
|
||||||
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
|
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
|
||||||
provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
|
provider: Literal['gemini', 'openai', 'local_s2s'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
|
||||||
gemini_api_key: SecretStr = SecretStr('')
|
gemini_api_key: SecretStr = SecretStr('')
|
||||||
gemini_model: str = Field(default='gemini-2.0-flash-exp', min_length=1, max_length=200)
|
gemini_model: str = Field(default='gemini-2.0-flash-exp', min_length=1, max_length=200)
|
||||||
gemini_voice: str = Field(default='Aoede', min_length=1, max_length=80)
|
gemini_voice: str = Field(default='Aoede', min_length=1, max_length=80)
|
||||||
@@ -184,26 +185,50 @@ class VoiceSettings(OpenAIInputSettings, BaseSettings):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def selected_model(self):
|
def selected_model(self):
|
||||||
|
if self.provider == 'local_s2s':
|
||||||
|
return self.local_s2s_llm_model
|
||||||
return self.gemini_model if self.provider == 'gemini' else self.openai_realtime_model
|
return self.gemini_model if self.provider == 'gemini' else self.openai_realtime_model
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def selected_voice(self):
|
def selected_voice(self):
|
||||||
|
if self.provider == 'local_s2s':
|
||||||
|
return self.local_s2s_tts_voice
|
||||||
return self.gemini_voice if self.provider == 'gemini' else self.openai_realtime_voice
|
return self.gemini_voice if self.provider == 'gemini' else self.openai_realtime_voice
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def selected_proxy(self):
|
def selected_proxy(self):
|
||||||
|
if self.provider == 'local_s2s':
|
||||||
|
return None
|
||||||
return self.gemini_proxy if self.provider == 'gemini' else self.openai_realtime_proxy
|
return self.gemini_proxy if self.provider == 'gemini' else self.openai_realtime_proxy
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def selected_key(self):
|
def selected_key(self):
|
||||||
|
if self.provider == 'local_s2s':
|
||||||
|
return self.local_s2s_token
|
||||||
return self.gemini_api_key if self.provider == 'gemini' else self.openai_realtime_api_key
|
return self.gemini_api_key if self.provider == 'gemini' else self.openai_realtime_api_key
|
||||||
|
|
||||||
def require_voice(self):
|
def require_voice(self):
|
||||||
|
if self.provider == 'local_s2s':
|
||||||
|
if (not self.local_s2s_enabled or not self.voice_transport_testing
|
||||||
|
or not all((self.local_s2s_stt_model, self.local_s2s_llm_model,
|
||||||
|
self.local_s2s_tts_model, self.local_s2s_tts_voice))):
|
||||||
|
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
||||||
|
token = self.local_s2s_token.get_secret_value()
|
||||||
|
if len(token) > 512 or (token and (not token.isascii() or any(c.isspace() for c in token))):
|
||||||
|
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
||||||
|
return
|
||||||
key = self.selected_key.get_secret_value()
|
key = self.selected_key.get_secret_value()
|
||||||
if not key or len(key) > 512 or not key.isascii() or any(c.isspace() for c in key):
|
if not key or len(key) > 512 or not key.isascii() or any(c.isspace() for c in key):
|
||||||
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
||||||
|
|
||||||
def profile(self):
|
def profile(self):
|
||||||
|
if self.provider == 'local_s2s':
|
||||||
|
from app.modules.voice.local_s2s import effective_identity, setup_session
|
||||||
|
return dict(provider='local_s2s', model=self.selected_model, voice=self.selected_voice,
|
||||||
|
input_sample_rate=24000, output_sample_rate=24000,
|
||||||
|
evidence_policy_revision='same-session-evidence-retained-v5',
|
||||||
|
development_only=True, interruption_policy='close_until_phase3',
|
||||||
|
local_s2s=effective_identity(self.components(), setup_session(self)))
|
||||||
profile = dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
|
profile = dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
|
||||||
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000,
|
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000,
|
||||||
evidence_policy_revision='same-session-evidence-retained-v5')
|
evidence_policy_revision='same-session-evidence-retained-v5')
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
"""Frozen, credential-free identity for the development-only local engine."""
|
||||||
|
from hashlib import sha256
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
from typing import Literal
|
||||||
|
from pydantic import BaseModel, Field, SecretStr, field_validator
|
||||||
|
from app.modules.voice.provider import canonical_json
|
||||||
|
|
||||||
|
UPSTREAM_REVISION = '619e3fe4f71d1c6f35c15870d588a3638de34722'
|
||||||
|
CONTRACT_REVISION = 'rag-local-s2s-phase2-v1'
|
||||||
|
PATCH_REVISION = 'rag-local-s2s-phase2-v3'
|
||||||
|
|
||||||
|
|
||||||
|
class LocalS2SSettings(BaseModel):
|
||||||
|
local_s2s_enabled: bool = False
|
||||||
|
local_s2s_endpoint: str = 'ws://local-s2s-engine:8765/v1/realtime'
|
||||||
|
local_s2s_token: SecretStr = SecretStr('')
|
||||||
|
local_s2s_engine_revision: Literal[UPSTREAM_REVISION] = UPSTREAM_REVISION
|
||||||
|
local_s2s_stt_model: str = Field(default='', max_length=200)
|
||||||
|
local_s2s_llm_model: str = Field(default='', max_length=200)
|
||||||
|
local_s2s_tts_model: str = Field(default='', max_length=200)
|
||||||
|
local_s2s_tts_voice: str = Field(default='', max_length=80)
|
||||||
|
local_s2s_language: Literal['fa'] = 'fa'
|
||||||
|
local_s2s_max_output_tokens: int = Field(default=256, ge=1, le=1024)
|
||||||
|
local_s2s_request_timeout_seconds: float = Field(default=30, gt=0, le=60, allow_inf_nan=False)
|
||||||
|
|
||||||
|
@field_validator('local_s2s_endpoint')
|
||||||
|
@classmethod
|
||||||
|
def endpoint(cls, value):
|
||||||
|
try:
|
||||||
|
p = urlsplit(value)
|
||||||
|
p.port
|
||||||
|
if (len(value) > 512 or p.scheme not in ('ws', 'wss') or not p.hostname
|
||||||
|
or p.username or p.password or p.query or p.fragment or p.path != '/v1/realtime'):
|
||||||
|
raise ValueError()
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError('Invalid local engine endpoint') from None
|
||||||
|
return value
|
||||||
|
|
||||||
|
@field_validator('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
|
||||||
|
@classmethod
|
||||||
|
def local_component_identifier(cls, value):
|
||||||
|
if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value):
|
||||||
|
raise ValueError('Invalid local component identifier')
|
||||||
|
return value
|
||||||
|
|
||||||
|
def components(self):
|
||||||
|
return dict(stt=dict(backend='openai', model=self.local_s2s_stt_model,
|
||||||
|
language='fa', response_format='json', final_only=True),
|
||||||
|
llm=dict(backend='chat-completions', model=self.local_s2s_llm_model,
|
||||||
|
max_output_tokens=self.local_s2s_max_output_tokens),
|
||||||
|
tts=dict(backend='openai', model=self.local_s2s_tts_model,
|
||||||
|
voice=self.local_s2s_tts_voice, response_format='pcm', sample_rate=24000),
|
||||||
|
request_timeout_seconds=self.local_s2s_request_timeout_seconds)
|
||||||
|
|
||||||
|
|
||||||
|
def setup_session(config):
|
||||||
|
# Reuse the existing backend tool schema/policy; no second retrieval path.
|
||||||
|
from app.infrastructure.realtime import RealtimeAdapter
|
||||||
|
session = RealtimeAdapter(None).setup()['session']
|
||||||
|
session.pop('reasoning', None)
|
||||||
|
session['model'] = config.local_s2s_llm_model
|
||||||
|
session['max_output_tokens'] = config.local_s2s_max_output_tokens
|
||||||
|
session['audio']['input']['transcription'] = dict(model=config.local_s2s_stt_model, language='fa')
|
||||||
|
session['audio']['output']['voice'] = config.local_s2s_tts_voice
|
||||||
|
session['audio']['output']['speed'] = 1.0
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
def effective_identity(components, session):
|
||||||
|
return dict(engine_revision=UPSTREAM_REVISION, patch_revision=PATCH_REVISION,
|
||||||
|
contract_revision=CONTRACT_REVISION, components=components,
|
||||||
|
effective_config_sha256=sha256(canonical_json(dict(components=components, session=session)).encode()).hexdigest())
|
||||||
|
|
||||||
|
|
||||||
|
def require_isolated_candidate(config, ingestion, *, database_url=None):
|
||||||
|
"""Run before startup reconciliation, never on the operational database."""
|
||||||
|
from sqlalchemy.engine import make_url
|
||||||
|
if config.provider != 'local_s2s':
|
||||||
|
return
|
||||||
|
config.require_voice()
|
||||||
|
url = make_url(database_url if database_url is not None else ingestion.database_url.get_secret_value())
|
||||||
|
if not url.database or not url.database.endswith('_local_s2s_test'):
|
||||||
|
raise ValueError('Local S2S requires an isolated *_local_s2s_test database')
|
||||||
|
for path in (ingestion.original_directory, ingestion.extraction_directory):
|
||||||
|
if 'local-s2s-test' not in path.resolve().parts:
|
||||||
|
raise ValueError('Local S2S requires dedicated local-s2s-test storage')
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Private provider port; browser events and runtime safety policy stay unchanged.
|
||||||
|
|
||||||
|
Events retain their admitted native identities and replay fingerprints. A terminal
|
||||||
|
response proves generation stopped, never that unheard history was repaired.
|
||||||
|
"""
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import json
|
||||||
|
from typing import Protocol
|
||||||
|
|
||||||
|
from app.modules.voice.settings import RuntimeSettings
|
||||||
|
|
||||||
|
|
||||||
|
class ProviderProtocolError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def canonical_json(value):
|
||||||
|
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
||||||
|
separators=(",", ":"), sort_keys=True)
|
||||||
|
|
||||||
|
|
||||||
|
def strict_json(raw):
|
||||||
|
def pairs(items):
|
||||||
|
value = {}
|
||||||
|
for key, item in items:
|
||||||
|
if key in value:
|
||||||
|
raise ValueError("Duplicate JSON key")
|
||||||
|
value[key] = item
|
||||||
|
return value
|
||||||
|
return json.loads(raw, object_pairs_hook=pairs,
|
||||||
|
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class HistoryRepair:
|
||||||
|
"""Runtime-frozen correlation, after terminal and final playback coordinates."""
|
||||||
|
session_id: str
|
||||||
|
generation: int
|
||||||
|
response_id: str
|
||||||
|
operation_id: str
|
||||||
|
item_id: str
|
||||||
|
content_index: int
|
||||||
|
played_ms: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class HistoryRepairReceipt:
|
||||||
|
repair: HistoryRepair
|
||||||
|
# Native provenance, not an invented provider history revision. OpenAI's
|
||||||
|
# truncate event supplies item/part/position, but no operation or revision.
|
||||||
|
native_event_id: str | None
|
||||||
|
provenance: str
|
||||||
|
|
||||||
|
|
||||||
|
class VoiceProvider(Protocol):
|
||||||
|
"""Required transport/setup/repair operations; no provider-name branching.
|
||||||
|
|
||||||
|
Native optional extensions (consumed/backlog/tool completion classification)
|
||||||
|
remain adapter-owned. Runtime owns all authority, deadlines and release gates.
|
||||||
|
"""
|
||||||
|
settings: RuntimeSettings
|
||||||
|
|
||||||
|
def setup(self) -> dict: ...
|
||||||
|
def acknowledged(self, session: dict) -> bool: ...
|
||||||
|
def serialize(self, event: dict) -> str: ...
|
||||||
|
async def send_serialized(self, wire: str) -> None: ...
|
||||||
|
async def send(self, event: dict) -> None: ...
|
||||||
|
async def receive(self) -> dict: ...
|
||||||
|
def cancellation_request(self, response_id: str, operation_id: str | None = None) -> dict: ...
|
||||||
|
def history_repair_request(self, repair: HistoryRepair) -> dict: ...
|
||||||
|
def confirm_history_repair(self, repair: HistoryRepair, event: dict) -> HistoryRepairReceipt: ...
|
||||||
|
def is_no_active(self, error: dict) -> bool: ...
|
||||||
|
def abort(self) -> bool: ...
|
||||||
|
async def close(self) -> None: ...
|
||||||
@@ -13,7 +13,9 @@ from pydantic import ValidationError
|
|||||||
from app.modules.knowledge.evidence import SearchExecution
|
from app.modules.knowledge.evidence import SearchExecution
|
||||||
from app.modules.knowledge.langchain_tool import ToolContext, create_search_tool
|
from app.modules.knowledge.langchain_tool import ToolContext, create_search_tool
|
||||||
from app.modules.knowledge.service import SearchInput, authority, transaction
|
from app.modules.knowledge.service import SearchInput, authority, transaction
|
||||||
from app.infrastructure.realtime import canonical_json, strict_json, ProviderProtocolError
|
from app.modules.voice.provider import (
|
||||||
|
canonical_json, strict_json, ProviderProtocolError, VoiceProvider, HistoryRepair, HistoryRepairReceipt,
|
||||||
|
)
|
||||||
from app.modules.voice.settings import RuntimeSettings
|
from app.modules.voice.settings import RuntimeSettings
|
||||||
from app.modules.voice.diagnostics import diagnostic, protocol_reason, terminal_failure_reason, trace
|
from app.modules.voice.diagnostics import diagnostic, protocol_reason, terminal_failure_reason, trace
|
||||||
from app.modules.voice.serialization import bounded_json, json_size, bounded_json_digest
|
from app.modules.voice.serialization import bounded_json, json_size, bounded_json_digest
|
||||||
@@ -133,6 +135,8 @@ class Audio:
|
|||||||
cleanup: str | None = None
|
cleanup: str | None = None
|
||||||
cleanup_deadline: float | None = None
|
cleanup_deadline: float | None = None
|
||||||
cleanup_dispatched: bool = False
|
cleanup_dispatched: bool = False
|
||||||
|
repair: HistoryRepair | None = None
|
||||||
|
repair_receipt: HistoryRepairReceipt | None = None
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Command:
|
class Command:
|
||||||
@@ -163,7 +167,7 @@ class VoiceRuntime:
|
|||||||
authority_check is a trusted async backend callback that captures/revalidates
|
authority_check is a trusted async backend callback that captures/revalidates
|
||||||
the session's persisted actor/epoch. It is never model input.
|
the session's persisted actor/epoch. It is never model input.
|
||||||
"""
|
"""
|
||||||
def __init__(self, adapter, service, runner, user_id, emit, *,
|
def __init__(self, adapter: VoiceProvider, service, runner, user_id, emit, *,
|
||||||
authority_check=None, clock=time.monotonic, tool_seconds=None,
|
authority_check=None, clock=time.monotonic, tool_seconds=None,
|
||||||
session_id=None, max_calls=None, settings=None, close_client=None, tool_store=None):
|
session_id=None, max_calls=None, settings=None, close_client=None, tool_store=None):
|
||||||
self.settings = settings or getattr(adapter, "settings", None) or RuntimeSettings()
|
self.settings = settings or getattr(adapter, "settings", None) or RuntimeSettings()
|
||||||
@@ -423,8 +427,7 @@ class VoiceRuntime:
|
|||||||
self.discard_pending_transcript(response)
|
self.discard_pending_transcript(response)
|
||||||
if not response.terminal and not response.cancel_event:
|
if not response.terminal and not response.cancel_event:
|
||||||
response.cancel_event = identity()
|
response.cancel_event = identity()
|
||||||
self.command(dict(type="response.cancel", response_id=response.id,
|
self.command(self.adapter.cancellation_request(response.id, response.cancel_event))
|
||||||
event_id=response.cancel_event))
|
|
||||||
task = asyncio.create_task(self._finish_failure(writable))
|
task = asyncio.create_task(self._finish_failure(writable))
|
||||||
self.tasks.add(task)
|
self.tasks.add(task)
|
||||||
task.add_done_callback(self._failure_finished)
|
task.add_done_callback(self._failure_finished)
|
||||||
@@ -970,8 +973,7 @@ class VoiceRuntime:
|
|||||||
audio.data.clear()
|
audio.data.clear()
|
||||||
if not response.terminal and not response.cancel_event:
|
if not response.terminal and not response.cancel_event:
|
||||||
response.cancel_event = identity()
|
response.cancel_event = identity()
|
||||||
self.command(dict(type="response.cancel", response_id=response.id,
|
self.command(self.adapter.cancellation_request(response.id, response.cancel_event))
|
||||||
event_id=response.cancel_event))
|
|
||||||
if any(r.visible for r in affected):
|
if any(r.visible for r in affected):
|
||||||
self.control(dict(type="turn_interrupted", turn_ref=old.ref,
|
self.control(dict(type="turn_interrupted", turn_ref=old.ref,
|
||||||
cancelled_tool_call_ids=[
|
cancelled_tool_call_ids=[
|
||||||
@@ -1109,8 +1111,9 @@ class VoiceRuntime:
|
|||||||
self.retire(audio)
|
self.retire(audio)
|
||||||
continue
|
continue
|
||||||
audio.cleanup = identity()
|
audio.cleanup = identity()
|
||||||
self.command(dict(type="conversation.item.truncate", event_id=audio.cleanup,
|
audio.repair = HistoryRepair(self.session_id, response.turn.token,
|
||||||
item_id=audio.item, content_index=audio.index, audio_end_ms=audio.played))
|
response.id, audio.cleanup, audio.item, audio.index, audio.played)
|
||||||
|
self.command(self.adapter.history_repair_request(audio.repair))
|
||||||
|
|
||||||
async def client_control(self, raw):
|
async def client_control(self, raw):
|
||||||
async with self.lock:
|
async with self.lock:
|
||||||
@@ -1492,7 +1495,7 @@ class VoiceRuntime:
|
|||||||
intent = wire.get("metadata", {}).get("voice_intent")
|
intent = wire.get("metadata", {}).get("voice_intent")
|
||||||
if (self.pending_create is None or not self.intent_dispatched
|
if (self.pending_create is None or not self.intent_dispatched
|
||||||
or intent != self.pending_create[0]):
|
or intent != self.pending_create[0]):
|
||||||
self.command(dict(type="response.cancel", response_id=wire["id"]))
|
self.command(self.adapter.cancellation_request(wire["id"]))
|
||||||
raise ValueError("Unsolicited response")
|
raise ValueError("Unsolicited response")
|
||||||
_, turn = self.pending_create
|
_, turn = self.pending_create
|
||||||
response = Response(wire["id"], turn, creation_intent=intent,
|
response = Response(wire["id"], turn, creation_intent=intent,
|
||||||
@@ -1504,8 +1507,7 @@ class VoiceRuntime:
|
|||||||
response.interrupted = True
|
response.interrupted = True
|
||||||
response.final_deadline = self.clock() + self.settings.final_progress_window_ms / 1000
|
response.final_deadline = self.clock() + self.settings.final_progress_window_ms / 1000
|
||||||
response.cancel_event = identity()
|
response.cancel_event = identity()
|
||||||
self.command(dict(type="response.cancel", response_id=response.id,
|
self.command(self.adapter.cancellation_request(response.id, response.cancel_event))
|
||||||
event_id=response.cancel_event))
|
|
||||||
elif self.responses[wire["id"]].creation_intent != wire.get("metadata", {}).get("voice_intent"):
|
elif self.responses[wire["id"]].creation_intent != wire.get("metadata", {}).get("voice_intent"):
|
||||||
raise ValueError("Response creation identity conflict")
|
raise ValueError("Response creation identity conflict")
|
||||||
elif kind in ("response.output_item.added", "response.output_item.done"):
|
elif kind in ("response.output_item.added", "response.output_item.done"):
|
||||||
@@ -1733,6 +1735,11 @@ class VoiceRuntime:
|
|||||||
event_type=kind, audio=matches[0] if len(matches) == 1 else None)
|
event_type=kind, audio=matches[0] if len(matches) == 1 else None)
|
||||||
return
|
return
|
||||||
audio = matches[0]
|
audio = matches[0]
|
||||||
|
receipt = self.adapter.confirm_history_repair(audio.repair, event)
|
||||||
|
if (not isinstance(receipt, HistoryRepairReceipt)
|
||||||
|
or receipt.repair != audio.repair):
|
||||||
|
raise ProviderProtocolError("Uncorrelated history repair receipt")
|
||||||
|
audio.repair_receipt = receipt
|
||||||
audio.cleanup_deadline = None
|
audio.cleanup_deadline = None
|
||||||
self.trace("truncate_acknowledged", audio=audio)
|
self.trace("truncate_acknowledged", audio=audio)
|
||||||
self.retire(audio)
|
self.retire(audio)
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ class RuntimeSettings(BaseSettings):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def for_provider(cls, provider):
|
def for_provider(cls, provider):
|
||||||
if provider not in ('openai', 'gemini'):
|
if provider not in ('openai', 'gemini', 'local_s2s'):
|
||||||
raise ValueError('Unsupported voice provider')
|
raise ValueError('Unsupported voice provider')
|
||||||
return cls(output_capacity_profile='openai-repair' if provider == 'openai' else 'standard')
|
return cls(output_capacity_profile='openai-repair' if provider == 'openai' else 'standard')
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
# Standalone file: never extend the operational compose stack.
|
||||||
|
name: rag-local-s2s-test
|
||||||
|
x-candidate-env: &candidate-env
|
||||||
|
PROVIDER: local_s2s
|
||||||
|
VOICE_PROVIDER: local_s2s
|
||||||
|
LOCAL_S2S_ENABLED: ${LOCAL_S2S_ENABLE_CANDIDATE:-false}
|
||||||
|
VOICE_TRANSPORT_TESTING: "true"
|
||||||
|
LOCAL_S2S_ENDPOINT: ws://local-s2s-engine:8765/v1/realtime
|
||||||
|
LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3}
|
||||||
|
LOCAL_S2S_LLM_MODEL: ${LOCAL_S2S_LLM_MODEL:-openai/gpt-4.1-mini}
|
||||||
|
LOCAL_S2S_TTS_MODEL: ${LOCAL_S2S_TTS_MODEL:-google/gemini-3.8-flash-lite-tts}
|
||||||
|
LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-Kore}
|
||||||
|
LOCAL_S2S_MAX_OUTPUT_TOKENS: "256"
|
||||||
|
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30"
|
||||||
|
LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-}
|
||||||
|
INGEST_DATABASE_URL: postgresql+psycopg://local_s2s_test:isolated-test-only@candidate_db:5432/rag_local_s2s_test
|
||||||
|
INGEST_ORIGINAL_DIRECTORY: /app/data/local-s2s-test/originals
|
||||||
|
INGEST_EXTRACTION_DIRECTORY: /app/data/local-s2s-test/extractions
|
||||||
|
# Greeting/transport-only profile; this endpoint deliberately cannot do inference.
|
||||||
|
INGEST_EMBEDDING_PROVIDER: openai
|
||||||
|
INGEST_EMBEDDING_ENDPOINT: http://127.0.0.1:9/v1
|
||||||
|
INGEST_EMBEDDING_MODEL: text-embedding-3-small
|
||||||
|
INGEST_EMBEDDING_DIMENSIONS: "1536"
|
||||||
|
INGEST_EMBEDDING_API_KEY: transport-test-no-inference
|
||||||
|
TRUSTED_ORIGINS: '["http://127.0.0.2:8091"]'
|
||||||
|
TRUSTED_HOSTS: '["127.0.0.2:8091"]'
|
||||||
|
COOKIE_SECURE: "false"
|
||||||
|
services:
|
||||||
|
candidate_db:
|
||||||
|
image: pgvector/pgvector:pg16
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: rag_local_s2s_test
|
||||||
|
POSTGRES_USER: local_s2s_test
|
||||||
|
POSTGRES_PASSWORD: isolated-test-only
|
||||||
|
volumes: [candidate_postgres:/var/lib/postgresql/data]
|
||||||
|
healthcheck:
|
||||||
|
test: [CMD-SHELL, pg_isready -U local_s2s_test -d rag_local_s2s_test]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
candidate_migrations:
|
||||||
|
image: rag-local-s2s-candidate:phase2
|
||||||
|
environment: *candidate-env
|
||||||
|
command: [alembic, upgrade, head]
|
||||||
|
depends_on:
|
||||||
|
candidate_db: {condition: service_healthy}
|
||||||
|
local-s2s-engine:
|
||||||
|
image: rag-local-s2s-candidate:phase2
|
||||||
|
environment:
|
||||||
|
PROVIDER: local_s2s
|
||||||
|
VOICE_PROVIDER: local_s2s
|
||||||
|
LOCAL_S2S_ENABLED: ${LOCAL_S2S_ENABLE_CANDIDATE:-false}
|
||||||
|
VOICE_TRANSPORT_TESTING: "true"
|
||||||
|
LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3}
|
||||||
|
LOCAL_S2S_LLM_MODEL: ${LOCAL_S2S_LLM_MODEL:-openai/gpt-4.1-mini}
|
||||||
|
LOCAL_S2S_TTS_MODEL: ${LOCAL_S2S_TTS_MODEL:-google/gemini-3.8-flash-lite-tts}
|
||||||
|
LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-Kore}
|
||||||
|
LOCAL_S2S_MAX_OUTPUT_TOKENS: "256"
|
||||||
|
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30"
|
||||||
|
LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-}
|
||||||
|
# No database URL or application identity is supplied to the engine.
|
||||||
|
# The inference key is sent only to the engine, never to the API/browser.
|
||||||
|
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||||
|
LOCAL_S2S_ALLOW_PAID_STARTUP: ${LOCAL_S2S_ALLOW_PAID_STARTUP:-false}
|
||||||
|
LOCAL_S2S_SILERO_SOURCE: /vad/silero-vad
|
||||||
|
LOCAL_S2S_NLTK_DATA: /assets/nltk
|
||||||
|
LOCAL_S2S_ASSET_MANIFEST: /assets/assets.json
|
||||||
|
LOCAL_S2S_ASSET_MANIFEST_SHA256: ${LOCAL_S2S_ASSET_MANIFEST_SHA256:-}
|
||||||
|
# Set to a separately provisioned local Silero source+asset bundle; no download.
|
||||||
|
volumes:
|
||||||
|
- type: bind
|
||||||
|
source: ${LOCAL_S2S_VAD_SOURCE:-./.local-s2s-build/vad-not-provisioned}
|
||||||
|
target: /vad/silero-vad
|
||||||
|
read_only: true
|
||||||
|
bind: {create_host_path: false}
|
||||||
|
- type: bind
|
||||||
|
source: ${LOCAL_S2S_NLTK_SOURCE:-./.local-s2s-build/nltk-not-provisioned}
|
||||||
|
target: /assets/nltk
|
||||||
|
read_only: true
|
||||||
|
bind: {create_host_path: false}
|
||||||
|
- type: bind
|
||||||
|
source: ${LOCAL_S2S_ASSET_MANIFEST_SOURCE:-./.local-s2s-build/assets.json}
|
||||||
|
target: /assets/assets.json
|
||||||
|
read_only: true
|
||||||
|
bind: {create_host_path: false}
|
||||||
|
mem_limit: 4g
|
||||||
|
cpus: 2
|
||||||
|
pids_limit: 128
|
||||||
|
candidate_api:
|
||||||
|
image: rag-local-s2s-candidate:phase2
|
||||||
|
command: [python, -m, app.server, --host, 0.0.0.0, --port, "8000"]
|
||||||
|
environment: *candidate-env
|
||||||
|
ports: ["127.0.0.2:8091:8000"]
|
||||||
|
volumes:
|
||||||
|
- candidate_originals:/app/data/local-s2s-test/originals
|
||||||
|
- candidate_extractions:/app/data/local-s2s-test/extractions
|
||||||
|
depends_on:
|
||||||
|
candidate_migrations: {condition: service_completed_successfully}
|
||||||
|
mem_limit: 2g
|
||||||
|
pids_limit: 128
|
||||||
|
volumes:
|
||||||
|
candidate_postgres:
|
||||||
|
candidate_originals:
|
||||||
|
candidate_extractions:
|
||||||
@@ -1,5 +1,27 @@
|
|||||||
# Phase 1 agent reference map
|
# Phase 1 agent reference map
|
||||||
|
|
||||||
|
Local S2S acceptance preparation (2026-10-15): [exact commands and gates](evaluation/local-s2s/phase-02-acceptance-checklist.md);
|
||||||
|
201 cached asset files fingerprinted, existing NLTK load verified, fresh disposable
|
||||||
|
PostgreSQL 2 local passed / expanded 57 passed and 6 documented baseline failures.
|
||||||
|
The guarded runner is `docs/evaluation/local-s2s/acceptance-postgres.py --suite local|expanded`
|
||||||
|
with `.venv/Scripts/python`; it verifies the target and restores its stopped state.
|
||||||
|
Phase 1 listening and Phase 2 real engine/SDK/POSIX, components and browser remain open.
|
||||||
|
No runtime edits, downloads/builds/paid calls or operational switch occurred.
|
||||||
|
|
||||||
|
Local S2S Phase 2 preparation (2026-10-15): guarded [local adapter](../app/infrastructure/local_s2s.py),
|
||||||
|
[engine/build/operator guide](../services/local_s2s/README.md) and standalone
|
||||||
|
[candidate Compose](../docker-compose.local-s2s-test.yml) now exist. Runtime startup
|
||||||
|
requires dedicated test DB/storage before reconciliation. [Evidence](evaluation/local-s2s/phase-02.md)
|
||||||
|
distinguishes offline fixtures/isolated PostgreSQL from unbuilt engine and unrun
|
||||||
|
real speech/browser checks. No phase acceptance or operational switch is implied.
|
||||||
|
|
||||||
|
Local S2S Phase 1 (2026-10-15): the private [provider port](../app/modules/voice/provider.py)
|
||||||
|
now owns the adapter interface and correlated native repair target/receipt. Runtime
|
||||||
|
retains generation-stop, playback, authority and next-turn gates. OpenAI/Gemini
|
||||||
|
selection, public events and frozen profiles are unchanged; local_s2s is not enabled.
|
||||||
|
See [Phase 1 evidence and offline replay](evaluation/local-s2s/phase-01.md).
|
||||||
|
Real OpenAI preservation acceptance remains pending.
|
||||||
|
|
||||||
Live repair diagnostics (2026-10-12): see [numeric trace guide](guides/live-conversation-traces.md)
|
Live repair diagnostics (2026-10-12): see [numeric trace guide](guides/live-conversation-traces.md)
|
||||||
for the opt-in runtime timeline, frontend consumed/discarded sample accounting,
|
for the opt-in runtime timeline, frontend consumed/discarded sample accounting,
|
||||||
and the provider-free fixed worklet trace command. Current Linux checks use
|
and the provider-free fixed worklet trace command. Current Linux checks use
|
||||||
@@ -2285,7 +2307,12 @@ The [phased plan](plans/local-s2s-adapter-plan.md),
|
|||||||
[execution ledger](plans/local-s2s-adapter-progress.md) and
|
[execution ledger](plans/local-s2s-adapter-progress.md) and
|
||||||
[copy-ready prompts](plans/local-s2s-adapter-prompts/README.md) describe local_s2s
|
[copy-ready prompts](plans/local-s2s-adapter-prompts/README.md) describe local_s2s
|
||||||
alongside OpenAI/Gemini, with initially remote OpenRouter STT/LLM/TTS stages.
|
alongside OpenAI/Gemini, with initially remote OpenRouter STT/LLM/TTS stages.
|
||||||
The four consolidated phases are not_started; the original eight-stage plan is archived. OpenAI preservation, actual context-repair
|
Phase 1 is offline_complete_live_pending; Phase 2 is in_progress with the v2
|
||||||
|
five-defect offline repair checkpoint (31 new, 107 combined and 242 preservation
|
||||||
|
checks passed). See the evaluation reports linked from the ledger and
|
||||||
|
`services/local_s2s/README.md` for required local asset fingerprints and commands.
|
||||||
|
Real engine/SDK, component audio and Persian browser acceptance remain pending.
|
||||||
|
The original eight-stage plan is archived. OpenAI preservation, actual context-repair
|
||||||
proof, shared RAG authority, isolated acceptance and rollback are hard gates.
|
proof, shared RAG authority, isolated acceptance and rollback are hard gates.
|
||||||
This planning record does not weaken existing browser/OpenAI contracts or claim
|
This planning record does not weaken existing browser/OpenAI contracts or claim
|
||||||
implementation, live validation or deployment.
|
implementation, live validation or deployment.
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""Guarded acceptance runner for the retained disposable DB; never uses .env."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[3]
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
from sqlalchemy import create_engine, text
|
||||||
|
from sqlalchemy.engine import URL
|
||||||
|
from tests.support.postgres import validated_test_url
|
||||||
|
|
||||||
|
NAME = 'rag-local-s2s-postgres-test'
|
||||||
|
IDENTITY = 'e5da8c342ed59fc48a49856bfd76010feda45e4a221f640d34aa330a5cd8a7da'
|
||||||
|
IMAGE = 'sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a'
|
||||||
|
VOLUME = '9f19da047744737e9bc010ba69c2f22e347f898939d1d42f7bbbb97c4591a3b6'
|
||||||
|
|
||||||
|
def inspect(name):
|
||||||
|
return json.loads(subprocess.check_output(['docker', 'inspect', name]))[0]
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--suite', choices=['local', 'expanded'], required=True)
|
||||||
|
args = parser.parse_args()
|
||||||
|
row, operational = inspect(NAME), inspect('rag-postgres')
|
||||||
|
values = dict(item.split('=', 1) for item in row['Config']['Env'] if '=' in item)
|
||||||
|
expected_ports = {'5432/tcp': [{'HostIp': '127.0.0.1', 'HostPort': '55439'}]}
|
||||||
|
if not (row['Id'] == IDENTITY and row['Image'] == IMAGE
|
||||||
|
and row['HostConfig']['PortBindings'] == expected_ports
|
||||||
|
and values.get('POSTGRES_DB') == 'rag_local_s2s_test'
|
||||||
|
and values.get('POSTGRES_USER') == 'local_s2s_test'
|
||||||
|
and row['State']['Status'] == 'exited'
|
||||||
|
and len(row['Mounts']) == 1 and row['Mounts'][0].get('Name') == VOLUME
|
||||||
|
and all(m.get('Name') != VOLUME for m in operational['Mounts'])
|
||||||
|
and values.get('POSTGRES_PASSWORD')):
|
||||||
|
raise SystemExit('DISPOSABLE_DATABASE_IDENTITY_MISMATCH')
|
||||||
|
url = validated_test_url(URL.create('postgresql+psycopg', username=values['POSTGRES_USER'],
|
||||||
|
password=values['POSTGRES_PASSWORD'], host='127.0.0.1', port=55439,
|
||||||
|
database=values['POSTGRES_DB']))
|
||||||
|
print(json.dumps(dict(stage='verified-container', container_id=IDENTITY,
|
||||||
|
database=url.database, host=url.host, port=url.port, volume=VOLUME)), flush=True)
|
||||||
|
started = False
|
||||||
|
try:
|
||||||
|
subprocess.run(['docker', 'start', IDENTITY], check=True, stdout=subprocess.DEVNULL)
|
||||||
|
started = True
|
||||||
|
for attempt in range(30):
|
||||||
|
ready = subprocess.run(['docker', 'exec', IDENTITY, 'pg_isready', '-U', 'local_s2s_test',
|
||||||
|
'-d', 'rag_local_s2s_test'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
|
if ready.returncode == 0:
|
||||||
|
break
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
raise SystemExit('DISPOSABLE_DATABASE_STARTUP_DEADLINE')
|
||||||
|
engine = create_engine(url, hide_parameters=True)
|
||||||
|
try:
|
||||||
|
with engine.connect() as conn:
|
||||||
|
actual = tuple(conn.execute(text('SELECT current_database(), current_user')).one())
|
||||||
|
if actual != ('rag_local_s2s_test', 'local_s2s_test'):
|
||||||
|
raise SystemExit('DISPOSABLE_DATABASE_SERVER_MISMATCH')
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
env = os.environ.copy()
|
||||||
|
env['TEST_DATABASE_URL'] = url.render_as_string(hide_password=False)
|
||||||
|
tests = ['tests/integration/test_local_s2s_phase2.py']
|
||||||
|
if args.suite == 'expanded':
|
||||||
|
tests.append('tests/integration/test_phase2_postgres.py')
|
||||||
|
command = [sys.executable, '-m', 'pytest', *tests, '-m', 'postgres',
|
||||||
|
'--require-postgres', '-q', '--tb=short', '-p', 'no:cacheprovider']
|
||||||
|
print(json.dumps(dict(stage='acceptance', suite=args.suite, schemas='test_<random>; fixture creates/drops',
|
||||||
|
require_postgres=True)), flush=True)
|
||||||
|
return subprocess.run(command, cwd=ROOT, env=env, timeout=600).returncode
|
||||||
|
finally:
|
||||||
|
if started:
|
||||||
|
stopped = subprocess.run(['docker', 'stop', '--time', '5', IDENTITY], stdout=subprocess.DEVNULL)
|
||||||
|
print(json.dumps(dict(stage='test-container-restored', stopped=stopped.returncode == 0,
|
||||||
|
status=inspect(NAME)['State']['Status'])), flush=True)
|
||||||
|
if stopped.returncode:
|
||||||
|
raise SystemExit('DISPOSABLE_DATABASE_STOP_FAILED')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Preparation only. Requires bounded OpenAI consent before launching the API.
|
||||||
|
# Paths resolve relative to the FIRST Compose file at repository root.
|
||||||
|
services:
|
||||||
|
candidate_db:
|
||||||
|
image: sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a
|
||||||
|
candidate_migrations:
|
||||||
|
image: sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3
|
||||||
|
environment:
|
||||||
|
PROVIDER: openai
|
||||||
|
VOICE_PROVIDER: openai
|
||||||
|
volumes:
|
||||||
|
- ./app:/app/app:ro
|
||||||
|
- ./migrations:/app/migrations:ro
|
||||||
|
- ./alembic.ini:/app/alembic.ini:ro
|
||||||
|
- ./pyproject.toml:/app/pyproject.toml:ro
|
||||||
|
tmpfs:
|
||||||
|
- /app/data:rw,noexec,nosuid,size=64m
|
||||||
|
candidate_api:
|
||||||
|
image: sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3
|
||||||
|
environment:
|
||||||
|
PROVIDER: openai
|
||||||
|
VOICE_PROVIDER: openai
|
||||||
|
OPENAI_REALTIME_API_KEY: ${OPENAI_REALTIME_API_KEY:-}
|
||||||
|
OPENAI_REALTIME_MODEL: ${OPENAI_REALTIME_MODEL:-gpt-realtime-mini}
|
||||||
|
OPENAI_REALTIME_VOICE: ${OPENAI_REALTIME_VOICE:-shimmer}
|
||||||
|
OPENAI_REALTIME_MAX_OUTPUT_TOKENS: "256"
|
||||||
|
volumes:
|
||||||
|
- ./app:/app/app:ro
|
||||||
|
- ./migrations:/app/migrations:ro
|
||||||
|
- ./alembic.ini:/app/alembic.ini:ro
|
||||||
|
- ./pyproject.toml:/app/pyproject.toml:ro
|
||||||
|
tmpfs:
|
||||||
|
- /app/data:rw,noexec,nosuid,size=64m
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
# Local S2S Phase 1 report
|
||||||
|
|
||||||
|
Date: 2026-10-15. Status: **offline_complete_live_pending**; Phase 1 is not accepted and Phase 2 has not started.
|
||||||
|
|
||||||
|
The internal provider boundary is implemented. OpenAI cancellation and truncation
|
||||||
|
keep their native requests, identities, acknowledgement checks, deadlines and
|
||||||
|
replay fingerprints. Gemini still refuses unsupported history repair. No new
|
||||||
|
provider, browser event, schema, profile revision or dependency was introduced.
|
||||||
|
|
||||||
|
## Changes and responsibility split
|
||||||
|
|
||||||
|
- `app/modules/voice/provider.py`: small structural provider port, shared strict
|
||||||
|
JSON/error helpers, immutable history-repair target and native receipt.
|
||||||
|
- `app/modules/voice/runtime.py`: uses the port for cancellation and repair;
|
||||||
|
freezes session/turn-generation/response/operation/item/part/played coordinates
|
||||||
|
and rejects a receipt rebound to another target. Retains authorization,
|
||||||
|
playback accounting, deadlines, evidence lifetime and next-response release.
|
||||||
|
- `app/infrastructure/realtime.py`: owns native cancel/truncate framing and repair
|
||||||
|
confirmation. Existing imports of the JSON/error helpers remain compatible.
|
||||||
|
- `app/infrastructure/gemini_live.py`: implements the same repair operations while
|
||||||
|
preserving conservative failure. `voice_provider.py` types the existing factory.
|
||||||
|
- `tests/unit/test_local_s2s_boundary.py`: deterministic before/after replay and
|
||||||
|
native adapter conformance. Existing test assertions were not weakened.
|
||||||
|
|
||||||
|
Generation-stop proof remains the correlated native terminal response. A no-active
|
||||||
|
cancel error alone never releases a turn. History-repair proof is independent:
|
||||||
|
one dispatched, frozen item/part/position must match a native acknowledgement
|
||||||
|
before retirement. Fully played audio needs no mutation. Only runtime releases a
|
||||||
|
new response after these gates, playback settlement and authority revalidation.
|
||||||
|
OpenAI provides no operation echo or applied history revision in its truncate
|
||||||
|
acknowledgement: the receipt records that limitation, not a fabricated revision.
|
||||||
|
The local engine will need its own actual mutation receipt; flags cannot bypass it.
|
||||||
|
|
||||||
|
## Preserved deployment (observed, unchanged)
|
||||||
|
|
||||||
|
Repository base: `872e5f25cbe2870d3fc3c66c8a4ab9c697d3d894`; implementation is an
|
||||||
|
uncommitted working-tree diff. Unrelated `.gitignore` edits and extraction artifacts
|
||||||
|
were present before work and retained.
|
||||||
|
|
||||||
|
| Role | Container ID | Image identity |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Running `rag-api-mini`, port 8080 | `4130f6de6e2a94e66befcb334badb6790fd22a1cdb1ab1a7d8ccfd6e0cd45043` | `rag-api-brief-answers:20261014`, `sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3` |
|
||||||
|
| Stopped original `rag-api` | `65c9fa765c150467bde2d6336b09fb46d5ffe451d1117eb1ab93a7bacff1037d` | `rag-technical-docs-assistant-api`, `sha256:6f9b1bc3e0eeb76e0143fb33e2773f3fe3e639fbc3c4b2c11139aaabb58ea028` |
|
||||||
|
|
||||||
|
Read-only container configuration inspection confirmed OpenAI, `gpt-realtime-2.1`,
|
||||||
|
`marin`, speed 1.3, reasoning low, max output tokens 2048, standard capacity;
|
||||||
|
ASR `gpt-transcribe`, languages fa/en; server VAD threshold 0.5, prefix 300 ms,
|
||||||
|
silence 500 ms, automatic response and interruption both false, noise reduction
|
||||||
|
null. Browser/provider PCM remains mono 24 kHz. Effective setup SHA-256:
|
||||||
|
`c5ae10c57660c9d051bb04b18d1b0feb55f3eaf10ac913563ddcdf0fcfe88182`.
|
||||||
|
This was computed inside the existing image from settings and adapter setup,
|
||||||
|
without opening a provider connection; it is not a new live setup acknowledgement
|
||||||
|
or inspection of any active reservation. No credentials were recorded.
|
||||||
|
|
||||||
|
Containers/images were retained in place; no build, restart, switch, database
|
||||||
|
write or second API was performed. Container writable-layer inspection reported
|
||||||
|
only `/app/docs/calibration` additions beneath `/app/docs`. Rollback was not
|
||||||
|
exercised. Retaining these IDs does not prove a successful restoration.
|
||||||
|
|
||||||
|
## Pinned upstream audit
|
||||||
|
|
||||||
|
[Source/build-input manifest](upstream-pin.json) pins
|
||||||
|
`huggingface/speech-to-speech` at
|
||||||
|
[`619e3fe4f71d1c6f35c15870d588a3638de34722`](https://github.com/huggingface/speech-to-speech/tree/619e3fe4f71d1c6f35c15870d588a3638de34722),
|
||||||
|
with SHA-256 and Git blob fingerprints for 17 inspected source/build/test inputs.
|
||||||
|
Patch revision: none (audit only). This is static compatibility evidence, not
|
||||||
|
upstream test execution or a built/validated engine.
|
||||||
|
|
||||||
|
| Concern | Pinned source evidence | Compatibility / remaining work |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Setup | `handlers/session.py`, `runtime_config.py` deep-merge session settings | Compare authoritative effective configuration; request echo is insufficient |
|
||||||
|
| Input consumption | `handlers/audio.py` emits committed input items on speech lifecycle | Preserve native item/turn correlation; transcript alone is not commit proof |
|
||||||
|
| Manual turns | `runtime_config.py`, `handlers/response.py` expose create/interrupt flags and explicit response creation | Both automatic flags must be disabled; verify in engine conformance |
|
||||||
|
| Identities | `handlers/response.py` preserves response metadata and native response/item IDs | Carry runtime intent and raw fingerprints; no fabricated IDs/acks |
|
||||||
|
| Tools | conversation/response handlers accept function outputs and terminal output items | Use existing trusted backend dispatcher and terminal validation in Phase 3 |
|
||||||
|
| Audio | `handlers/audio.py`, `service.py`: 16 kHz internal pipeline, stateful input/output conversion | Verify configured 24 kHz PCM boundary and actual HTTP STT/TTS formats |
|
||||||
|
| Terminal | `handlers/response.py` handles cancel/finish and structured status | Generation completion differs from browser playback completion |
|
||||||
|
| History repair | `websocket_router.py` truncate branch logs acceptance without mutation or ack; Realtime README confirms this | **Incompatible** with our repair gate; requires a versioned real mutation and receipt |
|
||||||
|
| Completed, unplayed output | History/generation lifecycle finishes before playback; truncate performs no repair | Next real LLM request must exclude unheard sentinel while preserving valid context; unproven |
|
||||||
|
| Remote work | STT/TTS handler/docs show HTTP stage lifecycle, progressive cumulative STT and streaming conversion | Final-only STT initially; separately measure obsolete work/cost and late output suppression |
|
||||||
|
| Build inputs | Pinned `pyproject.toml` and Dockerfile; CUDA 12.8.1 Ubuntu 24.04 tag, mutable apt/uv, ranged dependencies, NLTK downloads | No upstream Python lockfile; dependency lock, base-image digest and asset hashes remain required **before Phase 2 build** |
|
||||||
|
|
||||||
|
No weights/dependencies were installed and no engine was built. No exact Persian
|
||||||
|
heard-prefix alignment, engine repair revision, OpenRouter model/voice support,
|
||||||
|
quality, latency or cost claim is established. The no-op truncate and
|
||||||
|
completed-but-unplayed cases remain explicit Phase 3 hard gates; no weaker
|
||||||
|
whole-turn or duration-ratio policy was adopted.
|
||||||
|
|
||||||
|
## Checks and evidence
|
||||||
|
|
||||||
|
Commands ran from the repository root with the existing Windows virtualenv.
|
||||||
|
`-p no:cacheprovider` avoids pytest cache writes. No real providers were called.
|
||||||
|
|
||||||
|
1. Focused baseline, before source changes:
|
||||||
|
`.venv/Scripts/python -m pytest tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py -q -p no:cacheprovider`
|
||||||
|
— **215 passed in 29.48 s**.
|
||||||
|
2. Same replay fixture before refactor:
|
||||||
|
`.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py -q -s -p no:cacheprovider`
|
||||||
|
— **12 passed in 2.73 s**. Active and completed-unplayed generation; correct,
|
||||||
|
duplicate, wrong-item, wrong-position, missing, late and conflicting acks.
|
||||||
|
3. After initial extraction, focused baseline plus the same 12 replay cases:
|
||||||
|
— **227 passed in 30.12 s**.
|
||||||
|
4. Final focused suite, adding `tests/unit/test_local_s2s_boundary.py` and
|
||||||
|
`tests/unit/test_gemini_live.py` to command 1:
|
||||||
|
— **242 passed in 32.52 s**. Includes Gemini refusal and wrong-generation receipt rejection.
|
||||||
|
5. `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider`
|
||||||
|
? **2,079 passed, 5 failed, 3 skipped, 465 deselected in 305.56 s**.
|
||||||
|
This run collected the initial 12 replay cases before the final three
|
||||||
|
conformance cases and cancellation-routing edit; check 4 covers that final edit.
|
||||||
|
Four underlying failures also reproduce against the original HEAD modules:
|
||||||
|
- `test_openai_speech_configuration.py::test_transcript_ordering_repeated_words_delayed_completion_and_release`: waits for two transcript delta emissions; times out.
|
||||||
|
- `test_voice_search_interruption.py::test_profile_cancellation_diagnostics[shimmer-False]` and `[coral-False]`: expect an absent profile-specific diagnostic field.
|
||||||
|
- The same test's `[coral-True]`: expects profile-specific cancellation rejection inconsistent with the existing classifier.
|
||||||
|
- `test_test_environment.py::test_ordinary_suite_ignores_ambient_ingestion_configuration` reruns the suite and fails because of those same cases.
|
||||||
|
These tests were not changed. The three skips are unavailable Windows symlink privileges, not database acceptance.
|
||||||
|
6. Targeted failure comparison (current source):
|
||||||
|
`.venv/Scripts/python -m pytest tests/unit/test_openai_speech_configuration.py::test_transcript_ordering_repeated_words_delayed_completion_and_release tests/unit/test_voice_search_interruption.py::test_profile_cancellation_diagnostics -q --tb=short -p no:cacheprovider`
|
||||||
|
? **4 failed, 1 passed in 4.65 s**. Immutable HEAD module comparison below:
|
||||||
|
**same 4 failed, 1 passed in 4.32 s**. No files were reverted or rewritten.
|
||||||
|
7. Final visible replay command below ? **15 passed in 2.84 s**.
|
||||||
|
8. `git diff --check -- app docs tests` ? passed. Repository-wide
|
||||||
|
`git diff --check` reports the pre-existing `.gitignore:91` blank line at EOF;
|
||||||
|
that unrelated edit is preserved. New files were inspected separately.
|
||||||
|
9. `docker inspect --format '{{.Id}} {{.Image}} {{.State.Status}}' rag-api-mini rag-api`
|
||||||
|
? original IDs/images unchanged; running/stopped state unchanged.
|
||||||
|
`Invoke-RestMethod http://localhost:8080/health/ready` ? **ready / available**;
|
||||||
|
this is readiness, not a voice acceptance check.
|
||||||
|
|
||||||
|
To reproduce the original-module comparison without changing the working tree:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
@'
|
||||||
|
import subprocess, sys, types
|
||||||
|
from pathlib import Path
|
||||||
|
for name, path in (
|
||||||
|
('app.infrastructure.realtime', 'app/infrastructure/realtime.py'),
|
||||||
|
('app.infrastructure.gemini_live', 'app/infrastructure/gemini_live.py'),
|
||||||
|
('app.infrastructure.voice_provider', 'app/infrastructure/voice_provider.py'),
|
||||||
|
('app.modules.voice.runtime', 'app/modules/voice/runtime.py'),
|
||||||
|
):
|
||||||
|
source = subprocess.check_output(['git', 'show', 'HEAD:' + path]).decode('utf-8')
|
||||||
|
module = types.ModuleType(name)
|
||||||
|
module.__file__ = str(Path(path).resolve())
|
||||||
|
module.__package__ = name.rpartition('.')[0]
|
||||||
|
sys.modules[name] = module
|
||||||
|
exec(compile(source, module.__file__, 'exec'), module.__dict__)
|
||||||
|
import pytest
|
||||||
|
raise SystemExit(pytest.main([
|
||||||
|
'tests/unit/test_openai_speech_configuration.py::test_transcript_ordering_repeated_words_delayed_completion_and_release',
|
||||||
|
'tests/unit/test_voice_search_interruption.py::test_profile_cancellation_diagnostics',
|
||||||
|
'-q', '--tb=short', '-p', 'no:cacheprovider',
|
||||||
|
]))
|
||||||
|
'@ | .venv/Scripts/python -
|
||||||
|
```
|
||||||
|
|
||||||
|
The replays are **simulated native events with a controlled clock**. They prove
|
||||||
|
runtime ordering and unchanged cleanup behavior, not actual engine history
|
||||||
|
mutation or successful real speech. The matching path releases exactly one next
|
||||||
|
response after cleanup; missing/wrong/late proof closes safely. A later conflicting
|
||||||
|
replay closes the session even if a previous valid proof already released work.
|
||||||
|
|
||||||
|
Not run: real OpenAI interaction/human listening against the changed source;
|
||||||
|
engine build/upstream tests; OpenRouter calls; PostgreSQL acceptance (no persistence
|
||||||
|
contract changed); operational switch/rollback. No bounded paid-call authorization
|
||||||
|
or consent-controlled speech fixture was supplied for this task.
|
||||||
|
|
||||||
|
## See the result
|
||||||
|
|
||||||
|
Run this offline, from the repository root:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py -q -s -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
The trace prints `generation stopped; repair matched at 100ms; duplicate ignored;
|
||||||
|
exactly one next response`, then safe-close outcomes for bad/missing receipts.
|
||||||
|
It covers both active and already-completed generation. All 15 final cases should pass.
|
||||||
|
|
||||||
|
The existing OpenAI UI/deployment is unchanged. This phase adds an internal
|
||||||
|
boundary, so there is no new local voice option to click. Do not start a second
|
||||||
|
API on the operational database to try the source changes. A real changed-source
|
||||||
|
OpenAI demonstration needs an isolated candidate DB/storage/browser identity or
|
||||||
|
a separately authorized operational switch; use a short greeting, interrupt it,
|
||||||
|
and verify the next answer and normal close. Paid usage must be bounded first.
|
||||||
|
|
||||||
|
Verdict: offline implementation and deterministic acceptance evidence are delivered.
|
||||||
|
Required real OpenAI preservation acceptance remains open. Phase 2 must wait for
|
||||||
|
Phase 1 acceptance, and its build must resolve the recorded dependency/image pins.
|
||||||
|
|
||||||
|
|
||||||
|
## Acceptance prerequisite recheck (2026-10-15)
|
||||||
|
|
||||||
|
Phase 1 remains **offline_complete_live_pending**, not accepted. The later Phase 2
|
||||||
|
v3 preparation found the sibling Angular checkout and prepared an isolated
|
||||||
|
changed-source OpenAI recipe with read-only app mounts on the cached immutable API
|
||||||
|
image, masked inherited data and dedicated candidate DB/storage. See the
|
||||||
|
[acceptance checklist](phase-02-acceptance-checklist.md#phase-1-gate-prepared-source-only-candidate-not-launched).
|
||||||
|
The recipe was parsed and its isolation checked, not launched. A server-side OpenAI
|
||||||
|
key is configured, but no bounded live approval/consented speech or actual
|
||||||
|
interaction/listening evidence was supplied. Historical replay results remain
|
||||||
|
unchanged and do not close the listening gate. No operational container/image,
|
||||||
|
provider selection, reservation or database was changed.
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
# Local S2S Phase 2 acceptance checklist
|
||||||
|
|
||||||
|
Checkpoint: 2026-10-15, source HEAD `872e5f25cbe2870d3fc3c66c8a4ab9c697d3d894`
|
||||||
|
plus the preserved working tree. Engine pin `619e3fe4f71d1c6f35c15870d588a3638de34722`,
|
||||||
|
patch `rag-local-s2s-phase2-v3`, private shape v1. **Not accepted.**
|
||||||
|
Commands below run from the backend repository root unless stated. Examples under
|
||||||
|
conditional sections are NOT execution records or authorization. Do not run a
|
||||||
|
later gate when an earlier mandatory gate is open.
|
||||||
|
|
||||||
|
## Authorization and current evidence
|
||||||
|
|
||||||
|
| Gate | Actual state | Required next prerequisite |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Offline preparation / isolated DB checks | Authorized by this task; executed below | Preserve unrelated files and operational identities |
|
||||||
|
| Phase 1 changed-source OpenAI listening | Not run; server configuration has a key, but no bounded live consent/fixture | Explicit bounded OpenAI run and consenting speaker/listener |
|
||||||
|
| Immutable base | Cached Linux amd64 Python digest inspected | Keep exact digest; no mutable base substitution |
|
||||||
|
| Pinned source | Full pin absent locally; sibling checkout is `30af00916da85efb053b539a040fd71cf392e7e2` and dirty | Authorized source transfer or supplied clean offline checkout of exact pin |
|
||||||
|
| Assets | 201 existing files fingerprinted; NLTK 3.10.3 sentence/POS load passed with downloads blocked in sibling Windows venv | Review bundle and validate again in actual Linux engine; no new model download |
|
||||||
|
| Linux lock / image | Neither exists | Source, reviewed Linux CPU dependency hash lock, explicit dependency/build authorization; Phase 1 acceptance before Phase 2 build |
|
||||||
|
| Complete engine/SDK controlled I/O / POSIX | Not run; complete engine conformance harness remains to be completed against the full pinned checkout | Actual pinned source and locked Linux SDK/engine environment; no external network |
|
||||||
|
| Paid OpenRouter components | No approval, key or consented fixture supplied for this run | Engine offline conformance first, then bounded approval and approved speech/key |
|
||||||
|
| Existing browser | Located sibling Angular checkout; no source edits or browser run | Isolated candidate and fresh browser identity, trusted Origin, listener and consent |
|
||||||
|
| PostgreSQL | 2 local passed; expanded 57 passed / 6 existing failures | Broad acceptance remains non-green; do not relax assertions |
|
||||||
|
|
||||||
|
The earlier proposed 6 OpenRouter requests / 2,000 tokens / 30 seconds was not
|
||||||
|
approved (the reply expressed lack of understanding). It is not an authorization.
|
||||||
|
The reviewed 74/107/242 offline baseline remains historical, not a fresh rerun in
|
||||||
|
this preparation checkpoint. No runtime implementation changed, so those repairs
|
||||||
|
were not repeated. No paid request, dependency/model/source download, image build,
|
||||||
|
operational write or Phase 3 work occurred.
|
||||||
|
|
||||||
|
## Isolation and immediate stop rules
|
||||||
|
|
||||||
|
- Operational `rag-api-mini` ID `4130f6de6e2a94e66befcb334badb6790fd22a1cdb1ab1a7d8ccfd6e0cd45043`
|
||||||
|
remains running on image `sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3`.
|
||||||
|
Original `rag-api` ID `65c9fa765c150467bde2d6336b09fb46d5ffe451d1117eb1ab93a7bacff1037d`
|
||||||
|
remains stopped on image `sha256:6f9b1bc3e0eeb76e0143fb33e2773f3fe3e639fbc3c4b2c11139aaabb58ea028`.
|
||||||
|
- Acceptance DB runner targets ONLY the recorded container at 127.0.0.1:55439,
|
||||||
|
database/user `rag_local_s2s_test` / `local_s2s_test`, and its independent volume.
|
||||||
|
It checks container/image/port/volume, checks server identity, creates/drops
|
||||||
|
fixture-owned random schemas, uses --require-postgres and restores stopped state.
|
||||||
|
Operational `rag-postgres` port 5432 and its volume are never test targets.
|
||||||
|
- Browser/engine stack uses only `docker-compose.local-s2s-test.yml`, project
|
||||||
|
`rag-local-s2s-test`, separate candidate DB/storage volumes and loopback API
|
||||||
|
127.0.0.2:8091. Engine gets no DB credential; provider key stays server-side.
|
||||||
|
Frontend Origin is 127.0.0.2:4201 with an entirely fresh browser profile and test
|
||||||
|
account. Ports alone do not isolate cookies or databases.
|
||||||
|
- Stop on any identity/origin/profile/rate mismatch, unauthorized provider/model,
|
||||||
|
failed probe, missing terminal, incomplete audio, unavailable budget metering,
|
||||||
|
download attempt, counter discrepancy, teardown survivor, or gate not satisfied.
|
||||||
|
No retries or silent fallback. Keep partial streams incomplete; never invent
|
||||||
|
commit/repair/history/terminal receipts. Preserve frozen reservations.
|
||||||
|
- Stop only owned candidate services. Never compose down, remove volumes, prune,
|
||||||
|
retag/rebuild operational images, start an API against the operational DB, or
|
||||||
|
change the existing frontend proxy. Retain raw native IDs/fingerprints privately;
|
||||||
|
publish numeric/redacted observations, not keys or unconsented audio.
|
||||||
|
|
||||||
|
## Preparation executed: exact commands and observations
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker inspect --format '{{.Name}}|{{.Id}}|{{.Image}}|{{.State.Status}}' rag-api-mini rag-api
|
||||||
|
docker image inspect python:3.11-slim --format '{{json .RepoDigests}}|{{.Os}}|{{.Architecture}}|{{.Id}}'
|
||||||
|
git -C D:/raymand/projects/speech-to-speech-test rev-parse HEAD
|
||||||
|
git -C D:/raymand/projects/speech-to-speech-test status --short
|
||||||
|
git -C D:/raymand/projects/speech-to-speech-test cat-file -t 619e3fe4f71d1c6f35c15870d588a3638de34722
|
||||||
|
```
|
||||||
|
|
||||||
|
Recorded operational IDs/images matched. Cached base is
|
||||||
|
`python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce`
|
||||||
|
(linux/amd64). `cat-file` failed: required commit object absent. Sibling changes
|
||||||
|
were preserved; no checkout/fetch was attempted. Only hash-checked partial source
|
||||||
|
fixtures exist here; these are not a complete source tree.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m services.local_s2s.assets --nltk-root "$env:APPDATA/nltk_data" --vad-root D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master --output docs/evaluation/local-s2s/phase-02-local-assets.json
|
||||||
|
D:/raymand/projects/speech-to-speech-test/.venv/Scripts/python.exe -c "import json,os,nltk; from pathlib import Path; from services.local_s2s.assets import validate_assets,configure_nltk; root=Path(os.environ['APPDATA'])/'nltk_data'; vad=Path('D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master'); digest=validate_assets(root,vad,'docs/evaluation/local-s2s/phase-02-local-assets.json'); configure_nltk(nltk,root); print(json.dumps({'manifest_sha256':digest,'nltk_version':nltk.__version__,'sentence_and_pos_load':'passed','runtime_downloads':'blocked','environment':'existing Windows sibling virtualenv; not Linux engine'}))"
|
||||||
|
.venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite local
|
||||||
|
.venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite expanded
|
||||||
|
```
|
||||||
|
|
||||||
|
Manifest SHA-256 `8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8`,
|
||||||
|
201 files. Original assets unchanged; manifest refuses overwrite. NLTK 3.10.3
|
||||||
|
sentence/POS validation passed with download functions blocked. This validates
|
||||||
|
existing Windows resources, not Linux torch/JIT or complete engine compatibility.
|
||||||
|
Local DB: **2 passed in 5.18 s**. Expanded: **57 passed, 6 failed in 236.50 s**;
|
||||||
|
all six are `test_actual_asgi_tool_dispatch_persistence_and_public_sources`,
|
||||||
|
`ok|no_evidence|error` x `gemini|openai`, failing on RESPONSE_ACK_DEADLINE. They
|
||||||
|
match the earlier immutable-HEAD comparison in phase-02.md. That comparison was
|
||||||
|
not rerun here; no runtime changes were made. All assertions remain intact.
|
||||||
|
Runner restored the test container to exited after each suite. Expanded suite is
|
||||||
|
not acceptance-green; no broad DB pass is claimed.
|
||||||
|
|
||||||
|
## Phase 1 gate: prepared source-only candidate, NOT launched
|
||||||
|
|
||||||
|
No engine build is needed to test the changed API source: the prepared
|
||||||
|
`phase-01-openai-acceptance.override.yml` reuses the cached immutable API image
|
||||||
|
read-only as a dependency runtime, mounts current app/migrations read-only, masks
|
||||||
|
inherited /app/data with tmpfs, and uses only candidate volumes/DB. This does not
|
||||||
|
alter or retag that image or touch its operational container. Validate source
|
||||||
|
compatibility before proceeding. Preserve a source SHA-256 manifest at run time;
|
||||||
|
freeze edits during the observed session and record actual effective OpenAI profile.
|
||||||
|
|
||||||
|
After explicit bounded OpenAI consent and verification of test DB/storage:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml up --pull never -d candidate_db candidate_migrations candidate_api
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml exec -it candidate_api python -m app.bootstrap --organization-name Local-S2S-Test --username local-s2s-admin --assistant-name Local-S2S-Test --instruction "Answer briefly in Persian"
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a new test password; do not copy an operational account. Listen to one short
|
||||||
|
OpenAI greeting, interrupt once, verify the next answer and normal close on the
|
||||||
|
changed source. Record audible output, native stop/repair correlation, actual
|
||||||
|
transcripts and human listening observations. Readiness/replay/test tone do not
|
||||||
|
close this gate. Source-mount recipe is prepared, not runtime-tested or accepted.
|
||||||
|
Do not run the engine service in this Phase 1 session. Stop candidate_api before
|
||||||
|
changing the candidate provider; do not rewrite the old OpenAI reservation.
|
||||||
|
|
||||||
|
## Immutable build gate: conditional commands, NOT run
|
||||||
|
|
||||||
|
Acquire a clean checkout of the exact pin through an explicitly authorized source
|
||||||
|
transfer (or supply it offline). Never repurpose the dirty sibling checkout.
|
||||||
|
With the clean checkout and reviewed cached base:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python services/local_s2s/prepare_build.py --checkout <clean-pinned-checkout> --base-image python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce
|
||||||
|
```
|
||||||
|
|
||||||
|
In an authorized Linux resolver environment, pin the resolver version, review CPU
|
||||||
|
PyTorch and all transitive packages/licenses, and produce a complete hash lock:
|
||||||
|
|
||||||
|
```text
|
||||||
|
uv pip compile .local-s2s-build/requirements.in --python-version 3.11 --python-platform x86_64-unknown-linux-gnu --generate-hashes -o .local-s2s-build/requirements.lock
|
||||||
|
```
|
||||||
|
|
||||||
|
Record requirements.in, lock and prepared-source hashes, resolver/Python/platform,
|
||||||
|
base digest and v3 build manifest. No lock or resolved dependency graph exists yet;
|
||||||
|
full review cannot be performed on hashes of four source fixtures. Ensure controlled
|
||||||
|
acceptance test dependencies are separately hash-locked; pytest availability in the
|
||||||
|
runtime image is not assumed. Revalidate NLTK/VAD manifests after transfer.
|
||||||
|
|
||||||
|
Only after Phase 1 acceptance plus explicit dependency-download/image-build approval:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docker build --pull=false -f services/local_s2s/Dockerfile --build-arg ENGINE_BASE_IMAGE=python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce -t rag-local-s2s-candidate:phase2 .
|
||||||
|
docker image inspect rag-local-s2s-candidate:phase2 --format '{{.Id}}|{{json .RepoDigests}}'
|
||||||
|
```
|
||||||
|
|
||||||
|
No new weights are authorized; use only reviewed fingerprinted local VAD assets.
|
||||||
|
An image ID/digest and lock SHA must be actual outputs before provenance is filled.
|
||||||
|
|
||||||
|
## Complete engine/SDK controlled-I/O gate: NOT run
|
||||||
|
|
||||||
|
Use the complete pinned checkout and actual locked SDK, handler construction,
|
||||||
|
configured runtime, real local VAD and original NLTK. Replace only provider I/O with
|
||||||
|
controlled responses and isolate external networking. A full-engine conformance
|
||||||
|
runner does not yet exist here; completing it against that exact source is a
|
||||||
|
remaining prerequisite, not a fictitious executable command. Do not substitute the
|
||||||
|
AST/RecordingSDK harness as full-engine evidence. As a preliminary subset, with
|
||||||
|
hash-locked pytest and assets available inside the isolated Linux environment:
|
||||||
|
|
||||||
|
```text
|
||||||
|
python -m pytest /opt/speech-to-speech/tests/openai_realtime/test_realtime_protocol_contract.py /opt/speech-to-speech/tests/openai_realtime/test_response_input_identity.py -q -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
These paths were audited at the pin; that command has NOT been executed here and
|
||||||
|
upstream fixtures alone do not close the full-engine gate. The complete runner
|
||||||
|
must exercise and save observations for every row below before live activation:
|
||||||
|
|
||||||
|
| Trigger | Required actual observation |
|
||||||
|
| --- | --- |
|
||||||
|
| Constructor warmups, normal transcribed input, nondefault 17/83 token caps | Actual SDK outbound JSON caps, warmup attempts/counters; retryable HTTP and connect failure exactly once |
|
||||||
|
| Missing/corrupt local assets with downloader blocked | Fixed safe failure and zero provider operations |
|
||||||
|
| Session update and authoritative state | Models, voice, 24k rates, v3 profile and configured limits match initialized handlers/applied state; mismatch rejected |
|
||||||
|
| Input append/commit and manual create | Native input/item/turn correlation; no automatic response before explicit create; transcript alone is not commitment |
|
||||||
|
| Successful response, audio, transcripts | Native response/item/intent correlation and unchanged raw fingerprints; actual PCM and user/assistant completion semantics |
|
||||||
|
| Provider failure, empty/partial/trickled stream, peer close before headers/while silent | Accurate failure/incomplete framing; no invented terminal; zero retries, deadline limits, upstream cancellation/socket closure and slot release within v3 bounds |
|
||||||
|
| SIGINT and SIGTERM during in-flight request on Linux | Actual OS signal delivery to owned process, runtime stop, independent gateway/socket closure, joins and numeric final counters within bounded grace |
|
||||||
|
| Unsupported interruption | Safe close; no fabricated repair or continuation |
|
||||||
|
|
||||||
|
For each independently started, **owned offline** conformance container, actual
|
||||||
|
signal commands are `docker kill --signal=SIGINT <owned-conformance-container>`
|
||||||
|
and `docker kill --signal=SIGTERM <owned-conformance-container>`, followed by
|
||||||
|
`docker wait <owned-conformance-container>`. Start a fresh process for each signal.
|
||||||
|
Never target operational containers. Record complete runner command, mounts,
|
||||||
|
network isolation and SDK versions when the runner becomes executable.
|
||||||
|
|
||||||
|
## Real components and browser: conditional, NOT authorized or run
|
||||||
|
|
||||||
|
Proposed ceilings for approval (not a grant): Phase 1 one OpenAI Realtime session,
|
||||||
|
60 seconds wall time, at most three responses, 256 output tokens per response;
|
||||||
|
Phase 2 at most 12 OpenRouter HTTP attempts TOTAL including constructor warmups,
|
||||||
|
component smoke and browser, at most 2,000 aggregate LLM output tokens and 30 seconds
|
||||||
|
aggregate synthesized speech, 180 seconds live wall time. Input clips <=10 seconds.
|
||||||
|
Require a monetary ceiling and approved model/voice IDs before paid execution.
|
||||||
|
Actual startup counts must first come from complete controlled-I/O evidence. Count
|
||||||
|
in-flight attempts against the limit. If these aggregate bounds cannot be metered
|
||||||
|
and enforced, do not start. Split runs into separately budgeted stages; never assume
|
||||||
|
startup probes are free or add retries when a stage fails. Record provider usage
|
||||||
|
and request IDs privately; missing usage prevents a cost acceptance claim.
|
||||||
|
|
||||||
|
Supply a consented mono PCM16LE 24k Persian WAV and consent to retain the output;
|
||||||
|
no consented fixture was supplied here. Configure key only in server environment,
|
||||||
|
models/voice and the reviewed manifest paths/SHA. Existing component smoke executes
|
||||||
|
three sequential calls, zero retries, 128-token LLM cap, per-stage 30s and total90s;
|
||||||
|
its WAV header labels the requested rate and does not independently prove that the
|
||||||
|
provider's raw PCM really has that rate. Verify provider format/rate metadata and
|
||||||
|
actual audio with an independent listener/analyzer; ambiguous raw PCM fails the gate.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m app.local_s2s_smoke --live --input <consented-mono24k-PCM16.wav> --output <fresh-output.wav> --save-evaluation-audio
|
||||||
|
```
|
||||||
|
|
||||||
|
Stop on missing/incompatible STT/LLM/TTS or incomplete/oversized output; do not try a
|
||||||
|
replacement model. Record every attempted stage, even if smoke exits before its
|
||||||
|
success counters; use provider records for partial failures.
|
||||||
|
|
||||||
|
For the isolated engine/browser, after all gates and explicit live approval:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:LOCAL_S2S_NLTK_SOURCE = "$env:APPDATA/nltk_data"
|
||||||
|
$env:LOCAL_S2S_VAD_SOURCE = 'D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master'
|
||||||
|
$env:LOCAL_S2S_ASSET_MANIFEST_SOURCE = (Resolve-Path docs/evaluation/local-s2s/phase-02-local-assets.json).Path
|
||||||
|
$env:LOCAL_S2S_ASSET_MANIFEST_SHA256 = '8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8'
|
||||||
|
# Enable flags only under the approved budget; secrets remain in the server environment.
|
||||||
|
$env:LOCAL_S2S_ENABLE_CANDIDATE = 'true'
|
||||||
|
$env:LOCAL_S2S_ALLOW_PAID_STARTUP = 'true'
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml up --pull never -d candidate_db candidate_migrations local-s2s-engine candidate_api
|
||||||
|
```
|
||||||
|
|
||||||
|
Frontend checkout found at `D:/raymand/projects/faq_chatbot_frontend`, HEAD
|
||||||
|
`815191588c59fc43434cc2454cab3a8b2f8c1648`, with pre-existing package.json edit.
|
||||||
|
Its original proxy targets a LAN service; do not edit/use that proxy for acceptance.
|
||||||
|
Existing ng.cmd is available, so this conditional launch requires no npm download:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
Push-Location D:/raymand/projects/faq_chatbot_frontend
|
||||||
|
.\node_modules\.bin\ng.cmd serve --host 127.0.0.2 --port 4201 --proxy-config D:/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-browser.proxy.json
|
||||||
|
Pop-Location
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a new browser profile at http://127.0.0.2:4201, log into the disposable account,
|
||||||
|
send one consenting Persian greeting, listen to the answer, verify user/assistant
|
||||||
|
transcripts and normal close. Confirm request destinations and cookie/Origin/CSRF
|
||||||
|
checks belong to this candidate only. Record actual sample counts/rate and native
|
||||||
|
IDs privately with a human observation, not just readiness or a WAV header.
|
||||||
|
If testing interruption, acceptance is only the documented safe close; no Phase 3
|
||||||
|
barge-in/history repair is claimed. Use source/profile snapshots for each session.
|
||||||
|
Stop the owned candidate after observations (retain data):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml stop
|
||||||
|
```
|
||||||
|
|
||||||
|
No operational switch is part of this checklist. Acceptance can be marked only
|
||||||
|
when Phase 1 live evidence, complete engine/SDK/POSIX evidence, real components
|
||||||
|
and isolated Persian browser greeting/transcripts/normal close all exist.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Candidate only; never merge with operational Compose.
|
||||||
|
services:
|
||||||
|
candidate_db:
|
||||||
|
image: sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a
|
||||||
|
candidate_api:
|
||||||
|
environment:
|
||||||
|
TRUSTED_ORIGINS: '["http://127.0.0.2:4201","http://127.0.0.2:8091"]'
|
||||||
|
TRUSTED_HOSTS: '["127.0.0.2:4201","127.0.0.2:8091"]'
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"/api": {"target": "http://127.0.0.2:8091", "secure": false, "changeOrigin": true, "ws": true},
|
||||||
|
"/users": {"target": "http://127.0.0.2:8091", "secure": false, "changeOrigin": true}
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
{
|
||||||
|
"files": {
|
||||||
|
"nltk/taggers/averaged_perceptron_tagger_eng.zip": "6025f530624335c67d6547d44757b357b4e79bae030a0383e9887a92c1718f0b",
|
||||||
|
"nltk/taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.classes.json": "d152ffa69d45b8357276341a3d592c6c025911d52ec0d9068d4f382560dd48b6",
|
||||||
|
"nltk/taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.tagdict.json": "4c713731cb06727736962bc8cd94ad919217a040e76691059af99bc0c2c9c246",
|
||||||
|
"nltk/taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.weights.json": "789e8e35f6fac656d9b7eccea29ba4e8a137cbb5b525dd31f39e4291a9e80832",
|
||||||
|
"nltk/tokenizers/punkt_tab.zip": "e57f64187974277726a3417ca6f181ec5403676c717672eef6a748a7b20e0106",
|
||||||
|
"nltk/tokenizers/punkt_tab/README": "d3251cae66a9359bd68c039e3a46172a05ca9df0b27dcdfa23ae594d68d27ec4",
|
||||||
|
"nltk/tokenizers/punkt_tab/czech/abbrev_types.txt": "8eb1feb5a6a46f9bd8f6a5ae58e218428a65b459b5ebd61668d83fa80acfc329",
|
||||||
|
"nltk/tokenizers/punkt_tab/czech/collocations.tab": "fd58f549658c8389be32577e232187be9376c79708f66c60388a84916c8f3f3d",
|
||||||
|
"nltk/tokenizers/punkt_tab/czech/ortho_context.tab": "451cb1a68a03ba88ced1247e6bb48c442e87dce1c9f463104618fac509866cd4",
|
||||||
|
"nltk/tokenizers/punkt_tab/czech/sent_starters.txt": "42f1de18ab29f9842113b87ec020202c0c25316c97d37f968435a7c7ee3018ca",
|
||||||
|
"nltk/tokenizers/punkt_tab/danish/abbrev_types.txt": "4a358b26b7ba372cab3cedeb43b4e99a76ae9d01150493964141eb42a62e4a6e",
|
||||||
|
"nltk/tokenizers/punkt_tab/danish/collocations.tab": "b003d3b839afd47afa81d64620a1cf15b75b944212a7f3ee6a7571f041ae02ec",
|
||||||
|
"nltk/tokenizers/punkt_tab/danish/ortho_context.tab": "59d7ccda7b1eef6cbcddb6d2f1930c255a5d43600e66e32eff28eab8190c0727",
|
||||||
|
"nltk/tokenizers/punkt_tab/danish/sent_starters.txt": "f8dd41bdb1bb633574b22d38205e1c073639a0b80cb9591964bf92d84317527f",
|
||||||
|
"nltk/tokenizers/punkt_tab/dutch/abbrev_types.txt": "dcd4af07101692c986049ba07abcd6b7c1a2464ef4e46a932cf92d6e220388dd",
|
||||||
|
"nltk/tokenizers/punkt_tab/dutch/collocations.tab": "9a013563bce4637595a6db9d2eeb0ab3f68685d704ae20d97ad718aa91afbe4a",
|
||||||
|
"nltk/tokenizers/punkt_tab/dutch/ortho_context.tab": "e2077b5748564a9666e437c0a96ea9c5bed0fe3ab5c756535584785d3af20fc9",
|
||||||
|
"nltk/tokenizers/punkt_tab/dutch/sent_starters.txt": "734454acc5952d91a1dfaca8cdfdabb715d8cdd35789c749528639d80751f45c",
|
||||||
|
"nltk/tokenizers/punkt_tab/english/abbrev_types.txt": "92a3e070f43d9b4c5534758ca40ad7343b04e7e29bfe0c2eb658a39445a4f779",
|
||||||
|
"nltk/tokenizers/punkt_tab/english/collocations.tab": "8e2da1225e4dd2cc9dba261ee231ccb134859e21b46006e7f472c5ee269af0cf",
|
||||||
|
"nltk/tokenizers/punkt_tab/english/ortho_context.tab": "4bbcca25ed3d3f06c02402abf8419b9f033b8adc06e7b482eca4e45f81a5dc4c",
|
||||||
|
"nltk/tokenizers/punkt_tab/english/sent_starters.txt": "f3f8535483e1dba487241b764945168123bca3209a9645e59acd1225dc76edac",
|
||||||
|
"nltk/tokenizers/punkt_tab/estonian/abbrev_types.txt": "0307878fb32af1e21d8f3ba0644e39c89602f2f8aa4e4304943f7e9e0fd081b2",
|
||||||
|
"nltk/tokenizers/punkt_tab/estonian/collocations.tab": "f1400a7ebf3c82a3d5aac886eb5bf06a1a840946cf052bb1532da7c25094797f",
|
||||||
|
"nltk/tokenizers/punkt_tab/estonian/ortho_context.tab": "768b7e6e2ba93ff096e244af175c343b1a73463c4a1b99beebe6a9aa57ea1d78",
|
||||||
|
"nltk/tokenizers/punkt_tab/estonian/sent_starters.txt": "7ade7bb8ca7c527aac09517a6efbdf4f749e9a9fc0e43d2856c58be847030c83",
|
||||||
|
"nltk/tokenizers/punkt_tab/finnish/abbrev_types.txt": "7829baabcb5d69e26232839a1f5b6bc6d12b0e59b7f0a65f6ab1c163acbeb800",
|
||||||
|
"nltk/tokenizers/punkt_tab/finnish/collocations.tab": "4d717a1b4d1fb7108ca9c9ed2cc63f8b4813cfaf73819e96fce79495ddc48292",
|
||||||
|
"nltk/tokenizers/punkt_tab/finnish/ortho_context.tab": "43e55a8bfa977561337a09105c570036df11346c6f91e57d8631520eefb26167",
|
||||||
|
"nltk/tokenizers/punkt_tab/finnish/sent_starters.txt": "ab81cf3b774ef068ac98adb99fcb3b1a05caf0423bdfa302bdc285e15597567f",
|
||||||
|
"nltk/tokenizers/punkt_tab/french/abbrev_types.txt": "01747ecfed08830d582d8c94634b63a36da316c0a67feec2871cf03f0dd5c657",
|
||||||
|
"nltk/tokenizers/punkt_tab/french/collocations.tab": "8ddf150ef5a0d22694e7c4d807f80b6d55da731ca81ea139633f560b378af990",
|
||||||
|
"nltk/tokenizers/punkt_tab/french/ortho_context.tab": "7090ef4292647d4fe137159bd768a5304015d0614d59fdcfc30b2389634365ac",
|
||||||
|
"nltk/tokenizers/punkt_tab/french/sent_starters.txt": "b45a1ebdae9cdf46cf2e8be016b4718bf4f825445fc783d445faf0cfb2d569f8",
|
||||||
|
"nltk/tokenizers/punkt_tab/german/abbrev_types.txt": "259e5d78bc9d61a12d55ba47552c4e9c5ca08364d78a4669e864fd6de86818e3",
|
||||||
|
"nltk/tokenizers/punkt_tab/german/collocations.tab": "f77bd513f42e8179f5c932111c312be353d5913387d0bfe90a95c109111bca25",
|
||||||
|
"nltk/tokenizers/punkt_tab/german/ortho_context.tab": "023887e78cfb919f1a00f9a96a88f42131582748cf833fd469490ee66596307c",
|
||||||
|
"nltk/tokenizers/punkt_tab/german/sent_starters.txt": "fe4b63edbdd33f78ba0a755f035680a864948b145ae82fc99072440a62a77acd",
|
||||||
|
"nltk/tokenizers/punkt_tab/greek/abbrev_types.txt": "0d56253b7ebc83f0f2403479bcf2b8ea51ffdea89ee60e34018eb32e4750d683",
|
||||||
|
"nltk/tokenizers/punkt_tab/greek/collocations.tab": "0fd732534d56177c80874125ca894ae60aee7b052ee2865a405b454cfd737a6f",
|
||||||
|
"nltk/tokenizers/punkt_tab/greek/ortho_context.tab": "a87e4467791f974f808c0d396f6c82cd3a014d4fb4458a2287e2fcbce7084e9c",
|
||||||
|
"nltk/tokenizers/punkt_tab/greek/sent_starters.txt": "1a450aec85164e3fbfeb814768c9f120abd7139726af5bb5e2a577096739ca8e",
|
||||||
|
"nltk/tokenizers/punkt_tab/italian/abbrev_types.txt": "5d406f6bfb35e55f6bea282bf148bdcc9e4677860eb01a8e67c34b894274ac50",
|
||||||
|
"nltk/tokenizers/punkt_tab/italian/collocations.tab": "8167b58a049bb04de8d692ed33d72963503a061717cd37cacb33bb2d00669caf",
|
||||||
|
"nltk/tokenizers/punkt_tab/italian/ortho_context.tab": "462ffd48bc1c9b86efe66d04d826cd1e7a5745be871b8121759ed2920a967370",
|
||||||
|
"nltk/tokenizers/punkt_tab/italian/sent_starters.txt": "4dc2cdfda34d4f286e5875d6b62b148771a799a71f0d45b504da23cb61b59d51",
|
||||||
|
"nltk/tokenizers/punkt_tab/malayalam/abbrev_types.txt": "1ea2cd01629c8cbeac0799d39383e10c4d6948734c255d37e3ceda550ba62464",
|
||||||
|
"nltk/tokenizers/punkt_tab/malayalam/collocations.tab": "71bc38e42133f288c660a338169d8858944135282ad4166a2c5d23cc8a06ed73",
|
||||||
|
"nltk/tokenizers/punkt_tab/malayalam/ortho_context.tab": "5289e43f46ef3679f4ebbed95ef1fad5b64dd7aa8957042adb2b661cc6ae4425",
|
||||||
|
"nltk/tokenizers/punkt_tab/malayalam/sent_starters.txt": "918c902aa9d0b72700410258274ae335da51148fee7fc27095ab4114b23a245c",
|
||||||
|
"nltk/tokenizers/punkt_tab/norwegian/abbrev_types.txt": "beced74076edabe64f45effb823012d1396db41f35fa1d8be2ac6b69bf7bc40f",
|
||||||
|
"nltk/tokenizers/punkt_tab/norwegian/collocations.tab": "9c815b01e2f7518552b53f09012644df1fa0d8c7642baff9dc5f61e85e0be422",
|
||||||
|
"nltk/tokenizers/punkt_tab/norwegian/ortho_context.tab": "57ea2aa129de6ae414cd0cbecba8b2399c4fde775a2145776a7e8f1023f3f183",
|
||||||
|
"nltk/tokenizers/punkt_tab/norwegian/sent_starters.txt": "2b49ef0f0c2e1b4e8b06aee1172e4d88ce6ad01486fe4182cff6fc443a73ddeb",
|
||||||
|
"nltk/tokenizers/punkt_tab/polish/abbrev_types.txt": "426ea37ca486d0dcc3653653c613d853d0bb3929037f8ee6bf6c12ddae873aa1",
|
||||||
|
"nltk/tokenizers/punkt_tab/polish/collocations.tab": "961653f0606d85ecb8a760cad4f69df123f010bc4b35de0253feb2d7869666b4",
|
||||||
|
"nltk/tokenizers/punkt_tab/polish/ortho_context.tab": "f770804067012ee5707ffc65d90523180e09bab09230a49251777be821a1a4f6",
|
||||||
|
"nltk/tokenizers/punkt_tab/polish/sent_starters.txt": "8564076ae22be3d549a3f097a18458ac2967d65bd28dad7cc223c53f5ce27d1b",
|
||||||
|
"nltk/tokenizers/punkt_tab/portuguese/abbrev_types.txt": "cd5c3cf9c4c8b766bc9edbc96444b0e2189b837b26c583aa2cce83a18e4285f5",
|
||||||
|
"nltk/tokenizers/punkt_tab/portuguese/collocations.tab": "a150d2ca3b8bd9d87cd25f2e1d2142607cdf9344efe914bd034af6017a16d841",
|
||||||
|
"nltk/tokenizers/punkt_tab/portuguese/ortho_context.tab": "2d9c143f7b322fc74738a21e0b2b04feed1668245ac93e5a8e5399e6e0d8ed8a",
|
||||||
|
"nltk/tokenizers/punkt_tab/portuguese/sent_starters.txt": "7b7f4a1586b1df8592bf294c8dd0d19aaf90740d78ce3b40a31eff2b9669d15e",
|
||||||
|
"nltk/tokenizers/punkt_tab/russian/abbrev_types.txt": "75191526be516a9918948fe3ad46f6c2c4dee14314359a899b8c2ebf496cb631",
|
||||||
|
"nltk/tokenizers/punkt_tab/russian/collocations.tab": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||||
|
"nltk/tokenizers/punkt_tab/russian/ortho_context.tab": "b296cba91006569d3ef79eb2cff2378bf5be5b75e9e83ea119b883d3c3ee69b6",
|
||||||
|
"nltk/tokenizers/punkt_tab/russian/sent_starters.txt": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||||
|
"nltk/tokenizers/punkt_tab/slovene/abbrev_types.txt": "b1d6b16d1d2b3c0c4132c1528b9843d1557f7f544044db27f4e8d2d6985faf2b",
|
||||||
|
"nltk/tokenizers/punkt_tab/slovene/collocations.tab": "4c10daafdff496e369f3a8809bebf187abc851df630457ae93c7ca4fda350651",
|
||||||
|
"nltk/tokenizers/punkt_tab/slovene/ortho_context.tab": "3ba826bdd7e5543af7af8e317d4652ba8b47fd812157855a6274ec1387a46b3e",
|
||||||
|
"nltk/tokenizers/punkt_tab/slovene/sent_starters.txt": "85ae14dadef3c4c9f753491d84919abb10e09003adfe248794d4a597fabc5793",
|
||||||
|
"nltk/tokenizers/punkt_tab/spanish/abbrev_types.txt": "246a4b3efbad45b63eb9672b718574b535acef6d656f24dc17a46d13a38efba1",
|
||||||
|
"nltk/tokenizers/punkt_tab/spanish/collocations.tab": "fa5ea7dbf61f2b1c12180d660a3012c9faaf4962eb12549d77af95e2a40be65d",
|
||||||
|
"nltk/tokenizers/punkt_tab/spanish/ortho_context.tab": "1346ecfc57b26174987ffa9bd4a2558a66f46592a513da3859648790351df370",
|
||||||
|
"nltk/tokenizers/punkt_tab/spanish/sent_starters.txt": "4d4f7380ba16380b6158e9e8ead6973c52f27e3c9c88af63f15a41c490998319",
|
||||||
|
"nltk/tokenizers/punkt_tab/swedish/abbrev_types.txt": "1e1a78bd5e7fd6e7eb4b15b751a23d441cda845d5fc0b631958177b2f504da00",
|
||||||
|
"nltk/tokenizers/punkt_tab/swedish/collocations.tab": "bd2260433c94617ba7cf6102e4c1035099a72e5a2f6b60734639252e41633c04",
|
||||||
|
"nltk/tokenizers/punkt_tab/swedish/ortho_context.tab": "d48c5705d0570993628e539ca211f05cdb5aad7adfcc6ed7b24310941bfac9f8",
|
||||||
|
"nltk/tokenizers/punkt_tab/swedish/sent_starters.txt": "6f0f7a6773f7488a23bafc6c29e7d4554e792d89c6b7a89fbd6a83bec85ef767",
|
||||||
|
"nltk/tokenizers/punkt_tab/turkish/abbrev_types.txt": "de56078c5eeb3fe07e24eab67c4aaf44e2181cbe80edd976cb1622819599d6fd",
|
||||||
|
"nltk/tokenizers/punkt_tab/turkish/collocations.tab": "061ce2981776a8f875da4f24bebd7e138f8da1d9057b43d07f580148ec106a33",
|
||||||
|
"nltk/tokenizers/punkt_tab/turkish/ortho_context.tab": "fc214227f99d5ea3ee70d208df16b1984eab375d1946ed379061c6cf5c1718be",
|
||||||
|
"nltk/tokenizers/punkt_tab/turkish/sent_starters.txt": "93239fb55b5d2ae6d945a84a94e118ba8a816326b17cdc11ba8111bea0c97828",
|
||||||
|
"vad/.github/ISSUE_TEMPLATE/bug_report.md": "838e58d3039c5eade216dd8caac4ef7e823203f5686eaf39ed62817530ae746f",
|
||||||
|
"vad/.github/ISSUE_TEMPLATE/feature_request.md": "7de51a6efb528d29eaa7a0c6364c05849d518102c24eefcfdcaa11338b442eb9",
|
||||||
|
"vad/.github/ISSUE_TEMPLATE/questions---help---support.md": "061d6ca1262f97c9460b769f041a2d73b7eddd86733a1d2bd44b637c564d3c6a",
|
||||||
|
"vad/.github/workflows/python-publish.yml": "63f2a37d1f8f683ba9e3672ba48f5b81f277b35039d0bdf24c1937accf5203c8",
|
||||||
|
"vad/.github/workflows/test.yml": "d358f62320a79dd9b92b12efd50edae557841650ea88583f67a26b4e00302e29",
|
||||||
|
"vad/.gitignore": "9d3c43ecc95137fc4d1c88df4ceaae256fc7ba2d55a06c01e890d4e6b52214cb",
|
||||||
|
"vad/CITATION.cff": "dd9981387b59cf75853e0f2b7f7f79e8a694f3bf6aaa17dc9bcc72e70356477f",
|
||||||
|
"vad/CODE_OF_CONDUCT.md": "216247a1f9d0f9bd5daa7ba7f2957c42f3c8ea39a315dbc0a883f62ec8f17666",
|
||||||
|
"vad/LICENSE": "2e63e9a38b6e8fc0c7bc37ce174caca1862870856c6daf5697cfb785e925520b",
|
||||||
|
"vad/README.md": "cd0ee56c91b8042e62a714c0c94bc8b74dbea127a483e390f8033bb8ec8cec78",
|
||||||
|
"vad/datasets/README.md": "603353a37ec3351f0463307f0c5377eefb98547e2463defb889e5f5930a5536a",
|
||||||
|
"vad/examples/c++/README.md": "4874ad0ec4d21dc2e7d981d523ac98c95792d6ae57773c2da0d24e11f7185811",
|
||||||
|
"vad/examples/c++/aepyx.wav": "a622cb1cdd8a52db84b0d4bb524fa9a93f9ed387de40530f87c3a57d7493fd49",
|
||||||
|
"vad/examples/c++/aepyx_8k.wav": "3b36a5347bdad20ff72fb9e2613e4214d25f981c56b51ca17704f087b84fddc6",
|
||||||
|
"vad/examples/c++/main.cc": "b51075d99f6001449335b7f52f74fa3860d3d5c3e2cecbef9c1e73cdd0d32087",
|
||||||
|
"vad/examples/c++/silero.cc": "39aed6dce7a1c05000f4305134be07b6ee28e1ffad70ee3c996a37d3d8bc29a5",
|
||||||
|
"vad/examples/c++/silero.h": "ff37646d0aa859b7c96739bbfb6b4da7c53e945bda571d5fb1a4dbf0d6697687",
|
||||||
|
"vad/examples/c++/wav.h": "04bd8d3a8b849ad2dc099fcaff5dff0da76592cefd954cc17185331b180a2c45",
|
||||||
|
"vad/examples/colab_record_example.ipynb": "e9c994372b93e2032fb4e4341e44a6027439d78c44976fd75d3249e18ed486f1",
|
||||||
|
"vad/examples/cpp/README.md": "617379cfc84ef62d8cacf314314b30a922145eb5b39ec0ee3b5e970d90b69177",
|
||||||
|
"vad/examples/cpp/silero-vad-onnx.cpp": "dcd7ab46126d7201c495fae2349fb956e81aba00220dc185838df122104612c7",
|
||||||
|
"vad/examples/cpp/wav.h": "75e73e37f3f3e33d7239e51b529d5165f27bcc6273fb52710402d81c7b11dcae",
|
||||||
|
"vad/examples/cpp_libtorch/README.md": "11c49c5dace8473818aa3be9c5662abc8dff753dbe724dc4ae6250b83aff5288",
|
||||||
|
"vad/examples/cpp_libtorch/aepyx.wav": "d6aed597425ea4ce852db919912906e45471acd74e18ed3046360cbc3f06c27b",
|
||||||
|
"vad/examples/cpp_libtorch/main.cc": "af41235e0a4ec44cb8321d3793993cdc718118439362d7cefb1d046c0296b5b2",
|
||||||
|
"vad/examples/cpp_libtorch/silero": "f5b2fa15458ca5bf961042b2157f4b81481a6e9819c4b32f886f9251dc31563b",
|
||||||
|
"vad/examples/cpp_libtorch/silero_torch.cc": "a58aabc000caf6f190c55625d835ca0ae6f09a5dd2cac900b144cb3b174da8e3",
|
||||||
|
"vad/examples/cpp_libtorch/silero_torch.h": "c4f4d89723e065a4d4df5a7bda22f839eaa9af4b97f50a59817f82b2d69c94e5",
|
||||||
|
"vad/examples/cpp_libtorch/wav.h": "65a200886095c998eec13900973876572a08a2d0c5f9ea7b00bd35f2973fe6b6",
|
||||||
|
"vad/examples/cpp_libtorch_deprecated/README.md": "11c49c5dace8473818aa3be9c5662abc8dff753dbe724dc4ae6250b83aff5288",
|
||||||
|
"vad/examples/cpp_libtorch_deprecated/aepyx.wav": "d6aed597425ea4ce852db919912906e45471acd74e18ed3046360cbc3f06c27b",
|
||||||
|
"vad/examples/cpp_libtorch_deprecated/main.cc": "af41235e0a4ec44cb8321d3793993cdc718118439362d7cefb1d046c0296b5b2",
|
||||||
|
"vad/examples/cpp_libtorch_deprecated/silero": "f5b2fa15458ca5bf961042b2157f4b81481a6e9819c4b32f886f9251dc31563b",
|
||||||
|
"vad/examples/cpp_libtorch_deprecated/silero_torch.cc": "a58aabc000caf6f190c55625d835ca0ae6f09a5dd2cac900b144cb3b174da8e3",
|
||||||
|
"vad/examples/cpp_libtorch_deprecated/silero_torch.h": "c4f4d89723e065a4d4df5a7bda22f839eaa9af4b97f50a59817f82b2d69c94e5",
|
||||||
|
"vad/examples/cpp_libtorch_deprecated/wav.h": "65a200886095c998eec13900973876572a08a2d0c5f9ea7b00bd35f2973fe6b6",
|
||||||
|
"vad/examples/csharp/Program.cs": "863e88b3a1eb496fdedd22820bd8bcdc45369e0c63204b91a1afaa4386d7f9da",
|
||||||
|
"vad/examples/csharp/SileroSpeechSegment.cs": "5a9917e9c83021404b5a49cba4ef54a50468ae209bf8b9037487a4365db26cfb",
|
||||||
|
"vad/examples/csharp/SileroVadDetector.cs": "33f46cf85dd8108acb86da0744483ea3d23ec1cfd507eb2e369bfe042fa612ac",
|
||||||
|
"vad/examples/csharp/SileroVadOnnxModel.cs": "dca90558149d4be15184a80385e886a44dcb9e90ecade9da66ea93fd1c176455",
|
||||||
|
"vad/examples/csharp/VadDotNet.csproj": "881fd1d1647ea781e50d16c9bf8c0850a10bd8e6195a605a4a5bdfe883a283b1",
|
||||||
|
"vad/examples/csharp/VadDotNet.sln": "6e4cc97b9828a5b3a715ed6c6fe422690f4d309208f301faacbc8fe863b6d920",
|
||||||
|
"vad/examples/csharp/resources/put_model_here.txt": "576203b57768b84f12e4f8a137a2e084dbdf0b75fbd77f1a8358ab4305be319d",
|
||||||
|
"vad/examples/go/README.md": "c561f2f92d64bcf4a52b7e2e2de25266b62fc410fbed23925d8d7b72ac8aaafd",
|
||||||
|
"vad/examples/go/cmd/main.go": "cee81f9296f5baf491ce45469be361f6226172b3399fa88b9ab11e368959bda4",
|
||||||
|
"vad/examples/go/go.mod": "fa075afa55942727467ded19b540ddcf75db2a001d5f953e46f8c48a428f2b73",
|
||||||
|
"vad/examples/go/go.sum": "1d941ecfdb03b7a4f2f51012f928ef9b7c1938f3b5b6b3c840663aab44367a9b",
|
||||||
|
"vad/examples/haskell/README.md": "ac9065f5aedc0155c59a1f97d4f949cf313b74122567432f83d7c1feab2b5ae6",
|
||||||
|
"vad/examples/haskell/app/Main.hs": "cf7da6c2e5a7d73242b565e5aa24b637e038b9af6ff33f032565a6d52b95c99b",
|
||||||
|
"vad/examples/haskell/example.cabal": "3de0377572a072ac9233fef68113d657a8519853119bb14e30d549f61f9cb442",
|
||||||
|
"vad/examples/haskell/package.yaml": "21e7c7b96cf36203c1fe078b76d210ae7418bb1d4f9258e5b64c3fe12e8256a4",
|
||||||
|
"vad/examples/haskell/stack.yaml": "305887dc2d15d1178ad0275fcad4d33cbc5a74b6274cf4a551191e161820dc91",
|
||||||
|
"vad/examples/haskell/stack.yaml.lock": "62f31a1d3f9167e1f3627539dbfb7a46a1983f0d8e194b88904cf4c435dcb5b6",
|
||||||
|
"vad/examples/java-example/pom.xml": "1aaac050ffee4d97b30dfc70de202ba0bd06da337d80917e75cb6dee9b19eb76",
|
||||||
|
"vad/examples/java-example/src/main/java/org/example/App.java": "1089deb76157a6b0a35b7f1fd311ba86922bd3a6ead46279b12d96d70b4ac4d5",
|
||||||
|
"vad/examples/java-example/src/main/java/org/example/SlieroVadDetector.java": "81534ed59133a8118e8ab0dc08c03aaeace0fab0fb200ce92d78b872c13bb2b8",
|
||||||
|
"vad/examples/java-example/src/main/java/org/example/SlieroVadOnnxModel.java": "aa9159cf2219b018dd566aecd9e533bb811485bd0947750c2f89ead99a5267cf",
|
||||||
|
"vad/examples/java-wav-file-example/src/main/java/org/example/App.java": "d454f388ca1230c87d2480ad4913b7c91fd44e6f436e40ecf963d0448d2861e4",
|
||||||
|
"vad/examples/java-wav-file-example/src/main/java/org/example/SileroSpeechSegment.java": "69eecb8a7e033e6b1e971318bd2691da6ad82417b28e3d437d9c804c6b590299",
|
||||||
|
"vad/examples/java-wav-file-example/src/main/java/org/example/SileroVadDetector.java": "381a2a6b3b768b36e828979803d65ff02e8274506906bfdf9ebf93accaec7e39",
|
||||||
|
"vad/examples/java-wav-file-example/src/main/java/org/example/SileroVadOnnxModel.java": "0625123e9202542c017c26fe23087934b802e5dba94a3789d5ab5a59495b705d",
|
||||||
|
"vad/examples/microphone_and_webRTC_integration/README.md": "46374787966a54c80857b03bf9256fbe9cbf6b279c8a183bb3a78caa3552d839",
|
||||||
|
"vad/examples/microphone_and_webRTC_integration/microphone_and_webRTC_integration.py": "d1628b83eb8a1f84d038499a9c7eda962d6f2684b722bd2167a081fa3666d373",
|
||||||
|
"vad/examples/onnx_sequence/README.md": "970bae202a4ab5b3a90b47e1e82158238cbc7113709b3c2c1ba91d69c829eff9",
|
||||||
|
"vad/examples/onnx_sequence/export.py": "5e0889ac5a84d8b0bb0bee178e1febde50397484dc96bf2d93a66eb8eae973c3",
|
||||||
|
"vad/examples/onnx_sequence/run.py": "b45355bec6451b07043bc352b6f890fab72c203b3708318502f833dec4e80045",
|
||||||
|
"vad/examples/openvino/README.md": "afb6c97107fca4a028f22ada74ab01c8287b45277fdfbdf2916d2d8f572f9dce",
|
||||||
|
"vad/examples/openvino/convert.py": "4ed304326aebcffacfbbf9a342a0812953e89acfc76335299af39e5275c8cc6b",
|
||||||
|
"vad/examples/openvino/verify.py": "f211740338aa558220d194d8cb9dd1ed6c6be502657af5ae201f168647e5d29c",
|
||||||
|
"vad/examples/parallel_example.ipynb": "34a990d7b4aee8ab09469565034fce015772dcf9ba33c50ce6969254edb87592",
|
||||||
|
"vad/examples/pyaudio-streaming/README.md": "1ae63cbddfdc54a5a0af525b6dbb13d5dcbc1f36cc247c29feb0e6995f0185d7",
|
||||||
|
"vad/examples/pyaudio-streaming/pyaudio-streaming-examples.ipynb": "c885e43f025f4fe4c69e54b3956ef40d1290ca9425e33fd4a18374cfc992846c",
|
||||||
|
"vad/examples/rust-example/.gitignore": "87871cf70e846ad574df943e50f59d6ccfcdb501d6517ec228b714e4994fea09",
|
||||||
|
"vad/examples/rust-example/Cargo.lock": "a1415ffef47fa0d6254dba496e4b43df7f6b0fd6757e91737de45391b14300df",
|
||||||
|
"vad/examples/rust-example/Cargo.toml": "85aa11c75bdbd9e67fe868fe29e55f531b46c78c1de068711e7298f4316a5a70",
|
||||||
|
"vad/examples/rust-example/README.md": "46ecdf442525e4e912c8f349431d7787d3c0cc6d150ac4811cafcdb226eb4188",
|
||||||
|
"vad/examples/rust-example/src/main.rs": "1d4ff80632fc609ed99030e5af2b9c81d8a26bfdc79cb0af5c9e406c3c141091",
|
||||||
|
"vad/examples/rust-example/src/silero.rs": "8d1b00124206f96b1b0c18bab6c53c8ae6f90e94e7e93e310c5c5f9edcec5bcd",
|
||||||
|
"vad/examples/rust-example/src/utils.rs": "296eabc14c137d5575384b8bbfb81c3c754d667b926ff58f902751453832393a",
|
||||||
|
"vad/examples/rust-example/src/vad_iter.rs": "ae2b8799fcb89b800198d86b82f6b0f7cb70f81cc5645089c234aa18163fc0c0",
|
||||||
|
"vad/examples/rust-wav-processing-with-wavekat-vad/.gitignore": "5d77fbb6e90fb09e55e21161fd11333b862e409c994ee8593131ad3ae0a97401",
|
||||||
|
"vad/examples/rust-wav-processing-with-wavekat-vad/Cargo.lock": "1fdafd48875a6bd75ecbbe58ca81083bbbdae78b8e21416fa0e03660f67f661a",
|
||||||
|
"vad/examples/rust-wav-processing-with-wavekat-vad/Cargo.toml": "f43ce000cb1b7e923fe07eac64ea56b11a9d842bce89b2f3fa86aee11611c8b2",
|
||||||
|
"vad/examples/rust-wav-processing-with-wavekat-vad/README.md": "0d5ff7e0c34ec1b60c85233f2663a858de55360b691ce570874cad4d4f2731b1",
|
||||||
|
"vad/examples/rust-wav-processing-with-wavekat-vad/src/main.rs": "13b7cbec9d5d88691e89fcad64b31a085ff5aefeff1c0d584102b607d03a43c2",
|
||||||
|
"vad/files/silero_logo.jpg": "997ebb29131f24871c8299ffabbf168712f9ffffb0546f89be235a57efce4f96",
|
||||||
|
"vad/hubconf.py": "2637a3a91d061a6e921853f5de5430f873c292662b46e5fd61edaf648b4ae5bd",
|
||||||
|
"vad/pyproject.toml": "2aa7fecb20eb9c9feaf22ae31421f904f85d7b939c03d17d12c0113fea49e32f",
|
||||||
|
"vad/silero-vad.ipynb": "d11a53290f594af3a73ee203555bbc8a0dab8735e93736f708ff3bbd16f6e9a2",
|
||||||
|
"vad/src/silero_vad/__init__.py": "45fcf7e268eb0ba83ccee737b1a86cc94d7cf7487e2a1c0a31b9b72b899201f1",
|
||||||
|
"vad/src/silero_vad/data/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||||
|
"vad/src/silero_vad/data/silero_vad.jit": "e1122837f4154c511485fe0b9c64455f7b929c96fbb8d79fbdb336383ebd3720",
|
||||||
|
"vad/src/silero_vad/data/silero_vad.onnx": "1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3",
|
||||||
|
"vad/src/silero_vad/data/silero_vad_16k.safetensors": "c59271c284ae9c8335d795d60e0bfdb71aaaceec578d9bd9ffc1b8153c319ea1",
|
||||||
|
"vad/src/silero_vad/data/silero_vad_16k_op15.onnx": "7ed98ddbad84ccac4cd0aeb3099049280713df825c610a8ed34543318f1b2c49",
|
||||||
|
"vad/src/silero_vad/data/silero_vad_16k_sequence.onnx": "9ccdacc4719d8aa7e45a77536bfabec45a03ba1f2fad5e241ab4060b24238a85",
|
||||||
|
"vad/src/silero_vad/data/silero_vad_half.onnx": "1e0b195ad4806595ef4466f419d16fca7e4afcfc6669b8c0b5f76ea87547c769",
|
||||||
|
"vad/src/silero_vad/data/silero_vad_op18_ifless.onnx": "7671cd04b004e9076da0d4a7b1a5aec36adf161c39230c1cb94a4fd5db6bbd28",
|
||||||
|
"vad/src/silero_vad/data/silero_vad_openvino_16k.onnx": "7776b81ad1b0350c15d7f1555943b9232eb53e9ca5d989c6d0cea9ebc8664d87",
|
||||||
|
"vad/src/silero_vad/model.py": "40762a80d1278605480f75f90c6510c1a4ab71bd230f45c334e4f9c5e402181d",
|
||||||
|
"vad/src/silero_vad/sequence_vad.py": "c8b6e1194e36a5721a8f1ac6674e07f78c8a892c7585c51c9f9b40068cf34fbd",
|
||||||
|
"vad/src/silero_vad/tinygrad_model.py": "79afb8aae28bb9d20735df4053bef1191a85b74a0db335a5fc16c302ddda7e86",
|
||||||
|
"vad/src/silero_vad/utils_vad.py": "7e0f9b3334ee4feb79abcf2251be12458329077bce28c8540878ed9d35e5aa6b",
|
||||||
|
"vad/tests/conftest.py": "c53caa3c7b0cc071b358d8a3e5a6529502ffcdcd299e47106f54fb453644509c",
|
||||||
|
"vad/tests/data/test.mp3": "65a63b8ab116e80078cfc700ebec6d496b769c33bde72018ea41d535d4cfea0e",
|
||||||
|
"vad/tests/data/test.opus": "8c009ea434e0323f453dc311f03d980929406af6c44c34897503f0b01e84265e",
|
||||||
|
"vad/tests/data/test.wav": "89f17d9c94c4b31eb320f424628bcbc920abaddbee6e2760fd868bfb1d9a2e47",
|
||||||
|
"vad/tests/test_audio_backends.py": "ec981db4dd93bc816ed3b4c69e0cb4c6079d7ea630b7a8a26bd9de30313dd403",
|
||||||
|
"vad/tests/test_basic.py": "9211653f21693c77cec9bfc48b7061814bda9de85f0c4e33311a30ace2e33c26",
|
||||||
|
"vad/tests/test_optional_deps.py": "cfe2bdd068dfc1209666656546883ba246f8095cfd75dd9844e6bd590a329121",
|
||||||
|
"vad/tests/test_sequence_parity.py": "cecd9ff0904c6ecde4c36012a8c209ecc7d8f2a54cba368805528355ea0406f5",
|
||||||
|
"vad/tests/test_vad_iterator.py": "e24cca107756fa2caad439de3d933160dc92326485c2c0f13837067e144ef132",
|
||||||
|
"vad/tuning/README.md": "c727ad309a9da5230b997963a2753096073267bd9f7a4e8c97dd2fdbf89ed96d",
|
||||||
|
"vad/tuning/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||||
|
"vad/tuning/config.yml": "06443def6341c8ae6439325a0652dfbb6e01b022d9b31065d84261d0c4f358f0",
|
||||||
|
"vad/tuning/example_dataframe.feather": "d03db5681596414f284ba53c2da52028c0738ae3584cb0865246ff8ef792ce2f",
|
||||||
|
"vad/tuning/search_thresholds.py": "4b2670739897fc9ed577f52d594b2761a3e96e241ed3fa32841a951efdf908c0",
|
||||||
|
"vad/tuning/tune.py": "b4c2bb3724fa3fc1ae3818c3e0938e24707aa4f9104058546a989faf3fd87aef",
|
||||||
|
"vad/tuning/utils.py": "e1da62037c2171b424e705291fe6eadc3218a3c0514e5773b6ba6d707432f1a6"
|
||||||
|
},
|
||||||
|
"schema": 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,713 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-10-15",
|
||||||
|
"upstream_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||||
|
"expected_candidate_profile": {
|
||||||
|
"provider": "local_s2s",
|
||||||
|
"model": "openai/gpt-4.1-mini",
|
||||||
|
"voice": "Kore",
|
||||||
|
"input_sample_rate": 24000,
|
||||||
|
"output_sample_rate": 24000,
|
||||||
|
"evidence_policy_revision": "same-session-evidence-retained-v5",
|
||||||
|
"development_only": true,
|
||||||
|
"interruption_policy": "close_until_phase3",
|
||||||
|
"local_s2s": {
|
||||||
|
"engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||||
|
"patch_revision": "rag-local-s2s-phase2-v3",
|
||||||
|
"contract_revision": "rag-local-s2s-phase2-v1",
|
||||||
|
"components": {
|
||||||
|
"stt": {
|
||||||
|
"backend": "openai",
|
||||||
|
"model": "openai/whisper-large-v3",
|
||||||
|
"language": "fa",
|
||||||
|
"response_format": "json",
|
||||||
|
"final_only": true
|
||||||
|
},
|
||||||
|
"llm": {
|
||||||
|
"backend": "chat-completions",
|
||||||
|
"model": "openai/gpt-4.1-mini",
|
||||||
|
"max_output_tokens": 256
|
||||||
|
},
|
||||||
|
"tts": {
|
||||||
|
"backend": "openai",
|
||||||
|
"model": "google/gemini-3.8-flash-lite-tts",
|
||||||
|
"voice": "Kore",
|
||||||
|
"response_format": "pcm",
|
||||||
|
"sample_rate": 24000
|
||||||
|
},
|
||||||
|
"request_timeout_seconds": 30.0
|
||||||
|
},
|
||||||
|
"effective_config_sha256": "049a34b0d42ddb000d34dd52ab49844e3af958ab96eac4614c8a463236aa72a5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"observed_engine_profile": null,
|
||||||
|
"engine_image": null,
|
||||||
|
"base_image_digest": "sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce",
|
||||||
|
"dependency_lock": null,
|
||||||
|
"vad_bundle": {
|
||||||
|
"host_root": "D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master",
|
||||||
|
"combined_nltk_vad_manifest": "docs/evaluation/local-s2s/phase-02-local-assets.json",
|
||||||
|
"manifest_sha256": "8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8",
|
||||||
|
"linux_jit_validation": false
|
||||||
|
},
|
||||||
|
"engine_built": false,
|
||||||
|
"engine_live_validated": false,
|
||||||
|
"browser_demo": false,
|
||||||
|
"paid_requests": 0,
|
||||||
|
"files": {
|
||||||
|
".env.example": "c49816b66f435c246ac7c9de53229324dae4b1ac667e6294f79e368f400247b4",
|
||||||
|
".gitattributes": "b8726d6a05524d792be8f39d874d031168d72eb546a2258970cab23f9add6fc1",
|
||||||
|
".gitignore": "0b11c3566199edb6b1888b0d7318fc9a3c542074862f426ddef36280ead8f8d1",
|
||||||
|
"app/api/v1/live.py": "510ac4b9c5bbe8c90c90ef28981b0a7fec2aa857d178daaad96814eb3bc0d50c",
|
||||||
|
"app/infrastructure/gemini_live.py": "eaa6e9e1fbe02edd11df00b7ad311fbb04bb9a8af76307c09f0d4cbc33fabe7e",
|
||||||
|
"app/infrastructure/local_s2s.py": "2847552df0407949007c55ac1bc6a4558fae6b20a2b875af882a55bc2491f218",
|
||||||
|
"app/infrastructure/realtime.py": "34f423769222c1f76bd33c2109123cad0cc2dca8180c47dd24722eb2512233d0",
|
||||||
|
"app/infrastructure/voice_provider.py": "f017536fc4e06305f5c9a6ebf1fe891c746dd1f448bb743cbd268889772766f4",
|
||||||
|
"app/local_s2s_smoke.py": "fc5cf5783bf5af9b8711d1e6beef644ee748ee46d9b0652cea32b153fb85875c",
|
||||||
|
"app/main.py": "67c9cd5f886199ad7af70e329676ea5b9cc9ab6d069e99d2d722f16aed8f3a3c",
|
||||||
|
"app/modules/voice/configuration.py": "b3b8be699748c7bef094dc189282370e2146fee9e63385ac66143ec624f44c7e",
|
||||||
|
"app/modules/voice/local_s2s.py": "44f841b627e211ca41f373016a0c113daaa704f48add79f055266030d9acc78e",
|
||||||
|
"app/modules/voice/provider.py": "e9a47e0b13c2e9f4f8c0ab140548148a245999c787d2719b56b1c4e391cdf024",
|
||||||
|
"app/modules/voice/runtime.py": "81bece5d52ef086a9a7caa961643199dfc54e2528a40a5ee20fa2b142fa03b7d",
|
||||||
|
"app/modules/voice/settings.py": "c022bcc4bd0e77f20f999893ece573b964349fbc49319c03e814a31834102415",
|
||||||
|
"docker-compose.local-s2s-test.yml": "1b7748d2d4992b869749f5a27d674573637c4ab2f5406af13d2be70e44594de3",
|
||||||
|
"docs/agent-reference-map.md": "946f020edc9f309272e387819254add99080b36a686a325fef3692e6973153a6",
|
||||||
|
"docs/evaluation/local-s2s/acceptance-postgres.py": "6b3384950a75e2d18f1ada16fb8452623c195ac467d68ee8feba2a043f8c1eb9",
|
||||||
|
"docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml": "300af7997e90c18e2fdfc6c21fbc0d4be43fea8b66d3e51a9869779cc012a668",
|
||||||
|
"docs/evaluation/local-s2s/phase-01.md": "299c6e137d894e7e8177825df317251569ef40d05e2145e5ccee37acf36244a8",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-acceptance-checklist.md": "769b25e3dd3c85782b9776ec9a097ac43feb1595480e08b41fa55aabada18b7a",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-browser.override.yml": "faac069f111e3e98022c09bb9ac0ed9b6350394640091f66cc6ef6d2841c7fb2",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-browser.proxy.json": "0c57f025cfa2b47476a11b0c723800ca76923e65e4fa42f2a6ac9ccc002328f7",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-local-assets.json": "cdafcecf029073fb08d7028f90cf09e53955056c9d173cf84c804ac37ef12962",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-remaining-repairs.patch": "325f3abaa7b70a1d1448beae5f4021351de524bb39d8fa79c0398089f9ca9066",
|
||||||
|
"docs/evaluation/local-s2s/phase-02.md": "de78b6e93f6f3738de63e840f6c9fdf279362bc88e243d92df86dce3966c5cdb",
|
||||||
|
"docs/evaluation/local-s2s/upstream-pin.json": "73e3d50f7bbdff88893e921d19800c3941ff6d7604aba62b4faf63b13d72326a",
|
||||||
|
"docs/plans/local-s2s-adapter-plan.md": "e6c1cad582652312409e2c0b91f5279a95b13ae33b351a10ca91e687283a3dcc",
|
||||||
|
"docs/plans/local-s2s-adapter-progress.md": "1174d13aef2b101b57b6eb55a54a6e1e22429d43b4c3c3e2ce95be16e4498205",
|
||||||
|
"docs/specifications/RAG-Phase1-API-Catalog.md": "eff254d8dfa270d80e9866623aff550a2157b6331004e8f4b2ba5b610e17dbea",
|
||||||
|
"docs/specifications/RAG-Phase1-Database-Design.md": "48665ce9bdfbb419c4645cc4fc7ddeca737721a3b5e5a39a6f0cceb9b629422b",
|
||||||
|
"docs/specifications/RAG-Phase1-Implementation-Guide.md": "f567475b0fa539061c396756f7d2d6f6ef549be2efc06bbc45500aec6e42c448",
|
||||||
|
"services/local_s2s/Dockerfile": "dec0cc9310321d20fce89397930724770e6dd8053703ecf1d42526df3ae3d508",
|
||||||
|
"services/local_s2s/Dockerfile.dockerignore": "dc79074c16cca7f80050d4d269dd7b99e04d98a4b156e3a7e8ed2ddd82f51da3",
|
||||||
|
"services/local_s2s/README.md": "3b8335d70d7ed2b54489176b5db6dd7e5f8a0c1d0c5b557fb24529be0b7301e0",
|
||||||
|
"services/local_s2s/assets.py": "a16ae47b5fe196883662333cc849d0d4c301a9339b480926a721a436cb60b8cb",
|
||||||
|
"services/local_s2s/components.py": "b2f153e0ca9c230a62363dce4bdee10ca5da4e7b6367e3c525ca3cceeb623cea",
|
||||||
|
"services/local_s2s/engine.py": "497d034b3fd974c8d01db3bbc8af0df7295faa770c70d3294307d7af5a485f79",
|
||||||
|
"services/local_s2s/extension.py": "30f1435241284e2c5233cc6f45c703e10873454c77295f8bc97ee0b76ae83430",
|
||||||
|
"services/local_s2s/lifecycle.py": "5e59a4194d13fc4399464734403ee6355b9d8558ef0663f5cf0b66a48b3a2225",
|
||||||
|
"services/local_s2s/pipeline.yaml": "50c3fa906b0096db01dfdc8380cef72d6136eda10c699cb3cee317899ab25947",
|
||||||
|
"services/local_s2s/prepare_build.py": "11e2bde8ff448f0f909db2a42227f5f33d23c4a3af6f606132e90ea28892627e",
|
||||||
|
"services/local_s2s/request_policy.py": "0d4d322cf596e2b690699f77a1ab509c82688c9e44795ce42e0bdd5b3e21ba9f",
|
||||||
|
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
|
||||||
|
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
|
||||||
|
"tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
|
||||||
|
"tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
|
||||||
|
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
|
||||||
|
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
|
||||||
|
"tests/integration/test_local_s2s_phase2.py": "268346f00e5211063898319539a8f41161c5cc437cda8d0f968f26eafcae034b",
|
||||||
|
"tests/support/local_s2s_pinned.py": "db5bbb39ec364b1d5d67d5865e5ee82ee0fc84dfe60cc0d19555bd2fa8a7f048",
|
||||||
|
"tests/unit/test_local_s2s_boundary.py": "a7744bfb5fcc21be3f794d9d764f2ca4d91130182127896281005f65ae798345",
|
||||||
|
"tests/unit/test_local_s2s_engine.py": "fc8c84e8384f09640443a00411d81c6c520db33fbef3f7f8d70ca2ded468b4a9",
|
||||||
|
"tests/unit/test_local_s2s_phase2.py": "1d1f0199c92cbb47c671a2e19b8fe26bbbafef168bc7ac98f770b75706b4093e",
|
||||||
|
"tests/unit/test_local_s2s_repairs.py": "c076c2d51542ef4008cc358b0b15b74658f5685afbaa9a4359c82ab4fdf582da"
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"repair_regressions": {
|
||||||
|
"passed": 74,
|
||||||
|
"seconds": 7.68,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"final_combined": {
|
||||||
|
"passed": 107,
|
||||||
|
"seconds": 16.67,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"preservation": {
|
||||||
|
"passed": 242,
|
||||||
|
"seconds": 33.73,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"git_diff_check": "passed",
|
||||||
|
"compose_config_quiet": "passed",
|
||||||
|
"python_source_parse": 9,
|
||||||
|
"postgres": "executed fresh through guarded disposable runner; local passed, expanded non-green; historical results retained",
|
||||||
|
"paid_requests": 0,
|
||||||
|
"acceptance_local_postgres": {
|
||||||
|
"command": ".venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite local",
|
||||||
|
"pytest_arguments": [
|
||||||
|
"tests/integration/test_local_s2s_phase2.py",
|
||||||
|
"-m",
|
||||||
|
"postgres",
|
||||||
|
"--require-postgres",
|
||||||
|
"-q",
|
||||||
|
"--tb=short",
|
||||||
|
"-p",
|
||||||
|
"no:cacheprovider"
|
||||||
|
],
|
||||||
|
"passed": 2,
|
||||||
|
"failed": 0,
|
||||||
|
"skipped": 0,
|
||||||
|
"seconds": 5.18,
|
||||||
|
"exit_code": 0
|
||||||
|
},
|
||||||
|
"acceptance_expanded_postgres": {
|
||||||
|
"command": ".venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite expanded",
|
||||||
|
"pytest_arguments": [
|
||||||
|
"tests/integration/test_local_s2s_phase2.py",
|
||||||
|
"tests/integration/test_phase2_postgres.py",
|
||||||
|
"-m",
|
||||||
|
"postgres",
|
||||||
|
"--require-postgres",
|
||||||
|
"-q",
|
||||||
|
"--tb=short",
|
||||||
|
"-p",
|
||||||
|
"no:cacheprovider"
|
||||||
|
],
|
||||||
|
"passed": 57,
|
||||||
|
"failed": 6,
|
||||||
|
"skipped": 0,
|
||||||
|
"seconds": 236.5,
|
||||||
|
"exit_code": 1,
|
||||||
|
"failure_cases": [
|
||||||
|
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[ok-gemini]",
|
||||||
|
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[ok-openai]",
|
||||||
|
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[no_evidence-gemini]",
|
||||||
|
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[no_evidence-openai]",
|
||||||
|
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[error-gemini]",
|
||||||
|
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[error-openai]"
|
||||||
|
],
|
||||||
|
"diagnostic": "RESPONSE_ACK_DEADLINE",
|
||||||
|
"baseline_comparison": "same cases/diagnostic as previously reproduced immutable HEAD run; comparison not rerun in this checkpoint"
|
||||||
|
},
|
||||||
|
"acceptance_compose_configurations": {
|
||||||
|
"base": "passed",
|
||||||
|
"browser_override": "passed",
|
||||||
|
"phase1_plus_browser_overrides": "passed",
|
||||||
|
"phase1_private_boundary_assertions": "passed",
|
||||||
|
"launched": false
|
||||||
|
},
|
||||||
|
"asset_manifest_validation": {
|
||||||
|
"passed": true,
|
||||||
|
"files": 201,
|
||||||
|
"nltk_actual_load_passed": true,
|
||||||
|
"linux_engine_validated": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"test_container_final_state": "stopped-retained",
|
||||||
|
"previous_checkpoint": {
|
||||||
|
"expected_candidate_profile": {
|
||||||
|
"provider": "local_s2s",
|
||||||
|
"model": "openai/gpt-4.1-mini",
|
||||||
|
"voice": "Kore",
|
||||||
|
"input_sample_rate": 24000,
|
||||||
|
"output_sample_rate": 24000,
|
||||||
|
"evidence_policy_revision": "same-session-evidence-retained-v5",
|
||||||
|
"development_only": true,
|
||||||
|
"interruption_policy": "close_until_phase3",
|
||||||
|
"local_s2s": {
|
||||||
|
"engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||||
|
"patch_revision": "rag-local-s2s-phase2-v1",
|
||||||
|
"contract_revision": "rag-local-s2s-phase2-v1",
|
||||||
|
"components": {
|
||||||
|
"stt": {
|
||||||
|
"backend": "openai",
|
||||||
|
"model": "openai/whisper-large-v3",
|
||||||
|
"language": "fa",
|
||||||
|
"response_format": "json",
|
||||||
|
"final_only": true
|
||||||
|
},
|
||||||
|
"llm": {
|
||||||
|
"backend": "chat-completions",
|
||||||
|
"model": "openai/gpt-4.1-mini",
|
||||||
|
"max_output_tokens": 256
|
||||||
|
},
|
||||||
|
"tts": {
|
||||||
|
"backend": "openai",
|
||||||
|
"model": "google/gemini-3.8-flash-lite-tts",
|
||||||
|
"voice": "Kore",
|
||||||
|
"response_format": "pcm",
|
||||||
|
"sample_rate": 24000
|
||||||
|
},
|
||||||
|
"request_timeout_seconds": 30.0
|
||||||
|
},
|
||||||
|
"effective_config_sha256": "049a34b0d42ddb000d34dd52ab49844e3af958ab96eac4614c8a463236aa72a5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"files": {
|
||||||
|
"app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
|
||||||
|
"app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
|
||||||
|
"app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
|
||||||
|
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
|
||||||
|
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
|
||||||
|
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
|
||||||
|
"app/modules/voice/local_s2s.py": "dced0769bebb599aaa6af1e7dd8de3f89fa3a847a608d94f9f185f8064e49732",
|
||||||
|
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
|
||||||
|
"docker-compose.local-s2s-test.yml": "a3bb148f38b01915721f658bbe3cc6d56245fb6eb426955eb1cf6f11e4b90243",
|
||||||
|
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
|
||||||
|
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
|
||||||
|
"services/local_s2s/README.md": "99d079cbb0d2aee69254d866565f2b9c4101854823eacf842ae22de0df73a242",
|
||||||
|
"services/local_s2s/components.py": "d1cc832bb753248879429e93c134dbd4ea8e017a7dae804773ef9fbf12841f28",
|
||||||
|
"services/local_s2s/engine.py": "4e34793afd6c9fbe63d3542066a8a1388ad47fe49cdb5b589e280bdf464aea41",
|
||||||
|
"services/local_s2s/extension.py": "ae3834849d3e1534bbed609c3c9291719d3c7d8ba15551a75a2f4c312a4fc14c",
|
||||||
|
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
|
||||||
|
"services/local_s2s/prepare_build.py": "03ed65a5dd3da2f5f80a857b99d7e986c6302658ebc1ff1c0ed2e55a13653a02",
|
||||||
|
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
|
||||||
|
"tests/unit/test_local_s2s_engine.py": "8a89d6723434c9d5b4682abd01fd59972b151c5889b85466f27fcec32871b6c6",
|
||||||
|
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf"
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"final_combined_passed": 107,
|
||||||
|
"new_postgres_passed": 2,
|
||||||
|
"expanded_postgres_passed": 57,
|
||||||
|
"expanded_postgres_failed": 6,
|
||||||
|
"expanded_failures_reproduced_on_head": 6,
|
||||||
|
"paid_requests": 0
|
||||||
|
},
|
||||||
|
"test_container_final_state": "stopped-retained"
|
||||||
|
},
|
||||||
|
"patch_revision": "rag-local-s2s-phase2-v3",
|
||||||
|
"contract_revision": "rag-local-s2s-phase2-v1",
|
||||||
|
"acceptance_verdict": "offline_repairs_verified_live_acceptance_pending",
|
||||||
|
"phase_status": "in_progress",
|
||||||
|
"repair_checkpoint": {
|
||||||
|
"upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
|
||||||
|
"conformance": "hash-checked original pinned methods with isolated SDK/history/ML dependencies; real HTTPX and downstream/upstream TCP loopback transport checks; full SDK/engine unexecuted",
|
||||||
|
"full_sdk_ml_engine_conformance": false,
|
||||||
|
"signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
|
||||||
|
"paid_requests": 0,
|
||||||
|
"dependency_downloads": 0,
|
||||||
|
"model_downloads": 0,
|
||||||
|
"image_builds": 0,
|
||||||
|
"operational_changes": 0,
|
||||||
|
"postgres_acceptance": "not run; no disposable TEST_DATABASE_URL verified/used in this checkpoint",
|
||||||
|
"reservations_rewritten": false,
|
||||||
|
"required_local_assets": {
|
||||||
|
"manifest_schema": 1,
|
||||||
|
"manifest_sha256": "8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8",
|
||||||
|
"nltk_root": "/assets/nltk",
|
||||||
|
"vad_root": "/vad/silero-vad",
|
||||||
|
"manifest_path": "/assets/assets.json",
|
||||||
|
"provisioned": true,
|
||||||
|
"provisioning_scope": "existing host resources only; Linux engine validation pending"
|
||||||
|
},
|
||||||
|
"remaining_gates": [
|
||||||
|
"Phase 1 real OpenAI interaction/listening",
|
||||||
|
"reviewed dependency hash lock and immutable base image digest",
|
||||||
|
"provisioned fingerprinted NLTK and VAD assets",
|
||||||
|
"real pinned engine and complete SDK conformance",
|
||||||
|
"authorized component STT/LLM/TTS audio checks",
|
||||||
|
"isolated Persian browser greeting/transcripts/normal close"
|
||||||
|
],
|
||||||
|
"disconnect_cleanup_window_seconds": 1.0,
|
||||||
|
"disconnect_test_request_deadline_seconds": 5,
|
||||||
|
"disconnect_test_scheduling_tolerance_seconds": 0.6,
|
||||||
|
"half_close_policy": {
|
||||||
|
"ordinary_eof": "explicit cancellation, not inferred inability to receive",
|
||||||
|
"receive_only_header": "X-Local-S2S-Half-Close: receive-response",
|
||||||
|
"declared_fin": "complete bounded response; a subsequent graceful full close is indistinguishable",
|
||||||
|
"reset": "cancellation"
|
||||||
|
},
|
||||||
|
"warmup_constant": {
|
||||||
|
"name": "WARMUP_MAX_RETRIES",
|
||||||
|
"value": 6,
|
||||||
|
"fixture": "tests/fixtures/local_s2s_upstream/base.py.source",
|
||||||
|
"line": 66,
|
||||||
|
"extraction": "literal AST from hash-checked pinned source",
|
||||||
|
"prior_harness_override": 10,
|
||||||
|
"correction": "prior v2 descriptions incorrectly called the isolated value 10 upstream; historical execution results retained"
|
||||||
|
},
|
||||||
|
"identifier_validator": "LocalS2SSettings.local_component_identifier; VoiceSettings.identifier unchanged",
|
||||||
|
"scoped_diff": "docs/evaluation/local-s2s/phase-02-remaining-repairs.patch"
|
||||||
|
},
|
||||||
|
"checkpoint_history": [
|
||||||
|
{
|
||||||
|
"patch_revision": "rag-local-s2s-phase2-v2",
|
||||||
|
"expected_candidate_profile": {
|
||||||
|
"provider": "local_s2s",
|
||||||
|
"model": "openai/gpt-4.1-mini",
|
||||||
|
"voice": "Kore",
|
||||||
|
"input_sample_rate": 24000,
|
||||||
|
"output_sample_rate": 24000,
|
||||||
|
"evidence_policy_revision": "same-session-evidence-retained-v5",
|
||||||
|
"development_only": true,
|
||||||
|
"interruption_policy": "close_until_phase3",
|
||||||
|
"local_s2s": {
|
||||||
|
"engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||||
|
"patch_revision": "rag-local-s2s-phase2-v2",
|
||||||
|
"contract_revision": "rag-local-s2s-phase2-v1",
|
||||||
|
"components": {
|
||||||
|
"stt": {
|
||||||
|
"backend": "openai",
|
||||||
|
"model": "openai/whisper-large-v3",
|
||||||
|
"language": "fa",
|
||||||
|
"response_format": "json",
|
||||||
|
"final_only": true
|
||||||
|
},
|
||||||
|
"llm": {
|
||||||
|
"backend": "chat-completions",
|
||||||
|
"model": "openai/gpt-4.1-mini",
|
||||||
|
"max_output_tokens": 256
|
||||||
|
},
|
||||||
|
"tts": {
|
||||||
|
"backend": "openai",
|
||||||
|
"model": "google/gemini-3.8-flash-lite-tts",
|
||||||
|
"voice": "Kore",
|
||||||
|
"response_format": "pcm",
|
||||||
|
"sample_rate": 24000
|
||||||
|
},
|
||||||
|
"request_timeout_seconds": 30.0
|
||||||
|
},
|
||||||
|
"effective_config_sha256": "049a34b0d42ddb000d34dd52ab49844e3af958ab96eac4614c8a463236aa72a5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"files": {
|
||||||
|
".env.example": "c3b849f91611809200b832017a699d57c14fee3d7694c8227015fac78f85caa0",
|
||||||
|
"app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
|
||||||
|
"app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
|
||||||
|
"app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
|
||||||
|
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
|
||||||
|
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
|
||||||
|
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
|
||||||
|
"app/modules/voice/local_s2s.py": "65d86f2483ad2b3150aea5983f7690007ff043d1e2bc3c877bdbfa74ad3f36e2",
|
||||||
|
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
|
||||||
|
"docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
|
||||||
|
"docs/agent-reference-map.md": "1deba7eb98f045f49326e27ae6c20586f31989f5856d497a0c82904bc2dc6f92",
|
||||||
|
"docs/evaluation/local-s2s/phase-02.md": "885ad1c3e7f2f81e74677d9eed29fc4b36898677133b916df84fbafbdc07003e",
|
||||||
|
"docs/plans/local-s2s-adapter-progress.md": "8b42970f412ca14117daf5b2db7e393e355620fa3358ff9246f4333a4ef88629",
|
||||||
|
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
|
||||||
|
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
|
||||||
|
"services/local_s2s/README.md": "241d6e9942ee55794f79a5055622585358d6fd3a8906eb260fae6048f5a7f3f4",
|
||||||
|
"services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
|
||||||
|
"services/local_s2s/components.py": "caa60d0001e8c637c85aae2deb387291ca469e244665f64219cfaf01e6442290",
|
||||||
|
"services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
|
||||||
|
"services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
|
||||||
|
"services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
|
||||||
|
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
|
||||||
|
"services/local_s2s/prepare_build.py": "a2718307a85128c053aff82612c54ab2f6f170f921e05e9aca42b3cf18b9b4b3",
|
||||||
|
"services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
|
||||||
|
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
|
||||||
|
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
|
||||||
|
"tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
|
||||||
|
"tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
|
||||||
|
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
|
||||||
|
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
|
||||||
|
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
|
||||||
|
"tests/support/local_s2s_pinned.py": "25003276c7c6b557bb9861147702a81ab446219e527a4951897785837c1a09bb",
|
||||||
|
"tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
|
||||||
|
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
|
||||||
|
"tests/unit/test_local_s2s_repairs.py": "a57a8a09a3f213cead8437e0835fae41f5cac349c0c4f60e8871512ac4e8186d"
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"repair_regressions": {
|
||||||
|
"passed": 31,
|
||||||
|
"seconds": 6.82,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"final_combined": {
|
||||||
|
"passed": 107,
|
||||||
|
"seconds": 18.66,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"preservation": {
|
||||||
|
"passed": 242,
|
||||||
|
"seconds": 34.11,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"git_diff_check": "passed",
|
||||||
|
"compose_config_quiet": "passed",
|
||||||
|
"python_source_parse": 9,
|
||||||
|
"postgres": "not run in repair checkpoint; prior results retained under previous_checkpoint",
|
||||||
|
"paid_requests": 0
|
||||||
|
},
|
||||||
|
"repair_checkpoint": {
|
||||||
|
"upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
|
||||||
|
"conformance": "hash-checked original upstream setup/process/request/warmup/stop methods with isolated SDK I/O and ML/history stand-ins; actual HTTPX payload and loopback transport assertions",
|
||||||
|
"full_sdk_ml_engine_conformance": false,
|
||||||
|
"signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
|
||||||
|
"paid_requests": 0,
|
||||||
|
"dependency_downloads": 0,
|
||||||
|
"model_downloads": 0,
|
||||||
|
"image_builds": 0,
|
||||||
|
"operational_changes": 0,
|
||||||
|
"postgres_acceptance": "not run; no disposable TEST_DATABASE_URL verified/used in this checkpoint",
|
||||||
|
"reservations_rewritten": false,
|
||||||
|
"required_local_assets": {
|
||||||
|
"manifest_schema": 1,
|
||||||
|
"manifest_sha256": null,
|
||||||
|
"nltk_root": "/assets/nltk",
|
||||||
|
"vad_root": "/vad/silero-vad",
|
||||||
|
"manifest_path": "/assets/assets.json",
|
||||||
|
"provisioned": false
|
||||||
|
},
|
||||||
|
"remaining_gates": [
|
||||||
|
"Phase 1 real OpenAI interaction/listening",
|
||||||
|
"reviewed dependency hash lock and immutable base image digest",
|
||||||
|
"provisioned fingerprinted NLTK and VAD assets",
|
||||||
|
"real pinned engine and complete SDK conformance",
|
||||||
|
"authorized component STT/LLM/TTS audio checks",
|
||||||
|
"isolated Persian browser greeting/transcripts/normal close"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "v3 reviewed offline checkpoint before acceptance preparation",
|
||||||
|
"patch_revision": "rag-local-s2s-phase2-v3",
|
||||||
|
"files": {
|
||||||
|
".env.example": "c3b849f91611809200b832017a699d57c14fee3d7694c8227015fac78f85caa0",
|
||||||
|
"app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
|
||||||
|
"app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
|
||||||
|
"app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
|
||||||
|
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
|
||||||
|
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
|
||||||
|
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
|
||||||
|
"app/modules/voice/local_s2s.py": "10b27361116ef2284ac1a2fff9e1df29bec8017278b1139fe4c34e9f26c67a34",
|
||||||
|
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
|
||||||
|
"docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
|
||||||
|
"docs/agent-reference-map.md": "1deba7eb98f045f49326e27ae6c20586f31989f5856d497a0c82904bc2dc6f92",
|
||||||
|
"docs/evaluation/local-s2s/phase-02.md": "12f0d26dcf347586e8c610eb27f15a93efc3088bd429c128fb5ba134ee71fb70",
|
||||||
|
"docs/plans/local-s2s-adapter-progress.md": "d99a465c0bc3f16d0a2a614412ed2df131d1d50d1270a0bd6139b1ce4d9d5e9d",
|
||||||
|
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
|
||||||
|
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
|
||||||
|
"services/local_s2s/README.md": "d7a411f7dfd8410ceb58b229dcf9603f031dc83acfa78bf4ec0d16404b81e10e",
|
||||||
|
"services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
|
||||||
|
"services/local_s2s/components.py": "fe6f5bd4121b1c68bc3d4747fde82c540cf37d3f459d4a3f6aed0d859124e317",
|
||||||
|
"services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
|
||||||
|
"services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
|
||||||
|
"services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
|
||||||
|
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
|
||||||
|
"services/local_s2s/prepare_build.py": "89885abcd198a9efdedad403b9e34cc88b81935586c17e6221406204b7313b4e",
|
||||||
|
"services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
|
||||||
|
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
|
||||||
|
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
|
||||||
|
"tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
|
||||||
|
"tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
|
||||||
|
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
|
||||||
|
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
|
||||||
|
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
|
||||||
|
"tests/support/local_s2s_pinned.py": "9b82e843f1598eae104c04e27e700bb1b10c391d49f194cbf7de3eb1d6ab286e",
|
||||||
|
"tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
|
||||||
|
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
|
||||||
|
"tests/unit/test_local_s2s_repairs.py": "9cd2298ca3d19cdb34ab3548017ecda8efb02c5b1ed5bddb0b5c727f6985a47e"
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"repair_regressions": {
|
||||||
|
"passed": 74,
|
||||||
|
"seconds": 7.68,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"final_combined": {
|
||||||
|
"passed": 107,
|
||||||
|
"seconds": 16.67,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"preservation": {
|
||||||
|
"passed": 242,
|
||||||
|
"seconds": 33.73,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"git_diff_check": "passed",
|
||||||
|
"compose_config_quiet": "passed",
|
||||||
|
"python_source_parse": 9,
|
||||||
|
"postgres": "not run in repair checkpoint; prior results retained under previous_checkpoint",
|
||||||
|
"paid_requests": 0
|
||||||
|
},
|
||||||
|
"repair_checkpoint": {
|
||||||
|
"upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
|
||||||
|
"conformance": "hash-checked original pinned methods with isolated SDK/history/ML dependencies; real HTTPX and downstream/upstream TCP loopback transport checks; full SDK/engine unexecuted",
|
||||||
|
"full_sdk_ml_engine_conformance": false,
|
||||||
|
"signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
|
||||||
|
"paid_requests": 0,
|
||||||
|
"dependency_downloads": 0,
|
||||||
|
"model_downloads": 0,
|
||||||
|
"image_builds": 0,
|
||||||
|
"operational_changes": 0,
|
||||||
|
"postgres_acceptance": "not run; no disposable TEST_DATABASE_URL verified/used in this checkpoint",
|
||||||
|
"reservations_rewritten": false,
|
||||||
|
"required_local_assets": {
|
||||||
|
"manifest_schema": 1,
|
||||||
|
"manifest_sha256": null,
|
||||||
|
"nltk_root": "/assets/nltk",
|
||||||
|
"vad_root": "/vad/silero-vad",
|
||||||
|
"manifest_path": "/assets/assets.json",
|
||||||
|
"provisioned": false
|
||||||
|
},
|
||||||
|
"remaining_gates": [
|
||||||
|
"Phase 1 real OpenAI interaction/listening",
|
||||||
|
"reviewed dependency hash lock and immutable base image digest",
|
||||||
|
"provisioned fingerprinted NLTK and VAD assets",
|
||||||
|
"real pinned engine and complete SDK conformance",
|
||||||
|
"authorized component STT/LLM/TTS audio checks",
|
||||||
|
"isolated Persian browser greeting/transcripts/normal close"
|
||||||
|
],
|
||||||
|
"disconnect_cleanup_window_seconds": 1.0,
|
||||||
|
"disconnect_test_request_deadline_seconds": 5,
|
||||||
|
"disconnect_test_scheduling_tolerance_seconds": 0.6,
|
||||||
|
"half_close_policy": {
|
||||||
|
"ordinary_eof": "explicit cancellation, not inferred inability to receive",
|
||||||
|
"receive_only_header": "X-Local-S2S-Half-Close: receive-response",
|
||||||
|
"declared_fin": "complete bounded response; a subsequent graceful full close is indistinguishable",
|
||||||
|
"reset": "cancellation"
|
||||||
|
},
|
||||||
|
"warmup_constant": {
|
||||||
|
"name": "WARMUP_MAX_RETRIES",
|
||||||
|
"value": 6,
|
||||||
|
"fixture": "tests/fixtures/local_s2s_upstream/base.py.source",
|
||||||
|
"line": 66,
|
||||||
|
"extraction": "literal AST from hash-checked pinned source",
|
||||||
|
"prior_harness_override": 10,
|
||||||
|
"correction": "prior v2 descriptions incorrectly called the isolated value 10 upstream; historical execution results retained"
|
||||||
|
},
|
||||||
|
"identifier_validator": "LocalS2SSettings.local_component_identifier; VoiceSettings.identifier unchanged",
|
||||||
|
"scoped_diff": "docs/evaluation/local-s2s/phase-02-remaining-repairs.patch"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "acceptance preparation execution-byte fingerprints before Git packaging",
|
||||||
|
"files": {
|
||||||
|
".env.example": "c3b849f91611809200b832017a699d57c14fee3d7694c8227015fac78f85caa0",
|
||||||
|
"app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
|
||||||
|
"app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
|
||||||
|
"app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
|
||||||
|
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
|
||||||
|
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
|
||||||
|
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
|
||||||
|
"app/modules/voice/local_s2s.py": "10b27361116ef2284ac1a2fff9e1df29bec8017278b1139fe4c34e9f26c67a34",
|
||||||
|
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
|
||||||
|
"docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
|
||||||
|
"docs/agent-reference-map.md": "84c2bc8f977614cd3a1f582902f3a5c6ee148b5c8a98835f9ff8a2bca706c64f",
|
||||||
|
"docs/evaluation/local-s2s/acceptance-postgres.py": "cb58c6a7eba04588235d4227b76e4bf43e3ecf6a48c33258a5b035d4c9376957",
|
||||||
|
"docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml": "bb689597ac719b98ca2bd2510c9e42a673bf3963c2c655a4a77a1ea913d7468b",
|
||||||
|
"docs/evaluation/local-s2s/phase-01.md": "f1599ba3a8dd4ac10546d65b23bdb5e7bd282929dfeffbfc106d28b307d633ec",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-acceptance-checklist.md": "cff45f4c3a5992ab4f1ea426d8c30c75eacee5e770cc4021820ab4af47d30d7b",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-browser.override.yml": "c03dfacde7b1fddc4945681d067bb33f79017df8876038c7ce36c48c145ed6a7",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-browser.proxy.json": "6ede500f81c5402fd7bfa1f97e8156130205b2ad85c642447af8bc894d4e0dce",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-local-assets.json": "8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8",
|
||||||
|
"docs/evaluation/local-s2s/phase-02-remaining-repairs.patch": "325f3abaa7b70a1d1448beae5f4021351de524bb39d8fa79c0398089f9ca9066",
|
||||||
|
"docs/evaluation/local-s2s/phase-02.md": "18cc1b4281ef2f5d70733a3b3525d6a8379f7449e818fbdfb94fffbf3397d0b8",
|
||||||
|
"docs/plans/local-s2s-adapter-progress.md": "66b9ba930091ca8f8f50466c4d6eb9e0ad5140119e9b0f000646199d615499a8",
|
||||||
|
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
|
||||||
|
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
|
||||||
|
"services/local_s2s/README.md": "3bec6dd97b5cda2b70b97946a8ab077598bfe37f74360447820f1d973a45f389",
|
||||||
|
"services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
|
||||||
|
"services/local_s2s/components.py": "fe6f5bd4121b1c68bc3d4747fde82c540cf37d3f459d4a3f6aed0d859124e317",
|
||||||
|
"services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
|
||||||
|
"services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
|
||||||
|
"services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
|
||||||
|
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
|
||||||
|
"services/local_s2s/prepare_build.py": "89885abcd198a9efdedad403b9e34cc88b81935586c17e6221406204b7313b4e",
|
||||||
|
"services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
|
||||||
|
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
|
||||||
|
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
|
||||||
|
"tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
|
||||||
|
"tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
|
||||||
|
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
|
||||||
|
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
|
||||||
|
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
|
||||||
|
"tests/support/local_s2s_pinned.py": "9b82e843f1598eae104c04e27e700bb1b10c391d49f194cbf7de3eb1d6ab286e",
|
||||||
|
"tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
|
||||||
|
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
|
||||||
|
"tests/unit/test_local_s2s_repairs.py": "9cd2298ca3d19cdb34ab3548017ecda8efb02c5b1ed5bddb0b5c727f6985a47e"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"base_image_reference": "python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce",
|
||||||
|
"base_image_metadata": {
|
||||||
|
"os": "linux",
|
||||||
|
"architecture": "amd64",
|
||||||
|
"cached": true,
|
||||||
|
"candidate_built": false
|
||||||
|
},
|
||||||
|
"acceptance_preparation": {
|
||||||
|
"date": "2026-10-15",
|
||||||
|
"runtime_code_changed": false,
|
||||||
|
"reviewed_baseline": {
|
||||||
|
"repair": 74,
|
||||||
|
"combined": 107,
|
||||||
|
"preservation": 242,
|
||||||
|
"rerun": false,
|
||||||
|
"reason": "no material runtime changes; reviewed fingerprints verified unchanged"
|
||||||
|
},
|
||||||
|
"checklist": "docs/evaluation/local-s2s/phase-02-acceptance-checklist.md",
|
||||||
|
"authorization": {
|
||||||
|
"offline_preparation_and_isolated_database": "current user request",
|
||||||
|
"source_or_dependency_downloads": false,
|
||||||
|
"model_downloads": false,
|
||||||
|
"image_builds": false,
|
||||||
|
"paid_openai": false,
|
||||||
|
"paid_openrouter": false,
|
||||||
|
"consented_speech_supplied": false,
|
||||||
|
"prior_proposal_was_approved": false
|
||||||
|
},
|
||||||
|
"credentials_presence_only": {
|
||||||
|
"server_openai_configured": true,
|
||||||
|
"host_process_or_root_env_openrouter_configured": false,
|
||||||
|
"values_printed": false
|
||||||
|
},
|
||||||
|
"source": {
|
||||||
|
"required_engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||||
|
"sibling_head": "30af00916da85efb053b539a040fd71cf392e7e2",
|
||||||
|
"sibling_dirty": true,
|
||||||
|
"pin_object_present": false,
|
||||||
|
"clean_pinned_checkout_prepared": false
|
||||||
|
},
|
||||||
|
"assets": {
|
||||||
|
"manifest": "docs/evaluation/local-s2s/phase-02-local-assets.json",
|
||||||
|
"manifest_sha256": "8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8",
|
||||||
|
"file_count": 201,
|
||||||
|
"nltk_host_root": "C:/Users/A.mazaheri/AppData/Roaming/nltk_data",
|
||||||
|
"nltk_version": "3.10.3",
|
||||||
|
"actual_sentence_pos_validation": "passed with download entry points blocked in existing Windows sibling virtualenv",
|
||||||
|
"linux_engine_validation": false,
|
||||||
|
"source_assets_changed": false
|
||||||
|
},
|
||||||
|
"phase1": {
|
||||||
|
"accepted": false,
|
||||||
|
"changed_source_live_observation": null,
|
||||||
|
"listening": null,
|
||||||
|
"prepared_override": "docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml",
|
||||||
|
"configuration_parse": "passed",
|
||||||
|
"isolation_assertions": "passed",
|
||||||
|
"candidate_launched": false
|
||||||
|
},
|
||||||
|
"frontend": {
|
||||||
|
"checkout": "D:/raymand/projects/faq_chatbot_frontend",
|
||||||
|
"head": "815191588c59fc43434cc2454cab3a8b2f8c1648",
|
||||||
|
"preexisting_package_json_change_preserved": true,
|
||||||
|
"origin": "http://127.0.0.2:4201",
|
||||||
|
"candidate_proxy": "docs/evaluation/local-s2s/phase-02-browser.proxy.json",
|
||||||
|
"launched": false,
|
||||||
|
"source_changed": false
|
||||||
|
},
|
||||||
|
"complete_engine_sdk_runner": "not yet executable; requires full pinned source and locked Linux environment; AST fixtures do not meet this gate",
|
||||||
|
"actual_posix_termination": false,
|
||||||
|
"paid_requests": 0,
|
||||||
|
"downloads": 0,
|
||||||
|
"image_builds": 0,
|
||||||
|
"operational_writes": 0,
|
||||||
|
"postgres": {
|
||||||
|
"container_id": "e5da8c342ed59fc48a49856bfd76010feda45e4a221f640d34aa330a5cd8a7da",
|
||||||
|
"image": "sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a",
|
||||||
|
"host": "127.0.0.1",
|
||||||
|
"port": 55439,
|
||||||
|
"database": "rag_local_s2s_test",
|
||||||
|
"user": "local_s2s_test",
|
||||||
|
"volume": "9f19da047744737e9bc010ba69c2f22e347f898939d1d42f7bbbb97c4591a3b6",
|
||||||
|
"identity_and_no_operational_volume_overlap_verified": true,
|
||||||
|
"server_identity_verified": true,
|
||||||
|
"require_postgres": true,
|
||||||
|
"final_state": "exited",
|
||||||
|
"runner": "docs/evaluation/local-s2s/acceptance-postgres.py"
|
||||||
|
},
|
||||||
|
"remaining_gates": [
|
||||||
|
"bounded Phase 1 OpenAI consent and changed-source human listening",
|
||||||
|
"clean complete pinned source transfer/offline supply",
|
||||||
|
"reviewed Linux CPU dependency hash lock and explicit build/download authorization",
|
||||||
|
"Linux asset validation and complete pinned engine/SDK controlled-I/O runner",
|
||||||
|
"actual POSIX SIGINT/SIGTERM in-flight observations",
|
||||||
|
"OpenRouter key, bounded paid authorization and consented speech fixture",
|
||||||
|
"real component format/rate/audio observations",
|
||||||
|
"isolated Persian browser greeting/answer/user-assistant transcripts/normal close",
|
||||||
|
"expanded database suite remains non-green with documented baseline failures"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"files_hash_basis": "SHA-256 of staged Git blob bytes at commit packaging; execution working-tree byte fingerprints are preserved in checkpoint_history. This avoids platform newline ambiguity and excludes unrelated working-tree hunks."
|
||||||
|
}
|
||||||
@@ -0,0 +1,863 @@
|
|||||||
|
--- a/services/local_s2s/components.py
|
||||||
|
+++ b/services/local_s2s/components.py
|
||||||
|
@@ -3,8 +3,11 @@
|
||||||
|
from collections import Counter
|
||||||
|
import socket
|
||||||
|
from threading import Event, Thread
|
||||||
|
-import time
|
||||||
|
import httpx
|
||||||
|
+
|
||||||
|
+# One shared wall-clock window for cancellation, transport closure and slot release.
|
||||||
|
+CLEANUP_WINDOW_SECONDS = 1.0
|
||||||
|
+HALF_CLOSE_HEADER = 'x-local-s2s-half-close'
|
||||||
|
|
||||||
|
LIMITS = {'/v1/audio/transcriptions': (1100000, 65536),
|
||||||
|
'/v1/chat/completions': (1048576, 1048576),
|
||||||
|
@@ -79,8 +82,73 @@
|
||||||
|
async def _error(self, writer, status):
|
||||||
|
await self._write(writer, f'HTTP/1.1 {status} Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'.encode())
|
||||||
|
|
||||||
|
+ async def _watch_downstream(self, reader, writer, receive_only):
|
||||||
|
+ # FIN cannot distinguish full close from SHUT_WR. By contract it cancels
|
||||||
|
+ # ordinary requests; explicit receive-only clients may still read a reply.
|
||||||
|
+ try:
|
||||||
|
+ extra = await reader.read(1)
|
||||||
|
+ if not extra and receive_only:
|
||||||
|
+ await writer.wait_closed() # still observe a reset/transport loss
|
||||||
|
+ except (OSError, ValueError):
|
||||||
|
+ pass
|
||||||
|
+
|
||||||
|
+ async def _forward(self, client, writer, path, fields, body, response):
|
||||||
|
+ request = client.build_request('POST', 'https://openrouter.ai/api' + path,
|
||||||
|
+ headers={'Authorization': 'Bearer ' + self.key,
|
||||||
|
+ 'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'},
|
||||||
|
+ content=bytes(body))
|
||||||
|
+ # The owner closes the response independently, even if cancellation or a
|
||||||
|
+ # stalled stream prevents this operation from reaching normal completion.
|
||||||
|
+ result = await client.send(request, stream=True)
|
||||||
|
+ response.append(result)
|
||||||
|
+ if result.status_code != 200:
|
||||||
|
+ await self._error(writer, 502)
|
||||||
|
+ return
|
||||||
|
+ media = result.headers.get('content-type', '').split(';')[0]
|
||||||
|
+ expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream')
|
||||||
|
+ if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity':
|
||||||
|
+ await self._error(writer, 502)
|
||||||
|
+ return
|
||||||
|
+ await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media +
|
||||||
|
+ '\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii'))
|
||||||
|
+ total = 0
|
||||||
|
+ # No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
|
||||||
|
+ async for raw in result.aiter_bytes():
|
||||||
|
+ total += len(raw)
|
||||||
|
+ if total > LIMITS[path][1]:
|
||||||
|
+ raise ValueError('Response capacity')
|
||||||
|
+ for offset in range(0, len(raw), 8192):
|
||||||
|
+ part = raw[offset:offset + 8192]
|
||||||
|
+ await self._write(writer, f'{len(part):x}\r\n'.encode() + part + b'\r\n')
|
||||||
|
+ if not total:
|
||||||
|
+ raise ValueError('Empty component response')
|
||||||
|
+ await self._write(writer, b'0\r\n\r\n')
|
||||||
|
+
|
||||||
|
+ async def _close_owned(self, writer, tasks, client, response):
|
||||||
|
+ writer.close()
|
||||||
|
+ for task in tasks:
|
||||||
|
+ task.cancel()
|
||||||
|
+ # Close all transports independently; one stalled close must not defer
|
||||||
|
+ # another. asyncio.wait bounds the entire cleanup, including task joins.
|
||||||
|
+ closing = [asyncio.create_task(writer.wait_closed())]
|
||||||
|
+ if client is not None:
|
||||||
|
+ closing.append(asyncio.create_task(client.aclose()))
|
||||||
|
+ closing.extend(asyncio.create_task(result.aclose()) for result in response)
|
||||||
|
+ done, pending = await asyncio.wait(set(tasks) | set(closing), timeout=CLEANUP_WINDOW_SECONDS)
|
||||||
|
+ for task in done:
|
||||||
|
+ if not task.cancelled():
|
||||||
|
+ error = task.exception()
|
||||||
|
+ if task in closing and error is not None:
|
||||||
|
+ self.counts['close_errors'] += 1
|
||||||
|
+ if pending:
|
||||||
|
+ self.counts['close_errors'] += len(pending)
|
||||||
|
+ writer.transport.abort()
|
||||||
|
+ for task in pending:
|
||||||
|
+ task.cancel()
|
||||||
|
+ task.add_done_callback(lambda t: None if t.cancelled() else t.exception())
|
||||||
|
+
|
||||||
|
async def _serve(self, reader, writer, deadline):
|
||||||
|
- client = None
|
||||||
|
+ client, tasks, response = None, [], []
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout_at(deadline):
|
||||||
|
# Header acquisition has its own short bound, including partial headers.
|
||||||
|
@@ -97,7 +165,7 @@
|
||||||
|
if method != 'POST' or path not in LIMITS or version not in ('HTTP/1.0', 'HTTP/1.1'):
|
||||||
|
await self._error(writer, 403)
|
||||||
|
return
|
||||||
|
- request_limit, response_limit = LIMITS[path]
|
||||||
|
+ request_limit, _ = LIMITS[path]
|
||||||
|
size = int(fields.get('content-length', '-1'))
|
||||||
|
if 'transfer-encoding' in fields or not 0 < size <= request_limit:
|
||||||
|
await self._error(writer, 413)
|
||||||
|
@@ -111,34 +179,21 @@
|
||||||
|
if fields.get('authorization') != 'Bearer local-components':
|
||||||
|
await self._error(writer, 403)
|
||||||
|
return
|
||||||
|
+ half_close = fields.get(HALF_CLOSE_HEADER)
|
||||||
|
+ if half_close not in (None, 'receive-response'):
|
||||||
|
+ await self._error(writer, 400)
|
||||||
|
+ return
|
||||||
|
self.counts[path] += 1 # one admitted provider attempt, including failed probes
|
||||||
|
client = httpx.AsyncClient(transport=self.transport, timeout=httpx.Timeout(self.inactivity, connect=self.inactivity),
|
||||||
|
follow_redirects=False, trust_env=False)
|
||||||
|
- async with client.stream('POST', 'https://openrouter.ai/api' + path,
|
||||||
|
- headers={'Authorization': 'Bearer ' + self.key,
|
||||||
|
- 'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'}, content=bytes(body)) as result:
|
||||||
|
- if result.status_code != 200:
|
||||||
|
- await self._error(writer, 502)
|
||||||
|
- return
|
||||||
|
- media = result.headers.get('content-type', '').split(';')[0]
|
||||||
|
- expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream')
|
||||||
|
- if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity':
|
||||||
|
- await self._error(writer, 502)
|
||||||
|
- return
|
||||||
|
- await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media +
|
||||||
|
- '\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii'))
|
||||||
|
- total = 0
|
||||||
|
- # No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
|
||||||
|
- async for raw in result.aiter_bytes():
|
||||||
|
- total += len(raw)
|
||||||
|
- if total > response_limit:
|
||||||
|
- raise ValueError('Response capacity')
|
||||||
|
- for offset in range(0, len(raw), 8192):
|
||||||
|
- part = raw[offset:offset + 8192]
|
||||||
|
- await self._write(writer, f'{len(part):x}\r\n'.encode() + part + b'\r\n')
|
||||||
|
- if not total:
|
||||||
|
- raise ValueError('Empty component response')
|
||||||
|
- await self._write(writer, b'0\r\n\r\n')
|
||||||
|
+ forwarding = asyncio.create_task(self._forward(client, writer, path, fields, body, response))
|
||||||
|
+ watching = asyncio.create_task(self._watch_downstream(reader, writer, half_close == 'receive-response'))
|
||||||
|
+ tasks.extend((forwarding, watching))
|
||||||
|
+ done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||||
|
+ if forwarding in done:
|
||||||
|
+ forwarding.result()
|
||||||
|
+ else:
|
||||||
|
+ self.counts['disconnected'] += 1
|
||||||
|
except TimeoutError:
|
||||||
|
self.counts['expired'] += 1
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
@@ -148,17 +203,8 @@
|
||||||
|
asyncio.LimitOverrunError, httpx.HTTPError):
|
||||||
|
self.counts['failures'] += 1
|
||||||
|
finally:
|
||||||
|
- # Independent transport closure: failure never writes a successful final chunk.
|
||||||
|
- writer.close()
|
||||||
|
- if client is not None:
|
||||||
|
- try:
|
||||||
|
- await asyncio.wait_for(client.aclose(), .5)
|
||||||
|
- except (Exception, asyncio.CancelledError):
|
||||||
|
- self.counts['close_errors'] += 1
|
||||||
|
- try:
|
||||||
|
- await asyncio.wait_for(writer.wait_closed(), .5)
|
||||||
|
- except (Exception, asyncio.CancelledError):
|
||||||
|
- self.counts['close_errors'] += 1
|
||||||
|
+ # No successful terminal chunk is fabricated on any failure path.
|
||||||
|
+ await self._close_owned(writer, tasks, client, response)
|
||||||
|
|
||||||
|
def shutdown(self):
|
||||||
|
if self.loop is not None and self.loop.is_running():
|
||||||
|
--- a/app/modules/voice/local_s2s.py
|
||||||
|
+++ b/app/modules/voice/local_s2s.py
|
||||||
|
@@ -7,7 +7,7 @@
|
||||||
|
|
||||||
|
UPSTREAM_REVISION = '619e3fe4f71d1c6f35c15870d588a3638de34722'
|
||||||
|
CONTRACT_REVISION = 'rag-local-s2s-phase2-v1'
|
||||||
|
-PATCH_REVISION = 'rag-local-s2s-phase2-v2'
|
||||||
|
+PATCH_REVISION = 'rag-local-s2s-phase2-v3'
|
||||||
|
|
||||||
|
|
||||||
|
class LocalS2SSettings(BaseModel):
|
||||||
|
@@ -38,7 +38,7 @@
|
||||||
|
|
||||||
|
@field_validator('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
|
||||||
|
@classmethod
|
||||||
|
- def identifier(cls, value):
|
||||||
|
+ def local_component_identifier(cls, value):
|
||||||
|
if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value):
|
||||||
|
raise ValueError('Invalid local component identifier')
|
||||||
|
return value
|
||||||
|
--- a/services/local_s2s/prepare_build.py
|
||||||
|
+++ b/services/local_s2s/prepare_build.py
|
||||||
|
@@ -47,7 +47,7 @@
|
||||||
|
(target / 'requirements.in').write_text('\n'.join(sorted(set(dependencies))) + '\n', encoding='utf-8')
|
||||||
|
(target / 'build-manifest.json').write_text(json.dumps(dict(upstream=PIN, base_image=args.base_image,
|
||||||
|
upstream_pyproject_sha256=hashlib.sha256((source / 'pyproject.toml').read_bytes()).hexdigest(),
|
||||||
|
- patch_revision='rag-local-s2s-phase2-v2', built=False), indent=2) + '\n', encoding='utf-8')
|
||||||
|
+ patch_revision='rag-local-s2s-phase2-v3', built=False), indent=2) + '\n', encoding='utf-8')
|
||||||
|
print('Prepared source and dependency inputs. Resolve a Linux hash lock before building; no downloads performed.')
|
||||||
|
|
||||||
|
|
||||||
|
--- a/tests/support/local_s2s_pinned.py
|
||||||
|
+++ b/tests/support/local_s2s_pinned.py
|
||||||
|
@@ -26,3 +26,10 @@
|
||||||
|
module = ast.Module(body=[ast.ImportFrom(module='__future__', names=[ast.alias(name='annotations')], level=0)] + definitions, type_ignores=[])
|
||||||
|
exec(compile(ast.fix_missing_locations(module), str(ROOT / name), 'exec'), namespace)
|
||||||
|
return namespace
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+def constant(name, identifier):
|
||||||
|
+ """Read a literal from the hash-checked source, never a fixture override."""
|
||||||
|
+ node = next(n for n in tree(name).body if isinstance(n, ast.Assign)
|
||||||
|
+ and any(isinstance(t, ast.Name) and t.id == identifier for t in n.targets))
|
||||||
|
+ return ast.literal_eval(node.value)
|
||||||
|
--- a/tests/unit/test_local_s2s_repairs.py
|
||||||
|
+++ b/tests/unit/test_local_s2s_repairs.py
|
||||||
|
@@ -7,6 +7,7 @@
|
||||||
|
from pathlib import Path
|
||||||
|
import signal
|
||||||
|
import socket
|
||||||
|
+import socketserver
|
||||||
|
from threading import Event, Lock, Thread, Timer, current_thread, BoundedSemaphore
|
||||||
|
import time
|
||||||
|
from types import SimpleNamespace
|
||||||
|
@@ -14,10 +15,10 @@
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from services.local_s2s.request_policy import LimitedChatClient, install_client_policy
|
||||||
|
-from services.local_s2s.components import ComponentServer
|
||||||
|
+from services.local_s2s.components import ComponentServer, CLEANUP_WINDOW_SECONDS
|
||||||
|
from services.local_s2s.assets import REQUIRED_NLTK, REQUIRED_VAD, AssetError, validate_assets, configure_nltk, patch_pipeline_source
|
||||||
|
from services.local_s2s.lifecycle import cleanup, run_owned
|
||||||
|
-from tests.support.local_s2s_pinned import functions, tree, ROOT
|
||||||
|
+from tests.support.local_s2s_pinned import functions, tree, constant, ROOT
|
||||||
|
from tests.unit.test_local_s2s_phase2 import local_config
|
||||||
|
|
||||||
|
|
||||||
|
@@ -46,7 +47,7 @@
|
||||||
|
|
||||||
|
|
||||||
|
def upstream_handler(client):
|
||||||
|
- ns = dict(time=time, logger=logging.getLogger('pinned-fixture'), WARMUP_MAX_RETRIES=10,
|
||||||
|
+ ns = dict(time=time, logger=logging.getLogger('pinned-fixture'), WARMUP_MAX_RETRIES=constant('base.py.source', 'WARMUP_MAX_RETRIES'),
|
||||||
|
_build_chat_optional_kwargs=lambda *_: {})
|
||||||
|
functions('chat.py.source', [(None, '_request_chat_completions'),
|
||||||
|
('ChatCompletionsApiModelHandler', '_request'), ('ChatCompletionsApiModelHandler', 'warmup'),
|
||||||
|
@@ -155,8 +156,8 @@
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
-def gateway(handler=None, *, timeout=.2, inactivity=.1):
|
||||||
|
- server = ComponentServer('fixture-key', port=0, transport=httpx.MockTransport(handler or (lambda r: httpx.Response(503))),
|
||||||
|
+def gateway(handler=None, *, timeout=.2, inactivity=.1, transport=None):
|
||||||
|
+ server = ComponentServer('fixture-key', port=0, transport=transport or httpx.MockTransport(handler or (lambda r: httpx.Response(503))),
|
||||||
|
timeout=timeout, inactivity=inactivity)
|
||||||
|
thread = Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
@@ -421,3 +422,169 @@
|
||||||
|
monkeypatch.setattr(engine, 'build_runtime', lambda *a: calls.append('provider'))
|
||||||
|
assert engine.main() == 1 and calls == []
|
||||||
|
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+@contextmanager
|
||||||
|
+def loopback_upstream(*, headers=False, hang_close=False):
|
||||||
|
+ """Real local TCP upstream: cancellation must close its actual HTTP socket."""
|
||||||
|
+ entered, closed, transport_closed = Event(), Event(), Event()
|
||||||
|
+ class Handler(socketserver.BaseRequestHandler):
|
||||||
|
+ def handle(self):
|
||||||
|
+ self.request.settimeout(6)
|
||||||
|
+ try:
|
||||||
|
+ data = b''
|
||||||
|
+ while b'\r\n\r\n' not in data:
|
||||||
|
+ data += self.request.recv(4096)
|
||||||
|
+ head, body = data.split(b'\r\n\r\n', 1)
|
||||||
|
+ size = int(next(line.split(b':', 1)[1] for line in head.split(b'\r\n') if line.lower().startswith(b'content-length:')))
|
||||||
|
+ while len(body) < size:
|
||||||
|
+ body += self.request.recv(size - len(body))
|
||||||
|
+ if headers:
|
||||||
|
+ self.request.sendall(b'HTTP/1.1 200 OK\r\nContent-Type: audio/pcm\r\nTransfer-Encoding: chunked\r\n\r\n')
|
||||||
|
+ entered.set()
|
||||||
|
+ # No data is produced. Only owned cancellation closes this socket.
|
||||||
|
+ assert self.request.recv(1) == b''
|
||||||
|
+ except ConnectionResetError:
|
||||||
|
+ pass
|
||||||
|
+ finally:
|
||||||
|
+ closed.set()
|
||||||
|
+ class Server(socketserver.ThreadingTCPServer):
|
||||||
|
+ daemon_threads = True
|
||||||
|
+ remote = Server(('127.0.0.1', 0), Handler)
|
||||||
|
+ thread = Thread(target=remote.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
|
||||||
|
+ thread.start()
|
||||||
|
+ class Transport(httpx.AsyncHTTPTransport):
|
||||||
|
+ async def handle_async_request(self, request):
|
||||||
|
+ request.url = httpx.URL(f'http://127.0.0.1:{remote.server_address[1]}' + request.url.path)
|
||||||
|
+ return await super().handle_async_request(request)
|
||||||
|
+ async def aclose(self):
|
||||||
|
+ await super().aclose()
|
||||||
|
+ transport_closed.set()
|
||||||
|
+ if hang_close:
|
||||||
|
+ await asyncio.Event().wait()
|
||||||
|
+ try:
|
||||||
|
+ yield Transport(retries=0), entered, closed, transport_closed
|
||||||
|
+ finally:
|
||||||
|
+ remote.shutdown(); remote.server_close(); thread.join(1)
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+def speech_request(extra=b''):
|
||||||
|
+ return (b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 2\r\n'
|
||||||
|
+ b'Authorization: Bearer local-components\r\n' + extra + b'\r\n{}')
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+@pytest.mark.parametrize('headers', [False, True], ids=['before-upstream-headers', 'stalled-after-headers'])
|
||||||
|
+def test_disconnect_cancels_silent_real_upstream_and_releases_slot(headers):
|
||||||
|
+ with loopback_upstream(headers=headers) as (transport, entered, closed, transport_closed):
|
||||||
|
+ with gateway(transport=transport, timeout=5, inactivity=4) as server:
|
||||||
|
+ peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
|
||||||
|
+ try:
|
||||||
|
+ peer.sendall(speech_request())
|
||||||
|
+ assert entered.wait(1)
|
||||||
|
+ if headers:
|
||||||
|
+ received = b''
|
||||||
|
+ while b'\r\n\r\n' not in received:
|
||||||
|
+ received += peer.recv(4096)
|
||||||
|
+ assert received.startswith(b'HTTP/1.1 200')
|
||||||
|
+ assert not received.endswith(b'0\r\n\r\n')
|
||||||
|
+ began = time.monotonic()
|
||||||
|
+ finally:
|
||||||
|
+ peer.close()
|
||||||
|
+ assert closed.wait(CLEANUP_WINDOW_SECONDS + .4)
|
||||||
|
+ assert transport_closed.wait(.4)
|
||||||
|
+ wait_released(server)
|
||||||
|
+ assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
|
||||||
|
+ assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
|
||||||
|
+ assert server.counts['accepted'] == server.counts['released'] == 1
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+@pytest.mark.parametrize('half_close', [False, True], ids=['normal', 'declared-receive-only-half-close'])
|
||||||
|
+def test_success_and_declared_half_close_receive_complete_response(half_close):
|
||||||
|
+ entered = Event()
|
||||||
|
+ async def remote(request):
|
||||||
|
+ entered.set()
|
||||||
|
+ await asyncio.sleep(.08) # receive-side EOF precedes upstream headers
|
||||||
|
+ return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=b'xx')
|
||||||
|
+ with gateway(remote, timeout=2, inactivity=1) as server:
|
||||||
|
+ with socket.create_connection(('127.0.0.1', server.server_port), timeout=1) as peer:
|
||||||
|
+ peer.sendall(speech_request(b'X-Local-S2S-Half-Close: receive-response\r\n' if half_close else b''))
|
||||||
|
+ if half_close:
|
||||||
|
+ peer.shutdown(socket.SHUT_WR)
|
||||||
|
+ received = b''
|
||||||
|
+ while part := peer.recv(4096):
|
||||||
|
+ received += part
|
||||||
|
+ assert entered.is_set()
|
||||||
|
+ assert received.startswith(b'HTTP/1.1 200')
|
||||||
|
+ assert received.endswith(b'2\r\nxx\r\n0\r\n\r\n')
|
||||||
|
+ wait_released(server)
|
||||||
|
+ assert server.counts['disconnected'] == server.counts['expired'] == 0
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+def test_undeclared_half_close_is_explicit_cancellation_even_if_peer_can_receive():
|
||||||
|
+ with loopback_upstream() as (transport, entered, closed, transport_closed):
|
||||||
|
+ with gateway(transport=transport, timeout=5, inactivity=4) as server:
|
||||||
|
+ with socket.create_connection(('127.0.0.1', server.server_port), timeout=2) as peer:
|
||||||
|
+ peer.sendall(speech_request())
|
||||||
|
+ assert entered.wait(1)
|
||||||
|
+ peer.shutdown(socket.SHUT_WR)
|
||||||
|
+ assert peer.recv(4096) == b'' # policy cancellation, not inferred inability to receive
|
||||||
|
+ assert closed.wait(1) and transport_closed.wait(1)
|
||||||
|
+ wait_released(server)
|
||||||
|
+ assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+def test_disconnect_cleanup_has_shared_bound_even_if_transport_close_stalls():
|
||||||
|
+ with loopback_upstream(hang_close=True) as (transport, entered, closed, transport_closed):
|
||||||
|
+ with gateway(transport=transport, timeout=5, inactivity=4) as server:
|
||||||
|
+ peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
|
||||||
|
+ peer.sendall(speech_request())
|
||||||
|
+ assert entered.wait(1)
|
||||||
|
+ began = time.monotonic()
|
||||||
|
+ peer.close()
|
||||||
|
+ assert closed.wait(1) and transport_closed.wait(1)
|
||||||
|
+ wait_released(server)
|
||||||
|
+ assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
|
||||||
|
+ assert server.counts['close_errors'] >= 1
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+LOCAL_IDENTIFIERS = ('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
|
||||||
|
+@pytest.mark.parametrize('value', ['bad id', 'bad\tvalue', 'bad\nvalue', 'bad\x00value', 'bad\x7fvalue', 'bad\u00e9value'])
|
||||||
|
+def test_voice_settings_inherits_local_identifier_validation(field, value):
|
||||||
|
+ from pydantic import ValidationError
|
||||||
|
+ with pytest.raises(ValidationError, match='Invalid local component identifier'):
|
||||||
|
+ local_config(**{field: value}) # constructs the real VoiceSettings, not the base class
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
|
||||||
|
+def test_voice_settings_preserves_valid_local_identifiers(field):
|
||||||
|
+ value = 'vendor/Valid-Model_1.2'
|
||||||
|
+ assert getattr(local_config(**{field: value}), field) == value
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
|
||||||
|
+def test_invalid_local_identifiers_fail_before_assets_gateway_or_provider(monkeypatch, field, capsys):
|
||||||
|
+ from services.local_s2s import engine, assets, lifecycle
|
||||||
|
+ import sys
|
||||||
|
+ monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
|
||||||
|
+ monkeypatch.setenv('LOCAL_S2S_ALLOW_PAID_STARTUP', 'true')
|
||||||
|
+ monkeypatch.setenv(field.upper(), 'bad id')
|
||||||
|
+ calls = []
|
||||||
|
+ monkeypatch.setattr(assets, 'validate_assets', lambda *a: calls.append('assets'))
|
||||||
|
+ monkeypatch.setattr(lifecycle, 'run_owned', lambda *a: calls.append('provider'))
|
||||||
|
+ assert engine.main() == 1 and calls == []
|
||||||
|
+ assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+def test_warmup_retry_constant_is_read_from_hash_checked_upstream_source():
|
||||||
|
+ assert constant('base.py.source', 'WARMUP_MAX_RETRIES') == 6
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+@pytest.mark.parametrize('field', ['gemini_model', 'gemini_voice', 'openai_realtime_model', 'openai_realtime_voice'])
|
||||||
|
+def test_existing_provider_identifier_validators_remain_active(field):
|
||||||
|
+ from pydantic import ValidationError
|
||||||
|
+ with pytest.raises(ValidationError, match='Invalid voice profile identifier'):
|
||||||
|
+ local_config(**{field: 'bad id'})
|
||||||
|
+ assert getattr(local_config(**{field: 'Valid-1.2'}), field) == 'Valid-1.2'
|
||||||
|
--- a/services/local_s2s/README.md
|
||||||
|
+++ b/services/local_s2s/README.md
|
||||||
|
@@ -134,7 +134,8 @@
|
||||||
|
The request client policy is installed **before handler construction**. It puts
|
||||||
|
`max_tokens=LOCAL_S2S_MAX_OUTPUT_TOKENS` on every Chat Completions request, including
|
||||||
|
normal STT-derived text turns and the constructor's warmup, and forces zero retries
|
||||||
|
-even when pinned warmup asks `with_options(max_retries=10)`. The configured request
|
||||||
|
+even when pinned warmup asks `with_options(max_retries=6)` (see the provenance
|
||||||
|
+correction below; the earlier isolated harness supplied 10). The configured request
|
||||||
|
deadline also enters the actual base setup before warmup; attestation reads the
|
||||||
|
active client policy, not `gen_kwargs` (unused by that upstream text path).
|
||||||
|
|
||||||
|
@@ -202,3 +203,64 @@
|
||||||
|
Windows signal tests dispatch the installed handlers; they do not claim OS-level
|
||||||
|
POSIX signal delivery. Real engine, component audio and isolated Persian browser
|
||||||
|
greeting/transcripts/normal close evidence are still required for live acceptance.
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+## Phase 2 remaining repairs: extension v3
|
||||||
|
+
|
||||||
|
+Current behavior is `rag-local-s2s-phase2-v3`, with the v1 private contract shape.
|
||||||
|
+Fresh profiles and prepared build manifests use v3; v1/v2 reservations remain
|
||||||
|
+frozen and fail revision mismatch instead of being rewritten. Preserve earlier
|
||||||
|
+build inputs and prepare a fresh workspace for v3. The five v2 repairs remain.
|
||||||
|
+No browser events, PCM24k, retrieval authority or interruption capability changed.
|
||||||
|
+
|
||||||
|
+After the complete request body, an owned downstream watcher runs concurrently
|
||||||
|
+with upstream header acquisition and streaming. It does not need response data
|
||||||
|
+or a failed write to notice closure. Ordinary downstream EOF/reset cancels the
|
||||||
|
+upstream operation. Response/client closure and task joining share a **one-second
|
||||||
|
+cleanup window**, followed by slot release; stalled close operations are cancelled
|
||||||
|
+and the downstream transport is aborted when that window expires. Existing total
|
||||||
|
+and inactivity limits remain. Failed partial responses never gain a successful
|
||||||
|
+terminal HTTP chunk. Cancellation does not prove remote inference/billing stopped.
|
||||||
|
+
|
||||||
|
+TCP FIN alone cannot reveal whether a peer fully closed or only called SHUT_WR.
|
||||||
|
+The private component gateway therefore defines the following explicit policy:
|
||||||
|
+
|
||||||
|
+- Ordinary clients keep their send side open until completion. EOF is cancellation
|
||||||
|
+ by contract, even when that peer could still receive. SDK requests follow this path.
|
||||||
|
+- A client intentionally stopping its send side while retaining its receive side
|
||||||
|
+ must send `X-Local-S2S-Half-Close: receive-response` before the body. After a complete
|
||||||
|
+ body, FIN then allows the bounded response to finish. A reset/transport error still
|
||||||
|
+ cancels. A subsequent graceful full close is indistinguishable from the declared
|
||||||
|
+ half-close and remains bounded by the original request deadlines.
|
||||||
|
+- Other header values fail before provider admission; extra request bytes/pipelining
|
||||||
|
+ are unsupported. The half-close header is private, is not forwarded upstream and
|
||||||
|
+ does not change the browser protocol. The gateway closes its send side at completion.
|
||||||
|
+
|
||||||
|
+Real loopback tests exercise both downstream and upstream TCP sockets for disconnect
|
||||||
|
+before headers and after headers with no further upstream output. They assert local
|
||||||
|
+upstream socket closure, HTTP transport closure and slot release within the cleanup
|
||||||
|
+window plus scheduling tolerance, before the five-second test request deadline.
|
||||||
|
+Separate tests cover normal success, declared half-close success, undeclared FIN
|
||||||
|
+cancellation and a stalled transport close. They require no external services.
|
||||||
|
+
|
||||||
|
+The local identifier validator now has a distinct method name so VoiceSettings
|
||||||
|
+inherits it alongside its existing OpenAI/Gemini validator. All four local model/
|
||||||
|
+voice fields reject whitespace, controls and non-ASCII before assets, construction
|
||||||
|
+or probes. Valid identifiers and existing provider validation are retained.
|
||||||
|
+
|
||||||
|
+Provenance correction: the hash-checked pinned `base.py.source` defines
|
||||||
|
+`WARMUP_MAX_RETRIES = 6` at line 66; Chat Completions imports that constant. The v2
|
||||||
|
+harness injected 10 as an isolated override and incorrectly described it as the
|
||||||
|
+pinned value. Its historical 31/107/242 execution results remain unchanged, but
|
||||||
|
+that description was wrong. Current warmup tests read 6 from the verified source
|
||||||
|
+AST and test both retryable HTTP and connection failures with exactly one attempt.
|
||||||
|
+The full OpenAI SDK/ML engine still has not been executed.
|
||||||
|
+
|
||||||
|
+Final offline checks for v3: **74 repair, 107 combined and 242 preservation tests
|
||||||
|
+passed**, using `-p no:cacheprovider`. Compose configuration validation and
|
||||||
|
+`git diff --check` passed. Exact commands/timings and the scoped patch are in the
|
||||||
|
+[Phase 2 report](../../docs/evaluation/local-s2s/phase-02.md#remaining-defect-repair-checkpoint-extension-v3).
|
||||||
|
+No paid calls, downloads, image builds, operational changes or PostgreSQL acceptance
|
||||||
|
+were performed here. Phase 2 remains in_progress/live acceptance pending until
|
||||||
|
+real-engine, component-audio and isolated Persian browser greeting/transcripts/
|
||||||
|
+normal-close evidence exists, alongside the existing Phase 1 prerequisite.
|
||||||
|
--- a/docs/evaluation/local-s2s/phase-02.md
|
||||||
|
+++ b/docs/evaluation/local-s2s/phase-02.md
|
||||||
|
@@ -164,7 +164,7 @@
|
||||||
|
| Confirmed upstream behavior / defect | Scoped repair and evidence |
|
||||||
|
| --- | --- |
|
||||||
|
| Base `process()` handles STT text through Chat Completions `_request_chat_completions`; that path ignores the prior `gen_kwargs` cap. Constructor setup invokes warmup. | Install the client policy and configured setup timeout before construction. Every actual Chat Completions create receives `max_tokens`; pinned normal text, warmup and setup tests inspect JSON with nondefault limits 17/83 and 19/71. Active attestation reads the installed policy. |
|
||||||
|
-| Pinned `warmup()` explicitly clones the client with `WARMUP_MAX_RETRIES=10`. | Policy clones force zero retries; retryable HTTP 503 and connection failures each produce exactly one attempt. Counters count admitted failed probes. Owner construction/probe deadline is 90 seconds; per-exchange default is 30 seconds. |
|
||||||
|
+| Pinned `warmup()` explicitly clones the client with `WARMUP_MAX_RETRIES=6` (the earlier harness override was 10; correction below). | Policy clones force zero retries; retryable HTTP 503 and connection failures each produce exactly one attempt. Counters count admitted failed probes. Owner construction/probe deadline is 90 seconds; per-exchange default is 30 seconds. |
|
||||||
|
| Pipeline import catches missing punkt/tagger resources and calls `nltk.download`. | Build preparation replaces those blocks with local validation. Required NLTK files and local VAD bundle have a reviewed SHA-256 manifest and expected manifest digest. Preflight checks every asset and loads original sentence/POS functions before provider construction. Missing/corrupt/malformed assets or tokenizers attempting blocked downloads produce a fixed safe category with zero provider calls. No tokenizer substitution. |
|
||||||
|
| Prior gateway timing began after header acquisition and buffered streams in 8192-byte pieces. | Owned asynchronous connection lifecycle bounds silent/partial headers, body reads, upstream headers/reads and downstream drains. Total and inactivity deadlines are independent. Small SSE/PCM chunks flow immediately; expiration/disconnect cancels upstream, closes transports and releases slots. Failed partial chunked responses omit the terminal chunk. Tests exercise actual loopback sockets, cancellation and stalled writes. |
|
||||||
|
| Upstream `ConfiguredRuntime.stop()` can raise before clearing resources; `wait()` invokes stop. The launcher bypassed upstream command signal management. | Independent bounded runtime stop, gateway shutdown, socket close and thread join always produce numeric cleanup/request counters. Owned SIGINT/SIGTERM handlers signal the stop event and restore predecessors. Tests exercise the pinned failing stop method, a hung stop/construction and termination during an in-flight mock request. Windows tests dispatch installed handlers; OS-level POSIX signal delivery remains unverified. |
|
||||||
|
@@ -238,3 +238,92 @@
|
||||||
|
not an interpreter import failure. Scoped untracked repair files were also
|
||||||
|
checked for trailing whitespace. Compose validation parsed configuration only;
|
||||||
|
it did not create/start any service or print credentials.
|
||||||
|
+
|
||||||
|
+
|
||||||
|
+## Remaining-defect repair checkpoint: extension v3
|
||||||
|
+
|
||||||
|
+**Verdict: offline regressions passed; Phase 2 remains in_progress and live
|
||||||
|
+acceptance pending.** The five prior repairs remain; Phase 3 and operational
|
||||||
|
+services were untouched. The [scoped patch](phase-02-remaining-repairs.patch) is
|
||||||
|
+relative to this checkpoint's in-session pre-edit snapshots, so unrelated existing
|
||||||
|
+working-tree changes are excluded. Files: `services/local_s2s/components.py`,
|
||||||
|
+`app/modules/voice/local_s2s.py`, `services/local_s2s/prepare_build.py`, the pinned
|
||||||
|
+source harness and repair tests, operator guide, this report, provenance and ledger.
|
||||||
|
+No existing OpenAI/Gemini assertion was removed or relaxed.
|
||||||
|
+
|
||||||
|
+1. **Disconnect ownership.** A concurrent downstream watcher starts after the body
|
||||||
|
+ and cancels the owned forwarding task on ordinary EOF/reset, including before
|
||||||
|
+ upstream headers and while response streaming produces nothing. Response/client
|
||||||
|
+ transport closure and task joining share a one-second cleanup window; expiry
|
||||||
|
+ aborts the downstream transport, cancels remaining cleanup and releases the slot.
|
||||||
|
+ Total/inactivity deadlines and incomplete chunked failure remain intact.
|
||||||
|
+ Real upstream and downstream TCP loopback tests assert upstream socket closure,
|
||||||
|
+ transport closure and slot release before a five-second request deadline, with
|
||||||
|
+ a 0.6-second scheduling allowance beyond the cleanup window. A stalled close
|
||||||
|
+ test verifies the cleanup bound itself. The old continuous-output disconnect
|
||||||
|
+ test remains; the earlier v2 disconnect description alone did not establish
|
||||||
|
+ these stalled-upstream cases.
|
||||||
|
+2. **Half-close policy.** FIN cannot distinguish full close from SHUT_WR. For
|
||||||
|
+ ordinary requests, EOF is explicitly cancellation, even if the peer can receive.
|
||||||
|
+ Intentional receive-only half-close is supported with the private header
|
||||||
|
+ `X-Local-S2S-Half-Close: receive-response`; FIN after the complete body then keeps
|
||||||
|
+ response delivery alive, while reset/transport errors still cancel. A graceful
|
||||||
|
+ full close after that declaration is inherently indistinguishable and remains
|
||||||
|
+ bounded by request deadlines. This header is not forwarded upstream and is not
|
||||||
|
+ a browser event/API change. Loopback tests prove normal and declared half-close
|
||||||
|
+ success, plus undeclared half-close cancellation. Extra bytes/pipelining are
|
||||||
|
+ unsupported and unknown header values fail before provider admission.
|
||||||
|
+3. **Inherited validation.** Renamed only `LocalS2SSettings.identifier` to
|
||||||
|
+ `local_component_identifier`, avoiding Pydantic's inherited validator override
|
||||||
|
+ by `VoiceSettings.identifier`. Through the real VoiceSettings, all four local
|
||||||
|
+ STT/LLM/TTS model and TTS voice fields now reject whitespace, control and non-ASCII
|
||||||
|
+ values. Tests preserve valid identifiers, check unchanged OpenAI/Gemini validators
|
||||||
|
+ and verify invalid environment configuration fails before assets/gateway/provider
|
||||||
|
+ construction or probes.
|
||||||
|
+4. **Source provenance correction.** `WARMUP_MAX_RETRIES` is **6**, defined at
|
||||||
|
+ line 66 of hash-checked `base.py.source`, imported by `chat.py.source`. The v2
|
||||||
|
+ test harness supplied literal 10, an isolated override, and the report/guide
|
||||||
|
+ incorrectly identified it as upstream's value. Those descriptions are corrected;
|
||||||
|
+ historical execution counts/timings remain unchanged. The harness now extracts
|
||||||
|
+ the literal from the verified source AST, with an explicit value assertion.
|
||||||
|
+ Pinned warmup HTTP 503/connection-failure tests run using 6 and still assert one
|
||||||
|
+ attempt. Complete SDK retry/ML engine execution is not claimed.
|
||||||
|
+
|
||||||
|
+Intentional behavior changes use `rag-local-s2s-phase2-v3` in fresh identities and
|
||||||
|
+build manifests; the private shape revision remains v1. No old reservation or
|
||||||
|
+frozen profile was rewritten. Native fingerprints, browser PCM24k/events,
|
||||||
|
+authorization/replay/epoch checks and fail-safe unsupported interruption remain.
|
||||||
|
+Persistent provider credentials stay server-side. No terminal/history receipt
|
||||||
|
+was fabricated. The pinned source fixture bytes and hashes were not changed.
|
||||||
|
+
|
||||||
|
+Final commands and outcomes:
|
||||||
|
+
|
||||||
|
+```powershell
|
||||||
|
+.venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider
|
||||||
|
+# 74 passed in 7.68s (31 prior repairs retained; 43 added regressions)
|
||||||
|
+.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
|
||||||
|
+# 107 passed in 16.67s
|
||||||
|
+.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider
|
||||||
|
+# 242 passed in 33.73s
|
||||||
|
+docker compose -f docker-compose.local-s2s-test.yml config --quiet
|
||||||
|
+# Passed: parse only; no service started or rendered secrets printed
|
||||||
|
+git diff --check
|
||||||
|
+# Passed
|
||||||
|
+```
|
||||||
|
+
|
||||||
|
+The initial targeted run before the final existing-provider validation cases was
|
||||||
|
+70 passed in 7.35s. All requested final suites passed; no baseline failure was
|
||||||
|
+hidden or assertion weakened. Historical broader ordinary/DB failures above and
|
||||||
|
+in the Phase 1 report remain separate and unresolved. PostgreSQL was not run in
|
||||||
|
+this checkpoint: no verified disposable TEST_DATABASE_URL was used. Any later DB
|
||||||
|
+acceptance requires that verification and `--require-postgres`.
|
||||||
|
+
|
||||||
|
+Evidence boundaries and remaining gates: original upstream methods run with an
|
||||||
|
+isolated SDK/history/ML harness; HTTPX and the new loopback transport tests use real
|
||||||
|
+local sockets. These are offline fixture results, not complete engine/OpenAI SDK,
|
||||||
|
+provider-audio or browser acceptance. No paid calls, downloads, image builds,
|
||||||
|
+operational actions or Phase 3 work occurred. Still required: Phase 1 real OpenAI
|
||||||
|
+interaction/listening, reviewed Linux dependency hash lock and immutable base image
|
||||||
|
+digest, provisioned/fingerprinted NLTK and VAD assets, real pinned-engine/SDK
|
||||||
|
+conformance, authorized component audio, and isolated Persian browser greeting,
|
||||||
|
+transcripts and normal close. See the [v3 operator guide](../../../services/local_s2s/README.md#phase-2-remaining-repairs-extension-v3).
|
||||||
|
--- a/docs/evaluation/local-s2s/phase-02-provenance.json
|
||||||
|
+++ b/docs/evaluation/local-s2s/phase-02-provenance.json
|
||||||
|
@@ -12,7 +12,7 @@
|
||||||
|
"interruption_policy": "close_until_phase3",
|
||||||
|
"local_s2s": {
|
||||||
|
"engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||||
|
- "patch_revision": "rag-local-s2s-phase2-v2",
|
||||||
|
+ "patch_revision": "rag-local-s2s-phase2-v3",
|
||||||
|
"contract_revision": "rag-local-s2s-phase2-v1",
|
||||||
|
"components": {
|
||||||
|
"stt": {
|
||||||
|
@@ -56,22 +56,22 @@
|
||||||
|
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
|
||||||
|
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
|
||||||
|
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
|
||||||
|
- "app/modules/voice/local_s2s.py": "65d86f2483ad2b3150aea5983f7690007ff043d1e2bc3c877bdbfa74ad3f36e2",
|
||||||
|
+ "app/modules/voice/local_s2s.py": "10b27361116ef2284ac1a2fff9e1df29bec8017278b1139fe4c34e9f26c67a34",
|
||||||
|
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
|
||||||
|
"docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
|
||||||
|
"docs/agent-reference-map.md": "1deba7eb98f045f49326e27ae6c20586f31989f5856d497a0c82904bc2dc6f92",
|
||||||
|
- "docs/evaluation/local-s2s/phase-02.md": "885ad1c3e7f2f81e74677d9eed29fc4b36898677133b916df84fbafbdc07003e",
|
||||||
|
- "docs/plans/local-s2s-adapter-progress.md": "8b42970f412ca14117daf5b2db7e393e355620fa3358ff9246f4333a4ef88629",
|
||||||
|
+ "docs/evaluation/local-s2s/phase-02.md": "12f0d26dcf347586e8c610eb27f15a93efc3088bd429c128fb5ba134ee71fb70",
|
||||||
|
+ "docs/plans/local-s2s-adapter-progress.md": "d99a465c0bc3f16d0a2a614412ed2df131d1d50d1270a0bd6139b1ce4d9d5e9d",
|
||||||
|
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
|
||||||
|
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
|
||||||
|
- "services/local_s2s/README.md": "241d6e9942ee55794f79a5055622585358d6fd3a8906eb260fae6048f5a7f3f4",
|
||||||
|
+ "services/local_s2s/README.md": "d7a411f7dfd8410ceb58b229dcf9603f031dc83acfa78bf4ec0d16404b81e10e",
|
||||||
|
"services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
|
||||||
|
- "services/local_s2s/components.py": "caa60d0001e8c637c85aae2deb387291ca469e244665f64219cfaf01e6442290",
|
||||||
|
+ "services/local_s2s/components.py": "fe6f5bd4121b1c68bc3d4747fde82c540cf37d3f459d4a3f6aed0d859124e317",
|
||||||
|
"services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
|
||||||
|
"services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
|
||||||
|
"services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
|
||||||
|
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
|
||||||
|
- "services/local_s2s/prepare_build.py": "a2718307a85128c053aff82612c54ab2f6f170f921e05e9aca42b3cf18b9b4b3",
|
||||||
|
+ "services/local_s2s/prepare_build.py": "89885abcd198a9efdedad403b9e34cc88b81935586c17e6221406204b7313b4e",
|
||||||
|
"services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
|
||||||
|
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
|
||||||
|
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
|
||||||
|
@@ -80,25 +80,25 @@
|
||||||
|
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
|
||||||
|
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
|
||||||
|
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
|
||||||
|
- "tests/support/local_s2s_pinned.py": "25003276c7c6b557bb9861147702a81ab446219e527a4951897785837c1a09bb",
|
||||||
|
+ "tests/support/local_s2s_pinned.py": "9b82e843f1598eae104c04e27e700bb1b10c391d49f194cbf7de3eb1d6ab286e",
|
||||||
|
"tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
|
||||||
|
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
|
||||||
|
- "tests/unit/test_local_s2s_repairs.py": "a57a8a09a3f213cead8437e0835fae41f5cac349c0c4f60e8871512ac4e8186d"
|
||||||
|
+ "tests/unit/test_local_s2s_repairs.py": "9cd2298ca3d19cdb34ab3548017ecda8efb02c5b1ed5bddb0b5c727f6985a47e"
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"repair_regressions": {
|
||||||
|
- "passed": 31,
|
||||||
|
- "seconds": 6.82,
|
||||||
|
+ "passed": 74,
|
||||||
|
+ "seconds": 7.68,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"final_combined": {
|
||||||
|
"passed": 107,
|
||||||
|
- "seconds": 18.66,
|
||||||
|
+ "seconds": 16.67,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"preservation": {
|
||||||
|
"passed": 242,
|
||||||
|
- "seconds": 34.11,
|
||||||
|
+ "seconds": 33.73,
|
||||||
|
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
|
||||||
|
},
|
||||||
|
"git_diff_check": "passed",
|
||||||
|
@@ -179,13 +179,13 @@
|
||||||
|
},
|
||||||
|
"test_container_final_state": "stopped-retained"
|
||||||
|
},
|
||||||
|
- "patch_revision": "rag-local-s2s-phase2-v2",
|
||||||
|
+ "patch_revision": "rag-local-s2s-phase2-v3",
|
||||||
|
"contract_revision": "rag-local-s2s-phase2-v1",
|
||||||
|
"acceptance_verdict": "offline_repairs_verified_live_acceptance_pending",
|
||||||
|
"phase_status": "in_progress",
|
||||||
|
"repair_checkpoint": {
|
||||||
|
"upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
|
||||||
|
- "conformance": "hash-checked original upstream setup/process/request/warmup/stop methods with isolated SDK I/O and ML/history stand-ins; actual HTTPX payload and loopback transport assertions",
|
||||||
|
+ "conformance": "hash-checked original pinned methods with isolated SDK/history/ML dependencies; real HTTPX and downstream/upstream TCP loopback transport checks; full SDK/engine unexecuted",
|
||||||
|
"full_sdk_ml_engine_conformance": false,
|
||||||
|
"signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
|
||||||
|
"paid_requests": 0,
|
||||||
|
@@ -210,6 +210,157 @@
|
||||||
|
"real pinned engine and complete SDK conformance",
|
||||||
|
"authorized component STT/LLM/TTS audio checks",
|
||||||
|
"isolated Persian browser greeting/transcripts/normal close"
|
||||||
|
- ]
|
||||||
|
- }
|
||||||
|
+ ],
|
||||||
|
+ "disconnect_cleanup_window_seconds": 1.0,
|
||||||
|
+ "disconnect_test_request_deadline_seconds": 5,
|
||||||
|
+ "disconnect_test_scheduling_tolerance_seconds": 0.6,
|
||||||
|
+ "half_close_policy": {
|
||||||
|
+ "ordinary_eof": "explicit cancellation, not inferred inability to receive",
|
||||||
|
+ "receive_only_header": "X-Local-S2S-Half-Close: receive-response",
|
||||||
|
+ "declared_fin": "complete bounded response; a subsequent graceful full close is indistinguishable",
|
||||||
|
+ "reset": "cancellation"
|
||||||
|
+ },
|
||||||
|
+ "warmup_constant": {
|
||||||
|
+ "name": "WARMUP_MAX_RETRIES",
|
||||||
|
+ "value": 6,
|
||||||
|
+ "fixture": "tests/fixtures/local_s2s_upstream/base.py.source",
|
||||||
|
+ "line": 66,
|
||||||
|
+ "extraction": "literal AST from hash-checked pinned source",
|
||||||
|
+ "prior_harness_override": 10,
|
||||||
|
+ "correction": "prior v2 descriptions incorrectly called the isolated value 10 upstream; historical execution results retained"
|
||||||
|
+ },
|
||||||
|
+ "identifier_validator": "LocalS2SSettings.local_component_identifier; VoiceSettings.identifier unchanged",
|
||||||
|
+ "scoped_diff": "docs/evaluation/local-s2s/phase-02-remaining-repairs.patch"
|
||||||
|
+ },
|
||||||
|
+ "checkpoint_history": [
|
||||||
|
+ {
|
||||||
|
+ "patch_revision": "rag-local-s2s-phase2-v2",
|
||||||
|
+ "expected_candidate_profile": {
|
||||||
|
+ "provider": "local_s2s",
|
||||||
|
+ "model": "openai/gpt-4.1-mini",
|
||||||
|
+ "voice": "Kore",
|
||||||
|
+ "input_sample_rate": 24000,
|
||||||
|
+ "output_sample_rate": 24000,
|
||||||
|
+ "evidence_policy_revision": "same-session-evidence-retained-v5",
|
||||||
|
+ "development_only": true,
|
||||||
|
+ "interruption_policy": "close_until_phase3",
|
||||||
|
+ "local_s2s": {
|
||||||
|
+ "engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||||
|
+ "patch_revision": "rag-local-s2s-phase2-v2",
|
||||||
|
+ "contract_revision": "rag-local-s2s-phase2-v1",
|
||||||
|
+ "components": {
|
||||||
|
+ "stt": {
|
||||||
|
+ "backend": "openai",
|
||||||
|
+ "model": "openai/whisper-large-v3",
|
||||||
|
+ "language": "fa",
|
||||||
|
+ "response_format": "json",
|
||||||
|
+ "final_only": true
|
||||||
|
+ },
|
||||||
|
+ "llm": {
|
||||||
|
+ "backend": "chat-completions",
|
||||||
|
+ "model": "openai/gpt-4.1-mini",
|
||||||
|
+ "max_output_tokens": 256
|
||||||
|
+ },
|
||||||
|
+ "tts": {
|
||||||
|
+ "backend": "openai",
|
||||||
|
+ "model": "google/gemini-3.8-flash-lite-tts",
|
||||||
|
+ "voice": "Kore",
|
||||||
|
+ "response_format": "pcm",
|
||||||
|
+ "sample_rate": 24000
|
||||||
|
+ },
|
||||||
|
+ "request_timeout_seconds": 30.0
|
||||||
|
+ },
|
||||||
|
+ "effective_config_sha256": "049a34b0d42ddb000d34dd52ab49844e3af958ab96eac4614c8a463236aa72a5"
|
||||||
|
+ }
|
||||||
|
+ },
|
||||||
|
+ "files": {
|
||||||
|
+ ".env.example": "c3b849f91611809200b832017a699d57c14fee3d7694c8227015fac78f85caa0",
|
||||||
|
+ "app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
|
||||||
|
+ "app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
|
||||||
|
+ "app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
|
||||||
|
+ "app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
|
||||||
|
+ "app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
|
||||||
|
+ "app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
|
||||||
|
+ "app/modules/voice/local_s2s.py": "65d86f2483ad2b3150aea5983f7690007ff043d1e2bc3c877bdbfa74ad3f36e2",
|
||||||
|
+ "app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
|
||||||
|
+ "docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
|
||||||
|
+ "docs/agent-reference-map.md": "1deba7eb98f045f49326e27ae6c20586f31989f5856d497a0c82904bc2dc6f92",
|
||||||
|
+ "docs/evaluation/local-s2s/phase-02.md": "885ad1c3e7f2f81e74677d9eed29fc4b36898677133b916df84fbafbdc07003e",
|
||||||
|
+ "docs/plans/local-s2s-adapter-progress.md": "8b42970f412ca14117daf5b2db7e393e355620fa3358ff9246f4333a4ef88629",
|
||||||
|
+ "services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
|
||||||
|
+ "services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
|
||||||
|
+ "services/local_s2s/README.md": "241d6e9942ee55794f79a5055622585358d6fd3a8906eb260fae6048f5a7f3f4",
|
||||||
|
+ "services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
|
||||||
|
+ "services/local_s2s/components.py": "caa60d0001e8c637c85aae2deb387291ca469e244665f64219cfaf01e6442290",
|
||||||
|
+ "services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
|
||||||
|
+ "services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
|
||||||
|
+ "services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
|
||||||
|
+ "services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
|
||||||
|
+ "services/local_s2s/prepare_build.py": "a2718307a85128c053aff82612c54ab2f6f170f921e05e9aca42b3cf18b9b4b3",
|
||||||
|
+ "services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
|
||||||
|
+ "tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
|
||||||
|
+ "tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
|
||||||
|
+ "tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
|
||||||
|
+ "tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
|
||||||
|
+ "tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
|
||||||
|
+ "tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
|
||||||
|
+ "tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
|
||||||
|
+ "tests/support/local_s2s_pinned.py": "25003276c7c6b557bb9861147702a81ab446219e527a4951897785837c1a09bb",
|
||||||
|
+ "tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
|
||||||
|
+ "tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
|
||||||
|
+ "tests/unit/test_local_s2s_repairs.py": "a57a8a09a3f213cead8437e0835fae41f5cac349c0c4f60e8871512ac4e8186d"
|
||||||
|
+ },
|
||||||
|
+ "checks": {
|
||||||
|
+ "repair_regressions": {
|
||||||
|
+ "passed": 31,
|
||||||
|
+ "seconds": 6.82,
|
||||||
|
+ "command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
+ },
|
||||||
|
+ "final_combined": {
|
||||||
|
+ "passed": 107,
|
||||||
|
+ "seconds": 18.66,
|
||||||
|
+ "command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
|
||||||
|
+ },
|
||||||
|
+ "preservation": {
|
||||||
|
+ "passed": 242,
|
||||||
|
+ "seconds": 34.11,
|
||||||
|
+ "command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
|
||||||
|
+ },
|
||||||
|
+ "git_diff_check": "passed",
|
||||||
|
+ "compose_config_quiet": "passed",
|
||||||
|
+ "python_source_parse": 9,
|
||||||
|
+ "postgres": "not run in repair checkpoint; prior results retained under previous_checkpoint",
|
||||||
|
+ "paid_requests": 0
|
||||||
|
+ },
|
||||||
|
+ "repair_checkpoint": {
|
||||||
|
+ "upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
|
||||||
|
+ "conformance": "hash-checked original upstream setup/process/request/warmup/stop methods with isolated SDK I/O and ML/history stand-ins; actual HTTPX payload and loopback transport assertions",
|
||||||
|
+ "full_sdk_ml_engine_conformance": false,
|
||||||
|
+ "signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
|
||||||
|
+ "paid_requests": 0,
|
||||||
|
+ "dependency_downloads": 0,
|
||||||
|
+ "model_downloads": 0,
|
||||||
|
+ "image_builds": 0,
|
||||||
|
+ "operational_changes": 0,
|
||||||
|
+ "postgres_acceptance": "not run; no disposable TEST_DATABASE_URL verified/used in this checkpoint",
|
||||||
|
+ "reservations_rewritten": false,
|
||||||
|
+ "required_local_assets": {
|
||||||
|
+ "manifest_schema": 1,
|
||||||
|
+ "manifest_sha256": null,
|
||||||
|
+ "nltk_root": "/assets/nltk",
|
||||||
|
+ "vad_root": "/vad/silero-vad",
|
||||||
|
+ "manifest_path": "/assets/assets.json",
|
||||||
|
+ "provisioned": false
|
||||||
|
+ },
|
||||||
|
+ "remaining_gates": [
|
||||||
|
+ "Phase 1 real OpenAI interaction/listening",
|
||||||
|
+ "reviewed dependency hash lock and immutable base image digest",
|
||||||
|
+ "provisioned fingerprinted NLTK and VAD assets",
|
||||||
|
+ "real pinned engine and complete SDK conformance",
|
||||||
|
+ "authorized component STT/LLM/TTS audio checks",
|
||||||
|
+ "isolated Persian browser greeting/transcripts/normal close"
|
||||||
|
+ ]
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+ ]
|
||||||
|
}
|
||||||
|
--- a/docs/plans/local-s2s-adapter-progress.md
|
||||||
|
+++ b/docs/plans/local-s2s-adapter-progress.md
|
||||||
|
@@ -11,7 +11,7 @@
|
||||||
|
| Phase | Status | Evidence | Visible demo | Blockers |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| 1 - Preserve OpenAI and introduce the provider boundary | offline_complete_live_pending | [Phase 1 report](../evaluation/local-s2s/phase-01.md); baseline 215 passed, final focused 242 passed; full suite has 5 existing failures (details in report) | Before/after controlled-clock replay; command in report | Changed-source real OpenAI interaction/listening pending; build lock/image digest required before Phase 2 build |
|
||||||
|
-| 2 - Add an isolated local stack and browser voice session | in_progress | [Phase 2 report](../evaluation/local-s2s/phase-02.md); v2 repair checkpoint: 31 new regression, 107 final combined and 242 preservation checks passed; earlier 2 new PostgreSQL checks passed, expanded DB regressions have 6 failures reproduced on HEAD; DB not rerun for repairs | Playable offline test-tone WAV and simulated native audio/transcripts; real browser demo unrun | Phase 1 acceptance; dependency lock/base digest/fingerprinted NLTK and VAD assets; actual engine build/SDK conformance and authorized real Persian/browser checks |
|
||||||
|
+| 2 - Add an isolated local stack and browser voice session | in_progress | [Phase 2 report](../evaluation/local-s2s/phase-02.md); v3 repair checkpoint: 74 repair regressions (including 31 prior), 107 final combined and 242 preservation checks passed; pinned warmup constant corrected to 6; earlier 2 new PostgreSQL checks passed, expanded DB regressions have 6 failures reproduced on HEAD; DB not rerun for repairs | Playable offline test-tone WAV and simulated native audio/transcripts; real browser demo unrun | Phase 1 acceptance; dependency lock/base digest/fingerprinted NLTK and VAD assets; actual engine build/SDK conformance and authorized real Persian/browser checks |
|
||||||
|
| 3 - Complete interruption, shared RAG and used sources | not_started | Not run | Not demonstrated | Resolve prerequisites |
|
||||||
|
| 4 - Validate quality/cost and prove controlled switch/rollback | not_started | Not run | Not demonstrated | Resolve prerequisites |
|
||||||
|
|
||||||
@@ -0,0 +1,419 @@
|
|||||||
|
# Local S2S Phase 2 implementation report
|
||||||
|
|
||||||
|
Date: 2026-10-15. Status: **in_progress; offline candidate delivered, build/live acceptance pending**.
|
||||||
|
Phase 2 is **not accepted**. Phase 1 live acceptance remains open. No operational
|
||||||
|
provider switch, paid request, dependency/model download or engine build was performed.
|
||||||
|
|
||||||
|
## Delivered
|
||||||
|
|
||||||
|
- `local_s2s` configuration, factory and adapter alongside OpenAI/Gemini. It is
|
||||||
|
off by default and requires explicit development/transport-test opt-in.
|
||||||
|
- Immutable profile containing upstream/extension/contract revisions, component
|
||||||
|
models/voice, final-only Persian STT, fixed PCM24k and an effective configuration
|
||||||
|
digest. Secrets and secret-derived hashes are excluded.
|
||||||
|
- Versioned engine launcher/extension reading initialized component identities
|
||||||
|
and applied native session state. A session echo alone fails readiness.
|
||||||
|
Missing model/voice/rate/credential configuration fails safely; native input,
|
||||||
|
response/tool/transcript identities and replay fingerprints are preserved.
|
||||||
|
- Bounded local HTTP gateway, no retries, bounded pipeline queues, request
|
||||||
|
deadlines, final-only STT and startup request counters. Truncated streams omit
|
||||||
|
the final HTTP chunk so consumers observe failure. Counters are not cost proof.
|
||||||
|
- Unsupported interruption/history repair closes safely until Phase 3. No
|
||||||
|
acknowledgement, transcript alignment or successful terminal is invented.
|
||||||
|
- Standalone isolated Compose, pinned-source build preparation, Docker recipe,
|
||||||
|
local-only preprovisioned VAD loading, environment examples and operator guide.
|
||||||
|
The engine receives no database credentials. Application startup checks the
|
||||||
|
candidate database/storage before lifecycle reconciliation, and rechecks the
|
||||||
|
actual database connection at reservation/stream admission.
|
||||||
|
- Stub/opt-in live smoke with multipart or JSON STT and playable WAV output.
|
||||||
|
The saved stub WAV is explicitly a synthetic 440 Hz test tone.
|
||||||
|
|
||||||
|
Main files: `app/modules/voice/local_s2s.py`, `configuration.py`, `settings.py`,
|
||||||
|
`app/infrastructure/local_s2s.py`, `voice_provider.py`, `app/main.py`,
|
||||||
|
`app/api/v1/live.py`, `app/local_s2s_smoke.py`, `services/local_s2s/`, `docker-compose.local-s2s-test.yml`,
|
||||||
|
`.env.example`, and the three new Phase 2 test files. Phase 1 and unrelated
|
||||||
|
working-tree changes were retained. No schema migration or old-profile rewrite.
|
||||||
|
|
||||||
|
## Actual checks
|
||||||
|
|
||||||
|
Commands ran from the repository root with the existing Windows virtualenv;
|
||||||
|
`-p no:cacheprovider` avoids pytest cache writes.
|
||||||
|
|
||||||
|
| Check | Result |
|
||||||
|
| --- | --- |
|
||||||
|
| Focused OpenAI/Gemini/runtime plus new local adapter/engine tests | **277 passed in 143.65 s** |
|
||||||
|
| Final Phase 2 tests after adding transcript and rejected-body coverage | **35 passed in 3.94 s** |
|
||||||
|
| Existing auth/startup/lifecycle/HTTP regression tests | **72 passed in 16.32 s** |
|
||||||
|
| Final combined local + HTTP/startup suite after actual-connection isolation guard | **107 passed in 13.90 s** |
|
||||||
|
| New PostgreSQL profile replay/revocation tests with `--require-postgres` | **2 passed in 4.66 s** |
|
||||||
|
| Expanded PostgreSQL lifecycle/transport regressions | **57 passed, 6 failed in 292.92 s**; details below |
|
||||||
|
| `docker compose -f docker-compose.local-s2s-test.yml config --quiet` | Passed; no candidate started |
|
||||||
|
| `git diff --check` | Passed (Git reports the existing CRLF policy for `.env.example`) |
|
||||||
|
| Stub smoke and independent WAV header inspection | Passed; 3 mocked stages, **0 paid requests**, mono PCM16, 24,000 Hz, 9,600 samples (0.4 s) |
|
||||||
|
| Operational image/container inspection and `/health/ready` | Original IDs/images unchanged; **ready / available** |
|
||||||
|
|
||||||
|
Focused command:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_engine.py tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q --tb=short -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
Final local command:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py -q --tb=short -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
Final combined command:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
Existing HTTP/startup command:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
PostgreSQL tests used a **new cached-image container** `rag-local-s2s-postgres-test`,
|
||||||
|
ID `e5da8c342ed59fc48a49856bfd76010feda45e4a221f640d34aa330a5cd8a7da`,
|
||||||
|
image `sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a`,
|
||||||
|
at `127.0.0.1:55439`, database `rag_local_s2s_test`. No operational database was used.
|
||||||
|
The test harness created/dropped disposable schemas. Commands, with
|
||||||
|
`TEST_DATABASE_URL` set privately to this isolated database:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/integration/test_local_s2s_phase2.py -m postgres --require-postgres -q --tb=short -p no:cacheprovider
|
||||||
|
.venv/Scripts/python -m pytest tests/integration/test_local_s2s_phase2.py tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q --tb=short -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
The six expanded-suite failures are all
|
||||||
|
`test_actual_asgi_tool_dispatch_persistence_and_public_sources`, combinations of
|
||||||
|
`ok|no_evidence|error` and `gemini|openai`. They wait for public source events before
|
||||||
|
feeding subsequent provider responses and hit `RESPONSE_ACK_DEADLINE`. The new
|
||||||
|
local tests are green. Baseline comparison loaded immutable `HEAD` versions of settings, configuration,
|
||||||
|
Realtime, Gemini, factory, runtime and main **in memory**, using `git show HEAD:<path>`,
|
||||||
|
then ran the same six cases via `pytest.main` with `-k test_actual_asgi_tool_dispatch_persistence_and_public_sources -m postgres --require-postgres -q --tb=no -p no:cacheprovider`: **the same 6 failures, 55 deselected in 113.06 s**. No working files were reverted; no existing
|
||||||
|
assertions or timeout thresholds were weakened to hide failures. The full ordinary
|
||||||
|
suite was not rerun; its prior failures remain documented in the Phase 1 report.
|
||||||
|
|
||||||
|
## See the result now
|
||||||
|
|
||||||
|
Open [the generated WAV](../../../temp/local-s2s-phase2-stub.wav) in an audio player.
|
||||||
|
It is a **test tone, not actual Persian speech**. To generate another artifact:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m app.local_s2s_smoke --output temp/local-s2s-another-stub.wav
|
||||||
|
```
|
||||||
|
|
||||||
|
The command refuses to overwrite an existing file. Run the final local test command
|
||||||
|
above to see native setup, audio/transcript delivery, safe failure and close checks.
|
||||||
|
These are simulated provider events/HTTP responses, not a real engine/browser demo.
|
||||||
|
|
||||||
|
## Remaining gates and acceptance verdict
|
||||||
|
|
||||||
|
1. Phase 1 changed-source real OpenAI interaction/listening is still pending.
|
||||||
|
2. The real pinned engine was **not built or initialized**. Resolve/review the
|
||||||
|
Linux dependency hash lock and base-image digest, supply a preprovisioned VAD
|
||||||
|
source/asset bundle, then run actual upstream/configuration conformance.
|
||||||
|
The launcher is statically audited and fixture-tested; real dependency/API
|
||||||
|
incompatibilities remain possible. No reproducible image is claimed yet.
|
||||||
|
3. No paid-call approval was obtained: the user's clarification was not consent.
|
||||||
|
No OpenRouter key was accessed. Real STT/LLM/TTS requests, PCM-rate verification,
|
||||||
|
Persian listening and the isolated browser greeting/normal close remain open.
|
||||||
|
4. Model discovery was a free catalogue read: STT `openai/whisper-large-v3` and
|
||||||
|
LLM `openai/gpt-4.1-mini` were listed; the TTS candidate is
|
||||||
|
`google/gemini-3.8-flash-lite-tts` / `Kore`. This is not speech acceptance.
|
||||||
|
OpenAI TTS IDs were absent from the observed speech catalogue; no fallback was added.
|
||||||
|
5. The Angular source is absent from this repository. Repoint the existing client
|
||||||
|
in its own checkout, using a separate browser profile and candidate-only Origin.
|
||||||
|
This Compose profile intentionally uses a disabled embedding endpoint for a
|
||||||
|
greeting/transport demonstration; it does not certify RAG or interruption quality.
|
||||||
|
|
||||||
|
[Operator guide: build, isolated bootstrap, browser and consented live WAV steps](../../../services/local_s2s/README.md).
|
||||||
|
The application/browser PCM and public event contracts remain unchanged.
|
||||||
|
|
||||||
|
Operational identities remain those in [Phase 1](phase-01.md): running
|
||||||
|
`rag-api-mini` image `sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3`;
|
||||||
|
stopped original `rag-api` image
|
||||||
|
`sha256:6f9b1bc3e0eeb76e0143fb33e2773f3fe3e639fbc3c4b2c11139aaabb58ea028`.
|
||||||
|
No restart or rollback was attempted. Phase 3 must not start until Phase 2 acceptance.
|
||||||
|
|
||||||
|
The temporary acceptance database container was stopped after verification (retained, not removed).
|
||||||
|
[Phase 2 source fingerprints and expected candidate profile](phase-02-provenance.json)
|
||||||
|
record unbuilt/unverified state explicitly; they contain no provider credentials.
|
||||||
|
|
||||||
|
|
||||||
|
## Five-defect repair checkpoint (2026-10-15, extension v2)
|
||||||
|
|
||||||
|
This checkpoint supersedes the earlier candidate's offline safety claims for the
|
||||||
|
five repaired paths; earlier execution records above remain historical evidence.
|
||||||
|
**Verdict: offline repairs verified; Phase 2 remains in_progress, live acceptance
|
||||||
|
pending.** Phase 3 was not implemented and the operational deployment was not switched.
|
||||||
|
|
||||||
|
Verification used the actual source at upstream commit
|
||||||
|
`619e3fe4f71d1c6f35c15870d588a3638de34722`. Hash-checked source fixtures and the
|
||||||
|
upstream Apache license are in `tests/fixtures/local_s2s_upstream/`; their manifest
|
||||||
|
records original paths and SHA-256 values. Only source text/license was fetched.
|
||||||
|
The isolated harness compiles original upstream methods from those sources; it
|
||||||
|
isolates SDK I/O, history and ML imports. It inspects outgoing HTTPX JSON and actual
|
||||||
|
loopback HTTP framing/closure, rather than accepting fake handler attributes as
|
||||||
|
request conformance. Full SDK/ML/image execution remains a separate gate.
|
||||||
|
|
||||||
|
| Confirmed upstream behavior / defect | Scoped repair and evidence |
|
||||||
|
| --- | --- |
|
||||||
|
| Base `process()` handles STT text through Chat Completions `_request_chat_completions`; that path ignores the prior `gen_kwargs` cap. Constructor setup invokes warmup. | Install the client policy and configured setup timeout before construction. Every actual Chat Completions create receives `max_tokens`; pinned normal text, warmup and setup tests inspect JSON with nondefault limits 17/83 and 19/71. Active attestation reads the installed policy. |
|
||||||
|
| Pinned `warmup()` explicitly clones the client with `WARMUP_MAX_RETRIES=6` (the earlier harness override was 10; correction below). | Policy clones force zero retries; retryable HTTP 503 and connection failures each produce exactly one attempt. Counters count admitted failed probes. Owner construction/probe deadline is 90 seconds; per-exchange default is 30 seconds. |
|
||||||
|
| Pipeline import catches missing punkt/tagger resources and calls `nltk.download`. | Build preparation replaces those blocks with local validation. Required NLTK files and local VAD bundle have a reviewed SHA-256 manifest and expected manifest digest. Preflight checks every asset and loads original sentence/POS functions before provider construction. Missing/corrupt/malformed assets or tokenizers attempting blocked downloads produce a fixed safe category with zero provider calls. No tokenizer substitution. |
|
||||||
|
| Prior gateway timing began after header acquisition and buffered streams in 8192-byte pieces. | Owned asynchronous connection lifecycle bounds silent/partial headers, body reads, upstream headers/reads and downstream drains. Total and inactivity deadlines are independent. Small SSE/PCM chunks flow immediately; expiration/disconnect cancels upstream, closes transports and releases slots. Failed partial chunked responses omit the terminal chunk. Tests exercise actual loopback sockets, cancellation and stalled writes. |
|
||||||
|
| Upstream `ConfiguredRuntime.stop()` can raise before clearing resources; `wait()` invokes stop. The launcher bypassed upstream command signal management. | Independent bounded runtime stop, gateway shutdown, socket close and thread join always produce numeric cleanup/request counters. Owned SIGINT/SIGTERM handlers signal the stop event and restore predecessors. Tests exercise the pinned failing stop method, a hung stop/construction and termination during an in-flight mock request. Windows tests dispatch installed handlers; OS-level POSIX signal delivery remains unverified. |
|
||||||
|
|
||||||
|
Original source locations: `LLM/base_openai_compatible_language_model.py`
|
||||||
|
(`setup`, `process`), `LLM/chat_completions_language_model.py`
|
||||||
|
(`_request_chat_completions`, `warmup`), `s2s_pipeline.py` (NLTK import block),
|
||||||
|
and `configured_runtime.py` (`ConfiguredRuntime.stop`, `wait`). All paths are
|
||||||
|
under upstream `src/speech_to_speech/` at the pinned SHA.
|
||||||
|
|
||||||
|
The behavior revision is now `rag-local-s2s-phase2-v2`; private contract shape
|
||||||
|
remains `rag-local-s2s-phase2-v1`. New profiles pin v2. Existing reservations,
|
||||||
|
frozen profiles and historical v1 evidence are not rewritten. Raw event
|
||||||
|
fingerprints, authorization/replay/epoch checks, browser PCM24k/events and
|
||||||
|
fail-safe unsupported interruption remain covered by the preservation suites.
|
||||||
|
No existing OpenAI/Gemini assertions were weakened. Only the engine test client
|
||||||
|
fixture gained the effective policy fields required by v2 attestation.
|
||||||
|
|
||||||
|
Final repair regression command (31 passed in 6.82 s):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
Required final combined command (107 passed in 18.66 s):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
Required preservation command (242 passed in 34.11 s):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
These are offline tests, with zero paid calls, model/dependency downloads, image
|
||||||
|
builds or operational changes. PostgreSQL acceptance was **not run in this repair
|
||||||
|
checkpoint**: no disposable `TEST_DATABASE_URL` was verified/used. The earlier
|
||||||
|
2-pass and 57-pass/6-baseline-failure DB records above are not a fresh acceptance
|
||||||
|
claim; existing full-suite and database baseline failures remain open.
|
||||||
|
|
||||||
|
Reviewable repair files: `services/local_s2s/{request_policy,assets,lifecycle,
|
||||||
|
components,engine,extension,prepare_build}.py`, local behavior revision,
|
||||||
|
engine-only Compose asset mounts and example settings, pinned fixtures/harness,
|
||||||
|
`test_local_s2s_repairs.py`, engine fixture and these operator/evaluation records.
|
||||||
|
Unrelated working-tree changes were preserved. No terminal events, repair receipts
|
||||||
|
or live observations were fabricated; persistent provider credentials stay server-side.
|
||||||
|
|
||||||
|
To see the repaired behavior, run the three commands above. For actual speech,
|
||||||
|
follow the [updated operator guide](../../../services/local_s2s/README.md#phase-2-repair-checkpoint-extension-v2)
|
||||||
|
after separate authorization: provision/fingerprint local NLTK and VAD assets,
|
||||||
|
review Linux dependency lock and immutable base digest, build an isolated candidate,
|
||||||
|
then verify complete real-engine/SDK conformance, component audio and isolated
|
||||||
|
Persian browser greeting, transcripts and normal close. The Phase 1 real OpenAI
|
||||||
|
interaction/listening gate also remains open. No live acceptance is claimed until
|
||||||
|
those observations exist. The prior WAV remains a simulated test tone.
|
||||||
|
|
||||||
|
|
||||||
|
Additional offline checks:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
git diff --check
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml config --quiet
|
||||||
|
.venv/Scripts/python -c "import ast, tokenize; from pathlib import Path; paths=list(Path('services/local_s2s').glob('*.py'))+[Path('tests/unit/test_local_s2s_repairs.py'),Path('tests/support/local_s2s_pinned.py')]; [ast.parse(tokenize.open(p).read(),filename=str(p)) for p in paths]; print(str(len(paths))+' Python files parsed using Python source encodings')"
|
||||||
|
```
|
||||||
|
|
||||||
|
All passed; 9 Python source files parsed. An initial inspection using
|
||||||
|
`read_text(encoding='utf-8')` failed on the engine file's UTF-8 BOM; rerunning with
|
||||||
|
Python's source encoding detection passed. This was an inspection-command issue,
|
||||||
|
not an interpreter import failure. Scoped untracked repair files were also
|
||||||
|
checked for trailing whitespace. Compose validation parsed configuration only;
|
||||||
|
it did not create/start any service or print credentials.
|
||||||
|
|
||||||
|
|
||||||
|
## Remaining-defect repair checkpoint: extension v3
|
||||||
|
|
||||||
|
**Verdict: offline regressions passed; Phase 2 remains in_progress and live
|
||||||
|
acceptance pending.** The five prior repairs remain; Phase 3 and operational
|
||||||
|
services were untouched. The [scoped patch](phase-02-remaining-repairs.patch) is
|
||||||
|
relative to this checkpoint's in-session pre-edit snapshots, so unrelated existing
|
||||||
|
working-tree changes are excluded. Files: `services/local_s2s/components.py`,
|
||||||
|
`app/modules/voice/local_s2s.py`, `services/local_s2s/prepare_build.py`, the pinned
|
||||||
|
source harness and repair tests, operator guide, this report, provenance and ledger.
|
||||||
|
No existing OpenAI/Gemini assertion was removed or relaxed.
|
||||||
|
|
||||||
|
1. **Disconnect ownership.** A concurrent downstream watcher starts after the body
|
||||||
|
and cancels the owned forwarding task on ordinary EOF/reset, including before
|
||||||
|
upstream headers and while response streaming produces nothing. Response/client
|
||||||
|
transport closure and task joining share a one-second cleanup window; expiry
|
||||||
|
aborts the downstream transport, cancels remaining cleanup and releases the slot.
|
||||||
|
Total/inactivity deadlines and incomplete chunked failure remain intact.
|
||||||
|
Real upstream and downstream TCP loopback tests assert upstream socket closure,
|
||||||
|
transport closure and slot release before a five-second request deadline, with
|
||||||
|
a 0.6-second scheduling allowance beyond the cleanup window. A stalled close
|
||||||
|
test verifies the cleanup bound itself. The old continuous-output disconnect
|
||||||
|
test remains; the earlier v2 disconnect description alone did not establish
|
||||||
|
these stalled-upstream cases.
|
||||||
|
2. **Half-close policy.** FIN cannot distinguish full close from SHUT_WR. For
|
||||||
|
ordinary requests, EOF is explicitly cancellation, even if the peer can receive.
|
||||||
|
Intentional receive-only half-close is supported with the private header
|
||||||
|
`X-Local-S2S-Half-Close: receive-response`; FIN after the complete body then keeps
|
||||||
|
response delivery alive, while reset/transport errors still cancel. A graceful
|
||||||
|
full close after that declaration is inherently indistinguishable and remains
|
||||||
|
bounded by request deadlines. This header is not forwarded upstream and is not
|
||||||
|
a browser event/API change. Loopback tests prove normal and declared half-close
|
||||||
|
success, plus undeclared half-close cancellation. Extra bytes/pipelining are
|
||||||
|
unsupported and unknown header values fail before provider admission.
|
||||||
|
3. **Inherited validation.** Renamed only `LocalS2SSettings.identifier` to
|
||||||
|
`local_component_identifier`, avoiding Pydantic's inherited validator override
|
||||||
|
by `VoiceSettings.identifier`. Through the real VoiceSettings, all four local
|
||||||
|
STT/LLM/TTS model and TTS voice fields now reject whitespace, control and non-ASCII
|
||||||
|
values. Tests preserve valid identifiers, check unchanged OpenAI/Gemini validators
|
||||||
|
and verify invalid environment configuration fails before assets/gateway/provider
|
||||||
|
construction or probes.
|
||||||
|
4. **Source provenance correction.** `WARMUP_MAX_RETRIES` is **6**, defined at
|
||||||
|
line 66 of hash-checked `base.py.source`, imported by `chat.py.source`. The v2
|
||||||
|
test harness supplied literal 10, an isolated override, and the report/guide
|
||||||
|
incorrectly identified it as upstream's value. Those descriptions are corrected;
|
||||||
|
historical execution counts/timings remain unchanged. The harness now extracts
|
||||||
|
the literal from the verified source AST, with an explicit value assertion.
|
||||||
|
Pinned warmup HTTP 503/connection-failure tests run using 6 and still assert one
|
||||||
|
attempt. Complete SDK retry/ML engine execution is not claimed.
|
||||||
|
|
||||||
|
Intentional behavior changes use `rag-local-s2s-phase2-v3` in fresh identities and
|
||||||
|
build manifests; the private shape revision remains v1. No old reservation or
|
||||||
|
frozen profile was rewritten. Native fingerprints, browser PCM24k/events,
|
||||||
|
authorization/replay/epoch checks and fail-safe unsupported interruption remain.
|
||||||
|
Persistent provider credentials stay server-side. No terminal/history receipt
|
||||||
|
was fabricated. The pinned source fixture bytes and hashes were not changed.
|
||||||
|
|
||||||
|
Final commands and outcomes:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider
|
||||||
|
# 74 passed in 7.68s (31 prior repairs retained; 43 added regressions)
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
|
||||||
|
# 107 passed in 16.67s
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider
|
||||||
|
# 242 passed in 33.73s
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml config --quiet
|
||||||
|
# Passed: parse only; no service started or rendered secrets printed
|
||||||
|
git diff --check
|
||||||
|
# Passed
|
||||||
|
```
|
||||||
|
|
||||||
|
The initial targeted run before the final existing-provider validation cases was
|
||||||
|
70 passed in 7.35s. All requested final suites passed; no baseline failure was
|
||||||
|
hidden or assertion weakened. Historical broader ordinary/DB failures above and
|
||||||
|
in the Phase 1 report remain separate and unresolved. PostgreSQL was not run in
|
||||||
|
this checkpoint: no verified disposable TEST_DATABASE_URL was used. Any later DB
|
||||||
|
acceptance requires that verification and `--require-postgres`.
|
||||||
|
|
||||||
|
Evidence boundaries and remaining gates: original upstream methods run with an
|
||||||
|
isolated SDK/history/ML harness; HTTPX and the new loopback transport tests use real
|
||||||
|
local sockets. These are offline fixture results, not complete engine/OpenAI SDK,
|
||||||
|
provider-audio or browser acceptance. No paid calls, downloads, image builds,
|
||||||
|
operational actions or Phase 3 work occurred. Still required: Phase 1 real OpenAI
|
||||||
|
interaction/listening, reviewed Linux dependency hash lock and immutable base image
|
||||||
|
digest, provisioned/fingerprinted NLTK and VAD assets, real pinned-engine/SDK
|
||||||
|
conformance, authorized component audio, and isolated Persian browser greeting,
|
||||||
|
transcripts and normal close. See the [v3 operator guide](../../../services/local_s2s/README.md#phase-2-remaining-repairs-extension-v3).
|
||||||
|
|
||||||
|
|
||||||
|
## Acceptance preparation checkpoint (2026-10-15; v3 unchanged)
|
||||||
|
|
||||||
|
**Phase 2 remains in_progress / NOT ACCEPTED.** No runtime repair or refactor was
|
||||||
|
needed. The reviewed implementation/test fingerprints were checked unchanged
|
||||||
|
before documentation updates; the 74/107/242 baseline was not repeated. No paid
|
||||||
|
call, source/dependency/model download, image build, operational write, reservation
|
||||||
|
rewrite or Phase 3 implementation occurred. New files are acceptance preparation,
|
||||||
|
asset fingerprints and a guarded disposable-DB runner.
|
||||||
|
|
||||||
|
The [concrete acceptance checklist](phase-02-acceptance-checklist.md) records exact
|
||||||
|
commands, isolation, request ceilings proposed for approval, expected observations,
|
||||||
|
stop conditions and remaining gates. Candidate-only Phase 1 source-mount and
|
||||||
|
browser/proxy overrides were prepared and parsed; they were NOT launched. The
|
||||||
|
Phase 1 recipe uses the existing immutable API image as a dependency runtime,
|
||||||
|
mounts changed source read-only, masks inherited /app/data and uses separate test
|
||||||
|
DB/storage. It changes neither the operational container nor image. Source/runtime
|
||||||
|
compatibility still needs an actual consenting OpenAI interaction and listening.
|
||||||
|
Phase 1 stays open: server-side OpenAI key presence was verified without printing
|
||||||
|
its value; no bounded live approval or consented fixture is recorded. OpenRouter
|
||||||
|
key presence was false in both the checked host process and root server .env.
|
||||||
|
No key was copied to browser/profile/provenance.
|
||||||
|
|
||||||
|
Actual independent progress:
|
||||||
|
|
||||||
|
- Existing assets were found and fingerprinted: **201 files**, combined NLTK/Silero
|
||||||
|
manifest [phase-02-local-assets.json](phase-02-local-assets.json), SHA-256
|
||||||
|
`8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8`.
|
||||||
|
The existing sibling Windows environment loaded NLTK **3.10.3** sentence/POS
|
||||||
|
resources with downloader entry points blocked. No original asset changed.
|
||||||
|
Linux VAD/JIT and complete engine validation remain unrun.
|
||||||
|
- The cached immutable base was identified as
|
||||||
|
`python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce`,
|
||||||
|
Linux/amd64. No dependency lock or candidate image exists. The sibling engine
|
||||||
|
checkout is dirty at `30af00916da85efb053b539a040fd71cf392e7e2` and does NOT contain
|
||||||
|
the required pin object; `git cat-file -t <pin>` failed. Its changes were preserved.
|
||||||
|
Building/reviewing a full pinned source graph requires an authorized clean
|
||||||
|
transfer/offline source tree, followed by reviewed Linux dependency resolution.
|
||||||
|
- PostgreSQL was actually run with `--require-postgres` on the retained verified
|
||||||
|
disposable container/database at 127.0.0.1:55439, never operational port 5432.
|
||||||
|
The runner validates fixed container/image/volume and host port, non-overlap with
|
||||||
|
operational storage, and `current_database()/current_user` before tests. Secrets
|
||||||
|
stay inside the subprocess environment. Fixtures create/drop random owned schemas.
|
||||||
|
- Local DB acceptance: **2 passed in 5.18 s**, zero skips. Expanded: **57 passed,
|
||||||
|
6 failed in 236.50 s**, zero skips. All six are the same
|
||||||
|
`test_actual_asgi_tool_dispatch_persistence_and_public_sources`
|
||||||
|
`ok|no_evidence|error` x `gemini|openai` cases, with RESPONSE_ACK_DEADLINE. They
|
||||||
|
match the earlier immutable-HEAD baseline comparison recorded above; that
|
||||||
|
comparison was not rerun here. No application/test assertion changed and broad
|
||||||
|
database acceptance remains non-green. The test container returned to exited
|
||||||
|
after each run; no volumes or operational data were removed.
|
||||||
|
- Frontend source was found outside this repository at
|
||||||
|
`D:/raymand/projects/faq_chatbot_frontend`, HEAD
|
||||||
|
`815191588c59fc43434cc2454cab3a8b2f8c1648`, with a pre-existing package.json edit.
|
||||||
|
Its proxy and files were not modified. An external candidate-only proxy and
|
||||||
|
trusted Origin 127.0.0.2:4201 were prepared; no browser/microphone run occurred.
|
||||||
|
|
||||||
|
Executed acceptance commands:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m services.local_s2s.assets --nltk-root "$env:APPDATA/nltk_data" --vad-root D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master --output docs/evaluation/local-s2s/phase-02-local-assets.json
|
||||||
|
D:/raymand/projects/speech-to-speech-test/.venv/Scripts/python.exe -c "import json,os,nltk; from pathlib import Path; from services.local_s2s.assets import validate_assets,configure_nltk; root=Path(os.environ['APPDATA'])/'nltk_data'; vad=Path('D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master'); digest=validate_assets(root,vad,'docs/evaluation/local-s2s/phase-02-local-assets.json'); configure_nltk(nltk,root); print(json.dumps({'manifest_sha256':digest,'nltk_version':nltk.__version__,'sentence_and_pos_load':'passed','runtime_downloads':'blocked','environment':'existing Windows sibling virtualenv; not Linux engine'}))"
|
||||||
|
.venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite local
|
||||||
|
.venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite expanded
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml config --quiet
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml config --quiet
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml config --quiet
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
Asset commands passed; all three Compose parses passed. Rendered Phase 1 config
|
||||||
|
was inspected privately: read-only current app mount, masked inherited data,
|
||||||
|
non-operational DB/volumes, selected OpenAI provider, no OpenRouter key in API,
|
||||||
|
loopback binding and candidate Origin passed assertions. No rendered secret was
|
||||||
|
printed. Final git diff/metadata checks are recorded in provenance. The guarded
|
||||||
|
runner invokes the exact earlier local/expanded pytest commands with
|
||||||
|
`-m postgres --require-postgres -q --tb=short -p no:cacheprovider` and a verified
|
||||||
|
TEST_DATABASE_URL set privately. Its expanded exit code was 1; this is not hidden.
|
||||||
|
|
||||||
|
Remaining prerequisites are exact: Phase 1 bounded OpenAI consent and actual
|
||||||
|
changed-source listening; a clean complete pinned source tree; reviewed immutable
|
||||||
|
Linux dependency lock and build authorization; Linux asset compatibility; an
|
||||||
|
executable complete-engine controlled-I/O harness with actual SDK and POSIX signal
|
||||||
|
evidence; OpenRouter key and bounded paid consent plus consented Persian speech;
|
||||||
|
then real components and an isolated browser greeting/answer/transcripts/normal
|
||||||
|
close. The AST harness, NLTK load, DB passes and Compose parses do not replace any
|
||||||
|
of those observations. Proposed live limits in the checklist are NOT permission.
|
||||||
|
No automatic approval rejection blocked this checkpoint; dependent work remains
|
||||||
|
unrun because prerequisites/authorizations are absent.
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
{
|
||||||
|
"repository": "https://github.com/huggingface/speech-to-speech",
|
||||||
|
"commit": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||||
|
"patch_revision": "none-phase-1-audit-only",
|
||||||
|
"inputs": [
|
||||||
|
{
|
||||||
|
"path": "pyproject.toml",
|
||||||
|
"sha256": "87ace2c683f2625f998b2852ae25ccceead5e55ed73fafd5d731d88662e450ff",
|
||||||
|
"git_blob": "06d1b6ec6e662d01a67c1e84f7fffe026535ad25",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/pyproject.toml"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "Dockerfile",
|
||||||
|
"sha256": "1d23587e48dc063b6ddc436b958acf9aa78e6e7f22c833d665bc0365b3e143b0",
|
||||||
|
"git_blob": "99d58f7bd9dc30f5e0eb139909608b4b3c8f86cb",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/Dockerfile"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/api/openai_realtime/README.md",
|
||||||
|
"sha256": "6cab7c906ad307deaebf72890e982be4908765b4f3f5aee5bbd5d8b5fc311b23",
|
||||||
|
"git_blob": "ab9cfc85e3d2c99852fcb7fce1f1037cc9bf7281",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/api/openai_realtime/README.md"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/api/openai_realtime/websocket_router.py",
|
||||||
|
"sha256": "5b449bb1a774e187f50e99f4db6105281c791bbe4dd6a4810d41e6758b734469",
|
||||||
|
"git_blob": "368a0001455e395629e86f40ed7b3fb52a8d1455",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/api/openai_realtime/websocket_router.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/api/openai_realtime/service.py",
|
||||||
|
"sha256": "9c105a9f05790b250f18273edfeddf768625cea0d047e42eb5827bd405aecf49",
|
||||||
|
"git_blob": "52cdbc3e0a2de50683a07550475a859be5c7068a",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/api/openai_realtime/service.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/api/openai_realtime/runtime_config.py",
|
||||||
|
"sha256": "a5a03cd24435a242c1c77107e94c6db7bd7f63ae70b12a89e7da41e304b27c27",
|
||||||
|
"git_blob": "123a9e41f0c1d1113aedd5c2c08af25911cf54f4",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/api/openai_realtime/runtime_config.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/api/openai_realtime/handlers/session.py",
|
||||||
|
"sha256": "e8fe23105354276fb115550d3954e5b7108480ddb22b2b89da62003d648bb713",
|
||||||
|
"git_blob": "67b4d65fab209b25b2639c176653bd5918ba07b0",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/api/openai_realtime/handlers/session.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/api/openai_realtime/handlers/audio.py",
|
||||||
|
"sha256": "f8de10b81a9f86f8a25c3bfe707687efe98f269f87bc8a840f74ae958fcc7b57",
|
||||||
|
"git_blob": "11a9b9f396cb80b90fb29e08ff9abc63fe33a9d2",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/api/openai_realtime/handlers/audio.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/api/openai_realtime/handlers/response.py",
|
||||||
|
"sha256": "dbae7e84d274d3dd6010ca3c14c417246a424d18a99318dcfb390b4f0c5c48c0",
|
||||||
|
"git_blob": "44fce432470071276463347579720662ee06e3ba",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/api/openai_realtime/handlers/response.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/api/openai_realtime/handlers/conversation.py",
|
||||||
|
"sha256": "4e6f3cf7860d911a631a15e9c25ac715353f501a50847169a7f4b17808a0438b",
|
||||||
|
"git_blob": "0e1abf3945957ca4b33e8a4d48f62338de12b999",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/api/openai_realtime/handlers/conversation.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/api/openai_realtime/handlers/history.py",
|
||||||
|
"sha256": "835e0ee2ea72a8b2c468e1364d798c7b02fbcf795217aa9345c6272fd8cd43fb",
|
||||||
|
"git_blob": "4ebba270974c88ed6a54707413c17fbb4e1c24ca",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/api/openai_realtime/handlers/history.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/STT/openai_compatible_handler.py",
|
||||||
|
"sha256": "89393c8c26a9ad755e8db4da3020019f98ab094b9a5ad049bd9ed8a73d7a68c1",
|
||||||
|
"git_blob": "0605445e69112e4dc43e1c15d8b70e4d9f1f5fa0",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/STT/openai_compatible_handler.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/speech_to_speech/TTS/openai_compatible_handler.py",
|
||||||
|
"sha256": "8723e77e9ba7ebe6e0ae9a3b746cdf87b1faefeeb0c7114aed24986c98c3d3a8",
|
||||||
|
"git_blob": "d1eb738f2a380c8d3c08e36696b8b169ddb4a09a",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/src/speech_to_speech/TTS/openai_compatible_handler.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "tests/openai_realtime/test_realtime_protocol_contract.py",
|
||||||
|
"sha256": "da1fe6724aeea3a9232c9dfe750e26d1887a1e44a99822183abffd98984d6a62",
|
||||||
|
"git_blob": "c95274c2b5d615cd4a0fff319a729909434e0468",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/tests/openai_realtime/test_realtime_protocol_contract.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "tests/openai_realtime/test_response_input_identity.py",
|
||||||
|
"sha256": "581bfcbbff7b3d408044b8495811d0d964ce4ecd33c2fff604d43944116a1071",
|
||||||
|
"git_blob": "e30994bd3052b026d42eeafb232d6b268b4bfd5d",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/tests/openai_realtime/test_response_input_identity.py"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "docs/openai-compatible-stt.md",
|
||||||
|
"sha256": "57ecb39cb3027145e80fba47b61562f81449d38fc6a47b2eccfe3d7c7fed3c2e",
|
||||||
|
"git_blob": "e54df2af12fbeadaa9c9972a1e204cc34c064d9d",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/docs/openai-compatible-stt.md"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "docs/openai-compatible-tts.md",
|
||||||
|
"sha256": "3a18c99ac38bd26979aa421f73289e3cce55a1ec65a9097e422e7e50c48b26d3",
|
||||||
|
"git_blob": "d7da52896b7c91e90c6fea2272cb19291d6b14b6",
|
||||||
|
"url": "https://raw.githubusercontent.com/huggingface/speech-to-speech/619e3fe4f71d1c6f35c15870d588a3638de34722/docs/openai-compatible-tts.md"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"built": false,
|
||||||
|
"dependency_lock": null,
|
||||||
|
"base_image_digest": null,
|
||||||
|
"build_gate": "Before any Phase 2 build: resolve and review transitive dependency lock and base image digest. Upstream has no Python lockfile; its Dockerfile uses mutable apt/uv/dependency resolution and downloads NLTK assets. Do not claim a reproducible built image from this source pin."
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# Local speech-to-speech adapter: phased implementation plan
|
# Local speech-to-speech adapter: phased implementation plan
|
||||||
|
|
||||||
Date: 2026-10-15. Status: **planned; implementation and live acceptance not started**.
|
Date: 2026-10-15. Status: **Phase 1 offline implementation delivered; Phase 2 candidate prepared; build/live acceptance pending**.
|
||||||
|
|
||||||
## 1. Outcome and scope
|
## 1. Outcome and scope
|
||||||
|
|
||||||
@@ -13,7 +13,8 @@ Replacing individual stages with local models is a later independent optimizatio
|
|||||||
This is a plan, not authorization to switch the running application, download
|
This is a plan, not authorization to switch the running application, download
|
||||||
weights or perform unbounded paid evaluation. The original eight stages are consolidated into four phases without removing scope.
|
weights or perform unbounded paid evaluation. The original eight stages are consolidated into four phases without removing scope.
|
||||||
Each phase has a tangible demo,
|
Each phase has a tangible demo,
|
||||||
acceptance criteria, evidence and a copy-ready English prompt. No phase has run.
|
acceptance criteria, evidence and a copy-ready English prompt. Phase 1 offline
|
||||||
|
evidence is in [its report](../evaluation/local-s2s/phase-01.md); no phase is accepted.
|
||||||
|
|
||||||
## 2. Target architecture
|
## 2. Target architecture
|
||||||
|
|
||||||
@@ -130,8 +131,9 @@ silently present it as exact heard-prefix preservation.
|
|||||||
| 4 | Quality/cost decision and verified deployment rollback | Old 6 + 7 |
|
| 4 | Quality/cost decision and verified deployment rollback | Old 6 + 7 |
|
||||||
|
|
||||||
Only these four phases and their four prompts are active. The original version is
|
Only these four phases and their four prompts are active. The original version is
|
||||||
[archived](archive/local-s2s-eight-phase/README.md) for traceability. No implementation
|
[archived](archive/local-s2s-eight-phase/README.md) for traceability. The consolidation
|
||||||
phase has started, so this consolidation changes planning only. Required internal
|
changed planning only; subsequent Phase 1 implementation is tracked in the
|
||||||
|
progress ledger. Required internal
|
||||||
checkpoints remain acceptance conditions inside each phase, not separate execution
|
checkpoints remain acceptance conditions inside each phase, not separate execution
|
||||||
phases. The preserved OpenAI path remains the fallback chosen by the operator.
|
phases. The preserved OpenAI path remains the fallback chosen by the operator.
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
# Local S2S adapter progress - four phases
|
# Local S2S adapter progress - four phases
|
||||||
|
|
||||||
Updated: 2026-10-15. The original eight stages were consolidated into four before
|
Updated: 2026-10-15. The original eight stages were consolidated into four before
|
||||||
implementation started. Scope and acceptance requirements are retained. Planning
|
implementation started. Scope and acceptance requirements are retained.
|
||||||
only: no implementation, model downloads, paid validation or operational switch
|
The consolidation itself changed planning only. Phase 1/2 offline implementation
|
||||||
was performed by this consolidation.
|
and evaluation are now recorded below; no model downloads, paid validation or
|
||||||
|
operational switch was performed.
|
||||||
|
|
||||||
[Plan](local-s2s-adapter-plan.md) | [Four active prompts](local-s2s-adapter-prompts/README.md)
|
[Plan](local-s2s-adapter-plan.md) | [Four active prompts](local-s2s-adapter-prompts/README.md)
|
||||||
|
|
||||||
| Phase | Status | Evidence | Visible demo | Blockers |
|
| Phase | Status | Evidence | Visible demo | Blockers |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| 1 - Preserve OpenAI and introduce the provider boundary | not_started | Not run | Not demonstrated | Resolve prerequisites |
|
| 1 - Preserve OpenAI and introduce the provider boundary | offline_complete_live_pending | [Phase 1 report](../evaluation/local-s2s/phase-01.md); baseline 215 passed, final focused 242 passed; full suite has 5 existing failures (details in report) | Before/after controlled-clock replay; command in report | Changed-source real OpenAI interaction/listening pending; build lock/image digest required before Phase 2 build |
|
||||||
| 2 - Add an isolated local stack and browser voice session | not_started | Not run | Not demonstrated | Resolve prerequisites |
|
| 2 - Add an isolated local stack and browser voice session | in_progress | [Phase 2 report](../evaluation/local-s2s/phase-02.md); v3 repair checkpoint: 74 repair regressions (including 31 prior), 107 final combined and 242 preservation checks passed; pinned warmup constant corrected to 6; acceptance preparation: 201 local assets fingerprinted and NLTK load passed; fresh DB 2 local passed, expanded 57 passed/6 earlier baseline failures; checklist and isolated source/browser overrides prepared | Playable offline test-tone WAV and simulated native audio/transcripts; real browser demo unrun | Phase 1 acceptance; clean pinned source and reviewed Linux lock/build authorization; cached base and local assets found, Linux validation pending; actual engine/SDK/POSIX conformance and authorized real Persian/browser checks |
|
||||||
| 3 - Complete interruption, shared RAG and used sources | not_started | Not run | Not demonstrated | Resolve prerequisites |
|
| 3 - Complete interruption, shared RAG and used sources | not_started | Not run | Not demonstrated | Resolve prerequisites |
|
||||||
| 4 - Validate quality/cost and prove controlled switch/rollback | not_started | Not run | Not demonstrated | Resolve prerequisites |
|
| 4 - Validate quality/cost and prove controlled switch/rollback | not_started | Not run | Not demonstrated | Resolve prerequisites |
|
||||||
|
|
||||||
@@ -31,3 +32,12 @@ was performed by this consolidation.
|
|||||||
States: not_started, in_progress, offline_complete_live_pending, blocked, accepted.
|
States: not_started, in_progress, offline_complete_live_pending, blocked, accepted.
|
||||||
Only accepted closes a mandatory gate. Inspect current deployment before each
|
Only accepted closes a mandatory gate. Inspect current deployment before each
|
||||||
operational action; historical notes do not establish current provider selection.
|
operational action; historical notes do not establish current provider selection.
|
||||||
|
|
||||||
|
|
||||||
|
Acceptance preparation checkpoint: [concrete runbook](../evaluation/local-s2s/phase-02-acceptance-checklist.md).
|
||||||
|
Phase 1 remains open for actual changed-source OpenAI listening and bounded consent.
|
||||||
|
No reviewed runtime changes; the 74/107/242 baseline was not repeated. New local
|
||||||
|
DB checks used the guarded disposable target and restored stopped state. Asset
|
||||||
|
fingerprints/NLTK load are host evidence, not Linux engine or real audio evidence.
|
||||||
|
No downloads/builds/paid requests/operational switch. Phase 2 remains in_progress;
|
||||||
|
complete engine/POSIX, component audio and isolated Persian browser gates stay open.
|
||||||
|
|||||||
@@ -881,3 +881,14 @@ session setup acknowledgement remain separate. Cancellation event-ID correlation
|
|||||||
bounded terminal confirmation, final playback and truncation acknowledgement gates
|
bounded terminal confirmation, final playback and truncation acknowledgement gates
|
||||||
remain mandatory; unknown errors and failed/incomplete technical terminals remain
|
remain mandatory; unknown errors and failed/incomplete technical terminals remain
|
||||||
fatal. This change does not establish live acceptance for every OpenAI model.
|
fatal. This change does not establish live acceptance for every OpenAI model.
|
||||||
|
|
||||||
|
### Local S2S development candidate amendment (2026-10-15)
|
||||||
|
|
||||||
|
The server may select `local_s2s` only with explicit development/transport-test
|
||||||
|
opt-in. This does not add a client provider selector or change PCM24k/public
|
||||||
|
events. Private setup requires the pinned engine/extension/contract revision,
|
||||||
|
fixed component identities and effective post-application configuration proof;
|
||||||
|
a session echo alone is insufficient. Interruption requiring history repair fails
|
||||||
|
closed pending Phase 3. Preserve owner, Origin, cookie, CSRF, replay, profile and
|
||||||
|
epoch checks. Candidate startup requires dedicated test DB/storage. Build and
|
||||||
|
real Persian/browser acceptance remain open; see [Phase 2 evidence](../evaluation/local-s2s/phase-02.md).
|
||||||
|
|||||||
@@ -507,3 +507,14 @@ original identity, and missing/mismatched profile fields reject stream admission
|
|||||||
No schema/migration or session status enum changes. A limited audio answer keeps
|
No schema/migration or session status enum changes. A limited audio answer keeps
|
||||||
the session connected; incomplete tool/provider/context failures remain terminal.
|
the session connected; incomplete tool/provider/context failures remain terminal.
|
||||||
Current-session limited transcripts/events are not durable voice history.
|
Current-session limited transcripts/events are not durable voice history.
|
||||||
|
|
||||||
|
### Local S2S candidate profile (2026-10-15)
|
||||||
|
|
||||||
|
`live_sessions.provider` is already text without a provider enum constraint.
|
||||||
|
The guarded `local_s2s` candidate uses existing columns and a new private
|
||||||
|
`execution_profile.local_s2s` JSON object containing engine/patch/contract revision,
|
||||||
|
component identities and an effective configuration digest. Development-only and
|
||||||
|
close-on-interruption policy fields are frozen too. No schema migration is needed;
|
||||||
|
old rows/snapshots are not rewritten and credentials/secret-derived hashes are
|
||||||
|
excluded. Replays retain their original profile; changed/missing effective state
|
||||||
|
rejects stream admission. See [Phase 2 evidence](../evaluation/local-s2s/phase-02.md).
|
||||||
|
|||||||
@@ -499,3 +499,16 @@ Source order, text and locations are preserved; strict mode remains unchanged.
|
|||||||
This mode does not guarantee complete legal context within each chunk.
|
This mode does not guarantee complete legal context within each chunk.
|
||||||
117 focused regression checks passed, including malformed legal identifiers
|
117 focused regression checks passed, including malformed legal identifiers
|
||||||
and bounded splitting.
|
and bounded splitting.
|
||||||
|
|
||||||
|
### Local S2S isolated development workflow (2026-10-15)
|
||||||
|
|
||||||
|
The guarded local provider reuses VoiceRuntime, trusted tool dispatch and canonical
|
||||||
|
search; no engine database authority or browser provider configuration is added.
|
||||||
|
Before startup reconciliation, the candidate requires a dedicated test database
|
||||||
|
and local-s2s-test storage. The adapter validates initialized engine component and
|
||||||
|
applied session configuration proof, preserves native input/response identities,
|
||||||
|
and closes when interruption requires unsupported history mutation. The separate
|
||||||
|
engine initializes one final-only STT pipeline through bounded HTTP component
|
||||||
|
clients. Startup probes require explicit paid authorization. No real engine/browser
|
||||||
|
acceptance is claimed from fixtures. See the [operator guide](../../services/local_s2s/README.md)
|
||||||
|
and [Phase 2 evidence](../evaluation/local-s2s/phase-02.md).
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# Dependency resolution and the base digest are explicit preparation gates.
|
||||||
|
# See README.md; this Dockerfile does not fetch weights or use an operational image.
|
||||||
|
ARG ENGINE_BASE_IMAGE
|
||||||
|
FROM ${ENGINE_BASE_IMAGE}
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
|
||||||
|
WORKDIR /app
|
||||||
|
COPY .local-s2s-build/requirements.lock /build/requirements.lock
|
||||||
|
RUN pip install --no-cache-dir --require-hashes -r /build/requirements.lock
|
||||||
|
COPY .local-s2s-build/upstream /opt/speech-to-speech
|
||||||
|
RUN pip install --no-deps --no-build-isolation /opt/speech-to-speech
|
||||||
|
COPY pyproject.toml alembic.ini /app/
|
||||||
|
COPY app /app/app
|
||||||
|
COPY services/local_s2s /app/services/local_s2s
|
||||||
|
COPY migrations /app/migrations
|
||||||
|
COPY .local-s2s-build/build-manifest.json /app/engine-build-manifest.json
|
||||||
|
RUN pip install --no-deps --no-build-isolation -e /app
|
||||||
|
CMD ["python", "-m", "services.local_s2s.engine", "--allow-paid-startup"]
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
**
|
||||||
|
!pyproject.toml
|
||||||
|
!alembic.ini
|
||||||
|
!app/
|
||||||
|
!app/**
|
||||||
|
!migrations/
|
||||||
|
!migrations/**
|
||||||
|
!services/
|
||||||
|
!services/local_s2s/
|
||||||
|
!services/local_s2s/**
|
||||||
|
!.local-s2s-build/
|
||||||
|
!.local-s2s-build/**
|
||||||
|
**/.git
|
||||||
|
**/.venv
|
||||||
|
**/__pycache__
|
||||||
|
**/.env
|
||||||
|
**/*.pyc
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
# Phase 2 local engine (development only)
|
||||||
|
|
||||||
|
This stack is isolated from operational OpenAI. Phase 1 live acceptance is still
|
||||||
|
pending. Do not activate this candidate until that prerequisite is accepted and
|
||||||
|
a bounded live run is authorized. Offline tests do not prove real Persian voice.
|
||||||
|
|
||||||
|
## Offline result now
|
||||||
|
|
||||||
|
From the repository root:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py -q -p no:cacheprovider
|
||||||
|
.venv/Scripts/python -m app.local_s2s_smoke --output temp/local-s2s-stub.wav
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a fresh output name when re-running. Play the WAV in any audio player. It is
|
||||||
|
an explicit 440 Hz **test tone**, not synthesized Persian. No network or paid
|
||||||
|
requests occur in stub mode. Both multipart and JSON STT framing are covered by
|
||||||
|
HTTP fixtures. `--live` is a separate opt-in and never a health check.
|
||||||
|
|
||||||
|
## Build preparation (not executed in this checkpoint)
|
||||||
|
|
||||||
|
1. Obtain an authorized clean source checkout at
|
||||||
|
`619e3fe4f71d1c6f35c15870d588a3638de34722`. Obtain a Python 3.11 slim **registry
|
||||||
|
digest** and a separately provisioned local Silero source/model bundle. The
|
||||||
|
launcher refuses remote Torch Hub model loading and disables Smart Turn.
|
||||||
|
2. Prepare immutable source/dependency inputs:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python services/local_s2s/prepare_build.py --checkout <clean-upstream-checkout> --base-image python:3.11-slim@sha256:<registry-digest>
|
||||||
|
```
|
||||||
|
|
||||||
|
3. In an authorized dependency-resolution environment with `uv` installed, create
|
||||||
|
a Linux hash lock; do not resolve it from the Windows virtualenv:
|
||||||
|
|
||||||
|
```text
|
||||||
|
uv pip compile .local-s2s-build/requirements.in --python-version 3.11 --python-platform x86_64-unknown-linux-gnu --generate-hashes -o .local-s2s-build/requirements.lock
|
||||||
|
```
|
||||||
|
|
||||||
|
Review dependency size/licensing and CPU PyTorch selection before installing.
|
||||||
|
Source pinning alone is not a dependency lock. No lock/base digest is claimed
|
||||||
|
in this checkpoint. Keep the resolved lock and resulting image digest as
|
||||||
|
evaluation provenance. The recipe installs hashes and performs no weight fetch.
|
||||||
|
4. Build the separate image (after build/download authorization):
|
||||||
|
|
||||||
|
```text
|
||||||
|
docker build -f services/local_s2s/Dockerfile --build-arg ENGINE_BASE_IMAGE=python:3.11-slim@sha256:<same-digest> -t rag-local-s2s-candidate:phase2 .
|
||||||
|
```
|
||||||
|
|
||||||
|
A Dockerfile-specific ignore file excludes `.env`, operational data and tests.
|
||||||
|
The same image runs the separate engine and application API. The engine receives
|
||||||
|
no database credential or application identity. No operational image is rebuilt.
|
||||||
|
|
||||||
|
## Activation and browser demonstration (still pending)
|
||||||
|
|
||||||
|
Use **only** `docker-compose.local-s2s-test.yml`; it never extends the operational
|
||||||
|
Compose file. `docker compose ... config --quiet` is a safe syntax check; do not
|
||||||
|
print rendered configuration when secrets are set.
|
||||||
|
|
||||||
|
Set explicit model/voice identities and a preprovisioned VAD path. Current catalogue
|
||||||
|
inspection found `openai/whisper-large-v3` and `openai/gpt-4.1-mini`. The configured
|
||||||
|
TTS candidate is `google/gemini-3.8-flash-lite-tts`, voice `Kore`; its Persian quality
|
||||||
|
and 24 kHz PCM compatibility have not been measured. OpenAI TTS IDs were absent
|
||||||
|
from the observed speech catalogue. Do not silently fall back if a model fails.
|
||||||
|
|
||||||
|
`LOCAL_S2S_ENABLE_CANDIDATE=true` enables the development API. Set
|
||||||
|
`LOCAL_S2S_ALLOW_PAID_STARTUP=true` **only after authorization**: upstream STT, LLM
|
||||||
|
and TTS initialization can make paid warmup/probe requests. Their counts are printed
|
||||||
|
at startup/close. They are separate from the smoke command's three requests.
|
||||||
|
`OPENROUTER_API_KEY` belongs only in the engine process environment; an optional
|
||||||
|
`LOCAL_S2S_TOKEN` authenticates API-to-engine access and must match both services.
|
||||||
|
Never put keys in a profile, command-line argument, browser or committed file.
|
||||||
|
|
||||||
|
After the gates above:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml up -d candidate_db candidate_migrations local-s2s-engine candidate_api
|
||||||
|
docker compose -f docker-compose.local-s2s-test.yml exec -it candidate_api python -m app.bootstrap --organization-name Local-S2S-Test --username local-s2s-admin --assistant-name Local-S2S-Test --instruction "Answer briefly in Persian"
|
||||||
|
```
|
||||||
|
|
||||||
|
Bootstrap prompts for a **new test-only password**. It does not copy an operational
|
||||||
|
account. API URL: `http://127.0.0.2:8091`; use a fresh browser profile. Repoint the
|
||||||
|
existing Angular client's backend/proxy to this isolated URL using its own checkout's
|
||||||
|
configuration. That Angular source is not present in this repository, so no
|
||||||
|
frontend build/repointing was performed here. Ensure the browser uses the trusted
|
||||||
|
Origin `http://127.0.0.2:8091`, or configure the explicit isolated frontend Origin
|
||||||
|
and Host in the candidate only. Cookies are not isolated by port.
|
||||||
|
|
||||||
|
The configured embedding endpoint deliberately refuses inference: this is a
|
||||||
|
**greeting/transport-only** candidate, not a RAG quality demo. It cannot reuse
|
||||||
|
operational documents, sessions or calibrated search credentials. Phase 3 owns
|
||||||
|
shared RAG acceptance and exact interruption repair. Until then, interruption
|
||||||
|
requiring cleanup closes the local session; it does not continue unsafely.
|
||||||
|
|
||||||
|
For a separately consented real-stage WAV (three requests, no automatic retries):
|
||||||
|
|
||||||
|
```text
|
||||||
|
python -m app.local_s2s_smoke --live --input <consented-mono24k-PCM16.wav> --output <new-evaluation.wav> --save-evaluation-audio
|
||||||
|
```
|
||||||
|
|
||||||
|
The input is limited to 10 seconds, the LLM to 128 output tokens/300 answer
|
||||||
|
characters, and retained PCM to 10 seconds. Stream cutoff bounds local data;
|
||||||
|
it cannot prove remote compute/billing stopped. Meter actual usage separately.
|
||||||
|
No default conversation logging or automatic speech artifact collection exists.
|
||||||
|
|
||||||
|
## Limits and provenance
|
||||||
|
|
||||||
|
One initialized pipeline; final-only STT; 10-second VAD segments; bounded pipeline
|
||||||
|
queues (256 items each, overflow stops the candidate); component gateway admits
|
||||||
|
at most three requests with four pending sockets; request/response byte bounds
|
||||||
|
are in `components.py`; HTTP deadline defaults to 30 seconds; no SDK/transport
|
||||||
|
retry. Partial/oversized streams omit the final HTTP chunk so consumers observe
|
||||||
|
failure. Component startup counts are not a monetary cost measurement.
|
||||||
|
|
||||||
|
The extension confirms component identities from initialized handlers and projects
|
||||||
|
post-application native session state onto the setup contract. It never treats a
|
||||||
|
request echo as proof of active global models. Credentials must be configured and
|
||||||
|
startup probes succeed before admission. A configuration mismatch prevents setup;
|
||||||
|
no history receipt is fabricated. Engine construction/conformance against the real
|
||||||
|
pinned dependencies remains unexecuted and may reveal compatibility repairs.
|
||||||
|
|
||||||
|
Stop only this candidate with `docker compose -f docker-compose.local-s2s-test.yml stop`.
|
||||||
|
Do not run `compose down`, delete volumes or stop/rebuild either preserved OpenAI
|
||||||
|
container. A candidate container rollback is not a data rollback.
|
||||||
|
|
||||||
|
|
||||||
|
## Phase 2 repair checkpoint: extension v2
|
||||||
|
|
||||||
|
`rag-local-s2s-phase2-v2` changes the local extension behavior. New profiles pin
|
||||||
|
v2; existing v1 reservations are never rewritten and cannot silently use v2.
|
||||||
|
The private browser PCM/events, canonical retrieval, identities and unsupported
|
||||||
|
interruption policy are unchanged. No live acceptance or deployment switch occurred.
|
||||||
|
|
||||||
|
The request client policy is installed **before handler construction**. It puts
|
||||||
|
`max_tokens=LOCAL_S2S_MAX_OUTPUT_TOKENS` on every Chat Completions request, including
|
||||||
|
normal STT-derived text turns and the constructor's warmup, and forces zero retries
|
||||||
|
even when pinned warmup asks `with_options(max_retries=6)` (see the provenance
|
||||||
|
correction below; the earlier isolated harness supplied 10). The configured request
|
||||||
|
deadline also enters the actual base setup before warmup; attestation reads the
|
||||||
|
active client policy, not `gen_kwargs` (unused by that upstream text path).
|
||||||
|
|
||||||
|
Provision tokenizer assets in a separate, explicitly authorized staging environment.
|
||||||
|
Copy unpacked `punkt_tab` English data and `averaged_perceptron_tagger_eng` into
|
||||||
|
`LOCAL_S2S_NLTK_SOURCE`. Required relative files:
|
||||||
|
|
||||||
|
- `tokenizers/punkt_tab/english/{abbrev_types.txt,collocations.tab,sent_starters.txt,ortho_context.tab}`
|
||||||
|
- `taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.{weights,classes,tagdict}.json`
|
||||||
|
|
||||||
|
The local Silero bundle must contain `hubconf.py`,
|
||||||
|
`src/silero_vad/data/silero_vad.jit`, and all source files its hub entry point uses.
|
||||||
|
The whole supplied bundle is fingerprinted. No symlinks or unlisted extra files
|
||||||
|
are accepted (Git metadata and Python caches are ignored). Neither this repair
|
||||||
|
nor engine startup downloads any of these resources. Original NLTK sentence/POS
|
||||||
|
functions are retained; there is no fallback tokenizer.
|
||||||
|
|
||||||
|
Fingerprint already-provisioned local assets, placing the manifest outside both roots:
|
||||||
|
|
||||||
|
```text
|
||||||
|
python -m services.local_s2s.assets --nltk-root <unpacked-nltk-data> --vad-root <local-silero-bundle> --output <new-assets.json>
|
||||||
|
```
|
||||||
|
|
||||||
|
Review/archive the printed SHA-256 and manifest, then set the three Compose host
|
||||||
|
path variables and `LOCAL_S2S_ASSET_MANIFEST_SHA256`. The engine mounts the resources
|
||||||
|
at `/assets/nltk`, `/vad/silero-vad`, and manifest `/assets/assets.json`, read-only.
|
||||||
|
Preflight verifies every file and the expected manifest SHA, then actually loads
|
||||||
|
NLTK sentence/POS resources **before the gateway or paid probes exist**. Missing,
|
||||||
|
corrupt or unusable assets produce `LOCAL_ENGINE_ASSET_VALIDATION_FAILED` and zero
|
||||||
|
provider calls. Runtime NLTK downloader entry points are blocked. Build preparation
|
||||||
|
removes upstream's import-time download blocks and replaces them with local
|
||||||
|
validation. Previously prepared build inputs must be freshly prepared for v2;
|
||||||
|
do not reuse an old v1 source tree/image under the new revision.
|
||||||
|
|
||||||
|
Gateway bounds now start at connection acceptance. At most three connections own
|
||||||
|
slots; headers are capped at 16 KiB and must finish within `min(5 s, total)`. Body
|
||||||
|
reads, upstream headers/reads and downstream drains have that same inactivity
|
||||||
|
bound. A separate total deadline (default 30 s) covers the entire exchange;
|
||||||
|
small trickled SSE/PCM is forwarded without 8192-byte accumulation and cannot
|
||||||
|
extend it. Unsupported content encoding fails before decoding. On timeout or
|
||||||
|
disconnect, the downstream socket closes immediately, upstream work is cancelled,
|
||||||
|
and closure has at most a further 0.5 s per owned transport. Failed partial
|
||||||
|
responses omit the terminating HTTP chunk, so consumers observe an incomplete stream.
|
||||||
|
Local cancellation is not proof that remote inference/billing stopped.
|
||||||
|
|
||||||
|
Construction/probes have a 90 s owner deadline; the asset fingerprint walk has a
|
||||||
|
30 s check budget, 4096 files and 512 MiB total limits. Probe counters count one
|
||||||
|
admitted attempt even on provider failure. Runtime stop, gateway shutdown, socket
|
||||||
|
close and joining are independently guarded (2 s each); a stop exception or hang
|
||||||
|
cannot skip later cleanup or the final numeric counters. Nonzero cleanup outcomes
|
||||||
|
fail the process. SIGINT/SIGTERM handlers signal the owned stop event and previous
|
||||||
|
handlers are restored. Pinned upstream `wait()` can itself call `stop()` and raise;
|
||||||
|
the independent final cleanup still runs in that case.
|
||||||
|
|
||||||
|
Offline repair conformance (no providers/models/dependency installs):
|
||||||
|
|
||||||
|
```text
|
||||||
|
python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider
|
||||||
|
```
|
||||||
|
|
||||||
|
The harness executes hash-checked pinned setup, normal text `process`, request,
|
||||||
|
warmup and stop methods with isolated I/O/history dependencies. Outgoing HTTPX JSON
|
||||||
|
payloads and attempt counts are inspected. This is stronger than attribute-only
|
||||||
|
fixtures, but the complete OpenAI SDK/ML engine image remains unbuilt/unverified.
|
||||||
|
Windows signal tests dispatch the installed handlers; they do not claim OS-level
|
||||||
|
POSIX signal delivery. Real engine, component audio and isolated Persian browser
|
||||||
|
greeting/transcripts/normal close evidence are still required for live acceptance.
|
||||||
|
|
||||||
|
|
||||||
|
## Phase 2 remaining repairs: extension v3
|
||||||
|
|
||||||
|
Current behavior is `rag-local-s2s-phase2-v3`, with the v1 private contract shape.
|
||||||
|
Fresh profiles and prepared build manifests use v3; v1/v2 reservations remain
|
||||||
|
frozen and fail revision mismatch instead of being rewritten. Preserve earlier
|
||||||
|
build inputs and prepare a fresh workspace for v3. The five v2 repairs remain.
|
||||||
|
No browser events, PCM24k, retrieval authority or interruption capability changed.
|
||||||
|
|
||||||
|
After the complete request body, an owned downstream watcher runs concurrently
|
||||||
|
with upstream header acquisition and streaming. It does not need response data
|
||||||
|
or a failed write to notice closure. Ordinary downstream EOF/reset cancels the
|
||||||
|
upstream operation. Response/client closure and task joining share a **one-second
|
||||||
|
cleanup window**, followed by slot release; stalled close operations are cancelled
|
||||||
|
and the downstream transport is aborted when that window expires. Existing total
|
||||||
|
and inactivity limits remain. Failed partial responses never gain a successful
|
||||||
|
terminal HTTP chunk. Cancellation does not prove remote inference/billing stopped.
|
||||||
|
|
||||||
|
TCP FIN alone cannot reveal whether a peer fully closed or only called SHUT_WR.
|
||||||
|
The private component gateway therefore defines the following explicit policy:
|
||||||
|
|
||||||
|
- Ordinary clients keep their send side open until completion. EOF is cancellation
|
||||||
|
by contract, even when that peer could still receive. SDK requests follow this path.
|
||||||
|
- A client intentionally stopping its send side while retaining its receive side
|
||||||
|
must send `X-Local-S2S-Half-Close: receive-response` before the body. After a complete
|
||||||
|
body, FIN then allows the bounded response to finish. A reset/transport error still
|
||||||
|
cancels. A subsequent graceful full close is indistinguishable from the declared
|
||||||
|
half-close and remains bounded by the original request deadlines.
|
||||||
|
- Other header values fail before provider admission; extra request bytes/pipelining
|
||||||
|
are unsupported. The half-close header is private, is not forwarded upstream and
|
||||||
|
does not change the browser protocol. The gateway closes its send side at completion.
|
||||||
|
|
||||||
|
Real loopback tests exercise both downstream and upstream TCP sockets for disconnect
|
||||||
|
before headers and after headers with no further upstream output. They assert local
|
||||||
|
upstream socket closure, HTTP transport closure and slot release within the cleanup
|
||||||
|
window plus scheduling tolerance, before the five-second test request deadline.
|
||||||
|
Separate tests cover normal success, declared half-close success, undeclared FIN
|
||||||
|
cancellation and a stalled transport close. They require no external services.
|
||||||
|
|
||||||
|
The local identifier validator now has a distinct method name so VoiceSettings
|
||||||
|
inherits it alongside its existing OpenAI/Gemini validator. All four local model/
|
||||||
|
voice fields reject whitespace, controls and non-ASCII before assets, construction
|
||||||
|
or probes. Valid identifiers and existing provider validation are retained.
|
||||||
|
|
||||||
|
Provenance correction: the hash-checked pinned `base.py.source` defines
|
||||||
|
`WARMUP_MAX_RETRIES = 6` at line 66; Chat Completions imports that constant. The v2
|
||||||
|
harness injected 10 as an isolated override and incorrectly described it as the
|
||||||
|
pinned value. Its historical 31/107/242 execution results remain unchanged, but
|
||||||
|
that description was wrong. Current warmup tests read 6 from the verified source
|
||||||
|
AST and test both retryable HTTP and connection failures with exactly one attempt.
|
||||||
|
The full OpenAI SDK/ML engine still has not been executed.
|
||||||
|
|
||||||
|
Final offline checks for v3: **74 repair, 107 combined and 242 preservation tests
|
||||||
|
passed**, using `-p no:cacheprovider`. Compose configuration validation and
|
||||||
|
`git diff --check` passed. Exact commands/timings and the scoped patch are in the
|
||||||
|
[Phase 2 report](../../docs/evaluation/local-s2s/phase-02.md#remaining-defect-repair-checkpoint-extension-v3).
|
||||||
|
No paid calls, downloads, image builds, operational changes or PostgreSQL acceptance
|
||||||
|
were performed here. Phase 2 remains in_progress/live acceptance pending until
|
||||||
|
real-engine, component-audio and isolated Persian browser greeting/transcripts/
|
||||||
|
normal-close evidence exists, alongside the existing Phase 1 prerequisite.
|
||||||
|
|
||||||
|
|
||||||
|
## Acceptance runbook and newly located resources
|
||||||
|
|
||||||
|
See the [acceptance checklist](../../docs/evaluation/local-s2s/phase-02-acceptance-checklist.md)
|
||||||
|
for exact preparation/live commands, isolation boundaries, proposed request ceilings,
|
||||||
|
stop rules and actual outcomes. The checklist separates already authorized offline
|
||||||
|
preparation/DB tests from unapproved downloads/builds/paid calls; its examples are
|
||||||
|
not permission. v3 implementation and behavior are unchanged.
|
||||||
|
|
||||||
|
A 201-file local NLTK/Silero manifest now exists, SHA-256
|
||||||
|
`8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8`.
|
||||||
|
NLTK 3.10.3 sentence/POS loading passed in the existing sibling Windows environment
|
||||||
|
with downloads blocked. These host assets still need review and Linux validation.
|
||||||
|
The immutable Linux Python base is cached; full pinned source, reviewed dependency
|
||||||
|
lock and candidate image are still absent. Do not use the dirty sibling engine
|
||||||
|
checkout at a different revision as a substitute.
|
||||||
|
|
||||||
|
The sibling Angular checkout was located at
|
||||||
|
`D:/raymand/projects/faq_chatbot_frontend`; its original LAN proxy/package edit were
|
||||||
|
preserved. The prepared browser override uses Origin http://127.0.0.2:4201 and a
|
||||||
|
separate proxy file, retaining same-origin browser API/WS calls. Nothing was launched.
|
||||||
|
The Phase 1 override can run changed API source read-only on a cached immutable
|
||||||
|
image using isolated candidate DB/storage and masked inherited data, without an
|
||||||
|
engine build. Actual OpenAI listening still requires bounded live consent.
|
||||||
|
|
||||||
|
Fresh DB checks: 2 local passed; expanded 57 passed/6 existing baseline failures,
|
||||||
|
all with --require-postgres against a verified disposable DB. The guarded runner
|
||||||
|
restored its stopped state. No runtime assertion was relaxed. Phase 2 remains
|
||||||
|
NOT ACCEPTED until complete engine/SDK/POSIX, component audio and Persian browser
|
||||||
|
evidence exists along with Phase 1 acceptance. There were no paid calls, downloads,
|
||||||
|
image builds or operational changes in this preparation checkpoint.
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""Preflight local tokenizer/VAD resources. No runtime downloader is permitted."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import time
|
||||||
|
|
||||||
|
REQUIRED_NLTK = (
|
||||||
|
'tokenizers/punkt_tab/english/abbrev_types.txt',
|
||||||
|
'tokenizers/punkt_tab/english/collocations.tab',
|
||||||
|
'tokenizers/punkt_tab/english/sent_starters.txt',
|
||||||
|
'tokenizers/punkt_tab/english/ortho_context.tab',
|
||||||
|
'taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.weights.json',
|
||||||
|
'taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.classes.json',
|
||||||
|
'taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.tagdict.json',
|
||||||
|
)
|
||||||
|
REQUIRED_VAD = ('hubconf.py', 'src/silero_vad/data/silero_vad.jit')
|
||||||
|
|
||||||
|
|
||||||
|
class AssetError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def validate_assets(nltk_root, vad_root, manifest_path):
|
||||||
|
try:
|
||||||
|
roots = {'nltk': Path(nltk_root).resolve(strict=True), 'vad': Path(vad_root).resolve(strict=True)}
|
||||||
|
manifest_path = Path(manifest_path)
|
||||||
|
if manifest_path.stat().st_size > 1048576:
|
||||||
|
raise ValueError()
|
||||||
|
manifest_bytes = manifest_path.read_bytes()
|
||||||
|
manifest = json.loads(manifest_bytes)
|
||||||
|
if not isinstance(manifest, dict) or not isinstance(manifest.get('files'), dict):
|
||||||
|
raise ValueError()
|
||||||
|
files = manifest['files']
|
||||||
|
required = {'nltk/' + p for p in REQUIRED_NLTK} | {'vad/' + p for p in REQUIRED_VAD}
|
||||||
|
if manifest['schema'] != 1 or not required <= files.keys() or not 0 < len(files) <= 4096:
|
||||||
|
raise ValueError()
|
||||||
|
found = set()
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
total = 0
|
||||||
|
for kind, root in roots.items():
|
||||||
|
for path in root.rglob('*'):
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise ValueError()
|
||||||
|
if '.git' in path.parts or '__pycache__' in path.parts:
|
||||||
|
continue
|
||||||
|
if path.is_symlink():
|
||||||
|
raise ValueError()
|
||||||
|
if not path.is_file():
|
||||||
|
continue
|
||||||
|
name = kind + '/' + path.relative_to(root).as_posix()
|
||||||
|
found.add(name)
|
||||||
|
if len(found) > 4096 or name not in files:
|
||||||
|
raise ValueError()
|
||||||
|
total += path.stat().st_size
|
||||||
|
if total > 536870912:
|
||||||
|
raise ValueError()
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
with path.open('rb') as source:
|
||||||
|
while part := source.read(1048576):
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise ValueError()
|
||||||
|
digest.update(part)
|
||||||
|
if digest.hexdigest() != files[name]:
|
||||||
|
raise ValueError()
|
||||||
|
if found != set(files):
|
||||||
|
raise ValueError()
|
||||||
|
return hashlib.sha256(manifest_bytes).hexdigest()
|
||||||
|
except (ValueError, OSError, KeyError, TypeError):
|
||||||
|
raise AssetError('LOCAL_ENGINE_ASSET_VALIDATION_FAILED') from None
|
||||||
|
|
||||||
|
|
||||||
|
def forbid_download(*args, **kwargs):
|
||||||
|
raise AssetError('LOCAL_ENGINE_ASSET_DOWNLOAD_FORBIDDEN')
|
||||||
|
|
||||||
|
|
||||||
|
def configure_nltk(nltk, root):
|
||||||
|
nltk.data.path[:] = [str(Path(root).resolve())]
|
||||||
|
nltk.download = forbid_download
|
||||||
|
# Also block alternate public download entry points before upstream import.
|
||||||
|
if hasattr(nltk, 'downloader'):
|
||||||
|
nltk.downloader.download = forbid_download
|
||||||
|
nltk.downloader.Downloader.download = forbid_download
|
||||||
|
validate_nltk(nltk)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_nltk(nltk):
|
||||||
|
try:
|
||||||
|
nltk.data.find('tokenizers/punkt_tab/english/')
|
||||||
|
nltk.data.find('taggers/averaged_perceptron_tagger_eng/')
|
||||||
|
nltk.sent_tokenize('Local asset verification.')
|
||||||
|
nltk.pos_tag(['verification'], lang='eng')
|
||||||
|
except Exception:
|
||||||
|
raise AssetError('LOCAL_ENGINE_ASSET_VALIDATION_FAILED') from None
|
||||||
|
|
||||||
|
|
||||||
|
def patch_pipeline_source(source):
|
||||||
|
start = source.index('# Ensure that the necessary NLTK resources are available')
|
||||||
|
end = source.index('# caching allows', start)
|
||||||
|
return source[:start] + 'from services.local_s2s.assets import validate_nltk\nvalidate_nltk(nltk)\n\n' + source[end:]
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Fingerprint an already-provisioned local bundle; never fetch resources."""
|
||||||
|
import argparse
|
||||||
|
parser = argparse.ArgumentParser(description=main.__doc__)
|
||||||
|
parser.add_argument('--nltk-root', type=Path, required=True)
|
||||||
|
parser.add_argument('--vad-root', type=Path, required=True)
|
||||||
|
parser.add_argument('--output', type=Path, required=True)
|
||||||
|
args = parser.parse_args()
|
||||||
|
try:
|
||||||
|
roots = {'nltk': args.nltk_root.resolve(strict=True), 'vad': args.vad_root.resolve(strict=True)}
|
||||||
|
if args.output.exists() or any(root == args.output.resolve() or root in args.output.resolve().parents for root in roots.values()):
|
||||||
|
raise ValueError()
|
||||||
|
files, total = {}, 0
|
||||||
|
for kind, root in roots.items():
|
||||||
|
for path in root.rglob('*'):
|
||||||
|
if '.git' in path.parts or '__pycache__' in path.parts:
|
||||||
|
continue
|
||||||
|
if path.is_symlink():
|
||||||
|
raise ValueError()
|
||||||
|
if path.is_file():
|
||||||
|
total += path.stat().st_size
|
||||||
|
if len(files) >= 4096 or total > 536870912:
|
||||||
|
raise ValueError()
|
||||||
|
with path.open('rb') as source:
|
||||||
|
files[kind + '/' + path.relative_to(root).as_posix()] = hashlib.file_digest(source, 'sha256').hexdigest()
|
||||||
|
required = {'nltk/' + p for p in REQUIRED_NLTK} | {'vad/' + p for p in REQUIRED_VAD}
|
||||||
|
if not required <= files.keys():
|
||||||
|
raise ValueError()
|
||||||
|
with args.output.open('x', encoding='utf-8') as target:
|
||||||
|
json.dump(dict(schema=1, files=files), target, indent=2, sort_keys=True)
|
||||||
|
target.write('\n')
|
||||||
|
digest = validate_assets(roots['nltk'], roots['vad'], args.output)
|
||||||
|
except (ValueError, OSError):
|
||||||
|
parser.exit(1, 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED\n')
|
||||||
|
print(json.dumps(dict(manifest_sha256=digest, files=len(files))))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
"""Owned local HTTP gateway: total connection deadlines and bounded async I/O."""
|
||||||
|
import asyncio
|
||||||
|
from collections import Counter
|
||||||
|
import socket
|
||||||
|
from threading import Event, Thread
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
# One shared wall-clock window for cancellation, transport closure and slot release.
|
||||||
|
CLEANUP_WINDOW_SECONDS = 1.0
|
||||||
|
HALF_CLOSE_HEADER = 'x-local-s2s-half-close'
|
||||||
|
|
||||||
|
LIMITS = {'/v1/audio/transcriptions': (1100000, 65536),
|
||||||
|
'/v1/chat/completions': (1048576, 1048576),
|
||||||
|
'/v1/audio/speech': (16384, 1440000)}
|
||||||
|
|
||||||
|
|
||||||
|
class ComponentServer:
|
||||||
|
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None):
|
||||||
|
if not key or not key.isascii() or any(c.isspace() for c in key):
|
||||||
|
raise ValueError('LOCAL_COMPONENT_CREDENTIAL_REQUIRED')
|
||||||
|
self.key, self.transport, self.timeout = key, transport, timeout
|
||||||
|
self.inactivity = min(timeout, 5) if inactivity is None else min(timeout, inactivity)
|
||||||
|
if self.timeout <= 0 or self.inactivity <= 0:
|
||||||
|
raise ValueError('LOCAL_COMPONENT_DEADLINE_REQUIRED')
|
||||||
|
self.counts = Counter()
|
||||||
|
self.socket = socket.socket()
|
||||||
|
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
self.socket.bind(('127.0.0.1', port))
|
||||||
|
self.socket.listen(4)
|
||||||
|
self.socket.setblocking(False)
|
||||||
|
self.server_port = self.socket.getsockname()[1]
|
||||||
|
self.ready, self.done = Event(), Event()
|
||||||
|
self.loop = self.stopping = None
|
||||||
|
self.requests = {}
|
||||||
|
|
||||||
|
def serve_forever(self):
|
||||||
|
try:
|
||||||
|
asyncio.run(self._run())
|
||||||
|
finally:
|
||||||
|
self.socket.close()
|
||||||
|
self.done.set()
|
||||||
|
|
||||||
|
async def _run(self):
|
||||||
|
self.loop, self.stopping = asyncio.get_running_loop(), asyncio.Event()
|
||||||
|
server = await asyncio.start_server(self._accept, sock=self.socket, limit=16384)
|
||||||
|
self.ready.set()
|
||||||
|
try:
|
||||||
|
await self.stopping.wait()
|
||||||
|
finally:
|
||||||
|
server.close()
|
||||||
|
await server.wait_closed()
|
||||||
|
tasks = list(self.requests)
|
||||||
|
for task, writer in list(self.requests.items()):
|
||||||
|
writer.close()
|
||||||
|
task.cancel()
|
||||||
|
if tasks:
|
||||||
|
await asyncio.wait(tasks, timeout=1)
|
||||||
|
self.counts['shutdown_pending'] = sum(not t.done() for t in tasks)
|
||||||
|
|
||||||
|
def _accept(self, reader, writer):
|
||||||
|
accepted = self.loop.time()
|
||||||
|
if self.stopping.is_set() or len(self.requests) >= 3:
|
||||||
|
self.counts['rejected'] += 1
|
||||||
|
writer.close()
|
||||||
|
return
|
||||||
|
writer.transport.set_write_buffer_limits(high=16384, low=4096)
|
||||||
|
task = self.loop.create_task(self._serve(reader, writer, accepted + self.timeout))
|
||||||
|
self.requests[task] = writer
|
||||||
|
self.counts['accepted'] += 1
|
||||||
|
task.add_done_callback(self._finished)
|
||||||
|
|
||||||
|
def _finished(self, task):
|
||||||
|
self.requests.pop(task, None)
|
||||||
|
self.counts['released'] += 1
|
||||||
|
if not task.cancelled():
|
||||||
|
task.exception()
|
||||||
|
|
||||||
|
async def _write(self, writer, data):
|
||||||
|
writer.write(data)
|
||||||
|
await asyncio.wait_for(writer.drain(), self.inactivity)
|
||||||
|
|
||||||
|
async def _error(self, writer, status):
|
||||||
|
await self._write(writer, f'HTTP/1.1 {status} Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'.encode())
|
||||||
|
|
||||||
|
async def _watch_downstream(self, reader, writer, receive_only):
|
||||||
|
# FIN cannot distinguish full close from SHUT_WR. By contract it cancels
|
||||||
|
# ordinary requests; explicit receive-only clients may still read a reply.
|
||||||
|
try:
|
||||||
|
extra = await reader.read(1)
|
||||||
|
if not extra and receive_only:
|
||||||
|
await writer.wait_closed() # still observe a reset/transport loss
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def _forward(self, client, writer, path, fields, body, response):
|
||||||
|
request = client.build_request('POST', 'https://openrouter.ai/api' + path,
|
||||||
|
headers={'Authorization': 'Bearer ' + self.key,
|
||||||
|
'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'},
|
||||||
|
content=bytes(body))
|
||||||
|
# The owner closes the response independently, even if cancellation or a
|
||||||
|
# stalled stream prevents this operation from reaching normal completion.
|
||||||
|
result = await client.send(request, stream=True)
|
||||||
|
response.append(result)
|
||||||
|
if result.status_code != 200:
|
||||||
|
await self._error(writer, 502)
|
||||||
|
return
|
||||||
|
media = result.headers.get('content-type', '').split(';')[0]
|
||||||
|
expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream')
|
||||||
|
if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity':
|
||||||
|
await self._error(writer, 502)
|
||||||
|
return
|
||||||
|
await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media +
|
||||||
|
'\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii'))
|
||||||
|
total = 0
|
||||||
|
# No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
|
||||||
|
async for raw in result.aiter_bytes():
|
||||||
|
total += len(raw)
|
||||||
|
if total > LIMITS[path][1]:
|
||||||
|
raise ValueError('Response capacity')
|
||||||
|
for offset in range(0, len(raw), 8192):
|
||||||
|
part = raw[offset:offset + 8192]
|
||||||
|
await self._write(writer, f'{len(part):x}\r\n'.encode() + part + b'\r\n')
|
||||||
|
if not total:
|
||||||
|
raise ValueError('Empty component response')
|
||||||
|
await self._write(writer, b'0\r\n\r\n')
|
||||||
|
|
||||||
|
async def _close_owned(self, writer, tasks, client, response):
|
||||||
|
writer.close()
|
||||||
|
for task in tasks:
|
||||||
|
task.cancel()
|
||||||
|
# Close all transports independently; one stalled close must not defer
|
||||||
|
# another. asyncio.wait bounds the entire cleanup, including task joins.
|
||||||
|
closing = [asyncio.create_task(writer.wait_closed())]
|
||||||
|
if client is not None:
|
||||||
|
closing.append(asyncio.create_task(client.aclose()))
|
||||||
|
closing.extend(asyncio.create_task(result.aclose()) for result in response)
|
||||||
|
done, pending = await asyncio.wait(set(tasks) | set(closing), timeout=CLEANUP_WINDOW_SECONDS)
|
||||||
|
for task in done:
|
||||||
|
if not task.cancelled():
|
||||||
|
error = task.exception()
|
||||||
|
if task in closing and error is not None:
|
||||||
|
self.counts['close_errors'] += 1
|
||||||
|
if pending:
|
||||||
|
self.counts['close_errors'] += len(pending)
|
||||||
|
writer.transport.abort()
|
||||||
|
for task in pending:
|
||||||
|
task.cancel()
|
||||||
|
task.add_done_callback(lambda t: None if t.cancelled() else t.exception())
|
||||||
|
|
||||||
|
async def _serve(self, reader, writer, deadline):
|
||||||
|
client, tasks, response = None, [], []
|
||||||
|
try:
|
||||||
|
async with asyncio.timeout_at(deadline):
|
||||||
|
# Header acquisition has its own short bound, including partial headers.
|
||||||
|
header = await asyncio.wait_for(reader.readuntil(b'\r\n\r\n'), self.inactivity)
|
||||||
|
lines = header.decode('ascii').split('\r\n')
|
||||||
|
method, path, version = lines[0].split(' ')
|
||||||
|
fields = {}
|
||||||
|
for line in lines[1:-2]:
|
||||||
|
key, value = line.split(':', 1)
|
||||||
|
key = key.lower()
|
||||||
|
if key in fields:
|
||||||
|
raise ValueError('Repeated header')
|
||||||
|
fields[key] = value.strip()
|
||||||
|
if method != 'POST' or path not in LIMITS or version not in ('HTTP/1.0', 'HTTP/1.1'):
|
||||||
|
await self._error(writer, 403)
|
||||||
|
return
|
||||||
|
request_limit, _ = LIMITS[path]
|
||||||
|
size = int(fields.get('content-length', '-1'))
|
||||||
|
if 'transfer-encoding' in fields or not 0 < size <= request_limit:
|
||||||
|
await self._error(writer, 413)
|
||||||
|
return
|
||||||
|
body = bytearray()
|
||||||
|
while len(body) < size:
|
||||||
|
part = await asyncio.wait_for(reader.read(min(8192, size - len(body))), self.inactivity)
|
||||||
|
if not part:
|
||||||
|
raise ValueError('Incomplete request')
|
||||||
|
body.extend(part)
|
||||||
|
if fields.get('authorization') != 'Bearer local-components':
|
||||||
|
await self._error(writer, 403)
|
||||||
|
return
|
||||||
|
half_close = fields.get(HALF_CLOSE_HEADER)
|
||||||
|
if half_close not in (None, 'receive-response'):
|
||||||
|
await self._error(writer, 400)
|
||||||
|
return
|
||||||
|
self.counts[path] += 1 # one admitted provider attempt, including failed probes
|
||||||
|
client = httpx.AsyncClient(transport=self.transport, timeout=httpx.Timeout(self.inactivity, connect=self.inactivity),
|
||||||
|
follow_redirects=False, trust_env=False)
|
||||||
|
forwarding = asyncio.create_task(self._forward(client, writer, path, fields, body, response))
|
||||||
|
watching = asyncio.create_task(self._watch_downstream(reader, writer, half_close == 'receive-response'))
|
||||||
|
tasks.extend((forwarding, watching))
|
||||||
|
done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||||
|
if forwarding in done:
|
||||||
|
forwarding.result()
|
||||||
|
else:
|
||||||
|
self.counts['disconnected'] += 1
|
||||||
|
except TimeoutError:
|
||||||
|
self.counts['expired'] += 1
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
self.counts['cancelled'] += 1
|
||||||
|
raise
|
||||||
|
except (ValueError, OSError, UnicodeError, asyncio.IncompleteReadError,
|
||||||
|
asyncio.LimitOverrunError, httpx.HTTPError):
|
||||||
|
self.counts['failures'] += 1
|
||||||
|
finally:
|
||||||
|
# No successful terminal chunk is fabricated on any failure path.
|
||||||
|
await self._close_owned(writer, tasks, client, response)
|
||||||
|
|
||||||
|
def shutdown(self):
|
||||||
|
if self.loop is not None and self.loop.is_running():
|
||||||
|
self.loop.call_soon_threadsafe(self.stopping.set)
|
||||||
|
self.done.wait(2)
|
||||||
|
|
||||||
|
def server_close(self):
|
||||||
|
self.socket.close()
|
||||||
|
|
||||||
|
|
||||||
|
def start_components(key, timeout=30):
|
||||||
|
server = ComponentServer(key, timeout=timeout)
|
||||||
|
thread = Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
if not server.ready.wait(5):
|
||||||
|
server.server_close()
|
||||||
|
raise ValueError('LOCAL_COMPONENT_STARTUP_DEADLINE')
|
||||||
|
return server, thread
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""Development engine launcher; local asset preflight precedes every paid probe."""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def build_runtime(config, stop):
|
||||||
|
from services.local_s2s.extension import active_components, install_session_proof, FailClosedQueue, EngineTokenGuard
|
||||||
|
from services.local_s2s.request_policy import install_client_policy
|
||||||
|
from app.modules.voice.local_s2s import setup_session
|
||||||
|
from speech_to_speech.config import load_config, resolve_config
|
||||||
|
from speech_to_speech.configured_runtime import build_configured_server
|
||||||
|
from speech_to_speech.api.openai_realtime.handlers.session import SessionHandler
|
||||||
|
import speech_to_speech.s2s_pipeline as pipeline
|
||||||
|
import speech_to_speech.LLM.base_openai_compatible_language_model as base_llm
|
||||||
|
import speech_to_speech.api.openai_realtime.server as server_module
|
||||||
|
import torch
|
||||||
|
source = Path(os.environ.get('LOCAL_S2S_SILERO_SOURCE', '/vad/silero-vad'))
|
||||||
|
native_load = torch.hub.load
|
||||||
|
def local_vad(repo, *args, **kwargs):
|
||||||
|
if repo != 'snakers4/silero-vad:master':
|
||||||
|
raise ValueError('LOCAL_ENGINE_UNEXPECTED_MODEL_DOWNLOAD')
|
||||||
|
kwargs['source'] = 'local'
|
||||||
|
return native_load(str(source), *args, **kwargs)
|
||||||
|
torch.hub.load = local_vad
|
||||||
|
pipeline.Queue = lambda *args, **kwargs: FailClosedQueue(stop)
|
||||||
|
# Base setup invokes warmup from inside construction; install before it runs.
|
||||||
|
install_client_policy(base_llm, config)
|
||||||
|
resolved = resolve_config(load_config(Path(__file__).with_name('pipeline.yaml')), names=['local'])
|
||||||
|
runtime = build_configured_server(resolved, stop)
|
||||||
|
try:
|
||||||
|
units = runtime.server.pool
|
||||||
|
if len(units) != 1:
|
||||||
|
raise ValueError('LOCAL_ENGINE_SINGLE_PIPELINE_REQUIRED')
|
||||||
|
components = {id(unit.service): active_components(unit, config.components()) for unit in units}
|
||||||
|
install_session_proof(SessionHandler, components, setup_session(config))
|
||||||
|
create_app = server_module.create_app
|
||||||
|
def guarded_app(*args, **kwargs):
|
||||||
|
return EngineTokenGuard(create_app(*args, **kwargs), config.local_s2s_token.get_secret_value())
|
||||||
|
server_module.create_app = guarded_app
|
||||||
|
return runtime
|
||||||
|
except BaseException:
|
||||||
|
from services.local_s2s.lifecycle import bounded_call
|
||||||
|
bounded_call(runtime.stop, 2)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--allow-paid-startup', action='store_true')
|
||||||
|
args = parser.parse_args()
|
||||||
|
if not args.allow_paid_startup or os.environ.get('LOCAL_S2S_ALLOW_PAID_STARTUP') != 'true':
|
||||||
|
parser.error('Engine initialization performs paid component probes; authorize before starting.')
|
||||||
|
from app.modules.voice.configuration import VoiceSettings
|
||||||
|
from services.local_s2s.assets import validate_assets, configure_nltk, AssetError
|
||||||
|
from services.local_s2s.lifecycle import run_owned
|
||||||
|
try:
|
||||||
|
config = VoiceSettings(_env_file=None, provider='local_s2s')
|
||||||
|
config.require_voice()
|
||||||
|
root = os.environ.get('LOCAL_S2S_NLTK_DATA', '/assets/nltk')
|
||||||
|
fingerprint = validate_assets(root, os.environ.get('LOCAL_S2S_SILERO_SOURCE', '/vad/silero-vad'),
|
||||||
|
os.environ.get('LOCAL_S2S_ASSET_MANIFEST', '/assets/assets.json'))
|
||||||
|
if fingerprint != os.environ.get('LOCAL_S2S_ASSET_MANIFEST_SHA256'):
|
||||||
|
raise AssetError('LOCAL_ENGINE_ASSET_VALIDATION_FAILED')
|
||||||
|
import nltk
|
||||||
|
configure_nltk(nltk, root)
|
||||||
|
except (ValueError, OSError, ImportError):
|
||||||
|
print(json.dumps(dict(status='failed', category='LOCAL_ENGINE_ASSET_VALIDATION_FAILED')), flush=True)
|
||||||
|
return 1
|
||||||
|
logging.disable(logging.CRITICAL)
|
||||||
|
os.environ['HF_HUB_OFFLINE'] = '1'
|
||||||
|
os.environ['NLTK_DATA'] = root
|
||||||
|
key = os.environ.get('OPENROUTER_API_KEY', '')
|
||||||
|
if not key:
|
||||||
|
parser.error('OPENROUTER_API_KEY is required in the engine only.')
|
||||||
|
return run_owned(lambda stop: build_runtime(config, stop), key, config.local_s2s_request_timeout_seconds)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""Versioned extension for the pinned engine; no history-repair capability."""
|
||||||
|
from copy import deepcopy
|
||||||
|
from queue import Queue, Full
|
||||||
|
from app.modules.voice.local_s2s import effective_identity
|
||||||
|
|
||||||
|
|
||||||
|
class FailClosedQueue(Queue):
|
||||||
|
"""Saturation stops the candidate rather than blocking a teardown producer."""
|
||||||
|
def __init__(self, stop_event, maxsize=256):
|
||||||
|
super().__init__(maxsize=maxsize)
|
||||||
|
self.stop_event = stop_event
|
||||||
|
|
||||||
|
def put(self, item, block=True, timeout=None):
|
||||||
|
try:
|
||||||
|
return super().put(item, block=False)
|
||||||
|
except Full:
|
||||||
|
self.stop_event.set()
|
||||||
|
raise RuntimeError('LOCAL_ENGINE_QUEUE_CAPACITY') from None
|
||||||
|
|
||||||
|
|
||||||
|
def active_components(unit, expected):
|
||||||
|
"""Read initialized handlers, not session.update model/voice echoes."""
|
||||||
|
handlers = unit.handlers
|
||||||
|
stt = next(h for h in handlers if type(h).__module__.endswith('.STT.openai_compatible_handler'))
|
||||||
|
tts = next(h for h in handlers if type(h).__module__.endswith('.TTS.openai_compatible_handler'))
|
||||||
|
llm = next(h for h in handlers if hasattr(h, 'model_name') and hasattr(h, 'client'))
|
||||||
|
actual = dict(stt=dict(backend='openai', model=stt.model, language=stt.language,
|
||||||
|
response_format=stt.response_format, final_only=True),
|
||||||
|
llm=dict(backend='chat-completions', model=llm.model_name,
|
||||||
|
max_output_tokens=getattr(llm.client, 'token_limit', None)),
|
||||||
|
tts=dict(backend='openai', model=tts.model, voice=tts.voice,
|
||||||
|
response_format=tts.response_format, sample_rate=tts.sample_rate),
|
||||||
|
request_timeout_seconds=stt.timeout)
|
||||||
|
if (actual != expected or tts.timeout != stt.timeout or llm.request_timeout_s != stt.timeout
|
||||||
|
or stt.base_url != 'http://127.0.0.1:8766/v1' or tts.base_url != stt.base_url
|
||||||
|
or str(llm.client.base_url).rstrip('/') != stt.base_url
|
||||||
|
or stt.api_key != 'local-components' or tts.api_key != stt.api_key
|
||||||
|
or llm.client.api_key != stt.api_key):
|
||||||
|
raise ValueError('LOCAL_ENGINE_COMPONENT_MISMATCH')
|
||||||
|
# Startup configuration fixes these values; refuse any unsupported handler layout.
|
||||||
|
vad = handlers[0]
|
||||||
|
if getattr(vad, 'enable_realtime_transcription', None) is not False:
|
||||||
|
raise ValueError('LOCAL_ENGINE_FINAL_ONLY_REQUIRED')
|
||||||
|
if llm.client.max_retries != 0:
|
||||||
|
raise ValueError('LOCAL_ENGINE_RETRY_POLICY_MISMATCH')
|
||||||
|
return actual
|
||||||
|
|
||||||
|
|
||||||
|
def install_session_proof(handler_class, service_components, session_template):
|
||||||
|
original = handler_class.build_session_updated
|
||||||
|
def build_session_updated(self, conn_id):
|
||||||
|
result = original(self, conn_id)
|
||||||
|
cfg = self._state(conn_id).runtime_config
|
||||||
|
# Project the actual post-update state onto the requested contract shape.
|
||||||
|
# Extra SDK defaults do not change the effective contract fingerprint.
|
||||||
|
actual = cfg.session.model_dump(mode='json')
|
||||||
|
def project(value, shape):
|
||||||
|
if isinstance(shape, dict):
|
||||||
|
return {k: project(value[k], v) for k, v in shape.items()}
|
||||||
|
if isinstance(shape, list):
|
||||||
|
if not isinstance(value, list) or len(value) != len(shape):
|
||||||
|
raise ValueError('LOCAL_ENGINE_SESSION_LAYOUT')
|
||||||
|
return [project(a, b) for a, b in zip(value, shape)]
|
||||||
|
return value
|
||||||
|
session = project(actual, session_template)
|
||||||
|
components = service_components[id(self._service)]
|
||||||
|
identity = effective_identity(components, session)
|
||||||
|
return result.model_copy(update={'session': result.session.model_copy(update={'s2s_effective': identity})})
|
||||||
|
handler_class.build_session_updated = build_session_updated
|
||||||
|
return original
|
||||||
|
|
||||||
|
class EngineTokenGuard:
|
||||||
|
def __init__(self, app, token):
|
||||||
|
self.app, self.token = app, token
|
||||||
|
|
||||||
|
async def __call__(self, scope, receive, send):
|
||||||
|
import hmac
|
||||||
|
if scope['type'] in ('http', 'websocket') and self.token:
|
||||||
|
header = dict(scope.get('headers', [])).get(b'authorization', b'')
|
||||||
|
if not hmac.compare_digest(header, ('Bearer ' + self.token).encode('ascii')):
|
||||||
|
if scope['type'] == 'websocket':
|
||||||
|
await send({'type': 'websocket.close', 'code': 1008})
|
||||||
|
else:
|
||||||
|
await send({'type': 'http.response.start', 'status': 401, 'headers': []})
|
||||||
|
await send({'type': 'http.response.body', 'body': b''})
|
||||||
|
return
|
||||||
|
await self.app(scope, receive, send)
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""Independent bounded cleanup and owned process signal lifecycle."""
|
||||||
|
from contextlib import contextmanager
|
||||||
|
import json
|
||||||
|
import signal
|
||||||
|
from threading import Event, Lock, Thread
|
||||||
|
import time
|
||||||
|
from services.local_s2s.components import start_components
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def termination_signals(stop):
|
||||||
|
previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)}
|
||||||
|
try:
|
||||||
|
for sig in previous:
|
||||||
|
signal.signal(sig, lambda *_: stop.set())
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
for sig, handler in previous.items():
|
||||||
|
signal.signal(sig, handler)
|
||||||
|
|
||||||
|
|
||||||
|
def bounded_call(action, timeout):
|
||||||
|
finished, result = Event(), []
|
||||||
|
def run():
|
||||||
|
try:
|
||||||
|
action()
|
||||||
|
result.append(0)
|
||||||
|
except BaseException:
|
||||||
|
result.append(1)
|
||||||
|
finally:
|
||||||
|
finished.set()
|
||||||
|
Thread(target=run, daemon=True).start()
|
||||||
|
return result[0] if finished.wait(timeout) else 2
|
||||||
|
|
||||||
|
|
||||||
|
def cleanup(runtime, guard, thread, stop, *, timeout=2, emit=print):
|
||||||
|
stop.set()
|
||||||
|
counters = {}
|
||||||
|
# Every operation is independent; a failed or wedged stop cannot skip I/O cleanup.
|
||||||
|
for name, action in (
|
||||||
|
('runtime_stop', runtime.stop if runtime is not None else lambda: None),
|
||||||
|
('gateway_shutdown', guard.shutdown),
|
||||||
|
('gateway_close', guard.server_close),
|
||||||
|
('gateway_join', lambda: thread.join(timeout)),
|
||||||
|
):
|
||||||
|
counters[name] = bounded_call(action, timeout)
|
||||||
|
counters['gateway_alive'] = int(thread.is_alive())
|
||||||
|
emit(json.dumps(dict(stage='close', cleanup=counters, request_counts=dict(guard.counts))), flush=True)
|
||||||
|
return any(counters.values())
|
||||||
|
|
||||||
|
|
||||||
|
def run_owned(build, key, request_timeout, *, startup_timeout=90, cleanup_timeout=2, emit=print):
|
||||||
|
stop, constructed, finished, abandoned, lock = Event(), Event(), Event(), Event(), Lock()
|
||||||
|
runtime = None
|
||||||
|
result = {}
|
||||||
|
with termination_signals(stop):
|
||||||
|
guard, thread = start_components(key, request_timeout)
|
||||||
|
def drive():
|
||||||
|
nonlocal runtime
|
||||||
|
if stop.is_set():
|
||||||
|
return 1
|
||||||
|
def construct():
|
||||||
|
try:
|
||||||
|
value = build(stop)
|
||||||
|
with lock:
|
||||||
|
if not abandoned.is_set():
|
||||||
|
result['runtime'] = value
|
||||||
|
else:
|
||||||
|
bounded_call(value.stop, cleanup_timeout)
|
||||||
|
except BaseException:
|
||||||
|
result['failed'] = True
|
||||||
|
finally:
|
||||||
|
constructed.set()
|
||||||
|
Thread(target=construct, daemon=True).start()
|
||||||
|
deadline = time.monotonic() + startup_timeout
|
||||||
|
while not constructed.wait(.01):
|
||||||
|
if stop.is_set() or time.monotonic() >= deadline:
|
||||||
|
with lock:
|
||||||
|
abandoned.set()
|
||||||
|
emit(json.dumps(dict(status='failed', category='LOCAL_ENGINE_STARTUP_DEADLINE')), flush=True)
|
||||||
|
return 1
|
||||||
|
runtime = result.get('runtime')
|
||||||
|
if runtime is None or stop.is_set():
|
||||||
|
emit(json.dumps(dict(status='failed', category='LOCAL_ENGINE_STARTUP_OR_RUNTIME_FAILURE')), flush=True)
|
||||||
|
return 1
|
||||||
|
emit(json.dumps(dict(stage='startup', request_counts=dict(guard.counts))), flush=True)
|
||||||
|
def serve():
|
||||||
|
try:
|
||||||
|
runtime.start()
|
||||||
|
runtime.wait()
|
||||||
|
except BaseException:
|
||||||
|
result['failed'] = True
|
||||||
|
finally:
|
||||||
|
finished.set()
|
||||||
|
Thread(target=serve, daemon=True).start()
|
||||||
|
while not finished.wait(.02) and not stop.is_set():
|
||||||
|
pass
|
||||||
|
return int(bool(result.get('failed')))
|
||||||
|
try:
|
||||||
|
outcome = drive()
|
||||||
|
finally:
|
||||||
|
# Fetch a construction result which raced the deadline before abandoning it.
|
||||||
|
with lock:
|
||||||
|
abandoned.set()
|
||||||
|
runtime = runtime or result.get('runtime')
|
||||||
|
cleanup_failed = cleanup(runtime, guard, thread, stop, timeout=cleanup_timeout, emit=emit)
|
||||||
|
return int(outcome or cleanup_failed)
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
schema_version: 1
|
||||||
|
blocks:
|
||||||
|
vad:
|
||||||
|
kind: vad
|
||||||
|
backend: silero
|
||||||
|
settings:
|
||||||
|
smart_turn: false
|
||||||
|
max_speech_ms: 10000
|
||||||
|
min_silence_ms: 500
|
||||||
|
speech_pad_ms: 300
|
||||||
|
enable_realtime_transcription: false
|
||||||
|
stt:
|
||||||
|
kind: stt
|
||||||
|
backend: openai
|
||||||
|
settings:
|
||||||
|
openai_stt_base_url: http://127.0.0.1:8766/v1
|
||||||
|
openai_stt_api_key: local-components
|
||||||
|
openai_stt_model: {env: LOCAL_S2S_STT_MODEL}
|
||||||
|
openai_stt_language: fa
|
||||||
|
openai_stt_response_format: json
|
||||||
|
openai_stt_timeout: {env: LOCAL_S2S_REQUEST_TIMEOUT_SECONDS}
|
||||||
|
llm:
|
||||||
|
kind: llm
|
||||||
|
backend: chat-completions
|
||||||
|
settings:
|
||||||
|
model_name: {env: LOCAL_S2S_LLM_MODEL}
|
||||||
|
responses_api_base_url: http://127.0.0.1:8766/v1
|
||||||
|
responses_api_api_key: local-components
|
||||||
|
responses_api_stream: true
|
||||||
|
responses_api_disable_thinking: false
|
||||||
|
responses_api_reasoning_effort: null
|
||||||
|
compact_history: false
|
||||||
|
chat_size: 10
|
||||||
|
tts:
|
||||||
|
kind: tts
|
||||||
|
backend: openai
|
||||||
|
settings:
|
||||||
|
openai_tts_base_url: http://127.0.0.1:8766/v1
|
||||||
|
openai_tts_api_key: local-components
|
||||||
|
openai_tts_model: {env: LOCAL_S2S_TTS_MODEL}
|
||||||
|
openai_tts_voice: {env: LOCAL_S2S_TTS_VOICE}
|
||||||
|
openai_tts_sample_rate: 24000
|
||||||
|
openai_tts_response_format: pcm
|
||||||
|
openai_tts_stream: false
|
||||||
|
openai_tts_timeout: {env: LOCAL_S2S_REQUEST_TIMEOUT_SECONDS}
|
||||||
|
pipelines:
|
||||||
|
local:
|
||||||
|
num_pipelines: 1
|
||||||
|
stages: {vad: vad, stt: stt, llm: llm, tts: tts}
|
||||||
|
options:
|
||||||
|
device: cpu
|
||||||
|
enable_live_transcription: false
|
||||||
|
enable_llm_proxy: false
|
||||||
|
runtime:
|
||||||
|
log_level: critical
|
||||||
|
log_transcripts: false
|
||||||
|
torch_num_threads: 1
|
||||||
|
server: {host: 0.0.0.0, port: 8765}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""Prepare immutable engine build inputs from an already-authorized clean checkout.
|
||||||
|
|
||||||
|
Does not fetch source, resolve dependencies, build images or download weights.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tomllib
|
||||||
|
|
||||||
|
PIN = '619e3fe4f71d1c6f35c15870d588a3638de34722'
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument('--checkout', type=Path, required=True)
|
||||||
|
parser.add_argument('--base-image', required=True, help='python:3.11-slim@sha256:...')
|
||||||
|
args = parser.parse_args()
|
||||||
|
if not re.fullmatch(r'python:3\.11-slim@sha256:[0-9a-f]{64}', args.base_image):
|
||||||
|
parser.error('An immutable Python 3.11 base image digest is required.')
|
||||||
|
source = args.checkout.resolve()
|
||||||
|
sha = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip()
|
||||||
|
dirty = subprocess.check_output(['git', '-C', str(source), 'status', '--porcelain'], text=True).strip()
|
||||||
|
if sha != PIN or dirty:
|
||||||
|
parser.error('Requires a clean checkout of the Phase 1 upstream pin.')
|
||||||
|
root = Path(__file__).resolve().parents[2]
|
||||||
|
target = root / '.local-s2s-build'
|
||||||
|
if target.exists():
|
||||||
|
parser.error('.local-s2s-build exists; preserve it and choose a fresh workspace.')
|
||||||
|
dependencies = ['setuptools>=77.0.3', 'wheel']
|
||||||
|
for manifest in (source / 'pyproject.toml', root / 'pyproject.toml'):
|
||||||
|
data = tomllib.loads(manifest.read_text(encoding='utf-8'))
|
||||||
|
dependencies.extend(data['project']['dependencies'])
|
||||||
|
if manifest.parent == root:
|
||||||
|
for extra in ('api', 'voice', 'embedding'):
|
||||||
|
dependencies.extend(data['project']['optional-dependencies'][extra])
|
||||||
|
target.mkdir()
|
||||||
|
shutil.copytree(source, target / 'upstream', ignore=shutil.ignore_patterns('.git', '.venv', '__pycache__'))
|
||||||
|
from sys import path as import_path
|
||||||
|
import_path.insert(0, str(root))
|
||||||
|
from services.local_s2s.assets import patch_pipeline_source
|
||||||
|
pipeline = target / 'upstream/src/speech_to_speech/s2s_pipeline.py'
|
||||||
|
pipeline.write_text(patch_pipeline_source(pipeline.read_text(encoding='utf-8')), encoding='utf-8')
|
||||||
|
(target / 'requirements.in').write_text('\n'.join(sorted(set(dependencies))) + '\n', encoding='utf-8')
|
||||||
|
(target / 'build-manifest.json').write_text(json.dumps(dict(upstream=PIN, base_image=args.base_image,
|
||||||
|
upstream_pyproject_sha256=hashlib.sha256((source / 'pyproject.toml').read_bytes()).hexdigest(),
|
||||||
|
patch_revision='rag-local-s2s-phase2-v3', built=False), indent=2) + '\n', encoding='utf-8')
|
||||||
|
print('Prepared source and dependency inputs. Resolve a Linux hash lock before building; no downloads performed.')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""Fixed Chat Completions policy, applied before upstream setup/warmup."""
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
|
||||||
|
class LimitedChatClient:
|
||||||
|
def __init__(self, client, token_limit):
|
||||||
|
self._client, self.token_limit = client, token_limit
|
||||||
|
self.max_retries = 0
|
||||||
|
self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create))
|
||||||
|
|
||||||
|
def _create(self, **kwargs):
|
||||||
|
kwargs.pop('max_completion_tokens', None)
|
||||||
|
kwargs['max_tokens'] = self.token_limit
|
||||||
|
return self._client.chat.completions.create(**kwargs)
|
||||||
|
|
||||||
|
def with_options(self, **kwargs):
|
||||||
|
# Pinned warmup explicitly asks for WARMUP_MAX_RETRIES. Never honor it.
|
||||||
|
kwargs['max_retries'] = 0
|
||||||
|
return LimitedChatClient(self._client.with_options(**kwargs), self.token_limit)
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
return getattr(self._client, name)
|
||||||
|
|
||||||
|
|
||||||
|
def install_client_policy(base_module, config):
|
||||||
|
import httpx
|
||||||
|
native = base_module.OpenAI
|
||||||
|
def create(*args, **kwargs):
|
||||||
|
kwargs['max_retries'] = 0
|
||||||
|
kwargs['timeout'] = httpx.Timeout(config.local_s2s_request_timeout_seconds, connect=5)
|
||||||
|
return LimitedChatClient(native(*args, **kwargs), config.local_s2s_max_output_tokens)
|
||||||
|
base_module.OpenAI = create
|
||||||
|
# The pinned base defaults to 20 seconds. Apply the configured deadline
|
||||||
|
# before setup computes request_timeout and invokes its warmup.
|
||||||
|
base = base_module.BaseOpenAICompatibleHandler
|
||||||
|
native_setup = base.setup
|
||||||
|
def setup(self, *args, **kwargs):
|
||||||
|
kwargs['request_timeout_s'] = config.local_s2s_request_timeout_seconds
|
||||||
|
return native_setup(self, *args, **kwargs)
|
||||||
|
base.setup = setup
|
||||||
|
return native
|
||||||
+201
@@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [2024] [The HuggingFace Inc. team]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
+1128
File diff suppressed because it is too large
Load Diff
+389
@@ -0,0 +1,389 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
from openai import Stream
|
||||||
|
from openai.types.chat import (
|
||||||
|
ChatCompletionChunk,
|
||||||
|
ChatCompletionContentPartImageParam,
|
||||||
|
ChatCompletionContentPartParam,
|
||||||
|
ChatCompletionContentPartTextParam,
|
||||||
|
ChatCompletionNamedToolChoiceParam,
|
||||||
|
ChatCompletionToolChoiceOptionParam,
|
||||||
|
ChatCompletionToolParam,
|
||||||
|
)
|
||||||
|
from openai.types.chat.chat_completion_content_part_image_param import ImageURL
|
||||||
|
from openai.types.chat.chat_completion_named_tool_choice_param import Function as NamedToolChoiceFunction
|
||||||
|
from openai.types.realtime.realtime_conversation_item_assistant_message import (
|
||||||
|
Content as AssistantContent,
|
||||||
|
)
|
||||||
|
from openai.types.responses import ResponseFunctionToolCall
|
||||||
|
from openai.types.shared_params import FunctionDefinition
|
||||||
|
|
||||||
|
from speech_to_speech.LLM.base_openai_compatible_language_model import (
|
||||||
|
WARMUP_MAX_RETRIES,
|
||||||
|
AssistantMessage,
|
||||||
|
BaseOpenAICompatibleHandler,
|
||||||
|
ProviderEvent,
|
||||||
|
ProviderResponseEnd,
|
||||||
|
TextDelta,
|
||||||
|
ToolCall,
|
||||||
|
Usage,
|
||||||
|
)
|
||||||
|
from speech_to_speech.LLM.chat import Chat
|
||||||
|
from speech_to_speech.LLM.compaction_prompt import CompactGenerateFn
|
||||||
|
from speech_to_speech.utils.utils import _generate_id
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _to_chat_tools(req_tools: Any) -> list[ChatCompletionToolParam] | None:
|
||||||
|
"""Convert Responses-API function tools to Chat-Completions tool format.
|
||||||
|
|
||||||
|
Responses tools are flat ``{type:"function", name, description, parameters}``;
|
||||||
|
Chat Completions nests them under a ``function`` key. Items already in the
|
||||||
|
nested form (or non-function tools) are passed through untouched.
|
||||||
|
"""
|
||||||
|
if not req_tools:
|
||||||
|
return None
|
||||||
|
chat_tools: list[ChatCompletionToolParam] = []
|
||||||
|
for t in req_tools:
|
||||||
|
d = t if isinstance(t, dict) else t.model_dump(exclude_none=True)
|
||||||
|
if d.get("type") == "function" and "function" not in d:
|
||||||
|
fn = FunctionDefinition(name=d["name"])
|
||||||
|
if d.get("description") is not None:
|
||||||
|
fn["description"] = d["description"]
|
||||||
|
if d.get("parameters") is not None:
|
||||||
|
fn["parameters"] = d["parameters"]
|
||||||
|
chat_tools.append(ChatCompletionToolParam(type="function", function=fn))
|
||||||
|
else:
|
||||||
|
chat_tools.append(cast("ChatCompletionToolParam", d))
|
||||||
|
return chat_tools
|
||||||
|
|
||||||
|
|
||||||
|
def _to_chat_tool_choice(tool_choice: Any) -> ChatCompletionToolChoiceOptionParam:
|
||||||
|
"""Convert a Responses-API tool_choice to Chat-Completions form.
|
||||||
|
|
||||||
|
The string forms ("auto"/"required"/"none") are identical across both APIs;
|
||||||
|
only the forced-function object differs (flat ``name`` vs nested ``function``).
|
||||||
|
"""
|
||||||
|
if isinstance(tool_choice, dict) and tool_choice.get("type") == "function" and "name" in tool_choice:
|
||||||
|
return ChatCompletionNamedToolChoiceParam(
|
||||||
|
type="function", function=NamedToolChoiceFunction(name=tool_choice["name"])
|
||||||
|
)
|
||||||
|
if tool_choice is not None and not isinstance(tool_choice, (str, dict)):
|
||||||
|
d = tool_choice.model_dump(exclude_none=True)
|
||||||
|
if d.get("type") == "function" and "name" in d:
|
||||||
|
return ChatCompletionNamedToolChoiceParam(type="function", function=NamedToolChoiceFunction(name=d["name"]))
|
||||||
|
return cast("ChatCompletionToolChoiceOptionParam", d)
|
||||||
|
return cast("ChatCompletionToolChoiceOptionParam", tool_choice)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_chat_optional_kwargs(req_tools: Any, req_tool_choice: Any) -> dict[str, Any]:
|
||||||
|
"""Build Chat Completions tool arguments from the Responses-style session config."""
|
||||||
|
optional_kwargs: dict[str, Any] = {}
|
||||||
|
chat_tools = _to_chat_tools(req_tools)
|
||||||
|
if chat_tools is not None:
|
||||||
|
optional_kwargs["tools"] = chat_tools
|
||||||
|
if req_tool_choice is not None:
|
||||||
|
optional_kwargs["tool_choice"] = _to_chat_tool_choice(req_tool_choice)
|
||||||
|
return optional_kwargs
|
||||||
|
|
||||||
|
|
||||||
|
def _to_chat_content_part(
|
||||||
|
part: dict[str, Any],
|
||||||
|
audio_content_type: str = "input_audio",
|
||||||
|
) -> ChatCompletionContentPartParam:
|
||||||
|
"""Convert one Realtime/transformers content part to Chat Completions shape."""
|
||||||
|
ptype = part.get("type")
|
||||||
|
if ptype == "input_text":
|
||||||
|
return ChatCompletionContentPartTextParam(type="text", text=part.get("text") or "")
|
||||||
|
if ptype == "input_image":
|
||||||
|
raw_url: Any = part.get("image_url")
|
||||||
|
if isinstance(raw_url, dict):
|
||||||
|
image_url = cast("ImageURL", raw_url)
|
||||||
|
else:
|
||||||
|
image_url = ImageURL(url=raw_url)
|
||||||
|
detail = part.get("detail")
|
||||||
|
if detail is not None:
|
||||||
|
image_url["detail"] = detail
|
||||||
|
return ChatCompletionContentPartImageParam(type="image_url", image_url=image_url)
|
||||||
|
if ptype == "input_audio":
|
||||||
|
audio_b64 = part.get("audio") or ""
|
||||||
|
if audio_content_type == "audio_url":
|
||||||
|
return cast(
|
||||||
|
"ChatCompletionContentPartParam",
|
||||||
|
{
|
||||||
|
"type": "audio_url",
|
||||||
|
"audio_url": {
|
||||||
|
"url": f"data:audio/wav;base64,{audio_b64}",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return cast(
|
||||||
|
"ChatCompletionContentPartParam",
|
||||||
|
{
|
||||||
|
"type": "input_audio",
|
||||||
|
"input_audio": {
|
||||||
|
"data": audio_b64,
|
||||||
|
"format": "wav",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return cast("ChatCompletionContentPartParam", part)
|
||||||
|
|
||||||
|
|
||||||
|
def _chat_messages(
|
||||||
|
chat: Chat,
|
||||||
|
audio_content_type: str = "input_audio",
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""Serialise chat history, including media and tool messages, for Chat Completions."""
|
||||||
|
messages = chat.to_transformers_chat()
|
||||||
|
for message in messages:
|
||||||
|
for tool_call in message.get("tool_calls") or []:
|
||||||
|
fn = tool_call.get("function")
|
||||||
|
if fn is not None and not isinstance(fn.get("arguments"), str):
|
||||||
|
fn["arguments"] = json.dumps(fn.get("arguments") or {}, ensure_ascii=False)
|
||||||
|
content = message.get("content")
|
||||||
|
if isinstance(content, list):
|
||||||
|
message["content"] = [
|
||||||
|
_to_chat_content_part(part, audio_content_type=audio_content_type) for part in content
|
||||||
|
]
|
||||||
|
if message.get("role") == "tool":
|
||||||
|
message.pop("name", None)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
|
||||||
|
def _request_chat_completions(
|
||||||
|
*,
|
||||||
|
client: Any,
|
||||||
|
model_name: str,
|
||||||
|
messages: list[dict[str, Any]],
|
||||||
|
stream: bool,
|
||||||
|
extra_body: dict[str, Any] | None,
|
||||||
|
timeout: Any,
|
||||||
|
optional_kwargs: dict[str, Any],
|
||||||
|
) -> Any:
|
||||||
|
"""Issue a Chat Completions request with consistent streaming usage accounting."""
|
||||||
|
create_kwargs = dict(optional_kwargs)
|
||||||
|
if stream:
|
||||||
|
create_kwargs["stream_options"] = {"include_usage": True}
|
||||||
|
return client.chat.completions.create(
|
||||||
|
model=model_name,
|
||||||
|
messages=messages,
|
||||||
|
stream=stream,
|
||||||
|
extra_body=extra_body,
|
||||||
|
timeout=timeout,
|
||||||
|
**create_kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_calls_from_accum(tool_accum: dict[int, dict[str, str]]) -> Iterator[ToolCall]:
|
||||||
|
"""Turn accumulated Chat Completions tool deltas into normalized tool-call events."""
|
||||||
|
for index in sorted(tool_accum):
|
||||||
|
entry = tool_accum[index]
|
||||||
|
if not entry["name"]:
|
||||||
|
continue
|
||||||
|
yield ToolCall(
|
||||||
|
item=ResponseFunctionToolCall(
|
||||||
|
type="function_call",
|
||||||
|
name=entry["name"],
|
||||||
|
arguments=entry["args"] or "{}",
|
||||||
|
call_id=_generate_id("call"),
|
||||||
|
id=_generate_id("fc"),
|
||||||
|
status="completed",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _chat_response_end(finish_reason: str) -> ProviderResponseEnd:
|
||||||
|
if finish_reason == "length":
|
||||||
|
return ProviderResponseEnd(status="incomplete", reason="max_output_tokens")
|
||||||
|
if finish_reason == "content_filter":
|
||||||
|
return ProviderResponseEnd(status="incomplete", reason="content_filter")
|
||||||
|
return ProviderResponseEnd()
|
||||||
|
|
||||||
|
|
||||||
|
def _iter_chat_stream_events(api_response: Stream[ChatCompletionChunk]) -> Iterator[ProviderEvent]:
|
||||||
|
"""Normalize a streaming Chat Completions response."""
|
||||||
|
tool_accum: dict[int, dict[str, str]] = {}
|
||||||
|
usage: Usage | None = None
|
||||||
|
text_segment = ""
|
||||||
|
ending: ProviderResponseEnd | None = None
|
||||||
|
|
||||||
|
def flush_tools() -> Iterator[ProviderEvent]:
|
||||||
|
nonlocal text_segment
|
||||||
|
if text_segment:
|
||||||
|
yield AssistantMessage(content=[AssistantContent(type="output_text", text=text_segment)])
|
||||||
|
text_segment = ""
|
||||||
|
yield from _tool_calls_from_accum(tool_accum)
|
||||||
|
tool_accum.clear()
|
||||||
|
|
||||||
|
def accumulate_tools(tool_calls: Any) -> None:
|
||||||
|
for tool_call in tool_calls or []:
|
||||||
|
entry = tool_accum.setdefault(tool_call.index, {"name": "", "args": "", "id": ""})
|
||||||
|
if tool_call.id:
|
||||||
|
entry["id"] = tool_call.id
|
||||||
|
if tool_call.function is not None:
|
||||||
|
if tool_call.function.name:
|
||||||
|
entry["name"] = tool_call.function.name
|
||||||
|
if tool_call.function.arguments:
|
||||||
|
entry["args"] += tool_call.function.arguments
|
||||||
|
|
||||||
|
for chunk in api_response:
|
||||||
|
if chunk.usage is not None:
|
||||||
|
usage = Usage(
|
||||||
|
input_tokens=chunk.usage.prompt_tokens or 0,
|
||||||
|
output_tokens=chunk.usage.completion_tokens or 0,
|
||||||
|
)
|
||||||
|
if not chunk.choices:
|
||||||
|
continue
|
||||||
|
finish_reason = getattr(chunk.choices[0], "finish_reason", None)
|
||||||
|
if finish_reason is not None:
|
||||||
|
ending = _chat_response_end(finish_reason)
|
||||||
|
yield ending
|
||||||
|
delta = chunk.choices[0].delta
|
||||||
|
text_piece = delta.content or getattr(delta, "refusal", None)
|
||||||
|
continuing_tool = bool(tool_accum)
|
||||||
|
if continuing_tool:
|
||||||
|
accumulate_tools(delta.tool_calls)
|
||||||
|
if text_piece:
|
||||||
|
if continuing_tool:
|
||||||
|
yield from flush_tools()
|
||||||
|
text_segment += text_piece
|
||||||
|
yield TextDelta(text=text_piece)
|
||||||
|
if not continuing_tool:
|
||||||
|
accumulate_tools(delta.tool_calls)
|
||||||
|
|
||||||
|
if ending is None:
|
||||||
|
logger.warning("Chat Completions stream ended without a finish_reason")
|
||||||
|
if tool_accum and (ending is None or ending.status == "completed"):
|
||||||
|
yield from flush_tools()
|
||||||
|
if text_segment:
|
||||||
|
yield AssistantMessage(content=[AssistantContent(type="output_text", text=text_segment)])
|
||||||
|
if usage is not None:
|
||||||
|
yield usage
|
||||||
|
|
||||||
|
|
||||||
|
def _iter_chat_response_events(api_response: Any) -> Iterator[ProviderEvent]:
|
||||||
|
"""Normalize a non-streaming Chat Completions response."""
|
||||||
|
usage = api_response.usage
|
||||||
|
if usage:
|
||||||
|
yield Usage(input_tokens=usage.prompt_tokens or 0, output_tokens=usage.completion_tokens or 0)
|
||||||
|
if api_response.choices:
|
||||||
|
finish_reason = getattr(api_response.choices[0], "finish_reason", None)
|
||||||
|
if finish_reason is not None:
|
||||||
|
yield _chat_response_end(finish_reason)
|
||||||
|
message = api_response.choices[0].message if api_response.choices else None
|
||||||
|
if message is None:
|
||||||
|
return
|
||||||
|
raw_content = message.content or getattr(message, "refusal", None)
|
||||||
|
if raw_content:
|
||||||
|
yield AssistantMessage(content=[AssistantContent(type="output_text", text=raw_content)])
|
||||||
|
yield TextDelta(text=raw_content)
|
||||||
|
tool_accum: dict[int, dict[str, str]] = {}
|
||||||
|
for tool_call in message.tool_calls or []:
|
||||||
|
tool_accum[len(tool_accum)] = {
|
||||||
|
"name": tool_call.function.name or "",
|
||||||
|
"args": tool_call.function.arguments or "",
|
||||||
|
"id": tool_call.id or "",
|
||||||
|
}
|
||||||
|
yield from _tool_calls_from_accum(tool_accum)
|
||||||
|
|
||||||
|
|
||||||
|
class ChatCompletionsApiModelHandler(BaseOpenAICompatibleHandler):
|
||||||
|
"""LLM handler that talks to an OpenAI-compatible ``/v1/chat/completions`` server.
|
||||||
|
|
||||||
|
Functionally mirrors :class:`ResponsesApiModelHandler` but uses the mature
|
||||||
|
Chat Completions streaming tool-call protocol (``choices[].delta.tool_calls``)
|
||||||
|
instead of ``/v1/responses``. This is the robust path for vLLM + Qwen tool
|
||||||
|
calling. The conversation is serialised with :meth:`Chat.to_transformers_chat`,
|
||||||
|
which already emits OpenAI chat messages including ``tool_calls``/``tool`` roles.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def warmup(self) -> None:
|
||||||
|
logger.info(f"Warming up {self.__class__.__name__}")
|
||||||
|
start = time.time()
|
||||||
|
self.client.with_options(max_retries=WARMUP_MAX_RETRIES).chat.completions.create(
|
||||||
|
model=self.model_name,
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": "You are a helpful assistant"},
|
||||||
|
{"role": "user", "content": "Hello"},
|
||||||
|
],
|
||||||
|
extra_body=self._extra_body,
|
||||||
|
timeout=self.request_timeout,
|
||||||
|
)
|
||||||
|
end = time.time()
|
||||||
|
logger.info(f"{self.__class__.__name__}: warmed up! time: {(end - start):.3f} s")
|
||||||
|
|
||||||
|
def _build_compaction_generate_fn(self) -> CompactGenerateFn:
|
||||||
|
"""Return a generate fn that calls Chat Completions for compaction."""
|
||||||
|
client = self.client
|
||||||
|
model_name = self.model_name
|
||||||
|
timeout = self.request_timeout
|
||||||
|
extra_body = self._extra_body
|
||||||
|
|
||||||
|
def generate(system: str, user: str) -> str:
|
||||||
|
response = client.chat.completions.create(
|
||||||
|
model=model_name,
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": system},
|
||||||
|
{"role": "user", "content": user},
|
||||||
|
],
|
||||||
|
extra_body=extra_body,
|
||||||
|
timeout=timeout,
|
||||||
|
)
|
||||||
|
return response.choices[0].message.content or ""
|
||||||
|
|
||||||
|
return generate
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _to_chat_content_part(
|
||||||
|
part: dict[str, Any],
|
||||||
|
audio_content_type: str = "input_audio",
|
||||||
|
) -> ChatCompletionContentPartParam:
|
||||||
|
return _to_chat_content_part(part, audio_content_type=audio_content_type)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _chat_messages(
|
||||||
|
cls,
|
||||||
|
chat: Chat,
|
||||||
|
audio_content_type: str = "input_audio",
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
return _chat_messages(chat, audio_content_type=audio_content_type)
|
||||||
|
|
||||||
|
# ── base hooks ──────────────────────────────────────────────────────────--
|
||||||
|
|
||||||
|
def _serialize(self, active_chat: Chat) -> list[dict[str, Any]]:
|
||||||
|
return self._chat_messages(active_chat, audio_content_type=self.audio_content_type)
|
||||||
|
|
||||||
|
def _build_optional_kwargs(self, req_tools: Any, req_tool_choice: Any) -> dict[str, Any]:
|
||||||
|
return _build_chat_optional_kwargs(req_tools, req_tool_choice)
|
||||||
|
|
||||||
|
def _request(self, api_input: list[dict[str, Any]], optional_kwargs: dict[str, Any]) -> Any:
|
||||||
|
return _request_chat_completions(
|
||||||
|
client=self.client,
|
||||||
|
model_name=self.model_name,
|
||||||
|
messages=api_input,
|
||||||
|
stream=self.stream,
|
||||||
|
extra_body=self._extra_body,
|
||||||
|
timeout=self.request_timeout,
|
||||||
|
optional_kwargs=optional_kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _iter_stream_events(self, api_response: Stream[ChatCompletionChunk]) -> Iterator[ProviderEvent]:
|
||||||
|
yield from _iter_chat_stream_events(api_response)
|
||||||
|
|
||||||
|
def _iter_response_events(self, api_response: Any) -> Iterator[ProviderEvent]:
|
||||||
|
yield from _iter_chat_response_events(api_response)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _tool_calls_from_accum(tool_accum: dict[int, dict[str, str]]) -> Iterator[ToolCall]:
|
||||||
|
yield from _tool_calls_from_accum(tool_accum)
|
||||||
|
|
||||||
|
def on_session_end(self) -> None:
|
||||||
|
logger.debug("Chat Completions API language model session state reset")
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
"""Explicit configured construction and lifecycle. Construction can load models."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
from copy import deepcopy
|
||||||
|
from dataclasses import fields
|
||||||
|
from ipaddress import ip_address
|
||||||
|
from threading import Event, RLock, Thread, current_thread
|
||||||
|
from time import monotonic
|
||||||
|
from typing import TYPE_CHECKING, Any, Literal
|
||||||
|
|
||||||
|
from speech_to_speech.config import ConfigurationError, ResolvedConfig
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from speech_to_speech.api.openai_realtime.audio_client import RealtimeAudioClientConfig
|
||||||
|
from speech_to_speech.api.openai_realtime.pipeline_unit import PipelineUnit
|
||||||
|
from speech_to_speech.s2s_pipeline import ParsedArguments
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
_JOIN_TIMEOUT_S = 5.0
|
||||||
|
|
||||||
|
|
||||||
|
class ConfiguredRuntimeError(RuntimeError):
|
||||||
|
"""A runtime error that does not include provider diagnostics or credentials."""
|
||||||
|
|
||||||
|
|
||||||
|
def _explicit(config: ResolvedConfig, *path: str) -> bool:
|
||||||
|
return config.sources.get(path, "default") != "default"
|
||||||
|
|
||||||
|
|
||||||
|
def _cleanup(resource: Any) -> None:
|
||||||
|
try:
|
||||||
|
cleanup = getattr(resource, "cleanup", None) or getattr(resource, "reset", None)
|
||||||
|
if cleanup is None and hasattr(resource, "diarizer"):
|
||||||
|
cleanup = resource.diarizer.reset
|
||||||
|
if cleanup is not None:
|
||||||
|
cleanup()
|
||||||
|
except Exception:
|
||||||
|
logger.warning("Configured resource cleanup failed")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_counts(config: ResolvedConfig) -> None:
|
||||||
|
if not config.pipelines:
|
||||||
|
raise ConfigurationError("Select at least one pipeline definition.")
|
||||||
|
for pipeline in config.pipelines.values():
|
||||||
|
if type(pipeline.num_pipelines) is not int or pipeline.num_pipelines < 1:
|
||||||
|
raise ConfigurationError("Use positive integer pipeline instance counts.")
|
||||||
|
|
||||||
|
|
||||||
|
def _adapt(config: ResolvedConfig) -> dict[str, ParsedArguments]:
|
||||||
|
from speech_to_speech import s2s_pipeline as pipeline_module
|
||||||
|
from speech_to_speech.arguments_classes.local_audio_arguments import LocalAudioArguments
|
||||||
|
from speech_to_speech.arguments_classes.module_arguments import ModuleArguments
|
||||||
|
from speech_to_speech.arguments_classes.realtime_server_arguments import RealtimeServerArguments
|
||||||
|
from speech_to_speech.arguments_classes.vad_arguments import VADHandlerArguments
|
||||||
|
from speech_to_speech.backend_registry import LLM_BACKENDS, STT_BACKENDS, TTS_BACKENDS, BackendSelection
|
||||||
|
|
||||||
|
adapted = {}
|
||||||
|
for name, pipeline in config.pipelines.items():
|
||||||
|
options = deepcopy(pipeline.options)
|
||||||
|
preset = (
|
||||||
|
pipeline_module._mac_preset_defaults(pipeline.stages["llm"].backend)
|
||||||
|
if options.get("mac_optimal_settings")
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
for key, value in preset.items():
|
||||||
|
if key in options and not _explicit(config, "pipelines", name, "options", key):
|
||||||
|
options[key] = value
|
||||||
|
options.update(
|
||||||
|
stt=pipeline.stages["stt"].backend,
|
||||||
|
llm_backend=pipeline.stages["llm"].backend,
|
||||||
|
tts=pipeline.stages["tts"].backend,
|
||||||
|
num_pipelines=pipeline.num_pipelines,
|
||||||
|
log_level=config.runtime.get("log_level", "info"),
|
||||||
|
log_transcripts=config.runtime.get("log_transcripts", False),
|
||||||
|
torch_num_threads=config.runtime.get("torch_num_threads"),
|
||||||
|
)
|
||||||
|
if options.get("diarization") and options.get("diarization_model_name") is None:
|
||||||
|
options["diarization_model_name"] = "nvidia/Nemotron-3-Diarization"
|
||||||
|
selections = {}
|
||||||
|
for kind, registry in (("stt", STT_BACKENDS), ("llm", LLM_BACKENDS), ("tts", TTS_BACKENDS)):
|
||||||
|
stage = pipeline.stages[kind]
|
||||||
|
spec = registry[stage.backend]
|
||||||
|
settings = deepcopy(stage.settings)
|
||||||
|
for key in {field.name for field in fields(spec.config_type)} & preset.keys():
|
||||||
|
if not _explicit(config, "blocks", stage.block_id, "settings", key):
|
||||||
|
settings[key] = deepcopy(preset[key])
|
||||||
|
selections[kind] = BackendSelection(spec, spec.normalize(spec.config_type(**settings)))
|
||||||
|
args = pipeline_module.ParsedArguments(
|
||||||
|
module_kwargs=ModuleArguments(**options),
|
||||||
|
realtime_server_kwargs=RealtimeServerArguments(**deepcopy(config.runtime.get("server", {}))),
|
||||||
|
local_audio_kwargs=LocalAudioArguments(),
|
||||||
|
vad_handler_kwargs=VADHandlerArguments(**deepcopy(pipeline.stages["vad"].settings)),
|
||||||
|
stt_backend=selections["stt"],
|
||||||
|
llm_backend=selections["llm"],
|
||||||
|
tts_backend=selections["tts"],
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
pipeline_module.prepare_all_args(args)
|
||||||
|
except ValueError:
|
||||||
|
raise ConfigurationError("The selected pipeline settings are incompatible.") from None
|
||||||
|
adapted[name] = args
|
||||||
|
if pipeline_module.platform == "darwin" and sum(p.num_pipelines for p in config.pipelines.values()) > 1:
|
||||||
|
for args in adapted.values():
|
||||||
|
args.module_kwargs.enable_live_transcription = False
|
||||||
|
return adapted
|
||||||
|
|
||||||
|
|
||||||
|
def build_configured_client(config: ResolvedConfig, *, local: bool = False) -> RealtimeAudioClientConfig:
|
||||||
|
"""Build independent packaged client settings and load explicitly selected tools."""
|
||||||
|
from speech_to_speech.api.openai_realtime.audio_client import (
|
||||||
|
RealtimeAudioClientConfig,
|
||||||
|
build_session_update,
|
||||||
|
load_realtime_tool_module,
|
||||||
|
)
|
||||||
|
|
||||||
|
settings = deepcopy(config.client or {})
|
||||||
|
module = settings.pop("tool_module", None)
|
||||||
|
process_explicit = _explicit(config, "runtime", "log_transcripts")
|
||||||
|
client_explicit = _explicit(config, "runtime", "client", "log_transcripts")
|
||||||
|
process_log = config.runtime.get("log_transcripts", False)
|
||||||
|
if process_explicit and client_explicit and settings.get("log_transcripts", False) != process_log:
|
||||||
|
raise ConfigurationError("Process and client transcript settings must agree.")
|
||||||
|
if process_explicit or not client_explicit:
|
||||||
|
settings["log_transcripts"] = process_log
|
||||||
|
if module and _explicit(config, "runtime", "client", "tools"):
|
||||||
|
raise ConfigurationError("Use either a tool module or explicit client tools.")
|
||||||
|
if local:
|
||||||
|
if len(config.pipelines) != 1:
|
||||||
|
raise ConfigurationError("Local startup requires exactly one pipeline definition.")
|
||||||
|
server = config.runtime.get("server", {})
|
||||||
|
host = server.get("host", "127.0.0.1")
|
||||||
|
try:
|
||||||
|
loopback = host == "localhost" or ip_address(host).is_loopback
|
||||||
|
except ValueError:
|
||||||
|
loopback = False
|
||||||
|
if _explicit(config, "runtime", "server", "host") and not loopback:
|
||||||
|
raise ConfigurationError("Local startup requires a loopback server host.")
|
||||||
|
url = f"ws://127.0.0.1:{server.get('port', 8765)}/v1/realtime"
|
||||||
|
if _explicit(config, "runtime", "client", "url") and settings.get("url") != url:
|
||||||
|
raise ConfigurationError("Local client URL must match the loopback server port.")
|
||||||
|
settings["url"] = url
|
||||||
|
if not _explicit(config, "runtime", "client", "playback_buffer_ms"):
|
||||||
|
pipeline = next(iter(config.pipelines.values()))
|
||||||
|
settings["playback_buffer_ms"] = 196.0 if pipeline.stages["tts"].backend == "openai" else 0.0
|
||||||
|
if module:
|
||||||
|
tools, executor, create_response = load_realtime_tool_module(module)
|
||||||
|
settings.update(tools=tools, tool_executor=executor)
|
||||||
|
if not _explicit(config, "runtime", "client", "tool_response_create"):
|
||||||
|
settings["tool_response_create"] = create_response
|
||||||
|
try:
|
||||||
|
client = RealtimeAudioClientConfig(**settings)
|
||||||
|
build_session_update(client)
|
||||||
|
except ValueError:
|
||||||
|
raise ConfigurationError("Invalid packaged client settings or tool contract.") from None
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
class ConfiguredRuntime:
|
||||||
|
"""Own named worker pools and optional server/client resources without installing signals.
|
||||||
|
|
||||||
|
Running means managed threads have started. It does not indicate listener readiness.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, stop_event: Event) -> None:
|
||||||
|
self.pools: dict[str, list[PipelineUnit]] = {}
|
||||||
|
self.server: Any = None
|
||||||
|
self.client: Any = None
|
||||||
|
self.state = "constructed"
|
||||||
|
self._caller_stop = stop_event
|
||||||
|
self._stop = Event()
|
||||||
|
self._events: list[Event] = []
|
||||||
|
self._resources: list[Any] = []
|
||||||
|
self._handlers: list[Any] = []
|
||||||
|
self._threads: list[Thread] = []
|
||||||
|
self._started: set[int] = set()
|
||||||
|
self._monitor: Thread | None = None
|
||||||
|
self._failure: str | None = None
|
||||||
|
self._lock = RLock()
|
||||||
|
|
||||||
|
def _signal_stop(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
for event in self._events:
|
||||||
|
event.set()
|
||||||
|
|
||||||
|
def _run(self, handler: Any) -> None:
|
||||||
|
try:
|
||||||
|
if handler is self.client:
|
||||||
|
from speech_to_speech.api.openai_realtime.audio_client import listen_and_play_realtime
|
||||||
|
|
||||||
|
asyncio.run(listen_and_play_realtime(handler.config, stop_event=handler.stop_event))
|
||||||
|
else:
|
||||||
|
handler.run()
|
||||||
|
except BaseException:
|
||||||
|
self._failure = "A configured worker, listener, or client failed."
|
||||||
|
self._signal_stop()
|
||||||
|
finally:
|
||||||
|
if handler is self.server or handler is self.client:
|
||||||
|
self._signal_stop()
|
||||||
|
|
||||||
|
def _watch(self) -> None:
|
||||||
|
while not self._stop.wait(0.05):
|
||||||
|
if self._caller_stop.is_set() or any(event.is_set() for event in self._events):
|
||||||
|
self._signal_stop()
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
with self._lock:
|
||||||
|
if self.state == "running":
|
||||||
|
return
|
||||||
|
if self.state != "constructed":
|
||||||
|
raise ConfiguredRuntimeError("A stopped or failed configured runtime cannot restart.")
|
||||||
|
if self._caller_stop.is_set():
|
||||||
|
self.stop()
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
for handler in self._handlers:
|
||||||
|
if self._stop.is_set():
|
||||||
|
raise ConfiguredRuntimeError("Configured startup stopped before completion.")
|
||||||
|
thread = Thread(target=self._run, args=(handler,))
|
||||||
|
thread.start()
|
||||||
|
self._threads.append(thread)
|
||||||
|
self._started.add(id(handler))
|
||||||
|
monitor = Thread(target=self._watch, daemon=True)
|
||||||
|
monitor.start()
|
||||||
|
self._monitor = monitor
|
||||||
|
self.state = "running"
|
||||||
|
except BaseException:
|
||||||
|
self._failure = "Configured thread startup failed."
|
||||||
|
self.stop()
|
||||||
|
raise ConfiguredRuntimeError(self._failure) from None
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
with self._lock:
|
||||||
|
if self.state in {"stopped", "failed"}:
|
||||||
|
return
|
||||||
|
self.state = "stopping"
|
||||||
|
self._signal_stop()
|
||||||
|
deadline = monotonic() + _JOIN_TIMEOUT_S
|
||||||
|
for thread in self._threads:
|
||||||
|
if thread is not current_thread():
|
||||||
|
thread.join(max(0.0, deadline - monotonic()))
|
||||||
|
if self._monitor is not None and self._monitor is not current_thread():
|
||||||
|
self._monitor.join(max(0.0, deadline - monotonic()))
|
||||||
|
survivors = sum(thread.is_alive() for thread in self._threads)
|
||||||
|
if self._monitor is not None and self._monitor.is_alive():
|
||||||
|
survivors += 1
|
||||||
|
if survivors:
|
||||||
|
logger.warning("Configured shutdown has %d surviving threads", survivors)
|
||||||
|
raise ConfiguredRuntimeError("Configured shutdown has threads still running.")
|
||||||
|
for resource in reversed(self._resources):
|
||||||
|
if id(resource) not in self._started:
|
||||||
|
_cleanup(resource)
|
||||||
|
self.pools.clear()
|
||||||
|
self.server = self.client = None
|
||||||
|
self._resources.clear()
|
||||||
|
self._handlers.clear()
|
||||||
|
self._threads.clear()
|
||||||
|
self._started.clear()
|
||||||
|
self._events.clear()
|
||||||
|
self._monitor = None
|
||||||
|
self.state = "failed" if self._failure else "stopped"
|
||||||
|
|
||||||
|
def wait(self) -> None:
|
||||||
|
if self.state == "constructed":
|
||||||
|
return
|
||||||
|
while self.state == "running" and any(thread.is_alive() for thread in self._threads):
|
||||||
|
if self._caller_stop.wait(0.05) or self._stop.is_set():
|
||||||
|
break
|
||||||
|
self.stop()
|
||||||
|
if self._failure:
|
||||||
|
raise ConfiguredRuntimeError(self._failure)
|
||||||
|
|
||||||
|
|
||||||
|
def build_configured_runtime(config: ResolvedConfig, stop_event: Event) -> ConfiguredRuntime:
|
||||||
|
"""Construct independent named workers. Models can initialize before start()."""
|
||||||
|
_validate_counts(config)
|
||||||
|
return _build_runtime(_adapt(config), stop_event)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_runtime(arguments: dict[str, ParsedArguments], stop_event: Event) -> ConfiguredRuntime:
|
||||||
|
from speech_to_speech.s2s_pipeline import _build_pipeline_unit
|
||||||
|
|
||||||
|
result = ConfiguredRuntime(stop_event)
|
||||||
|
index = 0
|
||||||
|
try:
|
||||||
|
for name, args in arguments.items():
|
||||||
|
event = Event()
|
||||||
|
result._events.append(event)
|
||||||
|
result.pools[name] = []
|
||||||
|
for _ in range(args.module_kwargs.num_pipelines):
|
||||||
|
unit = _build_pipeline_unit(
|
||||||
|
index=index,
|
||||||
|
stop_event=event,
|
||||||
|
module_kwargs=deepcopy(args.module_kwargs),
|
||||||
|
vad_handler_kwargs=deepcopy(args.vad_handler_kwargs),
|
||||||
|
stt_backend=args.stt_backend.copy_for_pipeline(),
|
||||||
|
llm_backend=args.llm_backend.copy_for_pipeline(),
|
||||||
|
tts_backend=args.tts_backend.copy_for_pipeline(),
|
||||||
|
resource_ledger=result._resources,
|
||||||
|
)
|
||||||
|
result.pools[name].append(unit)
|
||||||
|
result._handlers.extend(unit.handlers)
|
||||||
|
index += 1
|
||||||
|
except BaseException as exc:
|
||||||
|
result._failure = f"Configured pipeline {name} construction failed."
|
||||||
|
result.stop()
|
||||||
|
raise ConfiguredRuntimeError(result._failure) from exc
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def build_configured_server(config: ResolvedConfig, stop_event: Event, *, local: bool = False) -> ConfiguredRuntime:
|
||||||
|
"""Publish one definition through a server, with an optional loopback client."""
|
||||||
|
_validate_counts(config)
|
||||||
|
if len(config.pipelines) != 1:
|
||||||
|
raise ConfigurationError("Serving requires exactly one selected pipeline definition.")
|
||||||
|
client_config = build_configured_client(config, local=True) if local else None
|
||||||
|
arguments = _adapt(config)
|
||||||
|
result = _build_runtime(arguments, stop_event)
|
||||||
|
try:
|
||||||
|
from speech_to_speech.api.openai_realtime.audio_client import RealtimeAudioClient
|
||||||
|
from speech_to_speech.api.openai_realtime.server import RealtimeServer
|
||||||
|
from speech_to_speech.s2s_pipeline import build_llm_proxy_config
|
||||||
|
|
||||||
|
args = next(iter(arguments.values()))
|
||||||
|
event = result._events[0]
|
||||||
|
result.server = RealtimeServer(
|
||||||
|
stop_event=event,
|
||||||
|
pool=next(iter(result.pools.values())),
|
||||||
|
host="127.0.0.1" if local else args.realtime_server_kwargs.host,
|
||||||
|
port=args.realtime_server_kwargs.port,
|
||||||
|
llm_proxy_config=build_llm_proxy_config(args.module_kwargs, args.llm_backend)
|
||||||
|
if args.module_kwargs.enable_llm_proxy
|
||||||
|
else None,
|
||||||
|
)
|
||||||
|
result._resources.append(result.server)
|
||||||
|
result._handlers.append(result.server)
|
||||||
|
if client_config is not None:
|
||||||
|
result.client = RealtimeAudioClient(event, client_config)
|
||||||
|
result._resources.append(result.client)
|
||||||
|
result._handlers.append(result.client)
|
||||||
|
except BaseException as exc:
|
||||||
|
result._failure = "Configured server construction failed."
|
||||||
|
result.stop()
|
||||||
|
raise ConfiguredRuntimeError(result._failure) from exc
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def run_configured_command(command: Literal["serve", "local", "talk"], config: ResolvedConfig) -> None:
|
||||||
|
"""Own CLI signal handlers and always stop constructed resources."""
|
||||||
|
from speech_to_speech.pipeline.transcript_logging import set_log_transcripts, warn_if_log_transcripts_enabled
|
||||||
|
|
||||||
|
stop_event = Event()
|
||||||
|
result: ConfiguredRuntime | None = None
|
||||||
|
previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)}
|
||||||
|
try:
|
||||||
|
for sig in previous:
|
||||||
|
signal.signal(sig, lambda *_: stop_event.set())
|
||||||
|
if command == "talk":
|
||||||
|
from speech_to_speech.api.openai_realtime.audio_client import listen_and_play_realtime
|
||||||
|
|
||||||
|
client = build_configured_client(config)
|
||||||
|
logging.basicConfig(level=config.runtime.get("log_level", "info").upper())
|
||||||
|
set_log_transcripts(client.log_transcripts)
|
||||||
|
warn_if_log_transcripts_enabled()
|
||||||
|
asyncio.run(listen_and_play_realtime(client, stop_event=stop_event))
|
||||||
|
else:
|
||||||
|
from speech_to_speech.s2s_pipeline import setup_logger
|
||||||
|
|
||||||
|
setup_logger(config.runtime.get("log_level", "info"))
|
||||||
|
result = build_configured_server(config, stop_event, local=command == "local")
|
||||||
|
set_log_transcripts(
|
||||||
|
result.client.config.log_transcripts
|
||||||
|
if command == "local"
|
||||||
|
else config.runtime.get("log_transcripts", False)
|
||||||
|
)
|
||||||
|
warn_if_log_transcripts_enabled()
|
||||||
|
result.start()
|
||||||
|
result.wait()
|
||||||
|
finally:
|
||||||
|
stop_event.set()
|
||||||
|
try:
|
||||||
|
if result is not None:
|
||||||
|
result.stop()
|
||||||
|
finally:
|
||||||
|
for sig, handler in previous.items():
|
||||||
|
signal.signal(sig, handler)
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"commit": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||||
|
"files": {
|
||||||
|
"chat.py.source": {
|
||||||
|
"path": "src/speech_to_speech/LLM/chat_completions_language_model.py",
|
||||||
|
"sha256": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015"
|
||||||
|
},
|
||||||
|
"base.py.source": {
|
||||||
|
"path": "src/speech_to_speech/LLM/base_openai_compatible_language_model.py",
|
||||||
|
"sha256": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609"
|
||||||
|
},
|
||||||
|
"pipeline.py.source": {
|
||||||
|
"path": "src/speech_to_speech/s2s_pipeline.py",
|
||||||
|
"sha256": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7"
|
||||||
|
},
|
||||||
|
"lifecycle.py.source": {
|
||||||
|
"path": "src/speech_to_speech/configured_runtime.py",
|
||||||
|
"sha256": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6"
|
||||||
|
},
|
||||||
|
"LICENSE": {
|
||||||
|
"path": "LICENSE",
|
||||||
|
"sha256": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,843 @@
|
|||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
from copy import deepcopy
|
||||||
|
from dataclasses import dataclass, fields, replace
|
||||||
|
from pathlib import Path
|
||||||
|
from queue import Queue
|
||||||
|
from sys import modules, platform
|
||||||
|
from threading import Event
|
||||||
|
from types import FrameType
|
||||||
|
from typing import Any, Literal, Optional, Sequence
|
||||||
|
|
||||||
|
import nltk
|
||||||
|
import torch
|
||||||
|
from rich.console import Console
|
||||||
|
from transformers import HfArgumentParser
|
||||||
|
|
||||||
|
from speech_to_speech.api.openai_realtime.pipeline_unit import PipelineUnit
|
||||||
|
from speech_to_speech.arguments_classes.language_model_arguments import MLX_DEFAULT_LM_MODEL
|
||||||
|
from speech_to_speech.arguments_classes.local_audio_arguments import LocalAudioArguments
|
||||||
|
from speech_to_speech.arguments_classes.module_arguments import ModuleArguments
|
||||||
|
from speech_to_speech.arguments_classes.realtime_server_arguments import (
|
||||||
|
LocalRealtimeServerArguments,
|
||||||
|
RealtimeServerArguments,
|
||||||
|
)
|
||||||
|
from speech_to_speech.arguments_classes.vad_arguments import VADHandlerArguments
|
||||||
|
from speech_to_speech.backend_registry import (
|
||||||
|
LLM_BACKENDS,
|
||||||
|
STT_BACKENDS,
|
||||||
|
TTS_BACKENDS,
|
||||||
|
BackendSelection,
|
||||||
|
BackendSpec,
|
||||||
|
HandlerContext,
|
||||||
|
create_backend_handler,
|
||||||
|
)
|
||||||
|
from speech_to_speech.pipeline.cancel_scope import CancelScope
|
||||||
|
from speech_to_speech.pipeline.queue_types import (
|
||||||
|
AudioInItem,
|
||||||
|
AudioOutItem,
|
||||||
|
LMOutItem,
|
||||||
|
STTOutItem,
|
||||||
|
TextEventItem,
|
||||||
|
TextPromptItem,
|
||||||
|
TTSInItem,
|
||||||
|
VADOutItem,
|
||||||
|
)
|
||||||
|
from speech_to_speech.pipeline.speculative_turns import SpeculativeTurnTracker
|
||||||
|
from speech_to_speech.pipeline.transcript_logging import (
|
||||||
|
set_log_transcripts,
|
||||||
|
warn_if_log_transcripts_enabled,
|
||||||
|
)
|
||||||
|
from speech_to_speech.pipeline.turn_latency import TurnLatencyStore
|
||||||
|
from speech_to_speech.STT.transcription_notifier import TranscriptionNotifier
|
||||||
|
from speech_to_speech.utils.thread_manager import ThreadManager
|
||||||
|
from speech_to_speech.utils.utils import resolve_device
|
||||||
|
from speech_to_speech.VAD.vad_handler import VADHandler
|
||||||
|
|
||||||
|
# Ensure that the necessary NLTK resources are available
|
||||||
|
try:
|
||||||
|
nltk.data.find("tokenizers/punkt_tab")
|
||||||
|
except (LookupError, OSError):
|
||||||
|
nltk.download("punkt_tab")
|
||||||
|
try:
|
||||||
|
nltk.data.find("taggers/averaged_perceptron_tagger_eng")
|
||||||
|
except (LookupError, OSError):
|
||||||
|
nltk.download("averaged_perceptron_tagger_eng")
|
||||||
|
|
||||||
|
# caching allows ~50% compilation time reduction
|
||||||
|
# see https://docs.google.com/document/d/1y5CRfMLdwEoF1nTk9q8qEu1mgMUuUtvhklPKJ2emLU8/edit#heading=h.o2asbxsrp1ma
|
||||||
|
CURRENT_DIR = Path(__file__).resolve().parent
|
||||||
|
os.environ["TORCHINDUCTOR_CACHE_DIR"] = os.path.join(CURRENT_DIR, "tmp")
|
||||||
|
|
||||||
|
console = Console()
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
logging.getLogger("numba").setLevel(logging.WARNING) # quiet down numba logs
|
||||||
|
|
||||||
|
OPENAI_TTS_PLAYBACK_BUFFER_MS = 196.0
|
||||||
|
|
||||||
|
|
||||||
|
def _mac_preset_defaults(llm_backend: str) -> dict[str, Any]:
|
||||||
|
"""Return macOS parser defaults, leaving explicit arguments free to override them."""
|
||||||
|
|
||||||
|
defaults: dict[str, Any] = {
|
||||||
|
"stt": "parakeet-tdt",
|
||||||
|
"llm_backend": "mlx-lm",
|
||||||
|
"tts": "qwen3",
|
||||||
|
"stt_device": "mps",
|
||||||
|
"diarization_device": "mps",
|
||||||
|
"paraformer_stt_device": "mps",
|
||||||
|
"facebook_mms_device": "mps",
|
||||||
|
"qwen3_tts_device": "mps",
|
||||||
|
}
|
||||||
|
if llm_backend not in {"responses-api", "chat-completions"}:
|
||||||
|
defaults["llm_device"] = "mps"
|
||||||
|
if llm_backend == "mlx-lm":
|
||||||
|
defaults["model_name"] = MLX_DEFAULT_LM_MODEL
|
||||||
|
return defaults
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ParsedArguments:
|
||||||
|
module_kwargs: ModuleArguments
|
||||||
|
realtime_server_kwargs: RealtimeServerArguments
|
||||||
|
local_audio_kwargs: LocalAudioArguments
|
||||||
|
vad_handler_kwargs: VADHandlerArguments
|
||||||
|
stt_backend: BackendSelection
|
||||||
|
llm_backend: BackendSelection
|
||||||
|
tts_backend: BackendSelection
|
||||||
|
|
||||||
|
|
||||||
|
def build_llm_proxy_config(
|
||||||
|
module_kwargs: ModuleArguments,
|
||||||
|
llm_backend: BackendSelection,
|
||||||
|
) -> Any:
|
||||||
|
"""Build proxy settings from the selected LLM's normalized configuration."""
|
||||||
|
from speech_to_speech.api.openai_realtime.llm_proxy import LLMProxyConfig
|
||||||
|
|
||||||
|
if not llm_backend.spec.capabilities.supports_llm_proxy:
|
||||||
|
supported = ", ".join(name for name, spec in LLM_BACKENDS.items() if spec.capabilities.supports_llm_proxy)
|
||||||
|
raise ValueError(
|
||||||
|
f"The LLM proxy requires a backend with proxy support; choose one of: {supported}. "
|
||||||
|
f"Got {llm_backend.name!r}."
|
||||||
|
)
|
||||||
|
config = llm_backend.config
|
||||||
|
return LLMProxyConfig(
|
||||||
|
enabled=module_kwargs.enable_llm_proxy,
|
||||||
|
llm_backend=module_kwargs.llm_backend,
|
||||||
|
upstream_base_url=config["base_url"],
|
||||||
|
upstream_api_key=config["api_key"],
|
||||||
|
model_name=config["model_name"],
|
||||||
|
connect_timeout_s=module_kwargs.llm_proxy_connect_timeout_s,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_selected_cli_configs(
|
||||||
|
parser: HfArgumentParser,
|
||||||
|
pipeline_args: list[str],
|
||||||
|
selected_specs: Sequence[BackendSpec],
|
||||||
|
) -> tuple[Any, ...]:
|
||||||
|
"""Parse selected configs while accepting legacy options for inactive backends."""
|
||||||
|
|
||||||
|
*parsed, remaining = parser.parse_args_into_dataclasses(
|
||||||
|
args=pipeline_args,
|
||||||
|
return_remaining_strings=True,
|
||||||
|
)
|
||||||
|
if not remaining:
|
||||||
|
return tuple(parsed)
|
||||||
|
|
||||||
|
selected_types = {spec.config_type for spec in selected_specs}
|
||||||
|
inactive_types: list[type[Any]] = []
|
||||||
|
for registry in (STT_BACKENDS, LLM_BACKENDS, TTS_BACKENDS):
|
||||||
|
for spec in registry.values():
|
||||||
|
if spec.config_type not in selected_types and spec.config_type not in inactive_types:
|
||||||
|
inactive_types.append(spec.config_type)
|
||||||
|
|
||||||
|
compatibility_parser = HfArgumentParser(
|
||||||
|
tuple(inactive_types), # type: ignore[arg-type]
|
||||||
|
add_help=False,
|
||||||
|
allow_abbrev=False,
|
||||||
|
conflict_handler="resolve",
|
||||||
|
)
|
||||||
|
known_options = compatibility_parser._option_string_actions
|
||||||
|
_, unknown = compatibility_parser.parse_known_args(remaining)
|
||||||
|
if unknown:
|
||||||
|
raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {unknown}")
|
||||||
|
|
||||||
|
ignored_options = sorted({token.split("=", 1)[0] for token in remaining if token.split("=", 1)[0] in known_options})
|
||||||
|
logger.warning(
|
||||||
|
"Ignoring options for inactive backends: %s",
|
||||||
|
", ".join(ignored_options),
|
||||||
|
)
|
||||||
|
return tuple(parsed)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_arguments(
|
||||||
|
argv: Sequence[str] | None = None,
|
||||||
|
*,
|
||||||
|
command: Literal["serve", "local"] = "serve",
|
||||||
|
) -> ParsedArguments:
|
||||||
|
module_defaults = ModuleArguments()
|
||||||
|
assert module_defaults.stt is not None
|
||||||
|
assert module_defaults.llm_backend is not None
|
||||||
|
assert module_defaults.tts is not None
|
||||||
|
|
||||||
|
pipeline_args = list(sys.argv[1:] if argv is None else argv)
|
||||||
|
_is_json = len(pipeline_args) == 1 and pipeline_args[0].endswith(".json")
|
||||||
|
pipeline_json: dict[str, Any] | None = None
|
||||||
|
if _is_json:
|
||||||
|
with open(pipeline_args[0]) as _f:
|
||||||
|
pipeline_json = json.load(_f)
|
||||||
|
_mac_preset_enabled = bool(pipeline_json.get("mac_optimal_settings", False))
|
||||||
|
_llm_name = pipeline_json.get("llm_backend") or (
|
||||||
|
"mlx-lm" if _mac_preset_enabled else module_defaults.llm_backend
|
||||||
|
)
|
||||||
|
if _mac_preset_enabled:
|
||||||
|
pipeline_json = {**_mac_preset_defaults(_llm_name), **pipeline_json}
|
||||||
|
_stt_name = pipeline_json.get("stt") or module_defaults.stt
|
||||||
|
_tts_name = pipeline_json.get("tts") or module_defaults.tts
|
||||||
|
else:
|
||||||
|
_pre = argparse.ArgumentParser(prog=f"speech-to-speech {command}", add_help=False)
|
||||||
|
_pre.add_argument("--mac-optimal-settings", action="store_true")
|
||||||
|
_pre.add_argument("--stt", choices=tuple(STT_BACKENDS))
|
||||||
|
_pre.add_argument("--llm_backend", "--llm-backend", choices=tuple(LLM_BACKENDS))
|
||||||
|
_pre.add_argument("--tts", choices=tuple(TTS_BACKENDS))
|
||||||
|
_pre_args = _pre.parse_known_args(pipeline_args)[0]
|
||||||
|
_mac_preset_enabled = _pre_args.mac_optimal_settings
|
||||||
|
_stt_name = _pre_args.stt or module_defaults.stt
|
||||||
|
_llm_name = _pre_args.llm_backend or ("mlx-lm" if _mac_preset_enabled else module_defaults.llm_backend)
|
||||||
|
_tts_name = _pre_args.tts or module_defaults.tts
|
||||||
|
|
||||||
|
selected_specs = []
|
||||||
|
for registry, name in (
|
||||||
|
(STT_BACKENDS, _stt_name),
|
||||||
|
(LLM_BACKENDS, _llm_name),
|
||||||
|
(TTS_BACKENDS, _tts_name),
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
selected_specs.append(registry[name])
|
||||||
|
except KeyError as exc:
|
||||||
|
choices = ", ".join(registry)
|
||||||
|
raise ValueError(f"Unsupported backend {name!r}; choose one of: {choices}.") from exc
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
"Backend pre-parse: stt=%s, llm=%s, tts=%s",
|
||||||
|
_stt_name,
|
||||||
|
_llm_name,
|
||||||
|
_tts_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
server_arguments_class = RealtimeServerArguments if command == "serve" else LocalRealtimeServerArguments
|
||||||
|
argument_classes: list[type[Any]] = [
|
||||||
|
ModuleArguments,
|
||||||
|
server_arguments_class,
|
||||||
|
]
|
||||||
|
if command == "local":
|
||||||
|
argument_classes.append(LocalAudioArguments)
|
||||||
|
argument_classes.extend(
|
||||||
|
[
|
||||||
|
VADHandlerArguments,
|
||||||
|
*(spec.config_type for spec in selected_specs),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
parser = HfArgumentParser(tuple(argument_classes), prog=f"speech-to-speech {command}") # type: ignore[arg-type]
|
||||||
|
mac_action = parser._option_string_actions.pop("--mac_optimal_settings")
|
||||||
|
mac_action.option_strings = [option for option in mac_action.option_strings if option != "--mac_optimal_settings"]
|
||||||
|
if _mac_preset_enabled:
|
||||||
|
parser.set_defaults(**_mac_preset_defaults(_llm_name))
|
||||||
|
|
||||||
|
if _is_json:
|
||||||
|
assert pipeline_json is not None
|
||||||
|
parsed = parser.parse_dict(pipeline_json, allow_extra_keys=True)
|
||||||
|
else:
|
||||||
|
parsed = _parse_selected_cli_configs(parser, pipeline_args, selected_specs)
|
||||||
|
|
||||||
|
# Build a {type: instance} lookup so field assignment is order-independent.
|
||||||
|
by_type: dict[type, Any] = {type(obj): obj for obj in parsed}
|
||||||
|
logger.debug("Parsed %d argument classes: %s", len(by_type), [t.__name__ for t in by_type])
|
||||||
|
if command == "serve":
|
||||||
|
realtime_server_kwargs = by_type[RealtimeServerArguments]
|
||||||
|
else:
|
||||||
|
realtime_server_kwargs = RealtimeServerArguments(
|
||||||
|
host="127.0.0.1",
|
||||||
|
port=by_type[LocalRealtimeServerArguments].port,
|
||||||
|
)
|
||||||
|
|
||||||
|
module_kwargs = by_type[ModuleArguments]
|
||||||
|
if module_kwargs.diarization and module_kwargs.diarization_model_name is None:
|
||||||
|
module_kwargs.diarization_model_name = "nvidia/Nemotron-3-Diarization"
|
||||||
|
module_kwargs.stt = _stt_name
|
||||||
|
module_kwargs.llm_backend = _llm_name
|
||||||
|
module_kwargs.tts = _tts_name
|
||||||
|
args = ParsedArguments(
|
||||||
|
module_kwargs=module_kwargs,
|
||||||
|
realtime_server_kwargs=realtime_server_kwargs,
|
||||||
|
local_audio_kwargs=by_type.get(LocalAudioArguments, LocalAudioArguments()),
|
||||||
|
vad_handler_kwargs=by_type[VADHandlerArguments],
|
||||||
|
stt_backend=BackendSelection(
|
||||||
|
selected_specs[0], selected_specs[0].normalize(by_type[selected_specs[0].config_type])
|
||||||
|
),
|
||||||
|
llm_backend=BackendSelection(
|
||||||
|
selected_specs[1], selected_specs[1].normalize(by_type[selected_specs[1].config_type])
|
||||||
|
),
|
||||||
|
tts_backend=BackendSelection(
|
||||||
|
selected_specs[2], selected_specs[2].normalize(by_type[selected_specs[2].config_type])
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return args
|
||||||
|
|
||||||
|
|
||||||
|
def setup_logger(log_level: str) -> None:
|
||||||
|
global logger
|
||||||
|
from speech_to_speech.pipeline.log_context import PipelineLogFilter
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=log_level.upper(),
|
||||||
|
format="%(asctime)s - %(pipeline_prefix)s%(name)s - %(levelname)s - %(message)s",
|
||||||
|
)
|
||||||
|
# Attach the filter to every existing handler so each LogRecord gets a
|
||||||
|
# `pipeline_prefix` attribute (matching the format string above).
|
||||||
|
pipeline_filter = PipelineLogFilter()
|
||||||
|
for h in logging.getLogger().handlers:
|
||||||
|
h.addFilter(pipeline_filter)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# torch compile logs
|
||||||
|
if log_level == "debug":
|
||||||
|
torch._logging.set_logs(graph_breaks=True, recompiles=True, cudagraphs=True)
|
||||||
|
|
||||||
|
|
||||||
|
def check_mac_settings(module_kwargs: ModuleArguments) -> None:
|
||||||
|
if platform == "darwin":
|
||||||
|
if module_kwargs.device == "cuda":
|
||||||
|
raise ValueError("Cannot use CUDA on macOS. Please set the device to 'cpu' or 'mps'.")
|
||||||
|
if module_kwargs.llm_backend != "mlx-lm":
|
||||||
|
logger.warning(
|
||||||
|
"For macOS users, it is recommended to use mlx-lm. You can activate it by passing --llm_backend mlx-lm."
|
||||||
|
)
|
||||||
|
if module_kwargs.tts not in ("pocket", "kokoro", "omnivoice", "qwen3"):
|
||||||
|
logger.warning(
|
||||||
|
"For macOS users, it is recommended to use qwen3 for TTS "
|
||||||
|
"(pocket, kokoro, and omnivoice are also valid options)."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_torch_num_threads(value: Any) -> None:
|
||||||
|
if value is not None and (type(value) is not int or value < 1):
|
||||||
|
raise ValueError(f"--torch_num_threads must be a positive integer; got {value!r}.")
|
||||||
|
|
||||||
|
|
||||||
|
def apply_torch_num_threads(module_kwargs: ModuleArguments) -> None:
|
||||||
|
"""Apply an explicit --torch_num_threads; with it unset, leave PyTorch's thread count alone."""
|
||||||
|
if module_kwargs.torch_num_threads is not None:
|
||||||
|
torch.set_num_threads(module_kwargs.torch_num_threads)
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_module_args(module_kwargs: ModuleArguments, llm_backend: BackendSelection) -> None:
|
||||||
|
validate_torch_num_threads(module_kwargs.torch_num_threads)
|
||||||
|
if module_kwargs.diarization_model_name and module_kwargs.stt == "none":
|
||||||
|
raise ValueError("Speaker-aware conversation requires an STT backend; --stt none does not produce transcripts.")
|
||||||
|
if module_kwargs.diarization_model_name and not 0 < module_kwargs.diarization_threshold < 1:
|
||||||
|
raise ValueError("--diarization_threshold must be between 0 and 1.")
|
||||||
|
if module_kwargs.tts is None:
|
||||||
|
module_kwargs.tts = "qwen3"
|
||||||
|
if module_kwargs.stt == "none" and not llm_backend.spec.capabilities.supports_audio_input:
|
||||||
|
supported = ", ".join(name for name, spec in LLM_BACKENDS.items() if spec.capabilities.supports_audio_input)
|
||||||
|
raise ValueError(f"--stt none requires an audio-input LLM backend; choose one of: {supported}.")
|
||||||
|
if module_kwargs.enable_llm_proxy and not llm_backend.spec.capabilities.supports_llm_proxy:
|
||||||
|
supported = ", ".join(name for name, spec in LLM_BACKENDS.items() if spec.capabilities.supports_llm_proxy)
|
||||||
|
raise ValueError(
|
||||||
|
f"The LLM proxy requires a backend with proxy support; choose one of: {supported}. "
|
||||||
|
f"Got {llm_backend.name!r}."
|
||||||
|
)
|
||||||
|
if platform == "darwin":
|
||||||
|
check_mac_settings(module_kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_all_args(args: ParsedArguments) -> None:
|
||||||
|
"""Validate selectors and apply the global device to selected configs only."""
|
||||||
|
|
||||||
|
prepare_module_args(args.module_kwargs, args.llm_backend)
|
||||||
|
if args.module_kwargs.device is None:
|
||||||
|
return
|
||||||
|
for field_name in ("stt_backend", "llm_backend", "tts_backend"):
|
||||||
|
selection = getattr(args, field_name)
|
||||||
|
if "device" not in selection.config:
|
||||||
|
continue
|
||||||
|
config = {**selection.config, "device": args.module_kwargs.device}
|
||||||
|
setattr(args, field_name, replace(selection, config=config))
|
||||||
|
|
||||||
|
|
||||||
|
def _build_handlers(
|
||||||
|
*,
|
||||||
|
stop_event: Event,
|
||||||
|
should_listen: Event,
|
||||||
|
recv_audio_chunks_queue: Queue[AudioInItem],
|
||||||
|
spoken_prompt_queue: Queue[VADOutItem],
|
||||||
|
stt_output_queue: Queue[STTOutItem],
|
||||||
|
text_prompt_queue: Queue[TextPromptItem],
|
||||||
|
lm_response_queue: Queue[LMOutItem],
|
||||||
|
lm_processed_queue: Queue[TTSInItem],
|
||||||
|
send_audio_chunks_queue: Queue[AudioOutItem],
|
||||||
|
text_output_queue: Queue[TextEventItem],
|
||||||
|
module_kwargs: ModuleArguments,
|
||||||
|
vad_handler_kwargs: VADHandlerArguments,
|
||||||
|
stt_backend: BackendSelection,
|
||||||
|
llm_backend: BackendSelection,
|
||||||
|
tts_backend: BackendSelection,
|
||||||
|
speculative_turns: SpeculativeTurnTracker,
|
||||||
|
cancel_scope: CancelScope,
|
||||||
|
pipeline_index: int,
|
||||||
|
resource_ledger: list[Any] | None = None,
|
||||||
|
) -> list[Any]:
|
||||||
|
"""Build a handler chain: VAD → STT/AudioInput → LM → TTS."""
|
||||||
|
from speech_to_speech.LLM.lm_output_processor import LMOutputProcessor
|
||||||
|
|
||||||
|
vad = VADHandler(
|
||||||
|
stop_event,
|
||||||
|
queue_in=recv_audio_chunks_queue,
|
||||||
|
queue_out=spoken_prompt_queue,
|
||||||
|
setup_args=(should_listen,),
|
||||||
|
setup_kwargs={
|
||||||
|
**{
|
||||||
|
config_field.name: deepcopy(getattr(vad_handler_kwargs, config_field.name))
|
||||||
|
for config_field in fields(vad_handler_kwargs)
|
||||||
|
},
|
||||||
|
"text_output_queue": text_output_queue,
|
||||||
|
"speculative_turns": speculative_turns,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if resource_ledger is not None:
|
||||||
|
resource_ledger.append(vad)
|
||||||
|
# Loading Silero sets PyTorch to one thread for the whole process. Re-apply an explicit
|
||||||
|
# --torch_num_threads after every VAD build, before the other models load and warm up.
|
||||||
|
apply_torch_num_threads(module_kwargs)
|
||||||
|
|
||||||
|
side_handlers: list[Any] = []
|
||||||
|
if module_kwargs.diarization_model_name:
|
||||||
|
from speech_to_speech.diarization import StreamingDiarizer
|
||||||
|
from speech_to_speech.diarization.streaming import DIARIZATION_DEVICES
|
||||||
|
from speech_to_speech.diarization.worker import DiarizationWorker
|
||||||
|
|
||||||
|
diarization_device = resolve_device(
|
||||||
|
module_kwargs.device or module_kwargs.diarization_device,
|
||||||
|
DIARIZATION_DEVICES,
|
||||||
|
"Nemotron diarization",
|
||||||
|
)
|
||||||
|
if diarization_device == "cpu":
|
||||||
|
logger.warning(
|
||||||
|
"Diarization is using CPU; sustained speech can outpace inference and disable speaker labels "
|
||||||
|
"until reconnect. CUDA or MPS is recommended for live sessions."
|
||||||
|
)
|
||||||
|
diarizer = StreamingDiarizer.from_pretrained(
|
||||||
|
module_kwargs.diarization_model_name,
|
||||||
|
revision=module_kwargs.diarization_revision,
|
||||||
|
device=diarization_device,
|
||||||
|
dtype=module_kwargs.diarization_dtype,
|
||||||
|
streaming_mode=module_kwargs.diarization_streaming_mode,
|
||||||
|
threshold=module_kwargs.diarization_threshold,
|
||||||
|
)
|
||||||
|
if resource_ledger is not None:
|
||||||
|
resource_ledger.append(diarizer)
|
||||||
|
if diarizer.sample_rate != vad_handler_kwargs.sample_rate:
|
||||||
|
raise ValueError("Diarization and VAD must use the same audio sample rate.")
|
||||||
|
diarizer.warmup()
|
||||||
|
logger.info(
|
||||||
|
"Diarization ready: device=%s mode=%s; speaker labels will accompany completed transcriptions",
|
||||||
|
diarization_device,
|
||||||
|
module_kwargs.diarization_streaming_mode,
|
||||||
|
)
|
||||||
|
vad.diarization_worker = DiarizationWorker(diarizer, stop_event)
|
||||||
|
if resource_ledger is not None:
|
||||||
|
# The worker takes ownership after all model preparation succeeds.
|
||||||
|
resource_ledger.remove(diarizer)
|
||||||
|
resource_ledger.append(vad.diarization_worker)
|
||||||
|
side_handlers.append(vad.diarization_worker)
|
||||||
|
|
||||||
|
needs_notifier = not stt_backend.spec.capabilities.bypasses_transcription_notifier
|
||||||
|
stt_queue_out: Queue[Any] = stt_output_queue if needs_notifier else text_prompt_queue
|
||||||
|
stt_context = HandlerContext(
|
||||||
|
stop_event=stop_event,
|
||||||
|
queue_in=spoken_prompt_queue,
|
||||||
|
queue_out=stt_queue_out,
|
||||||
|
text_output_queue=text_output_queue,
|
||||||
|
should_listen=should_listen,
|
||||||
|
cancel_scope=cancel_scope,
|
||||||
|
speculative_turns=speculative_turns,
|
||||||
|
pipeline_index=pipeline_index,
|
||||||
|
sample_rate=vad_handler_kwargs.sample_rate,
|
||||||
|
enable_live_transcription=module_kwargs.enable_live_transcription,
|
||||||
|
live_transcription_update_interval=module_kwargs.live_transcription_update_interval,
|
||||||
|
)
|
||||||
|
stt_handler = create_backend_handler(stt_backend, stt_context)
|
||||||
|
if resource_ledger is not None:
|
||||||
|
resource_ledger.append(stt_handler)
|
||||||
|
if stt_backend.spec.capabilities.streams_audio_chunks:
|
||||||
|
vad.streaming_stt_sink = stt_handler
|
||||||
|
speech_input_handlers = [stt_handler]
|
||||||
|
if needs_notifier:
|
||||||
|
transcription_notifier = TranscriptionNotifier(
|
||||||
|
stop_event,
|
||||||
|
queue_in=stt_output_queue,
|
||||||
|
queue_out=text_prompt_queue, # type: ignore[arg-type]
|
||||||
|
setup_kwargs={
|
||||||
|
"text_output_queue": text_output_queue,
|
||||||
|
"should_listen": should_listen,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if resource_ledger is not None:
|
||||||
|
resource_ledger.append(transcription_notifier)
|
||||||
|
speech_input_handlers.append(transcription_notifier)
|
||||||
|
|
||||||
|
def handler_context(queue_in: Queue[Any], queue_out: Queue[Any]) -> HandlerContext:
|
||||||
|
return HandlerContext(
|
||||||
|
stop_event=stop_event,
|
||||||
|
queue_in=queue_in,
|
||||||
|
queue_out=queue_out,
|
||||||
|
text_output_queue=text_output_queue,
|
||||||
|
should_listen=should_listen,
|
||||||
|
cancel_scope=cancel_scope,
|
||||||
|
speculative_turns=speculative_turns,
|
||||||
|
pipeline_index=pipeline_index,
|
||||||
|
sample_rate=vad_handler_kwargs.sample_rate,
|
||||||
|
enable_live_transcription=module_kwargs.enable_live_transcription,
|
||||||
|
live_transcription_update_interval=module_kwargs.live_transcription_update_interval,
|
||||||
|
detect_llm_output_language=module_kwargs.detect_llm_output_language,
|
||||||
|
)
|
||||||
|
|
||||||
|
lm_context = handler_context(text_prompt_queue, lm_response_queue)
|
||||||
|
lm = create_backend_handler(
|
||||||
|
llm_backend,
|
||||||
|
lm_context,
|
||||||
|
)
|
||||||
|
|
||||||
|
if resource_ledger is not None:
|
||||||
|
resource_ledger.append(lm)
|
||||||
|
|
||||||
|
lm_processor = LMOutputProcessor(
|
||||||
|
stop_event,
|
||||||
|
queue_in=lm_response_queue,
|
||||||
|
queue_out=lm_processed_queue,
|
||||||
|
setup_kwargs={
|
||||||
|
"speculative_turns": speculative_turns,
|
||||||
|
"text_output_queue": text_output_queue,
|
||||||
|
"detect_llm_output_language": module_kwargs.detect_llm_output_language,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if resource_ledger is not None:
|
||||||
|
resource_ledger.append(lm_processor)
|
||||||
|
|
||||||
|
tts_output_queue: Queue[AudioOutItem] = Queue() if module_kwargs.enable_visemes else send_audio_chunks_queue
|
||||||
|
tts_context = handler_context(lm_processed_queue, tts_output_queue)
|
||||||
|
tts = create_backend_handler(
|
||||||
|
tts_backend,
|
||||||
|
tts_context,
|
||||||
|
)
|
||||||
|
|
||||||
|
if resource_ledger is not None:
|
||||||
|
resource_ledger.append(tts)
|
||||||
|
|
||||||
|
handlers = [vad, *side_handlers, *speech_input_handlers, lm, lm_processor, tts]
|
||||||
|
if module_kwargs.enable_visemes:
|
||||||
|
from speech_to_speech.STV.w2v_stv_handler import Wav2Vec2STVHandler
|
||||||
|
|
||||||
|
handlers.append(
|
||||||
|
Wav2Vec2STVHandler(
|
||||||
|
stop_event,
|
||||||
|
queue_in=tts_output_queue,
|
||||||
|
queue_out=send_audio_chunks_queue,
|
||||||
|
setup_kwargs={
|
||||||
|
"model_name": module_kwargs.stv_model_name,
|
||||||
|
"device": module_kwargs.device or module_kwargs.stv_device,
|
||||||
|
"cancel_scope": cancel_scope,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if resource_ledger is not None:
|
||||||
|
resource_ledger.append(handlers[-1])
|
||||||
|
return handlers
|
||||||
|
|
||||||
|
|
||||||
|
def _stt_session_languages(selection: BackendSelection, handler: Any) -> set[str] | None:
|
||||||
|
if selection.name == "nemotron-streaming" and getattr(handler, "_is_farsi", False):
|
||||||
|
return {"fa"}
|
||||||
|
if selection.name == "faster-whisper":
|
||||||
|
supported = getattr(getattr(handler, "model", None), "supported_languages", None)
|
||||||
|
return set(supported) if supported is not None else None
|
||||||
|
if selection.name == "whisper":
|
||||||
|
generation_config = getattr(getattr(handler, "model", None), "generation_config", None)
|
||||||
|
# Transformers rejects any language argument for an English-only checkpoint.
|
||||||
|
return set() if getattr(generation_config, "is_multilingual", None) is False else None
|
||||||
|
if selection.name == "qwen3-asr":
|
||||||
|
return set(modules[type(handler).__module__].SUPPORTED_LANGUAGES)
|
||||||
|
if selection.name in {"parakeet-tdt", "parakeet-unified", "paraformer", "openai-realtime", "vllm-realtime"}:
|
||||||
|
return set()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _build_pipeline_unit(
|
||||||
|
*,
|
||||||
|
index: int,
|
||||||
|
stop_event: Event,
|
||||||
|
module_kwargs: ModuleArguments,
|
||||||
|
vad_handler_kwargs: VADHandlerArguments,
|
||||||
|
stt_backend: BackendSelection,
|
||||||
|
llm_backend: BackendSelection,
|
||||||
|
tts_backend: BackendSelection,
|
||||||
|
resource_ledger: list[Any] | None = None,
|
||||||
|
) -> "PipelineUnit":
|
||||||
|
"""Build one isolated pipeline with its own state and queues.
|
||||||
|
|
||||||
|
Returns a PipelineUnit that lives inside RealtimeServer's pool. Handler instances
|
||||||
|
are returned in `unit.handlers`; the caller threads them via ThreadManager. No uvicorn
|
||||||
|
is created here — the single server is owned by RealtimeServer.
|
||||||
|
"""
|
||||||
|
from speech_to_speech.api.openai_realtime.service import RealtimeService
|
||||||
|
|
||||||
|
# Per-unit copies isolate any setup-time mutation performed by third-party libraries.
|
||||||
|
vad_kw = deepcopy(vad_handler_kwargs)
|
||||||
|
stt_selection = stt_backend.copy_for_pipeline()
|
||||||
|
llm_selection = llm_backend.copy_for_pipeline()
|
||||||
|
tts_selection = tts_backend.copy_for_pipeline()
|
||||||
|
|
||||||
|
should_listen = Event()
|
||||||
|
response_playing = Event()
|
||||||
|
cancel_scope = CancelScope()
|
||||||
|
speculative_turns = SpeculativeTurnTracker()
|
||||||
|
turn_latency_store = TurnLatencyStore()
|
||||||
|
speculative_turns.wait_observer = turn_latency_store.record_smart_wait
|
||||||
|
recv_audio_chunks_queue: Queue[AudioInItem] = Queue()
|
||||||
|
send_audio_chunks_queue: Queue[AudioOutItem] = Queue()
|
||||||
|
spoken_prompt_queue: Queue[VADOutItem] = Queue()
|
||||||
|
stt_output_queue: Queue[STTOutItem] = Queue()
|
||||||
|
text_prompt_queue: Queue[TextPromptItem] = Queue()
|
||||||
|
lm_response_queue: Queue[LMOutItem] = Queue()
|
||||||
|
lm_processed_queue: Queue[TTSInItem] = Queue()
|
||||||
|
text_output_queue: Queue[TextEventItem] = Queue()
|
||||||
|
|
||||||
|
chat_size = llm_selection.config.get("chat_size", 10)
|
||||||
|
default_instructions = llm_selection.config.get("init_chat_prompt")
|
||||||
|
|
||||||
|
service = RealtimeService(
|
||||||
|
text_prompt_queue=text_prompt_queue,
|
||||||
|
should_listen=should_listen,
|
||||||
|
chat_size=chat_size,
|
||||||
|
speculative_turns=speculative_turns,
|
||||||
|
turn_latency_store=turn_latency_store,
|
||||||
|
default_instructions=default_instructions,
|
||||||
|
)
|
||||||
|
|
||||||
|
if module_kwargs.enable_live_transcription and not stt_selection.spec.capabilities.streams_audio_chunks:
|
||||||
|
vad_kw.enable_realtime_transcription = True
|
||||||
|
vad_kw.realtime_processing_pause = module_kwargs.live_transcription_update_interval
|
||||||
|
|
||||||
|
handlers = _build_handlers(
|
||||||
|
stop_event=stop_event,
|
||||||
|
should_listen=should_listen,
|
||||||
|
recv_audio_chunks_queue=recv_audio_chunks_queue,
|
||||||
|
spoken_prompt_queue=spoken_prompt_queue,
|
||||||
|
stt_output_queue=stt_output_queue,
|
||||||
|
text_prompt_queue=text_prompt_queue,
|
||||||
|
lm_response_queue=lm_response_queue,
|
||||||
|
lm_processed_queue=lm_processed_queue,
|
||||||
|
send_audio_chunks_queue=send_audio_chunks_queue,
|
||||||
|
text_output_queue=text_output_queue,
|
||||||
|
module_kwargs=module_kwargs,
|
||||||
|
vad_handler_kwargs=vad_kw,
|
||||||
|
stt_backend=stt_selection,
|
||||||
|
llm_backend=llm_selection,
|
||||||
|
tts_backend=tts_selection,
|
||||||
|
speculative_turns=speculative_turns,
|
||||||
|
cancel_scope=cancel_scope,
|
||||||
|
pipeline_index=index,
|
||||||
|
**({"resource_ledger": resource_ledger} if resource_ledger is not None else {}),
|
||||||
|
)
|
||||||
|
for h in handlers:
|
||||||
|
h.pipeline_index = index
|
||||||
|
h.turn_latency_store = turn_latency_store
|
||||||
|
|
||||||
|
# Validate only against language sets already known to the active backends.
|
||||||
|
# Faster Whisper reports the loaded checkpoint's actual language set.
|
||||||
|
service.stt_supported_languages = _stt_session_languages(stt_selection, handlers[1])
|
||||||
|
setup_language = stt_selection.config.get("language")
|
||||||
|
service.stt_auto_reset_supported = not (
|
||||||
|
stt_selection.name == "openai-realtime" and isinstance(setup_language, str) and bool(setup_language.strip())
|
||||||
|
)
|
||||||
|
|
||||||
|
tts_handler = handlers[-2] if module_kwargs.enable_visemes else handlers[-1]
|
||||||
|
tts_module = modules[type(tts_handler).__module__]
|
||||||
|
if tts_selection.name == "kokoro":
|
||||||
|
service.tts_supported_languages = {"en", "ja", "zh", "fr", "es", "it", "pt", "hi"}
|
||||||
|
elif tts_selection.name == "facebookMMS":
|
||||||
|
service.tts_supported_languages = set(tts_module.WHISPER_LANGUAGE_TO_FACEBOOK_LANGUAGE)
|
||||||
|
elif tts_selection.name == "supertonic":
|
||||||
|
service.tts_supported_languages = set(tts_module.SUPERTONIC_LANGUAGE_CODES)
|
||||||
|
elif tts_selection.name == "qwen3":
|
||||||
|
service.tts_supported_languages = {code for code in tts_module.QWEN3_LANGUAGE_ALIASES if len(code) == 2}
|
||||||
|
elif tts_selection.name in {"chatTTS", "pocket"}:
|
||||||
|
service.tts_supported_languages = set()
|
||||||
|
|
||||||
|
return PipelineUnit(
|
||||||
|
index=index,
|
||||||
|
service=service,
|
||||||
|
cancel_scope=cancel_scope,
|
||||||
|
should_listen=should_listen,
|
||||||
|
response_playing=response_playing,
|
||||||
|
input_queue=recv_audio_chunks_queue,
|
||||||
|
output_queue=send_audio_chunks_queue,
|
||||||
|
text_output_queue=text_output_queue,
|
||||||
|
text_prompt_queue=text_prompt_queue,
|
||||||
|
handlers=handlers,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_pipeline(
|
||||||
|
args: ParsedArguments,
|
||||||
|
stop_event: Event,
|
||||||
|
*,
|
||||||
|
host: str | None = None,
|
||||||
|
) -> ThreadManager:
|
||||||
|
"""Build a pool of pipeline units behind one server."""
|
||||||
|
from speech_to_speech.api.openai_realtime.server import RealtimeServer
|
||||||
|
|
||||||
|
module_kwargs = args.module_kwargs
|
||||||
|
pool = [
|
||||||
|
_build_pipeline_unit(
|
||||||
|
index=index,
|
||||||
|
stop_event=stop_event,
|
||||||
|
module_kwargs=module_kwargs,
|
||||||
|
vad_handler_kwargs=args.vad_handler_kwargs,
|
||||||
|
stt_backend=args.stt_backend,
|
||||||
|
llm_backend=args.llm_backend,
|
||||||
|
tts_backend=args.tts_backend,
|
||||||
|
)
|
||||||
|
for index in range(module_kwargs.num_pipelines)
|
||||||
|
]
|
||||||
|
|
||||||
|
server = RealtimeServer(
|
||||||
|
stop_event=stop_event,
|
||||||
|
pool=pool,
|
||||||
|
host=host or args.realtime_server_kwargs.host,
|
||||||
|
port=args.realtime_server_kwargs.port,
|
||||||
|
llm_proxy_config=(
|
||||||
|
build_llm_proxy_config(module_kwargs, args.llm_backend) if module_kwargs.enable_llm_proxy else None
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
handlers: list[Any] = []
|
||||||
|
for unit in pool:
|
||||||
|
handlers.extend(unit.handlers)
|
||||||
|
handlers.append(server)
|
||||||
|
return ThreadManager(handlers)
|
||||||
|
|
||||||
|
|
||||||
|
def build_local_pipeline(args: ParsedArguments, stop_event: Event) -> ThreadManager:
|
||||||
|
"""Compose the canonical server and audio client over a forced loopback URL."""
|
||||||
|
|
||||||
|
from speech_to_speech.api.openai_realtime.audio_client import (
|
||||||
|
RealtimeAudioClient,
|
||||||
|
RealtimeAudioClientConfig,
|
||||||
|
load_realtime_tool_module,
|
||||||
|
)
|
||||||
|
|
||||||
|
local_audio = args.local_audio_kwargs
|
||||||
|
playback_buffer_ms = local_audio.local_audio_playback_buffer_ms
|
||||||
|
if playback_buffer_ms is None:
|
||||||
|
playback_buffer_ms = OPENAI_TTS_PLAYBACK_BUFFER_MS if args.tts_backend.name == "openai" else 0.0
|
||||||
|
tools: list[dict[str, Any]] = []
|
||||||
|
tool_executor = None
|
||||||
|
tool_response_create = True
|
||||||
|
if local_audio.local_audio_tool_module:
|
||||||
|
tools, tool_executor, tool_response_create = load_realtime_tool_module(local_audio.local_audio_tool_module)
|
||||||
|
server_manager = build_pipeline(args, stop_event, host="127.0.0.1")
|
||||||
|
client = RealtimeAudioClient(
|
||||||
|
stop_event,
|
||||||
|
RealtimeAudioClientConfig(
|
||||||
|
url=f"ws://127.0.0.1:{args.realtime_server_kwargs.port}/v1/realtime",
|
||||||
|
api_key="local",
|
||||||
|
chunk_size=local_audio.local_audio_chunk_size,
|
||||||
|
playback_buffer_ms=playback_buffer_ms,
|
||||||
|
input_device=local_audio.local_audio_input_device,
|
||||||
|
output_device=local_audio.local_audio_output_device,
|
||||||
|
print_json=local_audio.local_audio_print_json,
|
||||||
|
block_mic_during_playback=local_audio.local_audio_block_mic_during_playback,
|
||||||
|
tools=tools,
|
||||||
|
tool_executor=tool_executor,
|
||||||
|
tool_response_create=tool_response_create,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return ThreadManager([*server_manager.handlers, client])
|
||||||
|
|
||||||
|
|
||||||
|
def run_pipeline_command(command: Literal["serve", "local"], argv: Sequence[str]) -> None:
|
||||||
|
"""Run the server alone or compose it with the loopback audio client."""
|
||||||
|
|
||||||
|
args = parse_arguments(argv, command=command)
|
||||||
|
|
||||||
|
setup_logger(args.module_kwargs.log_level)
|
||||||
|
# Set the transcript gate and warn before any conversation is processed, so an operator
|
||||||
|
# sees the notice ahead of the first turn rather than after content is already logged.
|
||||||
|
set_log_transcripts(args.module_kwargs.log_transcripts)
|
||||||
|
warn_if_log_transcripts_enabled()
|
||||||
|
|
||||||
|
if args.module_kwargs.num_pipelines < 1:
|
||||||
|
raise ValueError(f"--num_pipelines must be >= 1, got {args.module_kwargs.num_pipelines}")
|
||||||
|
|
||||||
|
prepare_all_args(args)
|
||||||
|
# On Apple Silicon, all MLX inference serializes through a global lock (utils/mlx_lock.py).
|
||||||
|
# The progressive STT path uses a short timeout and drops work under contention, producing
|
||||||
|
# a flood of warnings without affecting final transcripts. With a pool, pre-emptively turn
|
||||||
|
# it off so logs stay readable; the final STT path is unaffected. Non-darwin platforms
|
||||||
|
# don't share this lock, so leave their live transcription alone.
|
||||||
|
if args.module_kwargs.num_pipelines > 1 and platform == "darwin" and args.module_kwargs.enable_live_transcription:
|
||||||
|
logger.info(
|
||||||
|
"MLX contention: --num_pipelines=%d > 1 on Apple Silicon → disabling live transcription "
|
||||||
|
"(progressive STT contends on the global MLX lock)",
|
||||||
|
args.module_kwargs.num_pipelines,
|
||||||
|
)
|
||||||
|
args.module_kwargs.enable_live_transcription = False
|
||||||
|
|
||||||
|
stop_event = Event()
|
||||||
|
pipeline_manager = (
|
||||||
|
build_local_pipeline(args, stop_event) if command == "local" else build_pipeline(args, stop_event)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Set up graceful shutdown handler
|
||||||
|
shutdown_requested = [False] # Use list for nonlocal mutation
|
||||||
|
|
||||||
|
def signal_handler(_sig: int, _frame: Optional[FrameType]) -> None:
|
||||||
|
if not shutdown_requested[0]:
|
||||||
|
shutdown_requested[0] = True
|
||||||
|
console.print("\n[yellow]Shutting down gracefully...[/yellow]")
|
||||||
|
pipeline_manager.stop()
|
||||||
|
console.print("[green]✓ Pipeline stopped successfully[/green]")
|
||||||
|
|
||||||
|
signal.signal(signal.SIGINT, signal_handler)
|
||||||
|
signal.signal(signal.SIGTERM, signal_handler)
|
||||||
|
|
||||||
|
try:
|
||||||
|
pipeline_manager.start()
|
||||||
|
pipeline_manager.wait()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
if not shutdown_requested[0]:
|
||||||
|
console.print("\n[yellow]Shutting down gracefully...[/yellow]")
|
||||||
|
pipeline_manager.stop()
|
||||||
|
console.print("[green]✓ Pipeline stopped successfully[/green]")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""Compatibility entry point for direct module execution."""
|
||||||
|
|
||||||
|
from speech_to_speech.cli import main as cli_main
|
||||||
|
|
||||||
|
cli_main()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Real DB local profiles retain replay/owner/revocation authority."""
|
||||||
|
from uuid import UUID, uuid4
|
||||||
|
from sqlalchemy import text
|
||||||
|
import pytest
|
||||||
|
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):
|
||||||
|
e = seeded_env
|
||||||
|
cid = UUID(e.lifecycle.create_conversation(e.user, uuid4())['id'])
|
||||||
|
request = uuid4()
|
||||||
|
config = local_config()
|
||||||
|
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'])
|
||||||
|
changed = local_config(local_s2s_tts_voice='different')
|
||||||
|
replay = e.lifecycle.create_live_session(e.user, cid, request, provider='local_s2s',
|
||||||
|
model=changed.selected_model, execution_profile=changed.profile())
|
||||||
|
assert replay['session_id'] == first['session_id'] and replay['replayed']
|
||||||
|
info = e.lifecycle.validate_stream(e.user, sid, initial=True)
|
||||||
|
assert info['provider'] == 'local_s2s' and info['execution_profile'] == config.profile()
|
||||||
|
assert info['execution_profile'] != changed.profile()
|
||||||
|
with e.engine.begin() as conn:
|
||||||
|
row = conn.execute(text('SELECT execution_profile FROM live_sessions WHERE id=:id'), {'id': sid}).scalar_one()
|
||||||
|
assert row == config.profile()
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_profile_revocation_still_blocks_stream(seeded_env):
|
||||||
|
e = seeded_env
|
||||||
|
cid = UUID(e.lifecycle.create_conversation(e.user, uuid4())['id'])
|
||||||
|
c = local_config()
|
||||||
|
reservation = e.lifecycle.create_live_session(e.user, cid, uuid4(), provider='local_s2s', model=c.selected_model, execution_profile=c.profile())
|
||||||
|
with e.engine.begin() as conn:
|
||||||
|
conn.execute(text('UPDATE organization_settings SET access_epoch=access_epoch+1 WHERE organization_id=:org'), {'org': e.org})
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
e.lifecycle.validate_stream(e.user, UUID(reservation['session_id']), initial=True)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Execute hash-checked pinned methods without installing upstream ML dependencies."""
|
||||||
|
import ast
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1] / 'fixtures/local_s2s_upstream'
|
||||||
|
|
||||||
|
|
||||||
|
def tree(name):
|
||||||
|
manifest = json.loads((ROOT / 'manifest.json').read_text())
|
||||||
|
data = (ROOT / name).read_bytes()
|
||||||
|
assert hashlib.sha256(data).hexdigest() == manifest['files'][name]['sha256']
|
||||||
|
return ast.parse(data.decode())
|
||||||
|
|
||||||
|
|
||||||
|
def functions(name, selection, namespace):
|
||||||
|
definitions = []
|
||||||
|
for cls, method in selection:
|
||||||
|
nodes = tree(name).body
|
||||||
|
if cls:
|
||||||
|
nodes = next(n for n in nodes if isinstance(n, ast.ClassDef) and n.name == cls).body
|
||||||
|
node = next(n for n in nodes if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == method)
|
||||||
|
node.decorator_list = []
|
||||||
|
definitions.append(node)
|
||||||
|
module = ast.Module(body=[ast.ImportFrom(module='__future__', names=[ast.alias(name='annotations')], level=0)] + definitions, type_ignores=[])
|
||||||
|
exec(compile(ast.fix_missing_locations(module), str(ROOT / name), 'exec'), namespace)
|
||||||
|
return namespace
|
||||||
|
|
||||||
|
|
||||||
|
def constant(name, identifier):
|
||||||
|
"""Read a literal from the hash-checked source, never a fixture override."""
|
||||||
|
node = next(n for n in tree(name).body if isinstance(n, ast.Assign)
|
||||||
|
and any(isinstance(t, ast.Name) and t.id == identifier for t in n.targets))
|
||||||
|
return ast.literal_eval(node.value)
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
"""Provider-free Phase 1 replay: run unchanged before and after the boundary."""
|
||||||
|
import asyncio
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tests.unit.test_realtime_phase1 import (
|
||||||
|
runner, persisted, make, input_turn, response, delta, done, until, commands,
|
||||||
|
)
|
||||||
|
from tests.unit.test_realtime_repairs import Clock, without_ticker
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("completed", [False, True], ids=["active", "completed-unplayed"])
|
||||||
|
@pytest.mark.parametrize("receipt", ["matching", "wrong-item", "wrong-position", "missing", "late", "conflicting"])
|
||||||
|
def test_interruption_replay(runner, persisted, completed, receipt):
|
||||||
|
async def scenario():
|
||||||
|
clock = Clock()
|
||||||
|
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
|
||||||
|
await without_ticker(runtime)
|
||||||
|
try:
|
||||||
|
await input_turn(runtime)
|
||||||
|
await response(runtime, transport)
|
||||||
|
await runtime.handle(delta(48000))
|
||||||
|
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||||
|
audio = next(iter(runtime.audio.values()))
|
||||||
|
await runtime.playback_progress(audio.ref, 100)
|
||||||
|
if completed:
|
||||||
|
await done(runtime)
|
||||||
|
await input_turn(runtime, "u2", 10)
|
||||||
|
assert len(commands(transport, "response.create")) == 1
|
||||||
|
if not completed:
|
||||||
|
await until(lambda: commands(transport, "response.cancel"))
|
||||||
|
assert not runtime.responses["r1"].terminal
|
||||||
|
await done(runtime, status="cancelled")
|
||||||
|
clock.advance(1)
|
||||||
|
await runtime.tick()
|
||||||
|
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||||
|
request = commands(transport, "conversation.item.truncate")[0]
|
||||||
|
assert request["item_id"] == "a1" and request["audio_end_ms"] == 100
|
||||||
|
assert runtime.responses["r1"].terminal
|
||||||
|
assert len(commands(transport, "response.create")) == 1
|
||||||
|
ack = dict(type="conversation.item.truncated", event_id="repair-ack",
|
||||||
|
item_id="a1", content_index=0, audio_end_ms=100)
|
||||||
|
if receipt == "missing":
|
||||||
|
clock.now = audio.cleanup_deadline + .01
|
||||||
|
await runtime.tick()
|
||||||
|
else:
|
||||||
|
if receipt == "wrong-item":
|
||||||
|
ack["item_id"] = "unknown"
|
||||||
|
if receipt == "wrong-position":
|
||||||
|
ack["audio_end_ms"] = 101
|
||||||
|
if receipt == "late":
|
||||||
|
clock.now = audio.cleanup_deadline + .01
|
||||||
|
await runtime.handle(ack)
|
||||||
|
if receipt == "conflicting":
|
||||||
|
await runtime.handle(dict(ack, audio_end_ms=101))
|
||||||
|
if receipt == "matching":
|
||||||
|
await runtime.handle(ack)
|
||||||
|
await runtime.handle(dict(ack, event_id="duplicate-repair-ack"))
|
||||||
|
await runtime.tick()
|
||||||
|
await until(lambda: len(commands(transport, "response.create")) == 2)
|
||||||
|
assert runtime.usable and audio.state == "retired"
|
||||||
|
assert len(commands(transport, "response.create")) == 2
|
||||||
|
print("REPLAY: generation stopped; repair matched at 100ms; duplicate ignored; exactly one next response")
|
||||||
|
else:
|
||||||
|
assert not runtime.usable
|
||||||
|
# A matching ack can release before a later conflict arrives;
|
||||||
|
# the conflict must close the session, never release further work.
|
||||||
|
assert len(commands(transport, "response.create")) <= (2 if receipt == "conflicting" else 1)
|
||||||
|
print(f"REPLAY: {receipt} repair => closed safely ({runtime.failure})")
|
||||||
|
finally:
|
||||||
|
await runtime.close()
|
||||||
|
asyncio.run(scenario())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("provider", ["openai", "gemini"])
|
||||||
|
def test_native_repair_contract(provider):
|
||||||
|
from app.modules.voice.provider import HistoryRepair, ProviderProtocolError
|
||||||
|
from app.infrastructure.realtime import RealtimeAdapter
|
||||||
|
from app.infrastructure.gemini_live import GeminiLiveAdapter
|
||||||
|
from tests.unit.test_realtime_phase1 import Transport
|
||||||
|
adapter = (RealtimeAdapter if provider == "openai" else GeminiLiveAdapter)(Transport())
|
||||||
|
repair = HistoryRepair("session", 2, "response", "operation", "item", 0, 100)
|
||||||
|
assert adapter.cancellation_request("response", "cancel") == dict(
|
||||||
|
type="response.cancel", response_id="response", event_id="cancel")
|
||||||
|
assert adapter.history_repair_request(repair) == dict(type="conversation.item.truncate",
|
||||||
|
event_id="operation", item_id="item", content_index=0, audio_end_ms=100)
|
||||||
|
event = dict(type="conversation.item.truncated", event_id="native-ack",
|
||||||
|
item_id="item", content_index=0, audio_end_ms=100)
|
||||||
|
if provider == "gemini":
|
||||||
|
with pytest.raises(ProviderProtocolError):
|
||||||
|
adapter.confirm_history_repair(repair, event)
|
||||||
|
return
|
||||||
|
receipt = adapter.confirm_history_repair(repair, event)
|
||||||
|
assert receipt.repair == repair and receipt.native_event_id == "native-ack"
|
||||||
|
assert receipt.provenance == "openai.item_truncated"
|
||||||
|
for changes in ({"item_id": "other"}, {"content_index": False},
|
||||||
|
{"audio_end_ms": True}, {"audio_end_ms": 101}, {"type": "response.done"}):
|
||||||
|
with pytest.raises(ProviderProtocolError):
|
||||||
|
adapter.confirm_history_repair(repair, dict(event, **changes))
|
||||||
|
|
||||||
|
|
||||||
|
def test_adapter_receipt_cannot_rebind_runtime_generation(runner, persisted, monkeypatch):
|
||||||
|
from dataclasses import replace
|
||||||
|
from app.infrastructure.realtime import RealtimeAdapter
|
||||||
|
from app.modules.voice.provider import HistoryRepairReceipt
|
||||||
|
async def scenario():
|
||||||
|
clock = Clock()
|
||||||
|
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
|
||||||
|
await without_ticker(runtime)
|
||||||
|
try:
|
||||||
|
await input_turn(runtime)
|
||||||
|
await response(runtime, transport)
|
||||||
|
await runtime.handle(delta(48000))
|
||||||
|
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||||
|
await input_turn(runtime, "u2", 10)
|
||||||
|
await until(lambda: commands(transport, "response.cancel"))
|
||||||
|
await done(runtime, status="cancelled")
|
||||||
|
clock.advance(1)
|
||||||
|
await runtime.tick()
|
||||||
|
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||||
|
monkeypatch.setattr(RealtimeAdapter, "confirm_history_repair", lambda self, repair, event:
|
||||||
|
HistoryRepairReceipt(replace(repair, generation=repair.generation + 1), "ack", "wrong"))
|
||||||
|
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
|
||||||
|
content_index=0, audio_end_ms=0))
|
||||||
|
assert not runtime.usable
|
||||||
|
assert len(commands(transport, "response.create")) == 1
|
||||||
|
assert next(iter(runtime.audio.values())).repair_receipt is None
|
||||||
|
finally:
|
||||||
|
await runtime.close()
|
||||||
|
asyncio.run(scenario())
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""Pinned extension checks use initialized fake handlers; no models/providers."""
|
||||||
|
import asyncio
|
||||||
|
from copy import deepcopy
|
||||||
|
from queue import Empty
|
||||||
|
from threading import Event, Thread
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
from services.local_s2s.components import ComponentServer
|
||||||
|
from services.local_s2s.extension import FailClosedQueue, active_components, install_session_proof, EngineTokenGuard
|
||||||
|
from app.modules.voice.local_s2s import setup_session
|
||||||
|
from app.infrastructure.local_s2s import LocalS2SAdapter
|
||||||
|
from app.modules.voice.settings import RuntimeSettings
|
||||||
|
from tests.unit.test_local_s2s_phase2 import local_config
|
||||||
|
from tests.unit.test_realtime_phase1 import Transport
|
||||||
|
|
||||||
|
|
||||||
|
def test_saturated_pipeline_stops_without_blocking_teardown():
|
||||||
|
stop = Event()
|
||||||
|
queue = FailClosedQueue(stop, maxsize=1)
|
||||||
|
queue.put(b'one')
|
||||||
|
with pytest.raises(RuntimeError, match='QUEUE_CAPACITY'):
|
||||||
|
queue.put(b'two', block=True)
|
||||||
|
assert stop.is_set() and queue.get_nowait() == b'one'
|
||||||
|
with pytest.raises(Empty): queue.get_nowait()
|
||||||
|
|
||||||
|
|
||||||
|
def handlers(config):
|
||||||
|
stt_type = type('STT', (), {'__module__': 'speech_to_speech.STT.openai_compatible_handler'})
|
||||||
|
tts_type = type('TTS', (), {'__module__': 'speech_to_speech.TTS.openai_compatible_handler'})
|
||||||
|
stt, tts = stt_type(), tts_type()
|
||||||
|
stt.model, stt.language, stt.response_format = config.local_s2s_stt_model, 'fa', 'json'
|
||||||
|
stt.base_url, stt.api_key, stt.timeout = 'http://127.0.0.1:8766/v1', 'local-components', 30
|
||||||
|
tts.model, tts.voice, tts.response_format, tts.sample_rate = config.local_s2s_tts_model, config.local_s2s_tts_voice, 'pcm', 24000
|
||||||
|
tts.base_url, tts.api_key, tts.timeout = stt.base_url, stt.api_key, stt.timeout
|
||||||
|
class Client:
|
||||||
|
token_limit, max_retries = 256, 0
|
||||||
|
base_url, api_key = stt.base_url, stt.api_key
|
||||||
|
def with_options(self, **kwargs):
|
||||||
|
assert kwargs == {'max_retries': 0}
|
||||||
|
return self
|
||||||
|
llm = SimpleNamespace(model_name=config.local_s2s_llm_model, gen_kwargs={'max_tokens': 256}, request_timeout_s=30, client=Client())
|
||||||
|
return SimpleNamespace(handlers=[SimpleNamespace(enable_realtime_transcription=False), stt, llm, tts])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('change', ['none', 'model', 'voice', 'rate', 'credential', 'progressive'])
|
||||||
|
def test_authoritative_components_come_from_initialized_handlers(change):
|
||||||
|
config = local_config()
|
||||||
|
unit = handlers(config)
|
||||||
|
if change == 'model': unit.handlers[1].model = 'wrong'
|
||||||
|
if change == 'voice': unit.handlers[-1].voice = 'wrong'
|
||||||
|
if change == 'rate': unit.handlers[-1].sample_rate = 16000
|
||||||
|
if change == 'credential': unit.handlers[1].api_key = ''
|
||||||
|
if change == 'progressive': unit.handlers[0].enable_realtime_transcription = True
|
||||||
|
if change != 'none':
|
||||||
|
with pytest.raises(ValueError): active_components(unit, config.components())
|
||||||
|
else:
|
||||||
|
assert active_components(unit, config.components()) == config.components()
|
||||||
|
|
||||||
|
|
||||||
|
def test_native_session_proof_uses_applied_state_instead_of_request_echo():
|
||||||
|
config = local_config()
|
||||||
|
class Session(BaseModel):
|
||||||
|
model_config = ConfigDict(extra='allow')
|
||||||
|
class Result(BaseModel):
|
||||||
|
session: Session
|
||||||
|
actual = Session(**setup_session(config))
|
||||||
|
service = object()
|
||||||
|
class Handler:
|
||||||
|
_service = service
|
||||||
|
def _state(self, conn): return SimpleNamespace(runtime_config=SimpleNamespace(session=actual))
|
||||||
|
def build_session_updated(self, conn): return Result(session=actual.model_copy())
|
||||||
|
install_session_proof(Handler, {id(service): config.components()}, setup_session(config))
|
||||||
|
adapter = LocalS2SAdapter(Transport(), config=config, settings=RuntimeSettings(_env_file=None))
|
||||||
|
event = Handler().build_session_updated('native-session')
|
||||||
|
assert adapter.acknowledged(event.session.model_dump())
|
||||||
|
actual.model = 'other/model'
|
||||||
|
assert not adapter.acknowledged(Handler().build_session_updated('native-session').session.model_dump())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('kind', ['http', 'websocket'])
|
||||||
|
def test_engine_token_mismatch_refuses_before_native_handler(kind):
|
||||||
|
async def scenario():
|
||||||
|
sent, entered = [], []
|
||||||
|
async def app(scope, receive, send): entered.append(True)
|
||||||
|
async def send(e): sent.append(e)
|
||||||
|
async def receive(): return {}
|
||||||
|
guard = EngineTokenGuard(app, 'private-test-token')
|
||||||
|
await guard({'type': kind, 'headers': []}, receive, send)
|
||||||
|
assert not entered
|
||||||
|
assert sent[0].get('status', sent[0].get('code')) in (401, 1008)
|
||||||
|
await guard({'type': kind, 'headers': [(b'authorization', b'Bearer private-test-token')]}, receive, send)
|
||||||
|
assert entered == [True]
|
||||||
|
asyncio.run(scenario())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('failure', [False, True])
|
||||||
|
def test_loopback_gateway_credentials_pcm_and_detectable_stream_abort(failure):
|
||||||
|
observed = []
|
||||||
|
def upstream(request):
|
||||||
|
observed.append(request)
|
||||||
|
assert request.url == 'https://openrouter.ai/api/v1/audio/speech'
|
||||||
|
assert request.headers['authorization'] == 'Bearer fake-router-key'
|
||||||
|
size = 1440002 if failure else 9600
|
||||||
|
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=bytes(size))
|
||||||
|
server = ComponentServer('fake-router-key', port=0, transport=httpx.MockTransport(upstream))
|
||||||
|
thread = Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
try:
|
||||||
|
url = f'http://127.0.0.1:{server.server_port}/v1/audio/speech'
|
||||||
|
with httpx.Client(timeout=3, trust_env=False) as client:
|
||||||
|
assert client.post(url, content=b'{}').status_code == 403
|
||||||
|
if failure:
|
||||||
|
with pytest.raises(httpx.RemoteProtocolError):
|
||||||
|
client.post(url, content=b'{}', headers={'Authorization': 'Bearer local-components'})
|
||||||
|
else:
|
||||||
|
result = client.post(url, content=b'{}', headers={'Authorization': 'Bearer local-components'})
|
||||||
|
assert result.status_code == 200 and result.content == bytes(9600)
|
||||||
|
assert len(observed) == 1 and server.counts['/v1/audio/speech'] == 1
|
||||||
|
finally:
|
||||||
|
server.shutdown()
|
||||||
|
server.server_close()
|
||||||
|
thread.join(timeout=3)
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
"""Local development adapter, attestation, PCM and bounded component contracts."""
|
||||||
|
import asyncio
|
||||||
|
from copy import deepcopy
|
||||||
|
from io import BytesIO
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from uuid import uuid4
|
||||||
|
import wave
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from app.modules.voice.configuration import VoiceSettings
|
||||||
|
from app.modules.voice.settings import RuntimeSettings
|
||||||
|
from app.modules.voice.local_s2s import effective_identity, require_isolated_candidate
|
||||||
|
from app.infrastructure.local_s2s import LocalS2SAdapter, LocalS2SContextError
|
||||||
|
from app.modules.voice.runtime import VoiceRuntime
|
||||||
|
from app.local_s2s_smoke import stages, stub_response, tone, wav_bytes
|
||||||
|
from tests.unit.test_realtime_phase1 import Transport, runner, until, commands, input_turn, response, delta, done
|
||||||
|
|
||||||
|
|
||||||
|
def local_config(**changes):
|
||||||
|
values = dict(provider='local_s2s', local_s2s_enabled=True, voice_transport_testing=True,
|
||||||
|
local_s2s_stt_model='test/stt', local_s2s_llm_model='test/llm',
|
||||||
|
local_s2s_tts_model='test/tts', local_s2s_tts_voice='fixture')
|
||||||
|
values.update(changes)
|
||||||
|
return VoiceSettings(_env_file=None, **values)
|
||||||
|
|
||||||
|
|
||||||
|
def confirmed(adapter):
|
||||||
|
session = adapter.setup()['session']
|
||||||
|
session['s2s_effective'] = effective_identity(adapter.config.components(), deepcopy(session))
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('changed', [dict(local_s2s_enabled=False), dict(voice_transport_testing=False),
|
||||||
|
dict(local_s2s_stt_model=''), dict(local_s2s_tts_model=''), dict(local_s2s_tts_voice='')])
|
||||||
|
def test_opt_in_and_complete_fixed_profile_required(changed):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
local_config(**changed).require_voice()
|
||||||
|
|
||||||
|
|
||||||
|
def test_profile_has_no_credentials_and_changes_with_effective_components():
|
||||||
|
a = local_config(local_s2s_token='private-fixture')
|
||||||
|
a.require_voice()
|
||||||
|
profile = a.profile()
|
||||||
|
assert 'private-fixture' not in json.dumps(profile)
|
||||||
|
assert profile == local_config(local_s2s_token='rotated-fixture').profile()
|
||||||
|
assert profile != local_config(local_s2s_stt_model='other/stt').profile()
|
||||||
|
assert profile['development_only'] and profile['interruption_policy'] == 'close_until_phase3'
|
||||||
|
assert profile['input_sample_rate'] == profile['output_sample_rate'] == 24000
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('path', ['engine_revision', 'patch_revision', 'contract_revision',
|
||||||
|
'components', 'effective_config_sha256'])
|
||||||
|
def test_setup_echo_or_mismatched_engine_identity_never_ready(path):
|
||||||
|
adapter = LocalS2SAdapter(Transport(), config=local_config(), settings=RuntimeSettings(_env_file=None))
|
||||||
|
assert not adapter.acknowledged(adapter.setup()['session'])
|
||||||
|
session = confirmed(adapter)
|
||||||
|
assert adapter.acknowledged(session)
|
||||||
|
session['s2s_effective'][path] = 'wrong'
|
||||||
|
assert not adapter.acknowledged(session)
|
||||||
|
assert not adapter.acknowledged(dict(confirmed(adapter), model='other/llm'))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('kind', ['response.cancel', 'conversation.item.truncate'])
|
||||||
|
def test_no_fake_history_or_terminal_on_interruption(kind):
|
||||||
|
async def scenario():
|
||||||
|
wire = Transport()
|
||||||
|
adapter = LocalS2SAdapter(wire, config=local_config(), settings=RuntimeSettings(_env_file=None))
|
||||||
|
with pytest.raises(LocalS2SContextError):
|
||||||
|
await adapter.send({'type': kind})
|
||||||
|
assert not wire.sent
|
||||||
|
with pytest.raises(LocalS2SContextError):
|
||||||
|
adapter.confirm_history_repair(None, {})
|
||||||
|
asyncio.run(scenario())
|
||||||
|
|
||||||
|
|
||||||
|
def test_actual_runtime_normal_local_audio_and_close(runner):
|
||||||
|
async def scenario():
|
||||||
|
wire, output = Transport(), []
|
||||||
|
adapter = LocalS2SAdapter(wire, config=local_config(), settings=RuntimeSettings(_env_file=None))
|
||||||
|
async def emit(event): output.append(event)
|
||||||
|
async def authority(execution):
|
||||||
|
return execution.capture(dict(id=execution.user_id, organization_id='fixture', role='user'), 1)
|
||||||
|
runtime = VoiceRuntime(adapter, SimpleNamespace(engine=None), runner, uuid4(), emit, authority_check=authority)
|
||||||
|
try:
|
||||||
|
await runtime.start()
|
||||||
|
await until(lambda: commands(wire, 'session.update'))
|
||||||
|
assert not runtime.ready
|
||||||
|
await runtime.handle(dict(type='session.updated', session=confirmed(adapter)))
|
||||||
|
await until(lambda: runtime.ready)
|
||||||
|
await input_turn(runtime)
|
||||||
|
await response(runtime, wire)
|
||||||
|
await runtime.handle(dict(type='conversation.item.input_audio_transcription.completed', item_id='u1', content_index=0, transcript='hello fixture'))
|
||||||
|
await runtime.handle(delta(960))
|
||||||
|
await runtime.handle(dict(type='response.output_audio_transcript.done', response_id='r1', item_id='a1', output_index=0, content_index=0, transcript='answer fixture'))
|
||||||
|
await runtime.handle(dict(type='response.output_audio.done', response_id='r1', item_id='a1', output_index=0, content_index=0))
|
||||||
|
await done(runtime)
|
||||||
|
await until(lambda: any(isinstance(e, bytes) for e in output))
|
||||||
|
audio = next(iter(runtime.audio.values()))
|
||||||
|
await until(lambda: audio.sent == 960)
|
||||||
|
await runtime.playback_progress(audio.ref, 20)
|
||||||
|
assert runtime.usable and b''.join(e for e in output if isinstance(e, bytes)) == bytes(960)
|
||||||
|
await until(lambda: len([e for e in output if isinstance(e, dict) and e.get('type') == 'transcript']) >= 2)
|
||||||
|
assert {e['role'] for e in output if isinstance(e, dict) and e.get('type') == 'transcript'} == {'user', 'assistant'}
|
||||||
|
assert not commands(wire, 'conversation.item.truncate')
|
||||||
|
finally:
|
||||||
|
await runtime.close()
|
||||||
|
assert wire.closed
|
||||||
|
asyncio.run(scenario())
|
||||||
|
|
||||||
|
|
||||||
|
def test_factory_selects_local_only(monkeypatch):
|
||||||
|
import app.infrastructure.local_s2s as local
|
||||||
|
from app.infrastructure.voice_provider import create_adapter
|
||||||
|
wire = Transport()
|
||||||
|
async def connect(config, limits): return wire
|
||||||
|
monkeypatch.setattr(local, 'connect_local', connect)
|
||||||
|
async def scenario():
|
||||||
|
adapter = await create_adapter(local_config(), RuntimeSettings(_env_file=None))
|
||||||
|
assert isinstance(adapter, LocalS2SAdapter)
|
||||||
|
await adapter.close()
|
||||||
|
asyncio.run(scenario())
|
||||||
|
|
||||||
|
|
||||||
|
def test_isolation_precedes_startup_reconciliation(settings):
|
||||||
|
config = local_config()
|
||||||
|
with pytest.raises(ValueError, match='isolated'):
|
||||||
|
require_isolated_candidate(config, settings)
|
||||||
|
candidate = settings.model_copy(update={'database_url': __import__('pydantic').SecretStr('postgresql+psycopg://unused/app_local_s2s_test')})
|
||||||
|
with pytest.raises(ValueError, match='storage'):
|
||||||
|
require_isolated_candidate(config, candidate)
|
||||||
|
candidate = candidate.model_copy(update={'original_directory': Path('data/local-s2s-test/originals'),
|
||||||
|
'extraction_directory': Path('data/local-s2s-test/extractions')})
|
||||||
|
require_isolated_candidate(config, candidate)
|
||||||
|
# An edited environment cannot relabel the API's already-open operational DB.
|
||||||
|
with pytest.raises(ValueError, match='isolated'):
|
||||||
|
require_isolated_candidate(config, candidate, database_url='postgresql+psycopg://unused/operational')
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('mode', ['multipart', 'json'])
|
||||||
|
def test_stub_stages_forward_credentials_and_use_persian_pcm_contract(mode):
|
||||||
|
seen = []
|
||||||
|
def remote(request):
|
||||||
|
seen.append(request)
|
||||||
|
assert request.headers['authorization'] == 'Bearer fixture-secret'
|
||||||
|
return stub_response(request)
|
||||||
|
async def scenario():
|
||||||
|
async with httpx.AsyncClient(transport=httpx.MockTransport(remote)) as client:
|
||||||
|
pcm = await stages(local_config(), tone(), client, 'fixture-secret', stt_format=mode)
|
||||||
|
assert pcm == tone() and len(seen) == 3
|
||||||
|
with wave.open(BytesIO(wav_bytes(pcm)), 'rb') as audio:
|
||||||
|
assert (audio.getframerate(), audio.getnchannels(), audio.getsampwidth()) == (24000, 1, 2)
|
||||||
|
if mode == 'json':
|
||||||
|
assert json.loads(seen[0].content)['language'] == 'fa'
|
||||||
|
else:
|
||||||
|
assert b'name="file"' in seen[0].content and b'test/stt' in seen[0].content
|
||||||
|
assert json.loads(seen[1].content)['max_tokens'] == 128
|
||||||
|
assert json.loads(seen[2].content)['response_format'] == 'pcm'
|
||||||
|
asyncio.run(scenario())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('failure', ['http', 'odd-audio', 'oversize', 'unfinished-llm', 'json-error-audio'])
|
||||||
|
def test_stage_failures_are_bounded_and_never_become_success(failure):
|
||||||
|
def remote(request):
|
||||||
|
if failure == 'http': return httpx.Response(401, text='PRIVATE_KEY_PROVIDER_TEXT')
|
||||||
|
if request.url.path.endswith('/chat/completions') and failure == 'unfinished-llm':
|
||||||
|
return httpx.Response(200, json={'choices': [{'finish_reason': 'length'}]})
|
||||||
|
if request.url.path.endswith('/audio/speech'):
|
||||||
|
if failure == 'odd-audio': return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=b'x')
|
||||||
|
if failure == 'oversize': return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=bytes(480002))
|
||||||
|
if failure == 'json-error-audio': return httpx.Response(200, json={'error': 'private'})
|
||||||
|
return stub_response(request)
|
||||||
|
async def scenario():
|
||||||
|
async with httpx.AsyncClient(transport=httpx.MockTransport(remote)) as client:
|
||||||
|
with pytest.raises(ValueError, match='LOCAL_STAGE_'):
|
||||||
|
await stages(local_config(), tone(), client, 'fixture-secret')
|
||||||
|
asyncio.run(scenario())
|
||||||
@@ -0,0 +1,590 @@
|
|||||||
|
"""Regression evidence for five repairs: real pinned methods and owned loopback I/O."""
|
||||||
|
import asyncio
|
||||||
|
from contextlib import contextmanager
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
import signal
|
||||||
|
import socket
|
||||||
|
import socketserver
|
||||||
|
from threading import Event, Lock, Thread, Timer, current_thread, BoundedSemaphore
|
||||||
|
import time
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from services.local_s2s.request_policy import LimitedChatClient, install_client_policy
|
||||||
|
from services.local_s2s.components import ComponentServer, CLEANUP_WINDOW_SECONDS
|
||||||
|
from services.local_s2s.assets import REQUIRED_NLTK, REQUIRED_VAD, AssetError, validate_assets, configure_nltk, patch_pipeline_source
|
||||||
|
from services.local_s2s.lifecycle import cleanup, run_owned
|
||||||
|
from tests.support.local_s2s_pinned import functions, tree, constant, ROOT
|
||||||
|
from tests.unit.test_local_s2s_phase2 import local_config
|
||||||
|
|
||||||
|
|
||||||
|
class RecordingSDK:
|
||||||
|
"""SDK boundary stand-in; pinned request/setup/process/warmup methods run unchanged."""
|
||||||
|
def __init__(self, calls, *, max_retries=0, failure=None, **kwargs):
|
||||||
|
self.calls, self.max_retries, self.failure = calls, max_retries, failure
|
||||||
|
self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))
|
||||||
|
def with_options(self, **kwargs):
|
||||||
|
return RecordingSDK(self.calls, max_retries=kwargs.get('max_retries', self.max_retries), failure=self.failure)
|
||||||
|
def create(self, **kwargs):
|
||||||
|
payload = {key: value for key, value in kwargs.items() if key != 'timeout'}
|
||||||
|
def send(request):
|
||||||
|
self.calls.append(json.loads(request.content))
|
||||||
|
if self.failure:
|
||||||
|
raise self.failure
|
||||||
|
return httpx.Response(200, json={})
|
||||||
|
for attempt in range(self.max_retries + 1):
|
||||||
|
try:
|
||||||
|
with httpx.Client(transport=httpx.MockTransport(send), trust_env=False) as transport:
|
||||||
|
transport.post('https://fixture.invalid/v1/chat/completions', json=payload)
|
||||||
|
return payload
|
||||||
|
except httpx.HTTPError:
|
||||||
|
if attempt == self.max_retries:
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def upstream_handler(client):
|
||||||
|
ns = dict(time=time, logger=logging.getLogger('pinned-fixture'), WARMUP_MAX_RETRIES=constant('base.py.source', 'WARMUP_MAX_RETRIES'),
|
||||||
|
_build_chat_optional_kwargs=lambda *_: {})
|
||||||
|
functions('chat.py.source', [(None, '_request_chat_completions'),
|
||||||
|
('ChatCompletionsApiModelHandler', '_request'), ('ChatCompletionsApiModelHandler', 'warmup'),
|
||||||
|
('ChatCompletionsApiModelHandler', '_build_optional_kwargs')], ns)
|
||||||
|
functions('base.py.source', [('BaseOpenAICompatibleHandler', 'process'), ('BaseOpenAICompatibleHandler', 'setup')], ns)
|
||||||
|
ns.update(os=__import__('os'), httpx=httpx, BoundedSemaphore=BoundedSemaphore,
|
||||||
|
Lock=Lock, PREFETCH_PROVIDER_WORKER_LIMIT=2)
|
||||||
|
ns.update(is_out_of_band=lambda _: False, resolve_auto_language=lambda x: (x, None),
|
||||||
|
language_name_for_prompt=lambda *a, **k: None, response_wants_audio=lambda _: True,
|
||||||
|
_Turn=lambda **kw: SimpleNamespace(**kw))
|
||||||
|
Handler = type('PinnedHandler', (), {name: ns[name] for name in ('_request', 'warmup', '_build_optional_kwargs', 'process', 'setup')})
|
||||||
|
handler = Handler()
|
||||||
|
handler.client, handler.model_name, handler.stream = client, 'test/llm', False
|
||||||
|
handler._extra_body, handler.request_timeout, handler.cancel_scope = {}, 1, None
|
||||||
|
handler.enable_lang_prompt = False
|
||||||
|
handler._turn_is_latest = lambda *_: True
|
||||||
|
handler._apply_config = lambda *a, **kw: None
|
||||||
|
# Only serialization/history output is isolated; process calls the pinned _request.
|
||||||
|
handler._generate = lambda chat, original, turn, kw: iter([handler._request(chat.messages, kw)])
|
||||||
|
return handler
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('limit', [17, 83])
|
||||||
|
def test_pinned_normal_stt_turn_and_warmup_emit_actual_nondefault_token_limit(limit):
|
||||||
|
calls = []
|
||||||
|
client = LimitedChatClient(RecordingSDK(calls), limit)
|
||||||
|
handler = upstream_handler(client)
|
||||||
|
chat = SimpleNamespace(messages=[{'role': 'user', 'content': 'transcribed fixture'}], buffer=[],
|
||||||
|
copy=lambda **kw: chat, history_anchor_id=lambda: None, has_pending_tool_calls=lambda: False)
|
||||||
|
request = SimpleNamespace(audio=None, response=None, turn_id='turn', turn_revision=1,
|
||||||
|
speech_stopped_at_s=0, runtime_config=SimpleNamespace(chat=chat,
|
||||||
|
session=SimpleNamespace(instructions='fixture', tools=None, tool_choice=None)),
|
||||||
|
language_code='fa', selected_language='fa', response_key='r', prefetch_transaction=None)
|
||||||
|
list(handler.process(request))
|
||||||
|
handler.warmup()
|
||||||
|
assert len(calls) == 2
|
||||||
|
assert [c['max_tokens'] for c in calls] == [limit, limit]
|
||||||
|
assert calls[0]['messages'][0]['content'] == 'transcribed fixture'
|
||||||
|
assert calls[1]['messages'][-1]['content'] == 'Hello'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('failure', [httpx.ConnectError('fixture connection failure'),
|
||||||
|
httpx.HTTPStatusError('fixture retryable 503', request=httpx.Request('POST', 'https://fixture.invalid'), response=httpx.Response(503))])
|
||||||
|
def test_pinned_warmup_cannot_restore_retries(failure):
|
||||||
|
calls = []
|
||||||
|
handler = upstream_handler(LimitedChatClient(RecordingSDK(calls, failure=failure), 29))
|
||||||
|
with pytest.raises(type(failure)):
|
||||||
|
handler.warmup()
|
||||||
|
assert len(calls) == 1 and calls[0]['max_tokens'] == 29
|
||||||
|
|
||||||
|
|
||||||
|
def asset_bundle(tmp_path):
|
||||||
|
roots = {'nltk': tmp_path / 'nltk', 'vad': tmp_path / 'vad'}
|
||||||
|
files = {}
|
||||||
|
for kind, paths in [('nltk', REQUIRED_NLTK), ('vad', REQUIRED_VAD)]:
|
||||||
|
for name in paths:
|
||||||
|
path = roots[kind] / name
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_bytes(b'controlled asset fixture')
|
||||||
|
files[kind + '/' + name] = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||||
|
manifest = tmp_path / 'assets.json'
|
||||||
|
manifest.write_text(json.dumps(dict(schema=1, files=files)))
|
||||||
|
return roots, manifest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('fault', ['missing', 'changed', 'extra', 'valid'])
|
||||||
|
def test_required_assets_are_complete_and_fingerprinted_before_any_probe(tmp_path, fault):
|
||||||
|
roots, manifest = asset_bundle(tmp_path)
|
||||||
|
path = roots['nltk'] / REQUIRED_NLTK[0]
|
||||||
|
if fault == 'missing': path.unlink()
|
||||||
|
if fault == 'changed': path.write_bytes(b'changed')
|
||||||
|
if fault == 'extra': (roots['vad'] / 'untracked').write_bytes(b'x')
|
||||||
|
if fault == 'valid':
|
||||||
|
assert validate_assets(roots['nltk'], roots['vad'], manifest) == hashlib.sha256(manifest.read_bytes()).hexdigest()
|
||||||
|
else:
|
||||||
|
with pytest.raises(AssetError): validate_assets(roots['nltk'], roots['vad'], manifest)
|
||||||
|
|
||||||
|
|
||||||
|
def test_pinned_import_has_no_runtime_nltk_download_and_keeps_tokenization(tmp_path):
|
||||||
|
calls = []
|
||||||
|
nltk = SimpleNamespace(data=SimpleNamespace(path=[], find=lambda p: p),
|
||||||
|
sent_tokenize=lambda text: calls.append('sent') or [text],
|
||||||
|
pos_tag=lambda words, **kw: calls.append('pos') or [(words[0], 'NN')],
|
||||||
|
download=lambda *a: pytest.fail('download invoked'))
|
||||||
|
configure_nltk(nltk, tmp_path)
|
||||||
|
source = (ROOT / 'pipeline.py.source').read_text()
|
||||||
|
patched = patch_pipeline_source(source)
|
||||||
|
assert 'nltk.download(' not in patched
|
||||||
|
# Execute the exact import-time patched preflight, not a replacement tokenizer.
|
||||||
|
start, end = patched.index('from services.local_s2s.assets'), patched.index('# caching allows')
|
||||||
|
exec(patched[start:end], {'nltk': nltk})
|
||||||
|
assert calls == ['sent', 'pos', 'sent', 'pos']
|
||||||
|
with pytest.raises(AssetError): nltk.download('anything')
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_assets_main_fails_safely_before_provider_imports(monkeypatch, tmp_path, capsys):
|
||||||
|
from services.local_s2s import engine
|
||||||
|
import sys
|
||||||
|
monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
|
||||||
|
monkeypatch.setenv('LOCAL_S2S_ALLOW_PAID_STARTUP', 'true')
|
||||||
|
monkeypatch.setenv('LOCAL_S2S_NLTK_DATA', str(tmp_path / 'missing'))
|
||||||
|
monkeypatch.setattr('app.modules.voice.configuration.VoiceSettings', lambda **kw: local_config())
|
||||||
|
monkeypatch.setattr(engine, 'build_runtime', lambda *a: pytest.fail('provider construction reached'))
|
||||||
|
assert engine.main() == 1
|
||||||
|
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def gateway(handler=None, *, timeout=.2, inactivity=.1, transport=None):
|
||||||
|
server = ComponentServer('fixture-key', port=0, transport=transport or httpx.MockTransport(handler or (lambda r: httpx.Response(503))),
|
||||||
|
timeout=timeout, inactivity=inactivity)
|
||||||
|
thread = Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
assert server.ready.wait(2)
|
||||||
|
try: yield server
|
||||||
|
finally:
|
||||||
|
server.shutdown(); server.server_close(); thread.join(2)
|
||||||
|
assert not thread.is_alive()
|
||||||
|
|
||||||
|
|
||||||
|
def wait_released(server, count=1):
|
||||||
|
deadline = time.monotonic() + 2
|
||||||
|
while server.counts['released'] < count and time.monotonic() < deadline: time.sleep(.005)
|
||||||
|
assert server.counts['released'] >= count and not server.requests
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('partial', [b'', b'POST /v1/audio/speech HTTP/1.1\r\nContent-',
|
||||||
|
b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 100\r\n\r\nx'])
|
||||||
|
def test_silent_partial_headers_and_stalled_body_release_slots(partial):
|
||||||
|
with gateway() as server:
|
||||||
|
with socket.create_connection(('127.0.0.1', server.server_port), timeout=2) as client:
|
||||||
|
if partial: client.sendall(partial)
|
||||||
|
assert client.recv(4096) == b''
|
||||||
|
wait_released(server)
|
||||||
|
assert server.counts['expired'] == 1 and sum(server.counts[p] for p in ('/v1/audio/speech','/v1/chat/completions')) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_slow_upstream_headers_cancel_transport_and_release_slot():
|
||||||
|
cancelled = Event()
|
||||||
|
async def remote(request):
|
||||||
|
try: await asyncio.sleep(10)
|
||||||
|
finally: cancelled.set()
|
||||||
|
with gateway(remote) as server:
|
||||||
|
with httpx.Client(timeout=2, trust_env=False) as client:
|
||||||
|
with pytest.raises(httpx.RemoteProtocolError):
|
||||||
|
client.post(f'http://127.0.0.1:{server.server_port}/v1/audio/speech', content=b'{}', headers={'Authorization':'Bearer local-components'})
|
||||||
|
wait_released(server)
|
||||||
|
assert cancelled.is_set() and server.counts['/v1/audio/speech'] == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('path,media', [('/v1/audio/speech','audio/pcm'),('/v1/chat/completions','text/event-stream')])
|
||||||
|
def test_sub8192_trickle_is_forwarded_but_total_deadline_leaves_incomplete_stream(path, media):
|
||||||
|
closed = Event()
|
||||||
|
class Stream(httpx.AsyncByteStream):
|
||||||
|
async def __aiter__(self):
|
||||||
|
while True:
|
||||||
|
yield b'x'
|
||||||
|
await asyncio.sleep(.02)
|
||||||
|
async def aclose(self): closed.set()
|
||||||
|
def remote(request): return httpx.Response(200, headers={'content-type':media}, stream=Stream())
|
||||||
|
with gateway(remote, timeout=.2, inactivity=.1) as server:
|
||||||
|
began = time.monotonic()
|
||||||
|
with httpx.Client(timeout=2, trust_env=False) as client:
|
||||||
|
with client.stream('POST',f'http://127.0.0.1:{server.server_port}'+path,content=b'{}',headers={'Authorization':'Bearer local-components'}) as result:
|
||||||
|
iterator=result.iter_raw()
|
||||||
|
assert next(iterator) == b'x'
|
||||||
|
assert time.monotonic()-began < .18
|
||||||
|
with pytest.raises(httpx.RemoteProtocolError): list(iterator)
|
||||||
|
wait_released(server)
|
||||||
|
assert closed.is_set() and server.counts['expired'] == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_blocked_downstream_drain_is_bounded_and_transports_close():
|
||||||
|
async def scenario():
|
||||||
|
with gateway(lambda r:httpx.Response(200,headers={'content-type':'audio/pcm'},content=b'xx')) as server:
|
||||||
|
reader = asyncio.StreamReader()
|
||||||
|
reader.feed_data(b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 2\r\nAuthorization: Bearer local-components\r\n\r\n{}')
|
||||||
|
class Writer:
|
||||||
|
closed=False
|
||||||
|
def write(self,data): pass
|
||||||
|
drains=0
|
||||||
|
async def drain(self):
|
||||||
|
self.drains+=1
|
||||||
|
if self.drains>1: await asyncio.Event().wait()
|
||||||
|
def close(self): self.closed=True
|
||||||
|
async def wait_closed(self): pass
|
||||||
|
writer=Writer()
|
||||||
|
start=time.monotonic()
|
||||||
|
await server._serve(reader,writer,asyncio.get_running_loop().time()+.1)
|
||||||
|
assert writer.closed and time.monotonic()-start<.5 and writer.drains==2
|
||||||
|
asyncio.run(scenario())
|
||||||
|
|
||||||
|
|
||||||
|
def test_pinned_stop_exception_does_not_skip_gateway_cleanup():
|
||||||
|
ns=dict(monotonic=time.monotonic,current_thread=current_thread,_JOIN_TIMEOUT_S=.01,logger=logging.getLogger('pinned'),ConfiguredRuntimeError=RuntimeError,_cleanup=lambda _:None)
|
||||||
|
functions('lifecycle.py.source',[('ConfiguredRuntime','stop')],ns)
|
||||||
|
class Survivor:
|
||||||
|
def join(self,timeout): pass
|
||||||
|
def is_alive(self): return True
|
||||||
|
runtime=SimpleNamespace(_lock=Lock(),state='running',_signal_stop=lambda:None,_threads=[Survivor()],_monitor=None)
|
||||||
|
runtime.stop=lambda:ns['stop'](runtime)
|
||||||
|
logs=[]
|
||||||
|
with gateway() as guard:
|
||||||
|
thread=SimpleNamespace(join=lambda timeout:None,is_alive=lambda:False)
|
||||||
|
assert cleanup(runtime,guard,thread,Event(),timeout=.2,emit=lambda value,**kw:logs.append(json.loads(value)))
|
||||||
|
assert logs[-1]['cleanup']['runtime_stop']==1
|
||||||
|
assert logs[-1]['cleanup']['gateway_shutdown']==0
|
||||||
|
assert guard.done.is_set()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('sig',[signal.SIGINT,signal.SIGTERM])
|
||||||
|
def test_termination_during_inflight_restores_handlers_and_emits_final_counters(monkeypatch,sig):
|
||||||
|
import services.local_s2s.lifecycle as lifecycle
|
||||||
|
captured,logs=[],[]
|
||||||
|
previous={s:signal.getsignal(s) for s in (signal.SIGINT,signal.SIGTERM)}
|
||||||
|
entered=Event()
|
||||||
|
async def remote(request):
|
||||||
|
entered.set()
|
||||||
|
await asyncio.sleep(10)
|
||||||
|
def start(key,timeout):
|
||||||
|
guard=ComponentServer(key,port=0,transport=httpx.MockTransport(remote),timeout=1)
|
||||||
|
thread=Thread(target=guard.serve_forever,daemon=True);thread.start();assert guard.ready.wait(2)
|
||||||
|
captured.extend([guard,thread]);return guard,thread
|
||||||
|
monkeypatch.setattr(lifecycle,'start_components',start)
|
||||||
|
def build(stop):
|
||||||
|
class Runtime:
|
||||||
|
def start(self):
|
||||||
|
def request():
|
||||||
|
try:
|
||||||
|
with httpx.Client(timeout=2,trust_env=False) as client:
|
||||||
|
client.post(f'http://127.0.0.1:{captured[0].server_port}/v1/audio/speech',content=b'{}',headers={'Authorization':'Bearer local-components'})
|
||||||
|
except httpx.HTTPError: pass
|
||||||
|
Thread(target=request,daemon=True).start()
|
||||||
|
def wait(self): stop.wait()
|
||||||
|
def stop(self): raise RuntimeError('controlled stop failure')
|
||||||
|
def terminate():
|
||||||
|
assert entered.wait(2)
|
||||||
|
signal.getsignal(sig)(sig,None) # installed handler dispatch; portable on Windows
|
||||||
|
Thread(target=terminate,daemon=True).start()
|
||||||
|
return Runtime()
|
||||||
|
assert lifecycle.run_owned(build,'fixture-key',1,emit=lambda value,**kw:logs.append(json.loads(value)))==1
|
||||||
|
assert not captured[1].is_alive() and not captured[0].requests
|
||||||
|
assert logs[-1]['stage']=='close' and logs[-1]['request_counts']['released']==1
|
||||||
|
assert all(signal.getsignal(s)==handler for s,handler in previous.items())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('limit', [19, 71])
|
||||||
|
def test_real_pinned_setup_warmup_is_already_capped_before_constructor_returns(limit):
|
||||||
|
calls=[]
|
||||||
|
handler=upstream_handler(None)
|
||||||
|
ns=handler.setup.__func__.__globals__
|
||||||
|
module=SimpleNamespace(OpenAI=lambda **kw: RecordingSDK(calls, **kw),
|
||||||
|
BaseOpenAICompatibleHandler=type('Base', (), {'setup': handler.setup.__func__}))
|
||||||
|
install_client_policy(module, local_config(local_s2s_max_output_tokens=limit,local_s2s_request_timeout_seconds=9))
|
||||||
|
handler.setup=module.BaseOpenAICompatibleHandler.setup.__get__(handler)
|
||||||
|
ns['OpenAI']=module.OpenAI
|
||||||
|
handler._build_extra_body=lambda *a: {}
|
||||||
|
handler.setup(model_name='test/llm', api_key='fixture', base_url='http://127.0.0.1/v1', compact_history=False)
|
||||||
|
assert len(calls)==1 and calls[0]['max_tokens']==limit
|
||||||
|
assert handler.client.token_limit==limit and handler.gen_kwargs=={}
|
||||||
|
assert handler.request_timeout_s==9 and handler.request_timeout.read==9
|
||||||
|
|
||||||
|
|
||||||
|
def test_hung_construction_and_hung_stop_are_bounded_and_gateway_always_closes(monkeypatch):
|
||||||
|
import services.local_s2s.lifecycle as lifecycle
|
||||||
|
captured,logs=[],[]
|
||||||
|
def start(key,timeout):
|
||||||
|
server=ComponentServer(key,port=0,timeout=.2)
|
||||||
|
thread=Thread(target=server.serve_forever,daemon=True);thread.start();assert server.ready.wait(1)
|
||||||
|
captured.extend([server,thread]);return server,thread
|
||||||
|
monkeypatch.setattr(lifecycle,'start_components',start)
|
||||||
|
latch=Event()
|
||||||
|
began=time.monotonic()
|
||||||
|
assert lifecycle.run_owned(lambda stop:latch.wait(10),'fixture',.2,startup_timeout=.05,cleanup_timeout=.2,
|
||||||
|
emit=lambda value,**kw:logs.append(json.loads(value)))==1
|
||||||
|
assert time.monotonic()-began<1 and not captured[1].is_alive()
|
||||||
|
assert logs[-1]['stage']=='close'
|
||||||
|
latch.set()
|
||||||
|
with gateway() as server:
|
||||||
|
runtime=SimpleNamespace(stop=lambda:Event().wait(10))
|
||||||
|
logs=[]
|
||||||
|
assert cleanup(runtime,server,SimpleNamespace(join=lambda timeout:None,is_alive=lambda:False),Event(),timeout=.05,
|
||||||
|
emit=lambda value,**kw:logs.append(json.loads(value)))
|
||||||
|
assert logs[-1]['cleanup']['runtime_stop']==2 and server.done.is_set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_downstream_disconnect_closes_upstream_and_releases_slot():
|
||||||
|
closed=Event()
|
||||||
|
class Stream(httpx.AsyncByteStream):
|
||||||
|
async def __aiter__(self):
|
||||||
|
while True:
|
||||||
|
yield b'a'*256
|
||||||
|
await asyncio.sleep(.01)
|
||||||
|
async def aclose(self): closed.set()
|
||||||
|
with gateway(lambda r:httpx.Response(200,headers={'content-type':'audio/pcm'},stream=Stream()),timeout=.4,inactivity=.2) as server:
|
||||||
|
with httpx.Client(timeout=1,trust_env=False) as client:
|
||||||
|
with client.stream('POST',f'http://127.0.0.1:{server.server_port}/v1/audio/speech',content=b'{}',headers={'Authorization':'Bearer local-components'}) as result:
|
||||||
|
assert next(result.iter_raw())
|
||||||
|
wait_released(server)
|
||||||
|
assert closed.is_set()
|
||||||
|
|
||||||
|
|
||||||
|
def test_concurrency_slots_include_silent_connections_and_recover_after_expiry():
|
||||||
|
with gateway(timeout=.3,inactivity=.15) as server:
|
||||||
|
peers=[socket.create_connection(('127.0.0.1',server.server_port),timeout=1) for _ in range(4)]
|
||||||
|
try:
|
||||||
|
deadline=time.monotonic()+1
|
||||||
|
while server.counts['rejected']<1 and time.monotonic()<deadline: time.sleep(.005)
|
||||||
|
assert server.counts['rejected']==1 and server.counts['accepted']==3
|
||||||
|
wait_released(server,3)
|
||||||
|
finally:
|
||||||
|
for peer in peers: peer.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_asset_provisioning_is_local_only_and_emits_reviewable_fingerprint(tmp_path,monkeypatch,capsys):
|
||||||
|
import services.local_s2s.assets as assets
|
||||||
|
import sys
|
||||||
|
roots,_=asset_bundle(tmp_path)
|
||||||
|
output=tmp_path/'new-assets.json'
|
||||||
|
monkeypatch.setattr(sys,'argv',['assets','--nltk-root',str(roots['nltk']),'--vad-root',str(roots['vad']),'--output',str(output)])
|
||||||
|
assert assets.main()==0
|
||||||
|
record=json.loads(capsys.readouterr().out)
|
||||||
|
assert record['manifest_sha256']==validate_assets(roots['nltk'],roots['vad'],output)
|
||||||
|
assert record['files']==len(REQUIRED_NLTK)+len(REQUIRED_VAD)
|
||||||
|
|
||||||
|
|
||||||
|
def test_trickled_request_body_still_expires_on_total_deadline():
|
||||||
|
with gateway(timeout=.2,inactivity=.1) as server:
|
||||||
|
with socket.create_connection(('127.0.0.1',server.server_port),timeout=1) as client:
|
||||||
|
client.sendall(b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 100\r\n\r\n')
|
||||||
|
began=time.monotonic()
|
||||||
|
for _ in range(20):
|
||||||
|
try: client.sendall(b'x')
|
||||||
|
except OSError: break
|
||||||
|
time.sleep(.02)
|
||||||
|
try:
|
||||||
|
closed=client.recv(1024)==b''
|
||||||
|
except (ConnectionResetError, ConnectionAbortedError):
|
||||||
|
closed=True # Windows resets a timed-out socket with unread body bytes.
|
||||||
|
assert closed
|
||||||
|
assert time.monotonic()-began<.7
|
||||||
|
wait_released(server)
|
||||||
|
assert server.counts['expired']==1 and server.counts['/v1/audio/speech']==0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('invalid', [[], {'schema': 1, 'files': []}, {'schema': 1, 'files': None}])
|
||||||
|
def test_malformed_asset_manifest_has_safe_category(tmp_path, invalid):
|
||||||
|
roots, manifest = asset_bundle(tmp_path)
|
||||||
|
manifest.write_text(json.dumps(invalid))
|
||||||
|
with pytest.raises(AssetError, match='^LOCAL_ENGINE_ASSET_VALIDATION_FAILED$'):
|
||||||
|
validate_assets(roots['nltk'], roots['vad'], manifest)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unusable_tokenizer_with_downloads_blocked_fails_before_provider_calls(tmp_path, monkeypatch, capsys):
|
||||||
|
from services.local_s2s import engine
|
||||||
|
import sys
|
||||||
|
roots, manifest = asset_bundle(tmp_path)
|
||||||
|
nltk = SimpleNamespace(data=SimpleNamespace(path=[], find=lambda p: p),
|
||||||
|
download=lambda *a: pytest.fail('runtime download reached'),
|
||||||
|
pos_tag=lambda *a, **kw: [])
|
||||||
|
# A tokenizer trying to obtain a missing asset must hit the installed blocker.
|
||||||
|
nltk.sent_tokenize = lambda text: nltk.download('punkt_tab')
|
||||||
|
monkeypatch.setitem(sys.modules, 'nltk', nltk)
|
||||||
|
monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
|
||||||
|
for name, value in {'LOCAL_S2S_ALLOW_PAID_STARTUP': 'true',
|
||||||
|
'LOCAL_S2S_NLTK_DATA': str(roots['nltk']), 'LOCAL_S2S_SILERO_SOURCE': str(roots['vad']),
|
||||||
|
'LOCAL_S2S_ASSET_MANIFEST': str(manifest),
|
||||||
|
'LOCAL_S2S_ASSET_MANIFEST_SHA256': hashlib.sha256(manifest.read_bytes()).hexdigest()}.items():
|
||||||
|
monkeypatch.setenv(name, value)
|
||||||
|
monkeypatch.setattr('app.modules.voice.configuration.VoiceSettings', lambda **kw: local_config())
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(engine, 'build_runtime', lambda *a: calls.append('provider'))
|
||||||
|
assert engine.main() == 1 and calls == []
|
||||||
|
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def loopback_upstream(*, headers=False, hang_close=False):
|
||||||
|
"""Real local TCP upstream: cancellation must close its actual HTTP socket."""
|
||||||
|
entered, closed, transport_closed = Event(), Event(), Event()
|
||||||
|
class Handler(socketserver.BaseRequestHandler):
|
||||||
|
def handle(self):
|
||||||
|
self.request.settimeout(6)
|
||||||
|
try:
|
||||||
|
data = b''
|
||||||
|
while b'\r\n\r\n' not in data:
|
||||||
|
data += self.request.recv(4096)
|
||||||
|
head, body = data.split(b'\r\n\r\n', 1)
|
||||||
|
size = int(next(line.split(b':', 1)[1] for line in head.split(b'\r\n') if line.lower().startswith(b'content-length:')))
|
||||||
|
while len(body) < size:
|
||||||
|
body += self.request.recv(size - len(body))
|
||||||
|
if headers:
|
||||||
|
self.request.sendall(b'HTTP/1.1 200 OK\r\nContent-Type: audio/pcm\r\nTransfer-Encoding: chunked\r\n\r\n')
|
||||||
|
entered.set()
|
||||||
|
# No data is produced. Only owned cancellation closes this socket.
|
||||||
|
assert self.request.recv(1) == b''
|
||||||
|
except ConnectionResetError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
closed.set()
|
||||||
|
class Server(socketserver.ThreadingTCPServer):
|
||||||
|
daemon_threads = True
|
||||||
|
remote = Server(('127.0.0.1', 0), Handler)
|
||||||
|
thread = Thread(target=remote.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
|
||||||
|
thread.start()
|
||||||
|
class Transport(httpx.AsyncHTTPTransport):
|
||||||
|
async def handle_async_request(self, request):
|
||||||
|
request.url = httpx.URL(f'http://127.0.0.1:{remote.server_address[1]}' + request.url.path)
|
||||||
|
return await super().handle_async_request(request)
|
||||||
|
async def aclose(self):
|
||||||
|
await super().aclose()
|
||||||
|
transport_closed.set()
|
||||||
|
if hang_close:
|
||||||
|
await asyncio.Event().wait()
|
||||||
|
try:
|
||||||
|
yield Transport(retries=0), entered, closed, transport_closed
|
||||||
|
finally:
|
||||||
|
remote.shutdown(); remote.server_close(); thread.join(1)
|
||||||
|
|
||||||
|
|
||||||
|
def speech_request(extra=b''):
|
||||||
|
return (b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 2\r\n'
|
||||||
|
b'Authorization: Bearer local-components\r\n' + extra + b'\r\n{}')
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('headers', [False, True], ids=['before-upstream-headers', 'stalled-after-headers'])
|
||||||
|
def test_disconnect_cancels_silent_real_upstream_and_releases_slot(headers):
|
||||||
|
with loopback_upstream(headers=headers) as (transport, entered, closed, transport_closed):
|
||||||
|
with gateway(transport=transport, timeout=5, inactivity=4) as server:
|
||||||
|
peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
|
||||||
|
try:
|
||||||
|
peer.sendall(speech_request())
|
||||||
|
assert entered.wait(1)
|
||||||
|
if headers:
|
||||||
|
received = b''
|
||||||
|
while b'\r\n\r\n' not in received:
|
||||||
|
received += peer.recv(4096)
|
||||||
|
assert received.startswith(b'HTTP/1.1 200')
|
||||||
|
assert not received.endswith(b'0\r\n\r\n')
|
||||||
|
began = time.monotonic()
|
||||||
|
finally:
|
||||||
|
peer.close()
|
||||||
|
assert closed.wait(CLEANUP_WINDOW_SECONDS + .4)
|
||||||
|
assert transport_closed.wait(.4)
|
||||||
|
wait_released(server)
|
||||||
|
assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
|
||||||
|
assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
|
||||||
|
assert server.counts['accepted'] == server.counts['released'] == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('half_close', [False, True], ids=['normal', 'declared-receive-only-half-close'])
|
||||||
|
def test_success_and_declared_half_close_receive_complete_response(half_close):
|
||||||
|
entered = Event()
|
||||||
|
async def remote(request):
|
||||||
|
entered.set()
|
||||||
|
await asyncio.sleep(.08) # receive-side EOF precedes upstream headers
|
||||||
|
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=b'xx')
|
||||||
|
with gateway(remote, timeout=2, inactivity=1) as server:
|
||||||
|
with socket.create_connection(('127.0.0.1', server.server_port), timeout=1) as peer:
|
||||||
|
peer.sendall(speech_request(b'X-Local-S2S-Half-Close: receive-response\r\n' if half_close else b''))
|
||||||
|
if half_close:
|
||||||
|
peer.shutdown(socket.SHUT_WR)
|
||||||
|
received = b''
|
||||||
|
while part := peer.recv(4096):
|
||||||
|
received += part
|
||||||
|
assert entered.is_set()
|
||||||
|
assert received.startswith(b'HTTP/1.1 200')
|
||||||
|
assert received.endswith(b'2\r\nxx\r\n0\r\n\r\n')
|
||||||
|
wait_released(server)
|
||||||
|
assert server.counts['disconnected'] == server.counts['expired'] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_undeclared_half_close_is_explicit_cancellation_even_if_peer_can_receive():
|
||||||
|
with loopback_upstream() as (transport, entered, closed, transport_closed):
|
||||||
|
with gateway(transport=transport, timeout=5, inactivity=4) as server:
|
||||||
|
with socket.create_connection(('127.0.0.1', server.server_port), timeout=2) as peer:
|
||||||
|
peer.sendall(speech_request())
|
||||||
|
assert entered.wait(1)
|
||||||
|
peer.shutdown(socket.SHUT_WR)
|
||||||
|
assert peer.recv(4096) == b'' # policy cancellation, not inferred inability to receive
|
||||||
|
assert closed.wait(1) and transport_closed.wait(1)
|
||||||
|
wait_released(server)
|
||||||
|
assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_disconnect_cleanup_has_shared_bound_even_if_transport_close_stalls():
|
||||||
|
with loopback_upstream(hang_close=True) as (transport, entered, closed, transport_closed):
|
||||||
|
with gateway(transport=transport, timeout=5, inactivity=4) as server:
|
||||||
|
peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
|
||||||
|
peer.sendall(speech_request())
|
||||||
|
assert entered.wait(1)
|
||||||
|
began = time.monotonic()
|
||||||
|
peer.close()
|
||||||
|
assert closed.wait(1) and transport_closed.wait(1)
|
||||||
|
wait_released(server)
|
||||||
|
assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
|
||||||
|
assert server.counts['close_errors'] >= 1
|
||||||
|
|
||||||
|
|
||||||
|
LOCAL_IDENTIFIERS = ('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
|
||||||
|
@pytest.mark.parametrize('value', ['bad id', 'bad\tvalue', 'bad\nvalue', 'bad\x00value', 'bad\x7fvalue', 'bad\u00e9value'])
|
||||||
|
def test_voice_settings_inherits_local_identifier_validation(field, value):
|
||||||
|
from pydantic import ValidationError
|
||||||
|
with pytest.raises(ValidationError, match='Invalid local component identifier'):
|
||||||
|
local_config(**{field: value}) # constructs the real VoiceSettings, not the base class
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
|
||||||
|
def test_voice_settings_preserves_valid_local_identifiers(field):
|
||||||
|
value = 'vendor/Valid-Model_1.2'
|
||||||
|
assert getattr(local_config(**{field: value}), field) == value
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
|
||||||
|
def test_invalid_local_identifiers_fail_before_assets_gateway_or_provider(monkeypatch, field, capsys):
|
||||||
|
from services.local_s2s import engine, assets, lifecycle
|
||||||
|
import sys
|
||||||
|
monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
|
||||||
|
monkeypatch.setenv('LOCAL_S2S_ALLOW_PAID_STARTUP', 'true')
|
||||||
|
monkeypatch.setenv(field.upper(), 'bad id')
|
||||||
|
calls = []
|
||||||
|
monkeypatch.setattr(assets, 'validate_assets', lambda *a: calls.append('assets'))
|
||||||
|
monkeypatch.setattr(lifecycle, 'run_owned', lambda *a: calls.append('provider'))
|
||||||
|
assert engine.main() == 1 and calls == []
|
||||||
|
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
|
||||||
|
|
||||||
|
|
||||||
|
def test_warmup_retry_constant_is_read_from_hash_checked_upstream_source():
|
||||||
|
assert constant('base.py.source', 'WARMUP_MAX_RETRIES') == 6
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('field', ['gemini_model', 'gemini_voice', 'openai_realtime_model', 'openai_realtime_voice'])
|
||||||
|
def test_existing_provider_identifier_validators_remain_active(field):
|
||||||
|
from pydantic import ValidationError
|
||||||
|
with pytest.raises(ValidationError, match='Invalid voice profile identifier'):
|
||||||
|
local_config(**{field: 'bad id'})
|
||||||
|
assert getattr(local_config(**{field: 'Valid-1.2'}), field) == 'Valid-1.2'
|
||||||
Reference in New Issue
Block a user