Author SHA1 Message Date
amirhosein mazaheri 2bffb9476a fix(voice): handle response.cancel no-active race on local S2S provider
- implement LocalS2SAdapter.is_no_active to recognize cancellation of completed or inactive responses
- normalize local S2S history handler cancellation error to standard response_cancel_not_active contract
- align calibration distance for measured BGE-M3 search threshold
2026-10-17 17:01:28 +03:30
amirhosein mazaheri 5bb6945377 feat(spaces): add whisper persian v4 speech recognition demo space 2026-10-17 13:03:15 +03:30
amirhosein mazaheri 628aec8def feat(voice): implement local S2S responsiveness candidate and direct TTS routing
Add local S2S responsiveness candidate pinning ASR options and sentence-at-a-time generation. Route speech synthesis directly to OpenAI API for fluent Persian phonetics with gpt-4o-mini-tts-2025-12-15. Add responsiveness, budget carry, and browser watch unit tests along with acceptance benchmarks and evaluation evidence.
2026-10-17 13:02:41 +03:30
11linear11 a94b8cd3ea feat(voice): implement local S2S retained history and provider selection
Add pinned CPU engine dependencies, retained interrupted-response history, provider admission, offline evaluation and isolated browser tooling.

Record Phase 2 acceptance and Phase 3/4 preparation, bounded paid-test accounting and interruption incident findings. Human interruption acceptance, paired OpenAI evaluation and rollback remain pending.
2026-10-16 17:09:27 -04:00
140 changed files with 16650 additions and 91 deletions
+10 -2
View File
@@ -83,6 +83,8 @@ INGEST_EMBEDDING_MAX_RESPONSE_BYTES=16777216
# Backend voice selection; Gemini is the temporary default. No automatic fallback. # Backend voice selection; Gemini is the temporary default. No automatic fallback.
# Legacy PROVIDER is accepted; do not set it differently from VOICE_PROVIDER. # Legacy PROVIDER is accepted; do not set it differently from VOICE_PROVIDER.
VOICE_PROVIDER=gemini VOICE_PROVIDER=gemini
# Additional per-session UI choices; empty preserves default-provider-only admission.
VOICE_SELECTABLE_PROVIDERS=[]
GEMINI_API_KEY= GEMINI_API_KEY=
GEMINI_MODEL=gemini-2.0-flash-exp GEMINI_MODEL=gemini-2.0-flash-exp
GEMINI_VOICE=Aoede GEMINI_VOICE=Aoede
@@ -149,13 +151,19 @@ OPENAI_REALTIME_SPEED=1.30
# Local S2S Phase 2 candidate (off by default; isolated development only). # Local S2S Phase 2 candidate (off by default; isolated development only).
# See services/local_s2s/README.md. Do not change the operational VOICE_PROVIDER. # See services/local_s2s/README.md. Do not change the operational VOICE_PROVIDER.
LOCAL_S2S_ENABLED=false LOCAL_S2S_ENABLED=false
# Phase 3 development opt-in; saved interrupted text is not treated as heard.
LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS=false
# Isolated responsiveness candidate; pins ASR options and sentence-at-a-time generation.
LOCAL_S2S_RESPONSIVE=false
# Provider synthesis speed; 1.0 preserves normal local speech.
LOCAL_S2S_TTS_SPEED=1.0
LOCAL_S2S_ENDPOINT=ws://local-s2s-engine:8765/v1/realtime LOCAL_S2S_ENDPOINT=ws://local-s2s-engine:8765/v1/realtime
LOCAL_S2S_ENGINE_REVISION=619e3fe4f71d1c6f35c15870d588a3638de34722 LOCAL_S2S_ENGINE_REVISION=619e3fe4f71d1c6f35c15870d588a3638de34722
LOCAL_S2S_STT_MODEL=openai/whisper-large-v3 LOCAL_S2S_STT_MODEL=openai/whisper-large-v3
LOCAL_S2S_LLM_MODEL=openai/gpt-4.1-mini LOCAL_S2S_LLM_MODEL=openai/gpt-4.1-mini
# Candidate only: actual voice/rate/Persian compatibility is not accepted yet. # 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_MODEL=gpt-4o-mini-tts-2025-12-15
LOCAL_S2S_TTS_VOICE=Kore LOCAL_S2S_TTS_VOICE=alloy
LOCAL_S2S_MAX_OUTPUT_TOKENS=256 LOCAL_S2S_MAX_OUTPUT_TOKENS=256
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS=30 LOCAL_S2S_REQUEST_TIMEOUT_SECONDS=30
LOCAL_S2S_TOKEN= LOCAL_S2S_TOKEN=
+1
View File
@@ -86,6 +86,7 @@ temp/
# Immutable ingestion originals (may contain private uploaded content) # Immutable ingestion originals (may contain private uploaded content)
data/originals/ data/originals/
data/extractions/
# Isolated local S2S generated source and dependency inputs # Isolated local S2S generated source and dependency inputs
.local-s2s-build/ .local-s2s-build/
+9 -1
View File
@@ -1,5 +1,6 @@
"""K01/K02 and read-only F01, with backend-owned organization scope.""" """K01/K02 and read-only F01, with backend-owned organization scope."""
from uuid import UUID from uuid import UUID
from typing import Literal
from app.infrastructure.blocking import blocking from app.infrastructure.blocking import blocking
from fastapi import APIRouter, Depends, Request from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
@@ -64,7 +65,14 @@ async def replace(request: Request, user=Depends(require_admin), engine=Depends(
description='Query assistant capabilities, upload format limits, active policies, and live voice availability.', description='Query assistant capabilities, upload format limits, active policies, and live voice availability.',
) )
def configuration(user=Depends(get_current_user), engine=Depends(get_engine), def configuration(user=Depends(get_current_user), engine=Depends(get_engine),
ingest=Depends(get_ingestion_settings), voice=Depends(get_voice_settings)): ingest=Depends(get_ingestion_settings), voice=Depends(get_voice_settings),
provider: Literal['openai', 'local_s2s', 'gemini'] | None = None):
if provider is not None:
from app.modules.voice.configuration import select_voice_provider
try:
voice = select_voice_provider(voice, provider)
except ValueError as exc:
raise error(str(exc)) from None
try: try:
with transaction(engine) as conn: with transaction(engine) as conn:
_, settings = authority(conn, user.id) _, settings = authority(conn, user.id)
+37 -2
View File
@@ -12,7 +12,7 @@ from app.api.v1.dependencies import (get_auth_service, get_current_user, get_eng
from app.infrastructure.blocking import blocking from app.infrastructure.blocking import blocking
from app.modules.auth.service import COOKIE_NAME, UserContext, check_origin from app.modules.auth.service import COOKIE_NAME, UserContext, check_origin
from app.modules.voice.lifecycle import LiveLifecycleService from app.modules.voice.lifecycle import LiveLifecycleService
from app.modules.voice.configuration import VoiceSettings from app.modules.voice.configuration import VoiceSettings, select_voice_provider as select_provider
from app.modules.voice.runtime import VoiceRuntime from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.durable_tools import DurableTools from app.modules.voice.durable_tools import DurableTools
@@ -36,8 +36,10 @@ class CreateLiveSessionRequest(BaseModel):
model_config = ConfigDict(extra='forbid') model_config = ConfigDict(extra='forbid')
conversation_id: UUID conversation_id: UUID
client_request_id: UUID client_request_id: UUID
provider: Literal['gemini', 'openai', 'local_s2s'] | None = None
class LiveSessionResponse(BaseModel): class LiveSessionResponse(BaseModel):
provider: Literal['gemini', 'openai', 'local_s2s'] | None = None
session_id: str session_id: str
conversation_id: str conversation_id: str
status: str status: str
@@ -52,6 +54,34 @@ class CloseLiveSessionResponse(BaseModel):
close_reason: str | None = None close_reason: str | None = None
@router.get('/providers')
def voice_providers(user: Annotated[UserContext, Depends(get_current_user)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)],
engine: Annotated[object, Depends(get_engine)]):
rows = []
for provider, label in (('openai', 'OpenAI'), ('local_s2s', 'سرویس لوکال'), ('gemini', 'Gemini')):
reason = None
if provider not in {config.provider, *config.voice_selectable_providers}:
reason = 'disabled'
else:
try:
selected = select_provider(config, provider)
if provider == 'local_s2s':
from app.modules.voice.local_s2s import require_isolated_candidate
try:
require_isolated_candidate(selected, IngestionSettings(), database_url=engine.url)
except ValueError:
reason = 'isolated_environment_required'
if reason is None:
capability(selected)
except ValueError as exc:
reason = 'calibration_required' if str(exc) == 'CALIBRATION_REQUIRED' else 'not_configured'
rows.append(dict(id=provider, label=label, can_start=reason is None, reason=reason))
# Configuration eligibility only; no remote inference/paid readiness probe.
return dict(default_provider=config.provider, connection_checked=False, providers=rows)
def capability(config): def capability(config):
config.require_voice() config.require_voice()
try: try:
@@ -96,12 +126,14 @@ def create_voice_session(req: CreateLiveSessionRequest, response: Response,
if str(exc) != 'SESSION_NOT_FOUND': if str(exc) != 'SESSION_NOT_FOUND':
raise raise
else: else:
if result['conversation_id'] != str(req.conversation_id): if (result['conversation_id'] != str(req.conversation_id)
or (req.provider is not None and result.get('provider') != req.provider)):
raise ValueError('IDEMPOTENCY_CONFLICT') raise ValueError('IDEMPOTENCY_CONFLICT')
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id) result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id)
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
config = select_provider(config, req.provider)
if config.provider == 'local_s2s': if config.provider == 'local_s2s':
from app.modules.voice.local_s2s import require_isolated_candidate from app.modules.voice.local_s2s import require_isolated_candidate
require_isolated_candidate(config, IngestionSettings(), database_url=engine.url) require_isolated_candidate(config, IngestionSettings(), database_url=engine.url)
@@ -113,6 +145,8 @@ def create_voice_session(req: CreateLiveSessionRequest, response: Response,
profile["search"] = search_profile(cutoff, search_settings) profile["search"] = search_profile(cutoff, search_settings)
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id, result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id,
provider=config.provider, model=config.selected_model, execution_profile=profile) provider=config.provider, model=config.selected_model, execution_profile=profile)
if req.provider is not None and result.get('provider') != req.provider:
raise ValueError('IDEMPOTENCY_CONFLICT')
except ValueError as exc: except ValueError as exc:
raise error(str(exc)) from None raise error(str(exc)) from None
if result['replayed']: if result['replayed']:
@@ -169,6 +203,7 @@ 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)
config = select_provider(config, info['provider'])
if config.provider == 'local_s2s': if config.provider == 'local_s2s':
from app.modules.voice.local_s2s import require_isolated_candidate from app.modules.voice.local_s2s import require_isolated_candidate
require_isolated_candidate(config, search_service.settings, database_url=engine.url) require_isolated_candidate(config, search_service.settings, database_url=engine.url)
+71 -4
View File
@@ -1,4 +1,4 @@
"""Pinned local engine GA transport; no invented native input/history receipts.""" """Pinned local engine GA transport; no invented native input/history receipts."""
from app.infrastructure.realtime import RealtimeAdapter from app.infrastructure.realtime import RealtimeAdapter
from app.modules.voice.provider import ProviderProtocolError from app.modules.voice.provider import ProviderProtocolError
from app.modules.voice.local_s2s import setup_session, effective_identity from app.modules.voice.local_s2s import setup_session, effective_identity
@@ -17,12 +17,17 @@ class LocalS2SAdapter(RealtimeAdapter):
self._setup = setup_session(config) self._setup = setup_session(config)
self._identity = effective_identity(config.components(), self._setup) self._identity = effective_identity(config.components(), self._setup)
self._confirmed = False self._confirmed = False
self._engine_session = None
self._history_revision = 0
self._repair_receipts = {}
def setup(self): def setup(self):
from copy import deepcopy from copy import deepcopy
return dict(type='session.update', session=deepcopy(self._setup)) return dict(type='session.update', session=deepcopy(self._setup))
def acknowledged(self, session): def acknowledged(self, session):
self._confirmed = False
self._engine_session = None
# A session echo cannot certify a fixed global engine's real components. # A session echo cannot certify a fixed global engine's real components.
# The versioned engine extension derives this from initialized handlers. # The versioned engine extension derives this from initialized handlers.
if not isinstance(session, dict) or session.get('s2s_effective') != self._identity: if not isinstance(session, dict) or session.get('s2s_effective') != self._identity:
@@ -34,6 +39,9 @@ class LocalS2SAdapter(RealtimeAdapter):
return isinstance(actual, list) and len(actual) == len(expected) and all(matches(a, b) for a, b in zip(actual, expected)) 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 return type(actual) is type(expected) and actual == expected
self._confirmed = matches(session, self._setup) self._confirmed = matches(session, self._setup)
if self._confirmed and self.config.local_s2s_retain_interrupted_answers:
self._engine_session = session.get('id')
self._confirmed = isinstance(self._engine_session, str) and bool(self._engine_session)
return self._confirmed return self._confirmed
def token_limited(self, response): def token_limited(self, response):
@@ -41,16 +49,75 @@ class LocalS2SAdapter(RealtimeAdapter):
return False return False
def is_no_active(self, error): def is_no_active(self, error):
try:
return (isinstance(error, dict)
and (
(error.get("type") == "invalid_request_error"
and error.get("code") == "response_cancel_not_active"
and error.get("param") is None)
or (error.get("type") == "s2s_history_failed"
and error.get("message") == "Cancellation identity mismatch"
and error.get("param") is None)
))
except Exception:
return False return False
def history_repair_request(self, repair):
if not self.config.local_s2s_retain_interrupted_answers or not self._confirmed:
raise LocalS2SContextError('Local retained history is not enabled/confirmed')
return dict(type='conversation.item.truncate', event_id=repair.operation_id,
session_id=repair.session_id, engine_session_id=self._engine_session,
generation=repair.generation, response_id=repair.response_id,
item_id=repair.item_id, content_index=repair.content_index,
audio_end_ms=repair.played_ms)
def confirm_history_repair(self, repair, event): def confirm_history_repair(self, repair, event):
raise LocalS2SContextError('Local history repair is not available in Phase 2') from app.modules.voice.provider import HistoryRepairReceipt
from app.modules.voice.local_s2s import RETENTION_POLICY as POLICY
if repair is None:
raise LocalS2SContextError('Missing frozen history repair')
expected=self.history_repair_request(repair)
fields={k:v for k,v in expected.items() if k not in ('type','event_id')}
revision=event.get('history_revision')
if (event.get('s2s_native_type')!='s2s.history.retained'
or event.get('type')!='conversation.item.truncated'
or event.get('operation_id')!=repair.operation_id
or event.get('applied') is not True or event.get('policy')!=POLICY
or any(type(event.get(k)) is not type(v) or event.get(k)!=v for k,v in fields.items())
or not isinstance(event.get('event_id'),str) or not event['event_id']
or len(event['event_id'])>200
or type(revision) is not int or revision<=0):
raise LocalS2SContextError('Retained history receipt mismatch')
proof={k:v for k,v in event.items() if k!='event_id'}
prior=self._repair_receipts.get(repair.operation_id)
if prior is not None:
if prior!=proof:
raise LocalS2SContextError('Conflicting retained history receipt')
else:
if revision!=self._history_revision+1:
raise LocalS2SContextError('Stale retained history revision')
self._history_revision=revision
self._repair_receipts[repair.operation_id]=proof
return HistoryRepairReceipt(repair,event.get('event_id'),'local_s2s.retained_unheard_draft')
async def receive(self):
event=await super().receive()
if event.get('type')=='s2s.history.retained':
# Private normalization only: provenance and native type are retained.
# This receipt attests annotation, never OpenAI truncation/heard text.
event=dict(event,type='conversation.item.truncated',s2s_native_type=event['type'])
return event
async def send_serialized(self, wire): async def send_serialized(self, wire):
from app.modules.voice.provider import strict_json from app.modules.voice.provider import strict_json
event=strict_json(wire) event=strict_json(wire)
if event.get('type') in ('response.cancel', 'conversation.item.truncate'): if event.get('type') in ('response.cancel','conversation.item.truncate','s2s.history.retain'):
raise LocalS2SContextError('Local interruption requires Phase 3 history repair') if not self.config.local_s2s_retain_interrupted_answers or not self._confirmed:
raise LocalS2SContextError('Local retained history requires confirmed opt-in')
if event.get('type')=='conversation.item.truncate':
# Keep the shared runtime's cleanup command/deadline accounting;
# only the local adapter changes its private native wire operation.
wire=self.serialize(dict(event,type='s2s.history.retain'))
await self.transport.send(wire) await self.transport.send(wire)
+13 -1
View File
@@ -91,6 +91,7 @@ class OpenAIInputSettings(BaseModel):
class VoiceSettings(LocalS2SSettings, 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', 'local_s2s'] = 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'))
voice_selectable_providers: tuple[Literal['gemini', 'openai', 'local_s2s'], ...] = ()
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)
@@ -227,7 +228,8 @@ class VoiceSettings(LocalS2SSettings, OpenAIInputSettings, BaseSettings):
return dict(provider='local_s2s', model=self.selected_model, voice=self.selected_voice, return dict(provider='local_s2s', model=self.selected_model, voice=self.selected_voice,
input_sample_rate=24000, output_sample_rate=24000, input_sample_rate=24000, output_sample_rate=24000,
evidence_policy_revision='same-session-evidence-retained-v5', evidence_policy_revision='same-session-evidence-retained-v5',
development_only=True, interruption_policy='close_until_phase3', development_only=True, interruption_policy=('retain_unheard_draft_v1'
if self.local_s2s_retain_interrupted_answers else 'close_until_phase3'),
local_s2s=effective_identity(self.components(), setup_session(self))) 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,
@@ -245,3 +247,13 @@ class VoiceSettings(LocalS2SSettings, OpenAIInputSettings, BaseSettings):
from app.modules.voice.openai_style import instruction_profile from app.modules.voice.openai_style import instruction_profile
profile.update(instruction_profile(POLICY)) profile.update(instruction_profile(POLICY))
return profile return profile
def select_voice_provider(config, requested=None):
selected = requested or config.provider
if selected not in {config.provider, *config.voice_selectable_providers}:
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
# All secrets, models, speed and audio policy remain server-owned.
result = config.model_copy(update={'provider': selected})
result.require_voice()
return result
+1 -1
View File
@@ -87,7 +87,7 @@ class LiveLifecycleService:
@staticmethod @staticmethod
def _shape(row, *, replayed=False, eligible=True): def _shape(row, *, replayed=False, eligible=True):
sid = str(row['id']) sid = str(row['id'])
return dict(session_id=sid, conversation_id=str(row['conversation_id']), status=row['status'], return dict(session_id=sid, conversation_id=str(row['conversation_id']), status=row['status'], provider=row.get('provider'),
stream_path=f'/api/v1/voice/sessions/{sid}/stream' if eligible else None, stream_path=f'/api/v1/voice/sessions/{sid}/stream' if eligible else None,
expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed, expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed,
calibration_status=LiveLifecycleService._calibration_status(row)) calibration_status=LiveLifecycleService._calibration_status(row))
+28 -4
View File
@@ -9,9 +9,24 @@ UPSTREAM_REVISION = '619e3fe4f71d1c6f35c15870d588a3638de34722'
CONTRACT_REVISION = 'rag-local-s2s-phase2-v1' CONTRACT_REVISION = 'rag-local-s2s-phase2-v1'
PATCH_REVISION = 'rag-local-s2s-phase2-v3' PATCH_REVISION = 'rag-local-s2s-phase2-v3'
RETENTION_POLICY = 'retain_unheard_draft_v1'
DRAFT_MARKER = '[LOCAL_S2S_UNHEARD_DRAFT_V1]'
RETENTION_INSTRUCTIONS = (DRAFT_MARKER + ' Interrupted assistant output is a saved draft, not proof the user heard it. '
'For the same question you may answer from the draft again. Before using document facts, '
'call reuse_last_evidence to revalidate evidence, then report_used_sources with current labels. '
'Never treat a saved draft as fresh evidence or as a completed spoken answer. '
'Do not speak draft markers or internal status labels.')
RESPONSIVE_ASR_PROMPT = 'Transcribe conversational Iranian Persian faithfully, including short informal questions. Do not answer, translate, or add missing words.'
class LocalS2SSettings(BaseModel): class LocalS2SSettings(BaseModel):
local_s2s_enabled: bool = False local_s2s_enabled: bool = False
local_s2s_tts_speed: float = Field(default=1.0, ge=0.25, le=4.0, allow_inf_nan=False)
local_s2s_responsive: bool = False
local_s2s_retain_interrupted_answers: bool = False
local_s2s_endpoint: str = 'ws://local-s2s-engine:8765/v1/realtime' local_s2s_endpoint: str = 'ws://local-s2s-engine:8765/v1/realtime'
local_s2s_token: SecretStr = SecretStr('') local_s2s_token: SecretStr = SecretStr('')
local_s2s_engine_revision: Literal[UPSTREAM_REVISION] = UPSTREAM_REVISION local_s2s_engine_revision: Literal[UPSTREAM_REVISION] = UPSTREAM_REVISION
@@ -44,13 +59,19 @@ class LocalS2SSettings(BaseModel):
return value return value
def components(self): def components(self):
return dict(stt=dict(backend='openai', model=self.local_s2s_stt_model, result = dict(stt=dict(backend='openai', model=self.local_s2s_stt_model,
language='fa', response_format='json', final_only=True), language='fa', response_format='json', final_only=True),
llm=dict(backend='chat-completions', model=self.local_s2s_llm_model, llm=dict(backend='chat-completions', model=self.local_s2s_llm_model,
max_output_tokens=self.local_s2s_max_output_tokens), max_output_tokens=self.local_s2s_max_output_tokens),
tts=dict(backend='openai', model=self.local_s2s_tts_model, tts=dict(backend='openai', model=self.local_s2s_tts_model,
voice=self.local_s2s_tts_voice, response_format='pcm', sample_rate=24000), voice=self.local_s2s_tts_voice, response_format='pcm', sample_rate=24000),
request_timeout_seconds=self.local_s2s_request_timeout_seconds) request_timeout_seconds=self.local_s2s_request_timeout_seconds)
if self.local_s2s_tts_speed != 1.0:
result['tts']['speed'] = self.local_s2s_tts_speed
if self.local_s2s_responsive:
result['stt'].update(temperature=0, prompt=RESPONSIVE_ASR_PROMPT)
result['llm']['stream_batch_sentences'] = 1
return result
def setup_session(config): def setup_session(config):
@@ -62,13 +83,16 @@ def setup_session(config):
session['max_output_tokens'] = config.local_s2s_max_output_tokens 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']['input']['transcription'] = dict(model=config.local_s2s_stt_model, language='fa')
session['audio']['output']['voice'] = config.local_s2s_tts_voice session['audio']['output']['voice'] = config.local_s2s_tts_voice
session['audio']['output']['speed'] = 1.0 session['audio']['output']['speed'] = config.local_s2s_tts_speed
if config.local_s2s_retain_interrupted_answers:
session['instructions'] += '\n' + RETENTION_INSTRUCTIONS
return session return session
def effective_identity(components, session): def effective_identity(components, session):
return dict(engine_revision=UPSTREAM_REVISION, patch_revision=PATCH_REVISION, retention = session.get('instructions', '').endswith(RETENTION_INSTRUCTIONS)
contract_revision=CONTRACT_REVISION, components=components, return dict(engine_revision=UPSTREAM_REVISION, patch_revision='rag-local-s2s-responsive-v1' if 'stream_batch_sentences' in components['llm'] else ('rag-local-s2s-phase3-retain-v1' if retention else PATCH_REVISION),
contract_revision='rag-local-s2s-phase3-retain-v1' if retention else CONTRACT_REVISION, components=components,
effective_config_sha256=sha256(canonical_json(dict(components=components, session=session)).encode()).hexdigest()) effective_config_sha256=sha256(canonical_json(dict(components=components, session=session)).encode()).hexdigest())
+4 -4
View File
@@ -8,8 +8,8 @@ x-candidate-env: &candidate-env
LOCAL_S2S_ENDPOINT: ws://local-s2s-engine:8765/v1/realtime LOCAL_S2S_ENDPOINT: ws://local-s2s-engine:8765/v1/realtime
LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3} 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_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_MODEL: ${LOCAL_S2S_TTS_MODEL:-gpt-4o-mini-tts-2025-12-15}
LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-Kore} LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-alloy}
LOCAL_S2S_MAX_OUTPUT_TOKENS: "256" LOCAL_S2S_MAX_OUTPUT_TOKENS: "256"
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30" LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30"
LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-} LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-}
@@ -53,8 +53,8 @@ services:
VOICE_TRANSPORT_TESTING: "true" VOICE_TRANSPORT_TESTING: "true"
LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3} 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_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_MODEL: ${LOCAL_S2S_TTS_MODEL:-gpt-4o-mini-tts-2025-12-15}
LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-Kore} LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-alloy}
LOCAL_S2S_MAX_OUTPUT_TOKENS: "256" LOCAL_S2S_MAX_OUTPUT_TOKENS: "256"
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30" LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30"
LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-} LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-}
+144 -9
View File
@@ -1,5 +1,140 @@
# Phase 1 agent reference map # Phase 1 agent reference map
Latest document-intake override (2026-10-17): mandatory admin review disabled for new isolated-test uploads; existing Gemini 2.5 Flash Vision configured, automatic admission with warnings enabled. Four user files independently reimported and ready (5/100/3/21 chunks), 75 relevant tests passed. Historical failed rows preserved; active knowledge selection unchanged. Details in [combined runtime evidence](evaluation/local-s2s/combined-ready-20261017.md).
Latest user override and runtime (2026-10-17): [both voice providers and calibrated RAG ready](evaluation/local-s2s/combined-ready-20261017.md). Cost admission disabled explicitly; old budget ceilings below are historical. Memory prevention remains OFF. Direct OpenAI ASR/TTS, 85 focused tests passed, both actual session_ready/normal close passed, bge-m3 calibration reproduced 6/6 supported and 0/4 false positives. Microphone acceptance and immediate provider-switch cleanup remain open.
Latest responsive candidate (2026-10-17): [sentence-at-a-time and ASR policy implemented/live](evaluation/local-s2s/responsive-candidate-20261017.md). 157 unit +3 PostgreSQL passed; actual single-sentence native active-cancel/history fixture passed; real startup and proxied setup/normal close passed. Human Persian accuracy/latency comparison pending. Reserve $0.769884452, exclusive ceiling $0.981884452. Memory prevention OFF; no old-ledger restart.
Latest human result (2026-10-17): [two real playback interruptions and continuation passed](evaluation/local-s2s/windows-live-interruption-20261017.md). User confirms intentional barge-in and no stale audio. Generation had already completed at both cuts; active cancellation and same-answer repeat untested. New12 bills total $0.006186253; reconciled exposure $0.710884452. Engine stopped after attempt caps; UI/API remain. Memory prevention OFF. Phase3/4 open.
Latest active Windows handoff (2026-10-17): [second browser test ready](evaluation/local-s2s/windows-browser-handoff-02-20261017.md). Memory prevention OFF per user; startup and proxied session_ready/normal close passed. New exclusive billed carry baseline $0.704698199, reserve $0.763698199, ceiling $0.940698199. Human test now required; RAG/OpenAI comparison pending. Never restart the ledger.
User override (2026-10-17): Windows browser memory prevention is temporarily disabled by default; monitoring continues. `--enforce-memory-floor` restores preflight/runtime RAM checks. Docker memory cap, budget/exclusive ledger and time limits remain. See [incident and override](evaluation/local-s2s/windows-browser-stop-20261017.md). No paid restart occurred.
Latest Windows incident (2026-10-17): [engine stopped on memory floor before human tests](evaluation/local-s2s/windows-browser-stop-20261017.md). Earlier browser-ready handoff is inactive. Two user setup failures made no inference calls. Exact startup bills reconcile new exposure to $0.704698199, with full older reserves retained; exclusive ledger not restarted. Memory headroom and a verified billing-linked new carry are required before another paid launch.
Latest Windows handoff (2026-10-17): [human browser test ready](evaluation/local-s2s/windows-browser-handoff-20261017.md). Actual startup and proxied session_ready/normal close passed; carried reserve $0.763504399, exclusive ceiling $0.940504399. Real microphone/interruption acceptance, RAG and bounded OpenAI comparison remain pending. Engine expires after30minutes; never restart this ledger.
Current host continuation (2026-10-17): [Windows reconstruction and budget carry](evaluation/local-s2s/windows-continuation-20261017.md). Prior tests ran on another computer. Native images/private ledgers are absent here; verified source/assets and conservative $0.704504399 carry are prepared. No new paid inference or Phase 3/4 acceptance. Windows host memory and bounded admission remain launch gates.
Current preparation (2026-10-16): [Phase 4 frontend/provider selection and paired evaluation tooling](evaluation/local-s2s/phase-04.md).
Phase 3 retains interrupted answers as explicitly unheard drafts per the user's
revised policy; real barge-in/RAG/factual acceptance remains pending. Phase 4 is
prepared for isolated testing, not deployed or accepted. No new paid request,
audio tuning or operational switch. Earlier checkpoints below are historical.
Current verdict (2026-10-16): **Phase 2 accepted for isolated development-only
normal Persian browser voice**. [Final evidence](evaluation/local-s2s/phase-02-accepted-20261016.md)
and [machine-readable results](evaluation/local-s2s/phase-02-accepted-20261016.json):
125 local + 258 preservation + 63 PostgreSQL tests passed; actual browser response
fully played and closed normally. Conservative cost exposure $0.420504399, below
the same $1 cap; final invoice details remain unresolved with full reserves held.
Paid engine stopped normally. No buffer/speed change or operational promotion.
Phase 3/4 remain not_started. Earlier checkpoints below are historical and are
superseded where they describe open Phase 2 gates.
Current incident follow-up: [first browser-turn initialization stall repaired](evaluation/local-s2s/phase-02-browser-first-turn-repair-20261016.md).
User session failed after transcription. Native snapshots identified first-reply
Lingua model preload; same cache now warms before listener readiness. Three full
proxy/API/native continuous-input fixture sessions and98 focused tests pass.
Fixed image a51167d1952a; no buffer/speed/timeout change. Repair handoff carries all
prior attempts; cumulative reservation ceiling $0.995118333 of the same$1. Human
browser acceptance remains open; earlier ready checkpoints below are historical.
Current browser handoff (2026-10-16): [isolated browser is ready](evaluation/local-s2s/phase-02-browser-ready-20261016.md).
Angular/API/login and actual proxied WebSocket session_ready/normal close passed;
no inference in connection check. Three real startup probes passed. Human microphone/
reply/transcript acceptance remains open. Same $1 authorization; reconciled prior
exposure $0.689118333, cumulative ceiling $0.901118333, startup reserve $0.748118333.
Private login file and 30-minute engine watchdog documented. No tuning/operational change.
Latest actual run (2026-10-16): [real native Persian round trip passed](evaluation/local-s2s/phase-02-real-native-20261016.md).
Six actual requests succeeded, 2.528s reply audio, successful terminal/normal
release and clean shutdown. Cumulative reservation is $0.998 of the same $1;
final billing remains unresolved, so no further paid request. User accepted native output; browser/microphone remains open; earlier memory blocker below is historical.
No operational switch or audio tuning change.
Latest preparation (2026-10-16): [bounded real native session](evaluation/local-s2s/phase-02-native-paid-preparation-20261016.md).
Single-sample pronunciation accepted by the user. Cumulative reservation ceiling
is $0.998 including the retained $0.56; no new paid request. Real launch awaits
>5GiB host headroom. Budget/runner checks and actual native fixture pass; browser
and real session acceptance remain open. Audio tuning and operations unchanged.
Local S2S real components (2026-10-16): [actual speech/STT/LLM and $1 budget evidence](evaluation/local-s2s/phase-02-real-components-20261016.md).
Four attempts including initial WAV HTTP400; PCM TTS/Kore, Whisper and GPT-4.1 mini
then succeeded. $0.56 reservation retained; STT+LLM report $0.000338333333333, TTS
and final cost not verified. Single-sample pronunciation accepted by the user; real engine/browser remain open.
No heavy container, operational switch or audio tuning. Preserve the paid ledger;
do not restart paid tests or treat the shared key's $5 limit as a $1 test cap.
Local S2S native session/incident follow-up (2026-10-16): [actual tests and safe continuation](evaluation/local-s2s/phase-02-native-session-20261016.md).
110 tests plus real native normal-audio/close, SIGINT, SIGTERM and fixture-provider
failure cases passed in image 89c7295e5219. Final normal run verifies actual setup
mismatch rejection and intent/item correlation. Cleanup ordering repaired without
changing budgets/tuning. systemd-oomd killed VS Code during prior concurrent tests;
continuation runs one 3GiB/no-swap container with host headroom guard. Cold/one-core
failures disclosed. Real components/browser/quality and target cold start remain open.
Local S2S Queue repair (2026-10-16): [corrected image and real constructor regression](evaluation/local-s2s/phase-02-queue-repair-20261016.md).
Type-compatible queue subclass preserves existing capacity/overflow stop. 109
targeted tests plus actual asset-backed engine construction, three HTTP-fixture
warmups and cleanup passed in separate corrected image 6ad4a6a418ef. Older Queue
blocker below is resolved; native sessions/audio/POSIX and real-provider acceptance
remain open. No tuning, dependency, operational or paid-provider changes.
Local S2S authorized asset download (2026-10-16): [actual resources and construction defect](evaluation/local-s2s/phase-02-linux-assets-20261016.md).
Missing NLTK/Silero prerequisite resolved; all retained asset hashes match the old
manifest, actual image tokenizer/POS/JIT load and silence inference pass. Complete
construction fails on Queue[Any] because the local launcher replaces Queue with a
lambda. No runtime fix applied; repair type compatibility without changing queue
capacity/tuning, then continue engine conformance. No paid calls or operational changes.
Local S2S offline follow-up (2026-10-16): [resource inventory and POSIX subset](evaluation/local-s2s/phase-02-offline-preflight-20261016.md).
Four real Linux signal cases passed with actual lifecycle/gateway and fixture
runtime/provider I/O. Cached punkt files matched prior hashes and loaded; required
POS tagger and Silero source/JIT bundle remain missing. Full asset-backed engine
and native shutdown acceptance remain open. No runtime/tuning changes or downloads.
Local S2S successful image retry (2026-10-16): [actual build/native/SDK evidence](evaluation/local-s2s/phase-02-image-build-20261016.md).
Candidate image `5c80c77c54da` built from the reviewed source/base/lock. Package
check, 15 native imports, six actual pinned-handler/OpenAI SDK fixture scenarios,
two fail-closed startup guards and **423 provider-free tests passed**. Earlier
disk-blocked/unbuilt records below are historical. No voice tuning or provider
call; full asset-backed engine, POSIX, components/browser acceptance still open.
Torch/audio are CPU; full upstream also includes an unused CUDA-tagged TTS wheel.
Local S2S image-build attempt (2026-10-15): [disk-capacity evidence](evaluation/local-s2s/phase-02-image-build.md).
Reviewed build reached dependency installation, then its 384 MiB disk guard
cancelled it. No candidate image exists. Task resolver cache retained on tmpfs;
about 1.8 GiB root space available after cancellation. More Docker storage space
needed before retry; no unrelated cleanup, voice changes or provider startup.
Local S2S Linux dependency lock (2026-10-15): [review and evidence](evaluation/local-s2s/phase-02-dependency-lock.md)
record 134 hashed packages, matching CPU torch/audio 2.11.0, exact wheel URLs,
verified Python 3.11 slim-trixie amd64 manifest and a successful wheel-only
hash-required dry run. Source/lock/base-manifest gaps in older checkpoints below
are superseded. No dependency installation, model download, image build, voice
tuning or provider call occurred; Phase 2 runtime/asset/live gates remain open.
Local S2S pinned source acquisition (2026-10-15): clean detached checkout at
`tmp/local-s2s-upstream-619e3fe4`, exact upstream SHA `619e3fe4f71d1c6f35c15870d588a3638de34722`.
All 17 audited SHA-256/blob fingerprints and Git fsck passed; see
[source evidence](evaluation/local-s2s/phase-02-source-checkout.json).
Earlier missing-source statements below are historical. Dependency lock, engine
build/assets/conformance and Phase 2 live acceptance remain open. No source
execution, model/dependency installation or voice/service change in this step.
Local S2S Phase 1 final Linux acceptance (2026-10-15): user-reported Persian
speech/two interruptions/no errors match actual cancelled/completed terminals,
native truncate acknowledgements and persisted user-requested normal close.
Frozen 2048-token / speed 1.30 / PCM24k / 5,760,000-byte output profile verified.
See [final evidence](evaluation/local-s2s/phase-01-linux-preparation.md).
Provider-boundary/OpenAI preservation accepted; earlier live-pending checkpoints
below are historical. Phase 2 engine build/SDK/POSIX/components/local browser,
reviewed lock and actual rollback restoration remain unverified. No operational
switch or extra provider call was made while recording acceptance.
Local S2S acceptance preparation (2026-10-15): [exact commands and gates](evaluation/local-s2s/phase-02-acceptance-checklist.md); 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 201 cached asset files fingerprinted, existing NLTK load verified, fresh disposable
PostgreSQL 2 local passed / expanded 57 passed and 6 documented baseline failures. PostgreSQL 2 local passed / expanded 57 passed and 6 documented baseline failures.
@@ -70,7 +205,7 @@ Section numbers and heading names below are verified against these files; no inf
| --- | --- | --- | | --- | --- | --- |
| `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Knowledge Changes; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script | | `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Knowledge Changes; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script |
| `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Deferred text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation | | `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Deferred text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation |
| `RAG-Phase1-API-Catalog.md` | [API catalog](specifications/RAG-Phase1-API-Catalog.md) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and deferred text; 7. Voice contract أ¢â‚¬â€‌ OpenAI Realtime; frozen application audio/events; 9. Error envelope and mapping | | `RAG-Phase1-API-Catalog.md` | [API catalog](specifications/RAG-Phase1-API-Catalog.md) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and deferred text; 7. Voice contract ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬أ¢â‚¬إ’ OpenAI Realtime; frozen application audio/events; 9. Error envelope and mapping |
| `RAG-Phase1-Database-Design.md` | [Database design](specifications/RAG-Phase1-Database-Design.md) | Schema/constraints/transactions: 4. Knowledge tables; 5. Minimal voice conversation and evidence; deferred text tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation | | `RAG-Phase1-Database-Design.md` | [Database design](specifications/RAG-Phase1-Database-Design.md) | Schema/constraints/transactions: 4. Knowledge tables; 5. Minimal voice conversation and evidence; deferred text tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation |
| `RAG-Phase1-MVP-Scenarios.md` | [English MVP scenarios](specifications/RAG-Phase1-MVP-Scenarios.md) | Current journeys: 2. Examples and unseen files; 3. Upload/replay; 4-5. Exact review and factual FAQ; 6. Publication; 7-10. Voice/failure/revocation; 11-12. Restart/evaluation | | `RAG-Phase1-MVP-Scenarios.md` | [English MVP scenarios](specifications/RAG-Phase1-MVP-Scenarios.md) | Current journeys: 2. Examples and unseen files; 3. Upload/replay; 4-5. Exact review and factual FAQ; 6. Publication; 7-10. Voice/failure/revocation; 11-12. Restart/evaluation |
| `RAG-AI-Architecture.md` | [Architecture](specifications/RAG-AI-Architecture.md) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Historical prototype mapping; 19. Open Decisions and Owners; 22. Current Live document MVP decisions | | `RAG-AI-Architecture.md` | [Architecture](specifications/RAG-AI-Architecture.md) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Historical prototype mapping; 19. Open Decisions and Owners; 22. Current Live document MVP decisions |
@@ -329,11 +464,11 @@ Persian, ZWNJ, CJK and emoji metadata. No real provider checks were run; these
repairs introduce no provider behavior. Original-store power-loss guarantees and repairs introduce no provider behavior. Original-store power-loss guarantees and
unavailable Windows symlink creation remain outside the verified evidence. unavailable Windows symlink creation remain outside the verified evidence.
## Persian document and voice MVP documentation أ¢â‚¬â€‌ 2026-10-06 ## Persian document and voice MVP documentation ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬أ¢â‚¬إ’ 2026-10-06
The governing specifications now include page-level PDF quality/fallback, DOCX FAQ pairing, infographic group preservation, retained extraction artifacts, shared semantic/identifier retrieval and direct Gemini Live `search_knowledge`. The earlier proposed `search_documents` name and SDP request/answer contract are superseded; prototype `retriever_tool` remains unchanged. The governing specifications now include page-level PDF quality/fallback, DOCX FAQ pairing, infographic group preservation, retained extraction artifacts, shared semantic/identifier retrieval and direct Gemini Live `search_knowledge`. The earlier proposed `search_documents` name and SDP request/answer contract are superseded; prototype `retriever_tool` remains unchanged.
[Architecture Sections 7, 8 and 21](specifications/RAG-AI-Architecture.md) cover diagrams, decisions and static implementation evidence. [Delivery plan Sections 9 and 14أ¢â‚¬â€œ15](specifications/RAG-AI-Phase1-Delivery-Plan.md) retain P1-01أ¢â‚¬â€œP1-12, add P1-13أ¢â‚¬â€œP1-17 and record budget/account/rehearsal gates. [API Section 7](specifications/RAG-Phase1-API-Catalog.md) distinguishes HTTP, application Live WSS and internal tools. [Database Section 4.4](specifications/RAG-Phase1-Database-Design.md) proposes extraction artifacts without content-version entities. [Persian scenarios Sections 18أ¢â‚¬â€œ22](specifications/RAG-Phase1-Scenario-Report-FA.md) document actual sample inspection limits and worked examples. [Architecture Sections 7, 8 and 21](specifications/RAG-AI-Architecture.md) cover diagrams, decisions and static implementation evidence. [Delivery plan Sections 9 and 14ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œ15](specifications/RAG-AI-Phase1-Delivery-Plan.md) retain P1-01ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œP1-12, add P1-13ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œP1-17 and record budget/account/rehearsal gates. [API Section 7](specifications/RAG-Phase1-API-Catalog.md) distinguishes HTTP, application Live WSS and internal tools. [Database Section 4.4](specifications/RAG-Phase1-Database-Design.md) proposes extraction artifacts without content-version entities. [Persian scenarios Sections 18ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œ22](specifications/RAG-Phase1-Scenario-Report-FA.md) document actual sample inspection limits and worked examples.
All four supplied files exist in `data/documents/`; DOCX XML and infographic were inspected locally, and PDF structure confirms five/one pages. Full local PDF text/layout extraction was unavailable; prior word/number-order observations remain supplied context. No provider/OCR benchmark or Persian speech test was run. All four supplied files exist in `data/documents/`; DOCX XML and infographic were inspected locally, and PDF structure confirms five/one pages. Full local PDF text/layout extraction was unavailable; prior word/number-order observations remain supplied context. No provider/OCR benchmark or Persian speech test was run.
@@ -785,7 +920,7 @@ Executed evidence for these four semantic repairs (2026-10-06):
An intermediate corrected targeted run had one compatibility failure: An intermediate corrected targeted run had one compatibility failure:
`Decision dated 1403/01/02` was being treated as an identifier. The final parser `Decision dated 1403/01/02` was being treated as an identifier. The final parser
recognizes the explicit dated/ط¸â€¦ط¸ث†ط·آ±ط·آ® metadata qualifier; the existing control passes. recognizes the explicit dated/ط·آ·ط¢آ¸ط£آ¢أ¢â€ڑآ¬ط¢آ¦ط·آ·ط¢آ¸ط·آ«أ¢â‚¬آ ط·آ·ط¢آ·ط·آ¢ط¢آ±ط·آ·ط¢آ·ط·آ¢ط¢آ® metadata qualifier; the existing control passes.
Real-provider extraction quality and manual Persian fidelity acceptance remain Real-provider extraction quality and manual Persian fidelity acceptance remain
**unverified**. These generated fixtures and fake providers do not establish **unverified**. These generated fixtures and fake providers do not establish
@@ -819,7 +954,7 @@ changes, immutable originals, frozen profiles, normalization and applied migrati
Active position/case/hiding semantics fail safely; resets, harmless formatting Active position/case/hiding semantics fail safely; resets, harmless formatting
and unused styles pass. Deeper DOCX answer headings/table continuations stay and unused styles pass. Deeper DOCX answer headings/table continuations stay
atomic; incomplete/ambiguous/oversized groups fail. English singular/plural and atomic; incomplete/ambiguous/oversized groups fail. English singular/plural and
Persian ط¸â€¦ط·آ§ط·آ¯ط¸â€،/ط¸â€¦ط¸ث†ط·آ§ط·آ¯ targets support explicit conjunction/comma lists and simple Persian ط·آ·ط¢آ¸ط£آ¢أ¢â€ڑآ¬ط¢آ¦ط·آ·ط¢آ·ط·آ¢ط¢آ§ط·آ·ط¢آ·ط·آ¢ط¢آ¯ط·آ·ط¢آ¸ط£آ¢أ¢â€ڑآ¬ط·إ’/ط·آ·ط¢آ¸ط£آ¢أ¢â€ڑآ¬ط¢آ¦ط·آ·ط¢آ¸ط·آ«أ¢â‚¬آ ط·آ·ط¢آ·ط·آ¢ط¢آ§ط·آ·ط¢آ·ط·آ¢ط¢آ¯ targets support explicit conjunction/comma lists and simple
integer ranges; unsupported malformed/complex identifiers fail. Incidental integer ranges; unsupported malformed/complex identifiers fail. Incidental
citations and ordinary decision prose remain accepted. See the setup guide for citations and ordinary decision prose remain accepted. See the setup guide for
exact grammar and output/intake bounds. Attachment/reuse remain Phase 5 gated; exact grammar and output/intake bounds. Attachment/reuse remain Phase 5 gated;
@@ -1927,8 +2062,8 @@ Exactly one API process owns media guards; ingestion runs separately. Fake tests
are not real provider/Persian speech/browser hardware or frontend readiness proof. are not real provider/Persian speech/browser hardware or frontend readiness proof.
Verified final commands: `.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short` Verified final commands: `.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
أ¢â‚¬â€‌ **1679 passed**, two existing Windows path skips; `.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short` ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬أ¢â‚¬إ’ **1679 passed**, two existing Windows path skips; `.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
أ¢â‚¬â€‌ **372 passed**, zero skips, using only the isolated task-created test database. ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬أ¢â‚¬إ’ **372 passed**, zero skips, using only the isolated task-created test database.
Affected PostgreSQL cases: **61 passed**. Missing TEST_DATABASE_URL produced the Affected PostgreSQL cases: **61 passed**. Missing TEST_DATABASE_URL produced the
required prerequisite failure. Executable JS, syntax/compile, diff and baseline required prerequisite failure. Executable JS, syntax/compile, diff and baseline
preservation checks passed. See the report for exact durations, failed/interrupted preservation checks passed. See the report for exact durations, failed/interrupted
@@ -1945,7 +2080,7 @@ intake/review/worker/selection services, with bounded streaming
prior pending-HTTP statements above. The standalone frontend developer handoff is prior pending-HTTP statements above. The standalone frontend developer handoff is
[Phase 3 integration](guides/realtime-agent-phase3-handoff.md), with executable [Phase 3 integration](guides/realtime-agent-phase3-handoff.md), with executable
DocumentClient and a same-origin Vite proxy example. Existing VoiceClient/worklet, DocumentClient and a same-origin Vite proxy example. Existing VoiceClient/worklet,
Gemini/OpenAI selection, canonical search and migrations 0001أ¢â‚¬â€œ0005 are preserved. Gemini/OpenAI selection, canonical search and migrations 0001ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œ0005 are preserved.
`INGEST_OCR_REVIEW_REQUIRED=true` is a deployment default frozen in new job `INGEST_OCR_REVIEW_REQUIRED=true` is a deployment default frozen in new job
profiles; false admits only automatically validated OCR. Legacy profiles retain profiles; false admits only automatically validated OCR. Legacy profiles retain
@@ -2231,7 +2366,7 @@ current-turn labels from delivered search/reuse evidence; the existing sources
event shows that subset, not every retrieval candidate. Metadata reports do not event shows that subset, not every retrieval candidate. Metadata reports do not
create retrieval rows. See `tests/unit/test_voice_reported_sources.py` and create retrieval rows. See `tests/unit/test_voice_reported_sources.py` and
`tests/integration/test_voice_evidence_reuse.py` for validation and revocation `tests/integration/test_voice_evidence_reuse.py` for validation and revocation
coverage. Optional acknowledgement is only «یه لحظه…» once per turn, under coverage. Optional acknowledgement is only ط¢آ«ط؛إ’ط¸â€، ط¸â€‍ط·آ­ط·آ¸ط¸â€،أ¢â‚¬آ¦ط¢آ» once per turn, under
OpenAI delivery v5. New sessions pin the selected-evidence policy revision; OpenAI delivery v5. New sessions pin the selected-evidence policy revision;
existing reservations are not rewritten. Real provider adherence remains existing reservations are not rewritten. Real provider adherence remains
separate from deterministic runtime tests. separate from deterministic runtime tests.
@@ -8,7 +8,7 @@
"dimensions": 1024, "dimensions": 1024,
"preprocessing_version": "v1" "preprocessing_version": "v1"
}, },
"distance": 0.65, "distance": 0.72,
"retrieval_policy": "exact-first-cosine-id-50x2-whole-5-12000/nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2" "retrieval_policy": "exact-first-cosine-id-50x2-whole-5-12000/nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2"
}, },
"complete_support": 6, "complete_support": 6,
+259
View File
@@ -1,5 +1,185 @@
# Development notes # Development notes
## 2026-10-16 — User-authorized Phase 4 preparation and frontend provider choice
- Prepare Phase 4 while Phase 3 live/factual gates remain pending. The frontend
selects an allowed provider per new session; server-owned credentials, models,
tuning and canonical retrieval remain unchanged. No automatic fallback.
- Add optional V01/F01 provider, authenticated configuration-only provider metadata,
explicit-provider replay/race conflict and row-pinned stream settings. Preserve
old default-only clients and profiles; no schema migration.
- Close and verify terminal state before changing UI selection. Unknown closure
keeps the previous provider and ids. Start a fresh session on the next click.
- Add an offline paired latency/cost scorecard, unmeasured template, fault matrix,
isolated image/override and operational restoration runbook. No new paid call,
provider switch, dependency or audio buffer/speed change.
- See [Phase 4 evidence](evaluation/local-s2s/phase-04.md) for tests and remaining
real gates. No quality/savings/rollback acceptance is inferred from fixtures.
## 2026-10-16 — Phase 2 isolated normal browser voice accepted
- Required real component/native/Persian browser/normal-close evidence is complete.
Finish provider-free acceptance: 125 local, 258 OpenAI preservation and 63 real
isolated PostgreSQL tests pass. See [final evidence](evaluation/local-s2s/phase-02-accepted-20261016.md).
- Correct two stale test assumptions to the existing contract: source citations
require report_used_sources, and adjacent unsent transcript deltas may coalesce.
Preserve database/text/replay assertions; do not alter runtime or deadlines.
- Add phase-02-final-postgres.py: new test-owned resource-limited tmpfs PostgreSQL
container, default durability settings, no persistent mounts/provider keys,
explicit --require-postgres and automatic owned-container cleanup. This replaces
slow disk-backed execution without touching candidate or operational data.
- Read-only generation billing confirms $0.003504399; retain $0.417 for every
unresolved attempt, giving conservative exposure $0.420504399. Keep original
exclusive ledgers unchanged and do not restart paid inference. Delayed invoice
details remain a disclosed accounting follow-up; bounded-cost compliance is met.
- Stop the owned paid-engine watchdog normally; preserve candidate DB, images,
frontend, operational OpenAI and tuned buffer/speed configuration. Phase 3/4
remain not_started; no interruption/RAG acceptance or provider promotion.
## 2026-10-16 — First browser reply: native lazy language preload
- Actual human greeting reached transcript but provider-send stalled. Reproduce
through the real proxy/API using fixture HTTP, preserving paid ledgers.
- Native thread dumps locate lazy all-language Lingua preload at the first spoken
reply. Prime the same cache during engine construction, before listener startup;
preserve all detection behavior, buffers, speed, PCM and existing deadlines.
- Three full-path continuous-input fixture sessions and98 focused tests pass.
Native backend-selection experiment did not fix the issue and was discarded.
- Build separate COPY-only image a51167d1952a. Repair ledger retains previous
$0.807118333 and enforces cumulative$0.995118333; no retries/old-ledger reset.
Human browser acceptance remains open. See [evidence](evaluation/local-s2s/phase-02-browser-first-turn-repair-20261016.md).
## 2026-10-16 — Browser candidate running with bounded handoff
- Start existing isolated DB/migrations/API with corrected immutable image and
Angular with the separate proxy. New disposable user; private local credentials.
- Add evaluation-only browser transport, Compose override and engine watchdog.
Reconcile only three billed older calls; retain failed and unbilled reservations.
Cumulative ceiling $0.901118333 under the original $1; no key-cap change.
- Apply documented Google maxOutputTokens2048 in both endpoint options only to
this evaluation, not operational speech speed/buffers. LLM remains128 test tokens.
- Three real probes passed; actual cookie/Origin/CSRF API and proxied native
session_ready/closed user_requested passed with no inference. Human mic test
remains pending. Watchdog limits engine memory and stops it after30minutes.
- Budget regression/Compose/parse/diff checks pass. No frontend source or public
API contract change. See [handoff](evaluation/local-s2s/phase-02-browser-ready-20261016.md).
## 2026-10-16 — Native output listening accepted; earlier billing reconciled
- Record user acceptance of the 2.528s native reply. Browser/API/microphone
acceptance and applicable failed DB checks remain open; no Phase2 acceptance.
- Read-only billing now confirms the earlier three successful standalone calls:
$0.00078 TTS + $0.000308333 STT + $0.00003 LLM = $0.001118333. Exclude
the first failed WAV attempt and distinguish these from the newer native turn.
- New native generation records still return404. No inference or operational
changes; reservation accounting is not actual cost. See updated real-native
and real-components evidence.
## 2026-10-16 — Real native round trip passes within original $1 authorization
- Host memory recovered without lowering any guard; one owned container completed
actual STT/LLM/TTS probes and a native audio turn, successful terminal, correlation,
slot release and clean shutdown. Six real HTTP200 requests, 130.096s total.
- Save the 2.528s Persian reply for human listening. Recognized input retains the
earlier کتاه/کوتاه mismatch; browser/microphone and broad quality are not proved.
- Preserve both paid ledgers: cumulative reserve $0.998, not actual cost. Immediate
billing lookups remain404; no further paid request or automatic startup.
- No operational configuration, audio tuning, frontend or database changed.
See [actual evidence](evaluation/local-s2s/phase-02-real-native-20261016.md).
## 2026-10-16 — Bounded real native session preparation
- Record user acceptance of pronunciation for the single generated Persian sample.
- Extend the existing native harness with a real-provider mode and an evaluation-only
persistent admission guard. Retain the prior $0.56; two attempts per component
reserve at most $0.438 more, for a $0.998 cumulative ceiling under the same $1.
- Keep private credential mode0600; run its test container as its owner. Harden
the existing runner to report pre-start refusal, propagate failure and stop its
owned container on interruption. No dependency, operational or tuning change.
- Budget and runner regressions pass; actual native fixture passes in27.011s.
Real execution remains unaccepted: initial credential preflight failed before
admission, then host memory was below the unchanged5GiB startup requirement.
See [evidence](evaluation/local-s2s/phase-02-native-paid-preparation-20261016.md).
## 2026-10-16 — Authorized real Persian component evaluation, $1 total limit
- Add a standalone exclusive-ledger runner for fixed real TTS/STT/LLM requests,
conservative pre-admission reservations, no automatic retries and bounded data.
Keep the supplied credential ignored and private; existing key cap/settings stay.
- One WAV HTTP400 stopped the first sequence; explicitly announced PCM correction
then produced 5.16s of real Persian audio, a Whisper transcript and GPT-4.1 mini
reply. Four attempts retain $0.56 of the authorized $1 budget. Reported STT+LLM
cost is $0.000338333333333; TTS/final billing remains unverified, not free.
- Record کتاه/کوتاه transcript difference and pending human listening. No broad
quality/RAG/browser acceptance, heavy engine startup, audio tuning or operational
change. Files: evaluation runner/evidence and current index/ledger/README.
See [actual results](evaluation/local-s2s/phase-02-real-components-20261016.md).
## 2026-10-16 — Native local S2S session conformance and memory-safe continuation
- Add an actual native WebSocket/session/audio runner using real assets/handlers/
SDK and fixture-only upstream HTTP. Normal audio/close, setup mismatch and intent
correlation, SIGINT/SIGTERM during provider work and failed-provider terminal
checks passed. No real provider quality/listening claim. 110 focused tests pass.
- Repair shutdown order: cancel gateway/provider I/O before joining workers;
cancel accepted writers/tasks before Server.wait_closed (also fixes Python 3.13
client-wait semantics). Existing deadlines, queue capacity and voice tuning stay.
- Prior concurrent native runs coincided with systemd-oomd killing VS Code due to
memory pressure. Continue sequentially with a 3GiB/no-swap limit, two CPU cap,
host headroom checks and automatic owned-container stop. Record cold-start and
one-core timeout failures; do not change product timeouts to excuse them.
- Files: local lifecycle/components, one regression, native evaluation/guarded
runner and evidence/index/progress docs. Separate image 89c7295e5219 preserves
older candidates and operational selection. No downloads or paid calls.
See [actual evidence](evaluation/local-s2s/phase-02-native-session-20261016.md).
## 2026-10-16 — Preserve Queue type compatibility during engine construction
- Replace only the launcher's Queue lambda with a subclass of the existing
FailClosedQueue bound to its owner stop event. This retains generic annotations
while preserving 256 slots, FIFO and fail-closed overflow. No audio or contract
changes; existing v3 behavior/profile identity remains compatible.
- Enhance the real-image construction regression to verify typed queue creation,
capacity, overflow/stop and draining. 109 focused tests pass. The corrected
image constructs all real handlers with local assets and exactly three fixture
warmups, then cleans up successfully. Native server/sessions remain untested.
- Files: `services/local_s2s/engine.py`, construction evaluation script, repair
evidence and current index/ledger/README. A separate offline image layer keeps
the original image intact. No downloads, paid calls or operational changes.
See [actual evidence](evaluation/local-s2s/phase-02-queue-repair-20261016.md).
## 2026-10-16 — Authorized NLTK/Silero resource acquisition
- Download the previously missing tagger and minimal Silero JIT hub bundle from
fixed official revisions, under explicit user authorization. All 14 retained
resource hashes match prior evidence. Preserve resources in ignored build
storage and record the Linux subset manifest and acquisition provenance.
- Actual immutable-image NLTK sentence/POS loading and Silero JIT inference on
8/16 kHz silence pass with no networking. Complete engine construction then
exposes Queue[Any] versus launcher-lambda incompatibility. Report the defect;
no runtime fix, capacity/speed change, paid call or operational action here.
- Files: asset manifest, evaluation scripts/report/JSON, local README, reference
map and progress ledger. Next repair must preserve queue capacity and stop
behavior while retaining type compatibility. See
[evidence](evaluation/local-s2s/phase-02-linux-assets-20261016.md).
## 2026-10-16 — Local S2S resource inventory and Linux signal subset
- Retain the built image and application runtime unchanged. Reuse four existing
local punkt files whose hashes match the earlier asset manifest; stage copies
only under ignored build inputs. Image NLTK sentence loading passed, while full
preflight correctly rejects the absent POS tagger. Required Silero source/JIT
files were not found; the cached ONNX model is not substituted.
- Add a standalone evaluation script using existing lifecycle/gateway code,
fixture runtime/provider I/O, real local HTTP and OS SIGINT/SIGTERM. All four
cases passed, including runtime-stop failure. This demonstrates the isolated
lifecycle subset, not complete engine/native-worker shutdown or Persian audio.
- Files: evaluation script/report/JSON, progress ledger, reference map and local
service README. No new dependency, image rebuild, runtime edit, voice tuning,
database access, paid call or download. Next requires transfer or authorized
acquisition of missing real resources. See
[actual evidence](evaluation/local-s2s/phase-02-offline-preflight-20261016.md).
## 2026-10-12 — Live repair diagnostics and bounded Gemini cleanup ## 2026-10-12 — Live repair diagnostics and bounded Gemini cleanup
- Extend the existing numeric diagnostics with opt-in audio/cancellation timing; - Extend the existing numeric diagnostics with opt-in audio/cancellation timing;
@@ -157,6 +337,85 @@
Unrelated .aws must not be staged. This checkpoint changes documentation only. Unrelated .aws must not be staged. This checkpoint changes documentation only.
## Local S2S image retry and native checks — 2026-10-16
After the user freed disk, retried the exact reviewed source/base/lock with no
runtime or recipe changes. Image `rag-local-s2s-candidate:phase2`, ID
`sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1`,
built successfully (775.34s; size 2,349,831,100 bytes). Native package check, 15
imports, six real-handler/SDK controlled-I/O cases and two startup refusal guards
passed under network-disabled read-only containers. Existing focused regressions:
423 passed in 69.65s, zero skips. No paid calls, voice tuning, service restart or
DB acceptance. Real local assets/full engine/POSIX/provider-browser gates remain.
Full upstream includes unused CUDA-tagged qwentts wheel; CPU torch/audio alone
do not certify that all installed binaries are CPU-only. Evidence and smoke source
in `docs/evaluation/local-s2s/phase-02-image-build-20261016.*` / `image-sdk-smoke.py`.
## Historical Local S2S preparation notes — 2026-10-15
Phase 2 actual image-build attempt: user authorized the reviewed build. Added
binary-only dependency installation and excluded resolver cache/scratch artifacts
from Docker context (actual 6.64 MB). Moved only task-owned resolver cache to tmpfs
to preserve it and free about 780 MiB. A 384 MiB root-disk guard cancelled the
build during package installation; exit 130, no final image. Root returned to
about 1.8 GiB free; existing services remained running. No unrelated deletion,
pruning, model download, provider call or voice tuning. Evidence and retry-space
prerequisite in `docs/evaluation/local-s2s/phase-02-image-build.*`.
Phase 2 dependency follow-up: generated full Python 3.11/Linux manylinux_2_40
134-package hash lock and matching CPU torch/torchaudio 2.11.0 exact wheel
constraints, preserving upstream dependencies. Verified trixie amd64 base manifest;
wheel-only installation dry run passed. Kept PyPI as sole general index to avoid
CPU-index shadowing. Tracked lock/inputs, license/size metadata and exact commands
in `services/local_s2s/` and `docs/evaluation/local-s2s/phase-02-dependency-lock.*`.
Resolver cached metadata/wheel artifacts (including CPU torch); no library
installation, source build, model download, provider call or voice/service changes.
Native engine/image/asset acceptance remains pending.
Phase 2 source-only follow-up: fetched the user-authorized full pinned upstream
commit into ignored `tmp/local-s2s-upstream-619e3fe4`; clean detached checkout,
all 17 audited SHA-256/blob fingerprints match, Git fsck passed. Evidence:
`docs/evaluation/local-s2s/phase-02-source-checkout.json`. Existing checkouts and
services preserved. No execution/install/build/model download or provider call.
Reviewed Linux dependency lock is the next gate; Phase 2 remains in progress.
Final acceptance: user reports successful Persian speech, two interruptions and
no error. Correlated native diagnostics cover active and completed-unplayed
generation repair; both matching acknowledgements precede the next turn's audio.
Isolated persisted session is closed/user_requested with no error. Stored speed
1.30, 2048-token cap, PCM24k and 5,760,000-byte backlog verified. Phase 1 accepted
for provider-boundary/OpenAI preservation; plan/ledger/report/reference map updated.
No new call or runtime tuning. Phase 2 build/live checks and rollback stay open.
Removed the artificial candidate `LIVE_MAX_INTENTS=3` override after tracing a
user-run close to RESPONSE_INTENT_CAPACITY. Baseline capacity 256 restored;
actual 2048-token cap, speed 1.30 and inspected buffer values unchanged. Candidate
had no active sessions before recreation; readiness 200 afterward. No new paid
call; restoring runtime capacity does not authorize extra paid requests.
User feedback after real speech: preserve established voice tuning. Restored
candidate response cap from 256 to configured 2048 only. Verified speed 1.30,
OpenAI-repair backlog 5,760,000 bytes, credit 72,000 bytes and queue 96,000
bytes / 2 seconds unchanged; readiness 200. No extra paid call. Historical
256-token preparation evidence below is superseded for current generation cap.
Follow-up: initial readiness/auth checks missed `capabilities.voice=false`.
The first UI attempt stopped before reservation because the validation-only
embedding factory requires explicit request limits. Added conservative UTF-8
byte limits solely to the disabled candidate embedding endpoint configuration.
Recreated only candidate API; authenticated configuration now advertises
voice/captions=true with transport testing and uncalibrated status. No provider
calls or runtime/schema changes; real speech acceptance remains pending.
Prepared a candidate-only Linux Compose override and started isolated DB/API
plus Angular on 127.0.0.2:4201 using cached images and read-only current source.
Historical Windows image IDs are unavailable here; selected Linux identities and
actual checks are in `docs/evaluation/local-s2s/phase-01-linux-preparation.md`.
Session/intent/token limits are 60s/3/256. Migration, DB identity, bootstrap,
readiness and proxied auth/Origin/CSRF checks passed. No provider session was
opened; listening/native repair acceptance remains pending. No runtime code,
frontend source, applied migration or operational service was changed.
## Frontend commit checkpoint — 2026-10-12 ## Frontend commit checkpoint — 2026-10-12
Supersedes the earlier uncommitted-frontend status: at the user's explicit Supersedes the earlier uncommitted-frontend status: at the user's explicit
+106
View File
@@ -0,0 +1,106 @@
"""Paid-request guard exclusively for the isolated Phase2 browser evaluation."""
import importlib.util
import json
from decimal import Decimal
from pathlib import Path
import time
import httpx
spec = importlib.util.spec_from_file_location('native_budget', '/checks/native-budget-transport.py')
if not Path(spec.origin).exists():
spec = importlib.util.spec_from_file_location('native_budget', Path(__file__).with_name('native-budget-transport.py'))
native = importlib.util.module_from_spec(spec)
spec.loader.exec_module(native)
require = native.require
RESERVES = {'speech': Decimal('.035'), 'transcriptions': Decimal('.004'), 'completions': Decimal('.02')}
COUNTS = {'speech': 4, 'transcriptions': 3, 'completions': 3}
class BrowserBudget(native.BudgetTransport):
def __init__(self, root, *, upstream=None):
native.validate_prices(root)
prior = json.loads((root/'prior-components.json').read_text())
previous_native = json.loads((root/'prior-native.json').read_text())
billing = json.loads((root/'prior-billing.json').read_text())['earlier_components']
require(prior['reserved_usd'] == '0.56' and prior['paid_attempts'] == 4)
require(previous_native['reserved_usd'] == '0.998' and len(previous_native['attempts']) == 6)
# Release only three completed, individually billed old reservations.
# The first failed WAV and all six unbilled native attempts remain reserved.
successful = {s['stage']:s['headers']['x-generation-id'] for s in prior['stages'] if s['status']=='received'}
require(set(successful) == {'tts_pcm','stt','llm'})
costs = {}
for row in billing:
require(row['http_status'] == 200 and row['generation_id'] == successful[row['stage']])
require(row['stage'] not in costs)
amount = Decimal(str(row['billing']['total_cost']))
require(amount.is_finite() and amount >= 0)
costs[row['stage']] = amount
require(set(costs) == set(successful))
previous = Decimal('.25') + Decimal('.438') + sum(costs.values())
self.maximum_attempts=dict(COUNTS)
prior_browser=root/'previous-browser-ledger.json'
if prior_browser.exists():
earlier=json.loads(prior_browser.read_text())
require(earlier['previous_reserved_and_billed_usd']==str(previous) and len(earlier['attempts'])==6)
used=sum(Decimal(row['reserved_usd']) for row in earlier['attempts'])
require(used==Decimal('.118') and Decimal(earlier['reserved_usd'])==previous+used)
previous+=used
self.maximum_attempts={'speech':4,'transcriptions':2,'completions':2}
maximum = previous + sum(RESERVES[s]*self.maximum_attempts[s] for s in RESERVES)
require(maximum < 1)
endpoints = json.loads((root/'endpoints-google-gemini-3.8-flash-lite-tts.json').read_text())['data']['endpoints']
self.tags = [e['tag'] for e in endpoints]
require(set(self.tags) == {'google-ai-studio','google-vertex/global'})
# Both routes together, full prompt maxima and 2048 audio output tokens.
# Official TTS docs forward remaining options to Gemini generationConfig.
bound = sum(Decimal(e['pricing']['prompt'])*8192 + Decimal(e['pricing']['completion'])*2048 for e in endpoints)
require(bound < RESERVES['speech'])
require(Decimal('.000001')*16384 + Decimal('.000002')*128 < RESERVES['completions'])
self.state = {'previous_reserved_and_billed_usd':str(previous),
'reserved_usd':str(previous), 'maximum_cumulative_usd':str(maximum),
'reconciled_successful_components_usd':str(sum(costs.values())),
'failed_wav_retained_usd':'.25', 'unbilled_native_retained_usd':'.438',
'previous_browser_retained_usd':'.118' if prior_browser.exists() else '0',
'maximum_attempts':self.maximum_attempts,'attempts':[]}
self.path = root/'browser-paid-ledger.json'
with self.path.open('x') as output:
json.dump(self.state, output, indent=2)
self.upstream = upstream or httpx.AsyncHTTPTransport(retries=0, trust_env=False)
async def handle_async_request(self, request):
stage = request.url.path.rsplit('/',1)[-1]
if stage == 'completions':
require(request.method == 'POST' and str(request.url) == 'https://openrouter.ai/api/v1/chat/completions')
data=json.loads(request.content)
require(data['model']==native.MODELS['completions'] and 0 < data['max_tokens'] <= 128 and
len(json.dumps(data,ensure_ascii=False).encode()) <= 16384)
data['provider']={'allow_fallbacks':False,'max_price':{'prompt':1,'completion':2}}
request=httpx.Request('POST',request.url,headers={k:v for k,v in request.headers.items() if k!='content-length'},content=json.dumps(data).encode())
else:
stage, request = native.validate_request(request)
require(sum(row['stage']==stage for row in self.state['attempts']) < self.maximum_attempts[stage])
if stage == 'speech':
data = json.loads(request.content)
data['provider'] = {'options':{tag:{'maxOutputTokens':2048} for tag in self.tags}}
request = httpx.Request('POST',request.url,
headers={k:v for k,v in request.headers.items() if k!='content-length'},
content=json.dumps(data).encode())
total = Decimal(self.state['reserved_usd']) + RESERVES[stage]
require(total <= Decimal(self.state['maximum_cumulative_usd']) and total <= 1)
row = {'stage':stage,'reserved_usd':str(RESERVES[stage]),'status':'in_flight'}
self.state['attempts'].append(row)
self.state['reserved_usd']=str(total)
self.save()
began=time.monotonic()
try:
response=await self.upstream.handle_async_request(request)
row.update(status='headers_received',http_status=response.status_code,
generation_id=response.headers.get('x-generation-id'))
return response
except BaseException as exc:
row.update(status='failed',error_type=type(exc).__name__)
raise
finally:
row['headers_elapsed_seconds']=round(time.monotonic()-began,3)
self.save()
@@ -0,0 +1,34 @@
"""Use the actual engine launcher with the browser-only admission transport."""
import importlib.util
from pathlib import Path
from threading import Thread
from services.local_s2s.components import ComponentServer
import services.local_s2s.lifecycle as lifecycle
from services.local_s2s.engine import main
spec=importlib.util.spec_from_file_location('browser_budget','/checks/browser-budget.py')
module=importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def start_components(key, timeout):
transport=module.BrowserBudget(Path('/evidence'))
class OwnedGateway(ComponentServer):
async def _run(self):
try:
await super()._run()
finally:
await transport.close_owned()
gateway=OwnedGateway(key,port=8766,transport=transport,timeout=timeout)
thread=Thread(target=gateway.serve_forever,daemon=True)
thread.start()
if not gateway.ready.wait(5):
raise RuntimeError('BROWSER_GATEWAY_NOT_READY')
return gateway,thread
lifecycle.start_components=start_components
# The key is mounted only into this engine, never Compose environment/API/browser.
import os
os.environ['OPENROUTER_API_KEY']=Path('/secret/openrouter-test.key').read_text().strip()
raise SystemExit(main())
@@ -0,0 +1,42 @@
"""Offline browser-path reproduction: real native handlers, fixture HTTP only."""
import asyncio
import json
import logging
import os
from threading import Thread
import httpx
from services.local_s2s.components import ComponentServer
import services.local_s2s.lifecycle as lifecycle
from services.local_s2s.engine import main
async def upstream(request):
if request.url.path.endswith('/transcriptions'):
return httpx.Response(200,json={'text':'سلام'})
if request.url.path.endswith('/speech'):
from speech_to_speech.pipeline.language_detection import warm_language_detector
print(json.dumps({'stage':'fixture_language_cache','cache':warm_language_detector.cache_info()._asdict()}),flush=True)
return httpx.Response(200,headers={'content-type':'audio/pcm'},content=b'\x01\x00'*4800)
data=json.loads(request.content)
if not data.get('stream'):
return httpx.Response(200,json={'id':'fixture','object':'chat.completion','created':0,'model':data['model'],'choices':[{'index':0,'message':{'role':'assistant','content':'سلام'},'finish_reason':'stop'}]})
class Delayed(httpx.AsyncByteStream):
async def __aiter__(self):
for _ in range(12):
yield b': heartbeat\n\n'
await asyncio.sleep(1)
for text,stop in (('سلام.',None),('', 'stop')):
chunk={'id':'fixture','object':'chat.completion.chunk','created':0,'model':data['model'],'choices':[{'index':0,'delta':{'content':text},'finish_reason':stop}]}
yield ('data: '+json.dumps(chunk)+'\n\n').encode()
yield b'data: [DONE]\n\n'
return httpx.Response(200,headers={'content-type':'text/event-stream'},stream=Delayed())
def gateway(key,timeout):
server=ComponentServer('offline-fixture',transport=httpx.MockTransport(upstream),timeout=timeout)
thread=Thread(target=server.serve_forever,daemon=True);thread.start()
if not server.ready.wait(5):raise RuntimeError('Fixture gateway did not start')
return server,thread
lifecycle.start_components=gateway
os.environ['OPENROUTER_API_KEY']='offline-fixture'
raise SystemExit(main())
@@ -0,0 +1,53 @@
"""Provider-free regression for browser budget reconciliation and request caps."""
import asyncio
from decimal import Decimal
import importlib.util
import json
from pathlib import Path
import shutil
from tempfile import TemporaryDirectory
import httpx
spec=importlib.util.spec_from_file_location('browser_budget',Path(__file__).with_name('browser-budget.py'))
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
async def main():
with TemporaryDirectory() as directory:
root=Path(directory)
for p in Path('.local-s2s-build/browser-paid').glob('*.json'):
if p.name!='browser-paid-ledger.json':shutil.copyfile(p,root/p.name)
calls=[]
def upstream(request):
calls.append(request)
return httpx.Response(503)
guard=module.BrowserBudget(root,upstream=httpx.MockTransport(upstream))
assert Decimal(guard.state['reserved_usd'])==Decimal('.689118333')
assert Decimal(guard.state['maximum_cumulative_usd'])==Decimal('.901118333')
def speech():return httpx.Request('POST','https://openrouter.ai/api/v1/audio/speech',json={'model':'google/gemini-3.8-flash-lite-tts','voice':'Kore','input':'سلام','response_format':'pcm'})
for _ in range(4):await guard.handle_async_request(speech())
try:await guard.handle_async_request(speech())
except ValueError:pass
else:raise AssertionError('fifth TTS admitted')
data=json.loads(calls[0].content)
assert data['provider']['options']=={tag:{'maxOutputTokens':2048} for tag in ('google-ai-studio','google-vertex/global')}
text='x'*9000
r=httpx.Request('POST','https://openrouter.ai/api/v1/chat/completions',json={'model':'openai/gpt-4.1-mini','messages':[{'role':'user','content':text}],'max_tokens':128})
await guard.handle_async_request(r)
assert json.loads(calls[-1].content)['provider']['allow_fallbacks'] is False
assert Decimal(json.loads(guard.path.read_text())['reserved_usd'])==Decimal('.849118333')
try:module.BrowserBudget(root)
except FileExistsError:pass
else:raise AssertionError('ledger overwritten')
await guard.close_owned()
with TemporaryDirectory() as directory:
root=Path(directory)
for p in Path('.local-s2s-build/browser-repair-paid').glob('*.json'):
if p.name!='browser-paid-ledger.json':shutil.copyfile(p,root/p.name)
guard=module.BrowserBudget(root,upstream=httpx.MockTransport(lambda request:httpx.Response(503)))
assert Decimal(guard.state['reserved_usd'])==Decimal('.807118333')
assert Decimal(guard.state['maximum_cumulative_usd'])==Decimal('.995118333')
assert guard.maximum_attempts=={'speech':4,'transcriptions':2,'completions':2}
await guard.close_owned()
print('PASS: billed reservation release, unknown reservations retained, cumulative cap, failed-attempt retention, exact TTS endpoint options, LLM input/routing and exclusive ledger')
asyncio.run(main())
@@ -0,0 +1,49 @@
"""Actual proxied auth/API/native setup/normal close; sends no microphone audio."""
import asyncio
import json
from pathlib import Path
from uuid import uuid4
import httpx
from websockets.asyncio.client import connect
root=Path('.local-s2s-build')
account=json.loads((root/'browser-login.json').read_text())
origin='http://127.0.0.2:4201'
async def main():
report={}
with httpx.Client(base_url=origin,headers={'Origin':origin},timeout=20,trust_env=False) as client:
login=client.post('/api/v1/auth/login',json={k:account[k] for k in ('username','password')})
login.raise_for_status();csrf=login.json()['csrf_token']
client.headers['x-csrf-token']=csrf
created=client.post('/api/v1/conversations',json={'client_request_id':str(uuid4()),'title':'Phase2 browser connection check','mode':'voice'})
created.raise_for_status();conversation=created.json()['id']
session=client.post('/api/v1/voice/sessions',json={'conversation_id':conversation,'client_request_id':str(uuid4())})
session.raise_for_status();session=session.json()
report.update(conversation_id=conversation,session_id=session['session_id'],events=[])
cookie='; '.join(k+'='+v for k,v in client.cookies.items())
repair=json.loads((root/'browser-watch.json').read_text()).get('repair',False)
ledger=root/('browser-repair-paid' if repair else 'browser-paid')/'browser-paid-ledger.json'
before=len(json.loads(ledger.read_text())['attempts'])
try:
async with connect('ws://127.0.0.2:4201'+session['stream_path'],origin=origin,
additional_headers={'Cookie':cookie},proxy=None,close_timeout=3) as ws:
async with asyncio.timeout(20):
while True:
event=json.loads(await ws.recv());report['events'].append(event['type'])
if event['type']=='error':raise RuntimeError('Browser preflight received '+event['error']['code'])
if event['type']=='session_ready':break
report['session_ready']=True
closed=client.post('/api/v1/voice/sessions/'+session['session_id']+'/close')
closed.raise_for_status();report['close']=closed.json()
finally:
client.post('/api/v1/voice/sessions/'+session['session_id']+'/close')
client.post('/api/v1/auth/logout')
report['component_attempts_before']=before
report['component_attempts_after']=len(json.loads(ledger.read_text())['attempts'])
(root/'browser-connection-result.json').write_text(json.dumps(report,indent=2)+'\n')
assert report.get('session_ready')
assert before==report['component_attempts_after'],'Unexpected inference during connection-only check'
print(json.dumps(report))
asyncio.run(main())
@@ -0,0 +1,86 @@
"""HTTP-fixture-only browser duplex reproduction; synthesized input and sink."""
import asyncio
import json
from pathlib import Path
from uuid import uuid4
import httpx
import subprocess
from websockets.asyncio.client import connect
root=Path('.local-s2s-build')
account=json.loads((root/'browser-login.json').read_text())
origin='http://127.0.0.2:4201'
async def main():
engine=json.loads(subprocess.check_output(['docker','inspect','rag-local-s2s-test-local-s2s-engine-1'],text=True))[0]
if engine['Config']['Entrypoint']!=['python','/checks/browser-fixture-engine.py']:
raise RuntimeError('Refusing audio: native engine is not fixture-only')
if any(m['Destination'].startswith('/secret') for m in engine['Mounts']):
raise RuntimeError('Fixture engine must not mount a provider key')
report={}
with httpx.Client(base_url=origin,headers={'Origin':origin},timeout=20,trust_env=False) as client:
async with asyncio.timeout(30):
while True:
try:
ready=client.get('/api/v1/me')
if ready.status_code in (200,401):break
except httpx.HTTPError:pass
await asyncio.sleep(.5)
login=client.post('/api/v1/auth/login',json={k:account[k] for k in ('username','password')})
login.raise_for_status();csrf=login.json()['csrf_token']
client.headers['x-csrf-token']=csrf
created=client.post('/api/v1/conversations',json={'client_request_id':str(uuid4()),'title':'Phase2 browser connection check','mode':'voice'})
created.raise_for_status();conversation=created.json()['id']
session=client.post('/api/v1/voice/sessions',json={'conversation_id':conversation,'client_request_id':str(uuid4())})
session.raise_for_status();session=session.json()
report.update(conversation_id=conversation,session_id=session['session_id'],events=[],binary_bytes=0)
cookie='; '.join(k+'='+v for k,v in client.cookies.items())
ledger=root/'browser-paid/browser-paid-ledger.json'
before=len(json.loads(ledger.read_text())['attempts'])
microphone=None
try:
async with connect('ws://127.0.0.2:4201'+session['stream_path'],origin=origin,
additional_headers={'Cookie':cookie},proxy=None,close_timeout=3) as ws:
async with asyncio.timeout(20):
while True:
event=json.loads(await ws.recv());report['events'].append(event['type'])
if event['type']=='error':raise RuntimeError('Browser preflight received '+event['error']['code'])
if event['type']=='session_ready':break
report['session_ready']=True
raw=(root/'native-paid/input.pcm').read_bytes()
async def capture():
offset=0
while True:
await asyncio.wait_for(ws.send(raw[offset:offset+960] if offset<len(raw) else bytes(960)),5)
offset+=960
await asyncio.sleep(.02)
microphone=asyncio.create_task(capture())
async with asyncio.timeout(40):
while True:
event=await ws.recv()
if isinstance(event,bytes):
report['binary_bytes']+=len(event)
await ws.send(json.dumps({'type':'playback_progress','audio_ref':audio_ref,'played_ms':report['binary_bytes']//48}))
continue
event=json.loads(event);report['events'].append(event['type'])
if event['type']=='error':raise RuntimeError('Duplex fixture failed '+event['error']['code'])
if event['type']=='audio_started':audio_ref=event['audio_ref']
if event['type']=='audio_ended':break
microphone.cancel()
await asyncio.gather(microphone,return_exceptions=True)
closed=client.post('/api/v1/voice/sessions/'+session['session_id']+'/close')
closed.raise_for_status();report['close']=closed.json()
finally:
if microphone is not None:
microphone.cancel()
await asyncio.gather(microphone,return_exceptions=True)
client.post('/api/v1/voice/sessions/'+session['session_id']+'/close')
client.post('/api/v1/auth/logout')
report['component_attempts_before']=before
report['component_attempts_after']=len(json.loads(ledger.read_text())['attempts'])
(root/'browser-duplex-result.json').write_text(json.dumps(report,indent=2)+'\n')
assert report.get('session_ready') and report['binary_bytes']>0
assert before==report['component_attempts_after'],'Unexpected inference during connection-only check'
print(json.dumps(report))
asyncio.run(main())
@@ -0,0 +1,71 @@
"""Provider-free regression check for the cumulative native-test budget."""
import asyncio
import importlib.util
import json
from pathlib import Path
import shutil
from tempfile import TemporaryDirectory
import httpx
spec = importlib.util.spec_from_file_location('budget', Path(__file__).with_name('native-budget-transport.py'))
budget = importlib.util.module_from_spec(spec)
spec.loader.exec_module(budget)
async def check():
with TemporaryDirectory() as directory:
root = Path(directory)
for model in ('google/gemini-3.8-flash-lite-tts','openai/whisper-large-v3'):
name = 'endpoints-'+model.replace('/','-')+'.json'
shutil.copyfile(Path('.local-s2s-build')/name, root/name)
prior = root/'prior.json'
prior.write_text(json.dumps(dict(reserved_usd='0.56', paid_attempts=4)))
calls = []
def upstream(request):
calls.append(request)
return httpx.Response(503)
guard = budget.BudgetTransport(root, prior, upstream=httpx.MockTransport(upstream))
request = lambda: httpx.Request('POST','https://openrouter.ai/api/v1/audio/speech',
json={'model': budget.MODELS['speech'],'voice':'Kore','response_format':'pcm','input':'سلام'})
for _ in range(2):
result = await guard.handle_async_request(request())
assert result.status_code == 503
try:
await guard.handle_async_request(request())
except ValueError:
pass
else:
raise AssertionError('third TTS admitted')
assert len(calls) == 2
assert guard.state['reserved_usd'] == '0.970'
assert json.loads(guard.path.read_text())['reserved_usd'] == '0.970'
try:
budget.BudgetTransport(root, prior)
except FileExistsError:
pass
else:
raise AssertionError('existing ledger overwritten')
guard.state['reserved_usd'] = '.999'
try:
await guard.handle_async_request(httpx.Request('POST','https://openrouter.ai/api/v1/chat/completions',
json={'model':budget.MODELS['completions'],'messages':[], 'max_tokens':128}))
except ValueError:
pass
else:
raise AssertionError('cumulative overflow admitted')
assert len(calls) == 2
for data in ({'model':'wrong','voice':'Kore','response_format':'pcm','input':'سلام'},
{'model':budget.MODELS['speech'],'voice':'Kore','response_format':'pcm','input':'x'*4097}):
try:
budget.validate_request(httpx.Request('POST','https://openrouter.ai/api/v1/audio/speech',json=data))
except ValueError:
pass
else:
raise AssertionError('invalid input admitted')
_, rewritten = budget.validate_request(httpx.Request('POST','https://openrouter.ai/api/v1/chat/completions',
json={'model':budget.MODELS['completions'],'max_tokens':128,'messages':[]}))
assert json.loads(rewritten.content)['provider']['allow_fallbacks'] is False
await guard.close_owned()
print('PASS: price bounds, failed-attempt persistence, two-attempt limit, cumulative overflow, exclusive ledger, input/model and LLM route caps')
asyncio.run(check())
@@ -0,0 +1,53 @@
"""Provider-free checks: headroom refusal, owned stop and child exit propagation."""
import contextlib
from io import StringIO
from pathlib import Path
import runpy
from tempfile import TemporaryDirectory
from unittest.mock import patch
script = Path(__file__).with_name('run-image-session-smoke.py').resolve()
original_read = Path.read_text
def check(kind):
calls = []
memory = iter(([4*1024**2] if kind == 'headroom' else [6*1024**2, 2*1024**2]) + [6*1024**2]*4)
class Process:
returncode = None
def poll(self):
return self.returncode
def wait(self, timeout):
return self.returncode
process = Process()
def start(*args, **kwargs):
calls.append('start')
if kind == 'child_failure':
process.returncode = 7
return process
def stop(command, **kwargs):
if '--time' not in command:
raise AssertionError('Unexpected command')
calls.append('stop_owned')
process.returncode = 143
def read(path, *args, **kwargs):
if str(path) == '/proc/meminfo':
return 'MemAvailable: '+str(next(memory))+' kB\n'
return original_read(path, *args, **kwargs)
with TemporaryDirectory() as directory:
root = Path(directory)
(root/'.local-s2s-build').mkdir()
with patch('pathlib.Path.cwd', return_value=root), patch('pathlib.Path.read_text', read), \
patch('sys.argv', [str(script), 'normal']), patch('subprocess.Popen', start), \
patch('subprocess.run', stop), contextlib.redirect_stdout(StringIO()):
try:
runpy.run_path(str(script), run_name='__main__')
except SystemExit as exc:
assert exc.code == 1
else:
raise AssertionError('Failure returned success')
assert calls == ([] if kind == 'headroom' else ['start'] if kind == 'child_failure' else ['start','stop_owned'])
for case in ('headroom', 'low_memory', 'child_failure'):
check(case)
print('PASS: pre-start memory guard, owned-container stop, nonzero child propagation')
@@ -0,0 +1,27 @@
import importlib.util,tempfile,shutil,json,asyncio
from pathlib import Path
import httpx
s=importlib.util.spec_from_file_location('guard','docs/evaluation/local-s2s/phase4-browser-budget.py');m=importlib.util.module_from_spec(s);s.loader.exec_module(m)
async def main():
with tempfile.TemporaryDirectory() as d:
p=Path(d)
for f in Path('.local-s2s-build/phase4-browser-paid').glob('*.json'):
if f.name!='browser-paid-ledger.json':shutil.copyfile(f,p/f.name)
calls=[]
def mock(r):calls.append(r);return httpx.Response(503)
g=m.BrowserBudget(p,upstream=httpx.MockTransport(mock))
assert g.state['maximum_cumulative_usd']=='0.774504399'
request=httpx.Request('POST','https://openrouter.ai/api/v1/audio/speech',json={'model':'google/gemini-3.8-flash-lite-tts','voice':'Kore','input':'سلام','response_format':'pcm'})
for _ in range(6):await g.handle_async_request(request)
try:await g.handle_async_request(request)
except ValueError:pass
else:raise AssertionError('quota bypass')
assert g.state['last_denial']=={'stage':'speech','reason':'attempt_limit','admitted_attempts':6}
assert len(calls)==6 and len(g.state['attempts'])==6
assert g.state['unknown_prior_reservations_usd']=='0.417'
try:m.BrowserBudget(p,upstream=httpx.MockTransport(mock))
except FileExistsError:pass
else:raise AssertionError('ledger overwritten')
await g.close_owned()
print('PASS: carried exposure, fresh exclusive ledger, failure reservations, six-attempt ceiling, current prices')
asyncio.run(main())
@@ -0,0 +1,58 @@
"""Actual proxied auth/API/native setup/normal close; sends no microphone audio."""
import asyncio
import argparse
import json
from pathlib import Path
from uuid import uuid4
import httpx
from websockets.asyncio.client import connect
root=Path('.local-s2s-build')
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--account',type=Path,default=root/'browser-login.json')
parser.add_argument('--ledger',type=Path,default=root/'phase4-browser-paid/browser-paid-ledger.json')
parser.add_argument('--output',type=Path,default=root/'phase4-browser-connection-result.json')
args=parser.parse_args()
account=json.loads(args.account.read_text())
origin='http://127.0.0.2:4201'
async def main():
report={}
with httpx.Client(base_url=origin,headers={'Origin':origin},timeout=20,trust_env=False) as client:
login=client.post('/api/v1/auth/login',json={k:account[k] for k in ('username','password')})
login.raise_for_status();csrf=login.json()['csrf_token']
client.headers['x-csrf-token']=csrf
created=client.post('/api/v1/conversations',json={'client_request_id':str(uuid4()),'title':'Phase3/4 retained-history connection check','mode':'voice'})
created.raise_for_status();conversation=created.json()['id']
session=client.post('/api/v1/voice/sessions',json={'conversation_id':conversation,'client_request_id':str(uuid4()),'provider':'local_s2s'})
session.raise_for_status();session=session.json()
report.update(conversation_id=conversation,session_id=session['session_id'],events=[])
cookie='; '.join(k+'='+v for k,v in client.cookies.items())
metadata=client.get('/api/v1/voice/sessions/providers');metadata.raise_for_status()
report['providers']=metadata.json()
assert next(p for p in report['providers']['providers'] if p['id']=='local_s2s')['can_start']
assert not next(p for p in report['providers']['providers'] if p['id']=='openai')['can_start']
ledger=args.ledger
before=len(json.loads(ledger.read_text())['attempts'])
try:
async with connect('ws://127.0.0.2:4201'+session['stream_path'],origin=origin,
additional_headers={'Cookie':cookie},proxy=None,close_timeout=3) as ws:
async with asyncio.timeout(20):
while True:
event=json.loads(await ws.recv());report['events'].append(event['type'])
if event['type']=='error':raise RuntimeError('Browser preflight received '+event['error']['code'])
if event['type']=='session_ready':break
report['session_ready']=True
closed=client.post('/api/v1/voice/sessions/'+session['session_id']+'/close')
closed.raise_for_status();report['close']=closed.json()
finally:
client.post('/api/v1/voice/sessions/'+session['session_id']+'/close')
client.post('/api/v1/auth/logout')
report['component_attempts_before']=before
report['component_attempts_after']=len(json.loads(ledger.read_text())['attempts'])
args.output.write_text(json.dumps(report,indent=2)+'\n')
assert report.get('session_ready')
assert before==report['component_attempts_after'],'Unexpected inference during connection-only check'
print(json.dumps(report))
asyncio.run(main())
@@ -0,0 +1,51 @@
{
"status": "ready_for_human_test",
"date": "2026-10-17",
"environment": "isolated Windows Docker test",
"cost_controls": "disabled_by_explicit_user_request",
"memory_prevention": false,
"providers": {
"openai": {
"session_ready": true,
"events": [
"session_ready"
]
},
"local_s2s": {
"session_ready": true,
"events": [
"session_ready"
]
}
},
"local_components": {
"asr": "gpt-4o-transcribe",
"asr_endpoint": "https://api.openai.com/v1/audio/transcriptions",
"tts": "gpt-4o-mini-tts-2025-12-15",
"voice": "alloy",
"tts_endpoint": "https://api.openai.com/v1/audio/speech",
"llm": "openai/gpt-4.1-mini via OpenRouter"
},
"calibration": {
"calibration_id": "cd5c3bac-5c83-454a-bb34-19d6c2045294",
"status": "calibrated",
"complete_support": 6,
"unsupported_false_positives": 0,
"cutoff": {
"profile": {
"provider": "ollama",
"endpoint": "http://localhost:11434/v1",
"model": "bge-m3",
"dimensions": 1024,
"preprocessing_version": "v1"
},
"distance": 0.33686461167069426,
"retrieval_policy": "exact-first-cosine-id-50x2-whole-5-12000/nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2"
},
"provider_calls": 10,
"final_authorization_confirmed": true
},
"unit_tests": "85 passed",
"human_voice_acceptance": "pending",
"rapid_switch_before_media_cleanup": "403 observed; explicit close and waiting for WebSocket close passed"
}
@@ -0,0 +1,31 @@
# Combined voice and calibrated RAG test ? 2026-10-17
Explicit user override: cost admission controls are disabled for this isolated run. Historical bills/reserves are preserved and are no longer this run's admission ceiling. Memory prevention remains off. Docker memory bounds, request timeouts and cancellation remain. Session lifetime is restored to the existing 600-second setting.
Both OpenAI Realtime (existing gpt-realtime-2.1/marin/low/1.30 profile) and local_s2s reached session_ready through the actual frontend proxy. Local ASR gpt-4o-transcribe and TTS gpt-4o-mini-tts-2025-12-15/alloy route directly to OpenAI; LLM remains GPT-4.1 mini through OpenRouter. Direct audio refuses missing OpenAI credentials instead of forwarding the router key. Existing OpenRouter ASR compatibility remains. Four new routing regressions plus affected tests: 85 passed.
RAG uses a new isolated rag_bge_local_s2s_test database and dedicated volumes. The approved original hash and ten frozen labels were preserved; proper intake/worker published six chunks, then fenced selection activated the document. Ollama bge-m3/1024/v1 reproduced the original measured cutoff 0.33686461167069426, six supported cases and zero false positives in four unsupported cases. The old report currently contains 0.65 despite its guide/trials documenting the stricter measured cutoff; it was left unchanged. The new measured report is independently retained.
Runtime files are ignored under .local-s2s-build: windows-combined.compose.json, combined-compose.py, combined-engine.py and combined-evidence/. The launcher forwards only the two required OpenAI keys from the existing .env into the API runtime; it writes no copied provider credentials or full .env mount. Engine uses existing server-only secret mounts. Start from repository root using `.venv/Scripts/python .local-s2s-build/combined-compose.py up -d --no-deps candidate_api candidate_worker local-s2s-engine`. Do not use obsolete budget launchers/watchdogs for this run.
Browser: http://127.0.0.2:4201/login, existing test credentials. Refresh and log in again because test identity belongs to the new isolated database. Ask the approved sample pump-pressure question and unsupported land-price question on both providers. Only the approved calibration sample is loaded here; other operational documents were not silently copied.
Both provider setups and explicit normal close passed. OpenAI-to-local switching passed after waiting for WebSocket closure. Abruptly disconnecting and immediately starting another provider produced 403 while the single media slot was still cleaning up; immediate-switch acceptance remains open. No microphone, listening, ASR accuracy or full spoken RAG acceptance is claimed. Phase 3/4 remain open.
## Temporary automatic document intake override
2026-10-17, explicit user request: candidate API, worker and migration/operator configuration now use the existing OpenRouter Vision profile google/gemini-2.5-flash, 60-second timeout. INGEST_OCR_REVIEW_REQUIRED=false, INGEST_FACTUAL_REVIEW_REQUIRED=false and INGEST_ALLOW_PARTIAL_EXTRACTION=true. This last existing switch also bypasses direct-PDF visual review while retaining automatic-admission warnings. Factual placeholders remain excluded by the existing policy. No human approval was fabricated. This temporary setup admits outputs with warnings and is not a manual accuracy certification.
The launcher forwards only INGEST_VISION_API_KEY in addition to the two necessary OpenAI keys; no additional credential file is created. Existing originals/jobs/profiles are immutable: four files were independently reimported through proper intake with deterministic operation IDs. Old failed rows remain historical. New ready records: photo db37c610-4fb8-4f9f-aa9d-481720a64a86 (5 chunks), DOCX ba72acfa-4f3c-403e-bafe-879b08ed0ccb (100), PDF 5905? 0abd2545-05af-4c7c-8194-6a9182d164e7 (3), PDF 7364? d9c23e5a-8a51-4696-94ac-4a060957c58b (21). Two intermediate stricter-policy PDF attempts failed and remain historical too. All four final jobs published successfully; no pending administrator review. Knowledge selection was not changed by this intake operation; ready documents can be selected separately for RAG. Original calibration sample remains selected.
Validation: 75 relevant unit tests passed (test_phase5_review.py, test_partial_extraction.py, test_gemini_vision.py); real hosted Vision + local bge-m3 embedding + atomic worker publication succeeded. No application behavior code or database migration was changed for this configuration-only operation.
## Local speech pace and selector label
Explicit user request: LOCAL_S2S_TTS_SPEED=1.3 in the isolated runtime; default remains 1.0. Applied before native TTS setup/warmup, forwarded by the existing handler to the speech request, read from the actual initialized handler in component attestation, and included in session identity. No sample-rate or playback-buffer change. Provider metadata label changed to ????? ?????; frontend displays that server-provided label. 45 focused unit tests passed, including applied speed and rejection of a handler-speed mismatch.
## Follow-up: pace 1.6 and unanswered person query
User requested a further pace increase: active local TTS speed is now 1.6 (previously 1.3). Both actual proxied session_ready/normal-close checks passed again; local paid startup probes passed.
Read-only diagnosis: all five ready documents are active at knowledge revision 6. Local tool queries were the Persian equivalent of Mr. Danesh and deputy of planning; OpenAI queried Danesh. Both returned succeeded/no_evidence, not provider errors. The extracted 5905 PDF contains the salutation Mr. Danesh followed by deputy of planning. Candidate distances for Mr. Danesh started at 0.5615, while the active calibration cutoff is 0.33686461167069426; all 50 candidates were filtered out. Role query nearest distance 0.4371 was rejected too. Existing exact lexical matching handles article/date/alphanumeric identifiers, not person names. The calibration sample does not establish recall for these real document questions. No threshold or retrieval contract was changed; a name-query retrieval repair and real-corpus evaluation remain pending. Original PDF text-layer matching did not independently verify the OCR person spelling, so the extracted text is evidence of the retrieval defect, not manual certification of the original image.
@@ -0,0 +1,35 @@
"""Real local NLTK/Silero check; run on stdin in the network-isolated image."""
import json
import math
import nltk
import torch
from services.local_s2s.assets import validate_assets, configure_nltk, AssetError
expected = '869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26'
assert validate_assets('/assets/nltk', '/vad/silero-vad', '/assets/assets.json') == expected
configure_nltk(nltk, '/assets/nltk')
assert len(nltk.sent_tokenize('Local asset verification. Another sentence.')) == 2
assert nltk.pos_tag(['verification'], lang='eng') == [('verification', 'NN')]
try:
nltk.download('punkt')
except AssetError:
pass
else:
raise AssertionError('download was not blocked')
torch.set_num_threads(1)
model, utils = torch.hub.load('/vad/silero-vad', 'silero_vad', source='local', onnx=False)
results = []
for rate, width in [(8000, 256), (16000, 512)]:
model.reset_states()
probabilities = [model(torch.zeros(width), rate).item() for _ in range(8)]
assert all(math.isfinite(p) and 0 <= p <= 1 for p in probabilities)
segments = utils[0](torch.zeros(rate), model, sampling_rate=rate)
assert segments == []
results.append(dict(sample_rate=rate, windows=8, probabilities=probabilities,
silence_segments=segments, passed=True))
print(json.dumps(dict(manifest_sha256=expected, nltk_version=nltk.__version__,
nltk_sentence_pos='passed', nltk_download_block='passed',
torch_version=torch.__version__, silero_local_jit_load='passed',
inference=results, paid_calls=0, external_network='none',
scope='real local assets and silence inference; no speech quality claim')))
@@ -0,0 +1,93 @@
"""Actual asset-backed engine construction; only upstream provider HTTP is a fixture.
Run on stdin inside the isolated immutable image. Does not start native sessions.
"""
import json
import logging
import os
from queue import Empty
from threading import Event, Thread
import httpx
import nltk
from services.local_s2s.assets import validate_assets, configure_nltk
from services.local_s2s.components import ComponentServer
from services.local_s2s.engine import build_runtime
from app.modules.voice.configuration import VoiceSettings
logging.disable(logging.CRITICAL)
os.environ.update(LOCAL_S2S_SILERO_SOURCE='/vad/silero-vad',
LOCAL_S2S_STT_MODEL='fixture/stt', LOCAL_S2S_LLM_MODEL='fixture/llm',
LOCAL_S2S_TTS_MODEL='fixture/tts', LOCAL_S2S_TTS_VOICE='fixture',
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS='7')
fingerprint = validate_assets('/assets/nltk', '/vad/silero-vad', '/assets/assets.json')
configure_nltk(nltk, '/assets/nltk')
calls = []
def upstream(request):
path = request.url.path
calls.append(path)
if path.endswith('/audio/transcriptions'):
return httpx.Response(200, json={'text': 'fixture'})
if path.endswith('/audio/speech'):
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=bytes(4800))
assert path.endswith('/chat/completions')
payload = json.loads(request.content)
assert payload['max_tokens'] == 17
return httpx.Response(200, json={
'id': 'fixture', 'object': 'chat.completion', 'created': 0, 'model': 'fixture/llm',
'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': 'fixture'},
'finish_reason': 'stop'}]})
guard = ComponentServer('offline-fixture-key', port=8766,
transport=httpx.MockTransport(upstream), timeout=7)
thread = Thread(target=guard.serve_forever, daemon=True)
thread.start()
assert guard.ready.wait(3)
runtime = None
try:
config = VoiceSettings(_env_file=None, provider='local_s2s', local_s2s_enabled=True,
voice_transport_testing=True, local_s2s_stt_model='fixture/stt',
local_s2s_llm_model='fixture/llm', local_s2s_tts_model='fixture/tts',
local_s2s_tts_voice='fixture', local_s2s_request_timeout_seconds=7,
local_s2s_max_output_tokens=17)
config.require_voice()
stop = Event()
runtime = build_runtime(config, stop)
assert runtime.state == 'constructed' and len(runtime.server.pool) == 1
import speech_to_speech.s2s_pipeline as pipeline
queue = pipeline.Queue[int]()
assert queue.maxsize == 256 and not stop.is_set()
for index in range(256):
queue.put(index)
try:
queue.put(256)
except RuntimeError as error:
assert str(error) == 'LOCAL_ENGINE_QUEUE_CAPACITY'
else:
raise AssertionError('overflow must stop the candidate')
assert stop.is_set()
assert [queue.get_nowait() for _ in range(256)] == list(range(256))
try:
queue.get_nowait()
except Empty:
pass
else:
raise AssertionError('queue did not drain')
assert sorted(calls) == sorted(['/api/v1/audio/transcriptions',
'/api/v1/chat/completions', '/api/v1/audio/speech'])
print(json.dumps(dict(stage='construction', passed=True, manifest_sha256=fingerprint,
handlers=[type(h).__name__ for h in runtime.server.pool[0].handlers],
fixture_requests=calls, counts=dict(guard.counts), paid_calls=0,
queue_generic_and_capacity='passed', queue_capacity=256)), flush=True)
finally:
try:
if runtime is not None:
runtime.stop()
finally:
guard.shutdown()
guard.server_close()
thread.join(3)
assert not thread.is_alive()
print(json.dumps(dict(stage='construction_cleanup', passed=True,
runtime_state=runtime.state, counts=dict(guard.counts))), flush=True)
@@ -0,0 +1,133 @@
"""Offline Linux signals: actual lifecycle/gateway, fixture runtime and provider I/O.
Run in the immutable candidate with --network none. This does not construct the
asset-backed speech engine or prove native pipeline shutdown.
"""
import asyncio
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
from threading import Event, Thread
import time
def child(stop_fails):
import httpx
import services.local_s2s.lifecycle as lifecycle
from services.local_s2s.components import ComponentServer
captured, logs = [], []
cancelled, client_done, stopped = Event(), Event(), Event()
previous = {s: signal.getsignal(s) for s in (signal.SIGINT, signal.SIGTERM)}
async def remote(request):
print(json.dumps(dict(stage='inflight')), flush=True)
try:
await asyncio.Event().wait()
finally:
cancelled.set()
def start(key, timeout):
guard = ComponentServer(key, port=0, timeout=timeout,
transport=httpx.MockTransport(remote))
thread = Thread(target=guard.serve_forever, daemon=True)
thread.start()
assert guard.ready.wait(2)
captured.extend((guard, thread))
return guard, thread
def request():
try:
with httpx.Client(timeout=20, 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
finally:
client_done.set()
class Runtime:
def __init__(self, stop):
self.event = stop
def start(self):
Thread(target=request, daemon=True).start()
def wait(self):
self.event.wait()
def stop(self):
stopped.set()
if stop_fails:
raise RuntimeError('controlled runtime stop failure')
def emit(value, **kwargs):
logs.append(json.loads(value))
print(value, **kwargs)
lifecycle.start_components = start
outcome = lifecycle.run_owned(Runtime, 'offline-fixture-key', 20, emit=emit)
guard, thread = captured
assert outcome == int(stop_fails)
assert stopped.is_set() and cancelled.wait(1) and client_done.wait(1)
assert not thread.is_alive() and not guard.requests and guard.socket.fileno() == -1
assert all(signal.getsignal(s) == handler for s, handler in previous.items())
close = logs[-1]
assert close['stage'] == 'close'
assert close['cleanup']['runtime_stop'] == int(stop_fails)
assert all(v == 0 for k, v in close['cleanup'].items() if k != 'runtime_stop')
assert close['request_counts']['accepted'] == close['request_counts']['released'] == 1
assert close['request_counts']['cancelled'] == 1
assert close['request_counts']['shutdown_pending'] == 0
assert close['request_counts'].get('close_errors', 0) == 0
print(json.dumps(dict(stage='verified', stop_fails=stop_fails,
signal_handlers_restored=True, fixture_io_cancelled=True)), flush=True)
def main():
results = []
for sig in (signal.SIGINT, signal.SIGTERM):
for stop_fails in (False, True):
lines, ready = [], Event()
process = subprocess.Popen([sys.executable, '-u', str(Path(__file__).resolve()),
'--child', str(int(stop_fails))],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
def read():
for line in process.stdout:
lines.append(line)
if '"stage": "inflight"' in line:
ready.set()
reader = Thread(target=read, daemon=True)
reader.start()
try:
assert ready.wait(8), ''.join(lines)
began = time.monotonic()
os.kill(process.pid, sig)
assert process.wait(timeout=8) == 0, ''.join(lines)
reader.join(1)
elapsed = time.monotonic() - began
events = [json.loads(line) for line in lines]
assert events[-1]['stage'] == 'verified'
results.append(dict(signal=sig.name, stop_fails=stop_fails,
signal_to_exit_seconds=round(elapsed, 4), passed=True,
observations=events))
finally:
if process.poll() is None:
process.kill()
process.wait(timeout=3)
reader.join(1)
process.stdout.close()
print(json.dumps(dict(cases=results, paid_calls=0,
scope='real lifecycle and gateway; fixture runtime and upstream HTTP')))
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == '--child':
child(bool(int(sys.argv[2])))
else:
main()
@@ -0,0 +1,82 @@
"""Actual pinned Chat and SDK request inspection; HTTP is fixture-only."""
import json
from queue import Queue
from threading import Event
from types import SimpleNamespace
import httpx
from openai import OpenAI
from openai.types.realtime import RealtimeConversationItemFunctionCall, RealtimeConversationItemFunctionCallOutput
from services.local_s2s.history import RetainedHistory, MARKER
from speech_to_speech.LLM.chat import Chat, make_user_message, make_assistant_message
from speech_to_speech.LLM.chat_completions_language_model import ChatCompletionsApiModelHandler
import speech_to_speech.LLM.base_openai_compatible_language_model as base
from services.local_s2s.request_policy import install_client_policy
requests=[]
def fixture(request):
requests.append(json.loads(request.content))
return httpx.Response(200,json={'id':'fixture','object':'chat.completion','created':0,
'model':'fixture/llm','choices':[{'index':0,'message':{'role':'assistant','content':'fixture'},'finish_reason':'stop'}]})
native_factory=base.OpenAI
clients=[]
def factory(*args,**kwargs):
client=httpx.Client(transport=httpx.MockTransport(fixture),trust_env=False);clients.append(client)
return OpenAI(*args,**kwargs,http_client=client)
base.OpenAI=factory
install_client_policy(base,SimpleNamespace(local_s2s_request_timeout_seconds=7,local_s2s_max_output_tokens=17))
handler=ChatCompletionsApiModelHandler(Event(),Queue(),Queue(),setup_kwargs=dict(
model_name='fixture/llm',device='cpu',base_url='http://127.0.0.1:9/v1',api_key='fixture',stream=False))
try:
for cancelled in (False,True):
chat=Chat(10)
previous=make_user_message('PRIOR_USER');chat.add_item(previous)
valid=make_assistant_message('PRIOR_VALID_ANSWER');chat.add_item(valid)
chat.add_item(RealtimeConversationItemFunctionCall(type='function_call',call_id='call_keep',name='search_knowledge',arguments='{}'))
chat.add_item(RealtimeConversationItemFunctionCallOutput(type='function_call_output',call_id='call_keep',output='VALID_TOOL_RESULT'))
question=make_user_message('SAME_QUESTION');chat.add_item(question)
draft=make_assistant_message('UNHEARD_SENTINEL answer retained for repetition.');draft.id='native-draft'
chat.add_provisional_generation_items('key',[draft],after_item_id=question.id)
state=RetainedHistory();state.remember('response',[draft],['wire-item'],question.id)
if cancelled:
chat.rollback_provisional_generation('key')
else:
wire=make_assistant_message('wire');wire.id='wire-item'
chat.bind_assistant_item_ids('key',[wire]);chat.finalize_provisional_generation('key')
following=make_user_message('FOLLOWUP_USER');chat.add_item(following)
request=dict(type='s2s.history.retain',event_id='op',session_id='backend',engine_session_id='native',
generation=1,response_id='response',item_id='wire-item',content_index=0,audio_end_ms=100)
before=chat.to_transformers_chat()
for field,value in [('session_id',''),('engine_session_id','wrong'),('response_id','wrong'),('item_id','wrong'),('content_index',True),('audio_end_ms',-1)]:
invalid=dict(request);invalid[field]=value
try:state.apply(chat,invalid,'native')
except ValueError:pass
else:raise AssertionError('invalid repair accepted')
assert chat.to_transformers_chat()==before
receipt=state.apply(chat,request,'native')
assert receipt['applied'] and receipt['history_revision']==1
assert state.apply(chat,request,'native')==receipt
messages=chat.to_transformers_chat()
handler._request(messages,{})
actual=requests[-1]['messages']
serialized=json.dumps(actual)
assert all(text in serialized for text in ('PRIOR_USER','PRIOR_VALID_ANSWER','SAME_QUESTION','FOLLOWUP_USER','VALID_TOOL_RESULT'))
assert serialized.index('UNHEARD_SENTINEL')<serialized.index('FOLLOWUP_USER')
retained=[m for m in actual if 'UNHEARD_SENTINEL' in str(m.get('content',''))]
assert len(retained)==1 and MARKER in retained[0]['content']
assert state.records['response']['items'][0].content[0].text.startswith('UNHEARD_SENTINEL')
assert all(MARKER not in m['content'] for m in actual if m['role']=='user')
print(json.dumps(dict(case='cancelled_active' if cancelled else 'completed_unplayed',
next_actual_http_request_verified=True,raw_answer_retained=True,heard_delivery_claim=False,paid_calls=0)))
# A new operation cannot attest an annotation that disappeared.
with chat._lock:
target=next(item for item in chat.buffer if getattr(item,'role',None)=='assistant' and any((part.text or '').startswith(MARKER) for part in item.content))
target.content[0]=target.content[0].model_copy(update={'text':'CONTROLLED_STALE_REWRITE'})
unchanged=chat.to_transformers_chat()
try:state.apply(chat,dict(request,event_id='new-op'),'native')
except ValueError:pass
else:raise AssertionError('lost annotation attested')
assert state.revision==1 and chat.to_transformers_chat()==unchanged
chat.close()
finally:
handler.cleanup()
for client in clients:client.close()
@@ -0,0 +1,65 @@
"""Actual pinned handler + OpenAI SDK; only HTTP I/O is replaced with fixtures."""
import json
from queue import Queue
from threading import Event
from types import SimpleNamespace
import httpx
from openai import OpenAI, APIConnectionError, APIStatusError
import speech_to_speech.LLM.base_openai_compatible_language_model as base
from speech_to_speech.LLM.chat_completions_language_model import ChatCompletionsApiModelHandler
from services.local_s2s.request_policy import install_client_policy
original_factory, original_setup = base.OpenAI, base.BaseOpenAICompatibleHandler.setup
results = []
for limit in (17, 83):
for outcome in ('ok', 'http503', 'connect'):
calls, clients = [], []
def fixture(request):
calls.append(json.loads(request.content))
if outcome == 'connect':
raise httpx.ConnectError('controlled fixture', request=request)
if outcome == 'http503':
return httpx.Response(503, json={'error': {'message': 'fixture'}})
return httpx.Response(200, json={
'id': 'fixture', 'object': 'chat.completion', 'created': 0,
'model': 'fixture/model', 'choices': [{'index': 0,
'message': {'role': 'assistant', 'content': 'fixture'},
'finish_reason': 'stop'}]})
def factory(*args, **kwargs):
client = httpx.Client(transport=httpx.MockTransport(fixture), trust_env=False)
clients.append(client)
return OpenAI(*args, **kwargs, http_client=client)
base.OpenAI = factory
config = SimpleNamespace(local_s2s_request_timeout_seconds=7,
local_s2s_max_output_tokens=limit)
install_client_policy(base, config)
try:
try:
handler = ChatCompletionsApiModelHandler(Event(), Queue(), Queue(),
setup_kwargs=dict(model_name='fixture/model', device='cpu',
base_url='http://127.0.0.1:9/v1', api_key='fixture', stream=False))
except (APIConnectionError, APIStatusError):
assert outcome != 'ok' and len(calls) == 1
else:
try:
assert outcome == 'ok'
assert handler.request_timeout_s == 7
assert handler.client.max_retries == 0
handler._request([{'role': 'user', 'content': 'fixture'}],
{'max_tokens': 999, 'max_completion_tokens': 999})
assert len(calls) == 2
finally:
handler.cleanup()
assert calls and all(c['max_tokens'] == limit for c in calls)
assert all('max_completion_tokens' not in c for c in calls)
results.append(dict(limit=limit, outcome=outcome, attempts=len(calls), passed=True))
finally:
base.OpenAI = original_factory
base.BaseOpenAICompatibleHandler.setup = original_setup
for client in clients:
client.close()
print(json.dumps(dict(cases=results, paid_calls=0, http_io='controlled HTTPX fixtures')))
@@ -0,0 +1,342 @@
"""Actual native session/audio conformance; upstream provider HTTP is controlled.
Requires read-only real assets and /checks/input.pcm (24k mono PCM16). No real
provider key or external network. Argument: normal, failure, sigint, sigterm.
"""
import asyncio
import base64
import faulthandler
from collections import Counter
from copy import deepcopy
import hashlib
import json
import logging
import os
from pathlib import Path
import signal
import socket
import sys
from threading import Event, Thread
import time
import traceback
import httpx
import nltk
from websockets.asyncio.client import connect
from app.infrastructure.local_s2s import LocalS2SAdapter
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.settings import RuntimeSettings
from services.local_s2s.assets import configure_nltk, validate_assets
from services.local_s2s.components import ComponentServer
from services.local_s2s.engine import build_runtime
import services.local_s2s.lifecycle as lifecycle
mode = sys.argv[1] if len(sys.argv) > 1 else 'normal'
assert mode in ('normal', 'failure', 'sigint', 'sigterm', 'real')
logging.disable(logging.CRITICAL)
real = mode == 'real'
duplex = '--duplex' in sys.argv
retention = '--retention' in sys.argv or '--retention-active' in sys.argv
retention_active = '--retention-active' in sys.argv
responsive = '--responsive' in sys.argv
assert not (retention and real)
assert not (duplex and real)
models = ('openai/whisper-large-v3', 'openai/gpt-4.1-mini', 'google/gemini-3.8-flash-lite-tts', 'Kore') if real else ('fixture/stt', 'fixture/llm', 'fixture/tts', 'fixture')
timeout = 30 if real or duplex else 7
limit = 128 if real else 17
os.environ.update(LOCAL_S2S_SILERO_SOURCE='/vad/silero-vad',
LOCAL_S2S_STT_MODEL=models[0], LOCAL_S2S_LLM_MODEL=models[1],
LOCAL_S2S_TTS_MODEL=models[2], LOCAL_S2S_TTS_VOICE=models[3],
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS=str(timeout))
fingerprint = validate_assets('/assets/nltk', '/vad/silero-vad', '/assets/assets.json')
configure_nltk(nltk, '/assets/nltk')
config = VoiceSettings(_env_file=None, provider='local_s2s', local_s2s_enabled=True,
voice_transport_testing=True, local_s2s_token='fixture-engine-token',
local_s2s_stt_model=models[0], local_s2s_llm_model=models[1],
local_s2s_tts_model=models[2], local_s2s_tts_voice=models[3],
local_s2s_request_timeout_seconds=timeout, local_s2s_max_output_tokens=limit,
local_s2s_retain_interrupted_answers=retention, local_s2s_responsive=responsive)
config.require_voice()
adapter = LocalS2SAdapter(None, config=config, settings=RuntimeSettings(_env_file=None))
calls, events, logs, owned = [], [], [], {}
provider_payloads = []
inflight, cancelled, client_done = Event(), Event(), Event()
late_release = Event()
fixture_text = 'RETAINED_UNHEARD_SENTINEL.' if retention else 'سلام.'
# A tone tests nonzero PCM transport, not synthesized speech quality.
import numpy as np
pcm = (np.sin(2 * np.pi * 440 * np.arange(4800) / 24000) * 2000).astype('<i2').tobytes()
async def upstream(request):
path = request.url.path
calls.append(path)
if path.endswith('/audio/transcriptions'):
return httpx.Response(200, json={'text': 'آزمایش محلی'})
if path.endswith('/audio/speech'):
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=pcm)
payload = json.loads(request.content)
provider_payloads.append(payload)
assert path.endswith('/chat/completions') and payload['max_tokens'] == 17
if not payload.get('stream'):
return httpx.Response(200, json={
'id': 'fixture', 'object': 'chat.completion', 'created': 0, 'model': 'fixture/llm',
'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': 'fixture'},
'finish_reason': 'stop'}]})
if mode == 'failure':
return httpx.Response(503, json={'error': {'message': 'controlled provider failure'}})
if mode in ('sigint', 'sigterm'):
inflight.set()
try:
await asyncio.Event().wait()
finally:
cancelled.set()
chunks = [dict(id='fixture', object='chat.completion.chunk', created=0, model='fixture/llm',
choices=[dict(index=0, delta=dict(role='assistant', content=fixture_text), finish_reason=None)]),
dict(id='fixture', object='chat.completion.chunk', created=0, model='fixture/llm',
choices=[dict(index=0, delta={}, finish_reason='stop')])]
data = ''.join('data: ' + json.dumps(c) + '\n\n' for c in chunks) + 'data: [DONE]\n\n'
if retention_active and len(provider_payloads)==3:
class InterruptedStream(httpx.AsyncByteStream):
async def __aiter__(self):
initial=deepcopy(chunks[0])
initial['choices'][0]['delta']['content']=fixture_text+(' Pending fragment' if responsive else ' One preserved sentence. Another preserved sentence. Pending fragment')
yield ('data: '+json.dumps(initial)+'\n\n').encode()
try:
while not late_release.is_set():
yield b': keepalive\n\n'
await asyncio.sleep(.1)
stale=deepcopy(chunks[0]);stale['choices'][0]['delta']['content']='STALE_OUTPUT_SENTINEL.'
yield ('data: '+json.dumps(stale)+'\n\n'+'data: '+json.dumps(chunks[1])+'\n\ndata: [DONE]\n\n').encode()
finally:
cancelled.set()
return httpx.Response(200,headers={'content-type':'text/event-stream'},stream=InterruptedStream())
if duplex:
class SlowStream(httpx.AsyncByteStream):
async def __aiter__(self):
for _ in range(12):
yield b': keepalive\n\n'
await asyncio.sleep(1)
yield data.encode()
return httpx.Response(200, headers={'content-type':'text/event-stream'},stream=SlowStream())
return httpx.Response(200, headers={'content-type': 'text/event-stream'}, content=data.encode())
def start_components(key, timeout):
if real:
import importlib.util
spec = importlib.util.spec_from_file_location('native_budget', '/checks/native-budget-transport.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
transport = module.BudgetTransport(Path('/evidence'), Path('/evidence/live-components-one-dollar-ledger.json'))
else:
transport = httpx.MockTransport(upstream)
class OwnedGateway(ComponentServer):
async def _run(self):
try:
await super()._run()
finally:
if real:
await transport.close_owned()
guard = OwnedGateway(key, port=8766, transport=transport, timeout=timeout, responsive=responsive)
thread = Thread(target=guard.serve_forever, daemon=True)
thread.start()
assert guard.ready.wait(3)
owned.update(guard=guard, gateway_thread=thread)
return guard, thread
def build(stop):
runtime = build_runtime(config, stop)
owned.update(runtime=runtime, stop=stop, unit=runtime.server.pool[0])
return runtime
def emit(value, **kwargs):
logs.append(json.loads(value))
print(value, **kwargs)
async def receive(ws):
event = json.loads(await asyncio.wait_for(ws.recv(), 40 if real or duplex else 12))
events.append(event)
if event.get('type') == 'error' and mode != 'failure':
raise AssertionError(json.dumps(event))
return event
async def until(ws, kind):
async with asyncio.timeout(70 if real or duplex else 15):
while True:
event = await receive(ws)
if event.get('type') == kind:
return event
async def session():
deadline = time.monotonic() + 100
while True:
try:
with socket.create_connection(('127.0.0.1', 8765), timeout=.2):
break
except OSError:
assert time.monotonic() < deadline, 'native listener startup deadline'
await asyncio.sleep(.05)
async with connect('ws://127.0.0.1:8765/v1/realtime', proxy=None, compression=None,
additional_headers={'Authorization': 'Bearer fixture-engine-token'},
close_timeout=2) as ws:
await until(ws, 'session.created')
await ws.send(json.dumps(adapter.setup()))
updated = await until(ws, 'session.updated')
assert adapter.acknowledged(updated['session']), 'native setup attestation mismatch'
mismatched = deepcopy(adapter.setup())
mismatched['session']['model'] = 'fixture/other'
await ws.send(json.dumps(mismatched))
changed = await until(ws, 'session.updated')
assert not adapter.acknowledged(changed['session']), 'model mismatch incorrectly accepted'
await ws.send(json.dumps(adapter.setup()))
restored = await until(ws, 'session.updated')
assert adapter.acknowledged(restored['session']), 'correct setup did not restore admission'
owned['mismatch_rejected'] = True
raw = Path('/checks/input.pcm').read_bytes() + bytes(24000 * 2)
for offset in range(0, len(raw), 4800):
await ws.send(json.dumps(dict(type='input_audio_buffer.append',
audio=base64.b64encode(raw[offset:offset+4800]).decode())))
await ws.send(json.dumps(dict(type='input_audio_buffer.commit')))
transcription = await until(ws, 'conversation.item.input_audio_transcription.completed')
committed = [e for e in events if e['type'] == 'input_audio_buffer.committed']
assert committed and committed[-1]['item_id'] == transcription['item_id']
assert transcription['transcript'].strip() if real else transcription['transcript'] == 'آزمایش محلی'
assert not any(e['type'] == 'response.created' for e in events)
assert (owned['guard'].counts['/v1/chat/completions'] if real else calls.count('/api/v1/chat/completions')) == 1, 'automatic response before manual create'
response = dict(metadata=dict(voice_intent='fixture-intent-1'))
if real:
response.update(instructions='فقط بگو: سلام، صدای شما دریافت شد.', tool_choice='none')
await ws.send(json.dumps(dict(type='response.create', event_id='fixture-create-1', response=response)))
if duplex:
async def microphone():
count=0
try:
while True:
await asyncio.wait_for(ws.send(json.dumps(dict(type='input_audio_buffer.append',audio=base64.b64encode(bytes(960)).decode()))),5)
count+=1
await asyncio.sleep(.02)
finally:
owned['duplex_frames']=count
mic=asyncio.create_task(microphone())
owned['mic_task']=mic
if mode in ('sigint', 'sigterm'):
assert await asyncio.to_thread(inflight.wait, 5), 'no in-flight provider fixture'
owned['signal_at'] = time.monotonic()
os.kill(os.getpid(), signal.SIGINT if mode == 'sigint' else signal.SIGTERM)
# Remain connected until the owned server closes this native session.
try:
await until(ws, 'response.done')
except Exception:
pass
return
done = await until(ws, 'response.done')
created = next(e for e in events if e['type'] == 'response.created')
assert created['response']['metadata']['voice_intent'] == 'fixture-intent-1'
assert done['response']['metadata']['voice_intent'] == 'fixture-intent-1'
owned['intent_correlated'] = True
if mode == 'failure':
assert done['response']['status'] == 'failed', done
assert calls.count('/api/v1/chat/completions') == 2, 'provider failure was retried'
owned['failure_verified'] = True
else:
assert done['response']['status'] == 'completed', done
response_id = done['response']['id']
audio = [e for e in events if e['type'] == 'response.output_audio.delta']
assert audio and all(e['response_id'] == response_id for e in audio)
output = b''.join(base64.b64decode(e['delta']) for e in audio)
assert output and len(output) % 2 == 0 and any(output)
transcripts = [e for e in events if e['type'] == 'response.output_audio_transcript.done']
assert transcripts and (transcripts[-1]['transcript'].strip() if real else transcripts[-1]['transcript'] == fixture_text)
if real:
import wave
with wave.open('/evidence/native-real-output.wav', 'wb') as saved:
saved.setnchannels(1); saved.setsampwidth(2); saved.setframerate(24000)
saved.writeframes(output)
owned['audio_result'] = dict(bytes=len(output), samples=len(output)//2,
sha256=hashlib.sha256(output).hexdigest())
owned['normal_complete'] = True
if retention:
from app.modules.voice.provider import HistoryRepair
from app.modules.voice.local_s2s import DRAFT_MARKER
item=audio[0]['item_id']
repair=HistoryRepair('fixture-backend',1,response_id,'retain-op-1',item,0,10)
adapter.transport=ws
await adapter.send(adapter.history_repair_request(repair))
proof=await until(ws,'s2s.history.retained')
normalized=dict(proof,type='conversation.item.truncated',s2s_native_type=proof['type'])
assert adapter.confirm_history_repair(repair,normalized).repair==repair
await ws.send(json.dumps(dict(type='response.create',event_id='repeat-create',
response=dict(metadata=dict(voice_intent='repeat-intent')))))
if retention_active:
active_created=await until(ws,'response.created')
active_audio=await until(ws,'response.output_audio.delta')
await adapter.send(adapter.cancellation_request(active_created['response']['id'],'active-cancel'))
active_done=await until(ws,'response.done')
assert active_done['response']['status']=='cancelled'
late_release.set()
repair2=HistoryRepair('fixture-backend',2,active_created['response']['id'],
'retain-op-2',active_audio['item_id'],0,10)
await adapter.send(adapter.history_repair_request(repair2))
proof2=await until(ws,'s2s.history.retained')
adapter.confirm_history_repair(repair2,dict(proof2,type='conversation.item.truncated',s2s_native_type=proof2['type']))
await ws.send(json.dumps(dict(type='response.create',event_id='after-active-create',
response=dict(metadata=dict(voice_intent='after-active')))))
repeated=await until(ws,'response.done')
assert repeated['response']['status']=='completed'
actual=provider_payloads[-1]['messages']
drafts=[m for m in actual if m.get('role')=='assistant' and fixture_text in str(m.get('content',''))]
assert drafts and all(DRAFT_MARKER in m['content'] for m in drafts)
if retention_active:
assert len(drafts)==2
assert 'STALE_OUTPUT_SENTINEL' not in json.dumps(actual)
owned['active_retention_verified']=True
assert any(m.get('role')=='user' for m in actual)
owned['retention_verified']=True
if duplex:
mic.cancel()
await asyncio.gather(mic,return_exceptions=True)
assert owned.get('duplex_frames',0)>=500
deadline = time.monotonic() + 12
while owned['unit'].session is not None:
assert time.monotonic() < deadline, 'native unit did not release after normal close'
await asyncio.sleep(.05)
owned['unit_released'] = True
def client():
try:
asyncio.run(session())
except BaseException:
owned['client_error'] = traceback.format_exc()
faulthandler.dump_traceback(file=sys.stderr, all_threads=True)
finally:
client_done.set()
if 'stop' in owned:
owned['stop'].set()
lifecycle.start_components = start_components
worker = Thread(target=client, daemon=True)
worker.start()
key = Path('/secret/openrouter-test.key').read_text().strip() if real else 'offline-fixture-key'
outcome = lifecycle.run_owned(build, key, timeout, emit=emit)
worker.join(15)
summary = dict(responsive=responsive, single_sentence_probe=responsive and retention_active, active_retention_verified=owned.get('active_retention_verified',False), retention_verified=owned.get('retention_verified',False), mode=mode, duplex=duplex, duplex_frames=owned.get('duplex_frames',0), lifecycle_outcome=outcome, client_done=client_done.is_set(),
client_error=owned.get('client_error'), events=dict(Counter(e['type'] for e in events)),
native_events=[{k:v for k,v in e.items() if k != 'delta'} if e['type'] == 'response.output_audio.delta' else e for e in events] if real else events, fixture_attempts=dict(Counter(calls)),
fixture_llm_payloads=provider_payloads,
final_cleanup=logs[-1] if logs else None, manifest_sha256=fingerprint,
audio_result=owned.get('audio_result'), normal_complete=owned.get('normal_complete', False),
unit_released=owned.get('unit_released', False), fixture_cancelled=cancelled.is_set(),
failure_verified=owned.get('failure_verified', False),
mismatch_rejected=owned.get('mismatch_rejected', False),
intent_correlated=owned.get('intent_correlated', False),
runtime_state=owned['runtime'].state if 'runtime' in owned else None,
paid_calls=sum(owned['guard'].counts[p] for p in ('/v1/audio/speech','/v1/audio/transcriptions','/v1/chat/completions')) if real else 0,
external_network='OpenRouter only via guarded transport' if real else 'none')
if 'signal_at' in owned:
summary['signal_to_cleanup_seconds'] = round(time.monotonic()-owned['signal_at'], 4)
print(json.dumps(dict(stage='session_result', **summary)), flush=True)
assert outcome == 0 and not owned.get('client_error') and client_done.is_set()
assert not owned['gateway_thread'].is_alive() and not owned['guard'].requests
if mode in ('normal', 'failure', 'real'):
assert (owned.get('normal_complete') or owned.get('failure_verified')) and owned['unit_released']
else:
assert cancelled.is_set()
@@ -0,0 +1,203 @@
"""Bounded three-stage component test; no engine startup or automatic retry.
Run from the repo root. Credential lives only in ignored local storage. A fresh
exclusive ledger prevents accidentally re-running the paid sequence. --check
validates the captured prices and budget without reading the credential.
"""
import argparse
from decimal import Decimal
from io import BytesIO
import json
from pathlib import Path
import time
import wave
import httpx
if not __debug__:
raise RuntimeError('Budget checks require Python assertions enabled')
ROOT = Path('.local-s2s-build')
LEDGER = ROOT / 'live-components-one-dollar-ledger.json'
API = 'https://openrouter.ai/api/v1/'
RESERVES = {'tts': Decimal('.25'), 'stt': Decimal('.05'), 'llm': Decimal('.01')}
TEXT = 'سلام، این یک آزمایش کوتاه برای بررسی صدای فارسی است.'
def validate_budget():
assert sum(RESERVES.values()) <= Decimal('1')
tts = json.loads((ROOT / 'endpoints-google-gemini-3.8-flash-lite-tts.json').read_text())['data']['endpoints']
assert 0 < len(tts) <= 2
full = Decimal('0')
for endpoint in tts:
assert endpoint['max_completion_tokens'] == 16384 and endpoint['max_prompt_tokens'] == 8192
p = endpoint['pricing']
assert Decimal(p['prompt']) <= Decimal('.0000005')
assert Decimal(p['completion']) <= Decimal('.000006')
assert Decimal(str(p.get('request', 0))) == 0
full += Decimal(p['prompt']) * 8192 + Decimal(p['completion']) * 16384
# Reserve even a full model-size result at each currently listed TTS endpoint.
assert full < RESERVES['tts']
stt = json.loads((ROOT / 'endpoints-openai-whisper-large-v3.json').read_text())['data']['endpoints']
assert 0 < len(stt) <= 3
assert all(Decimal(e['pricing']['prompt']) <= Decimal('.000031') for e in stt)
# Up to ten seconds of audio; reserve far above a full minute on every route.
assert sum(Decimal(e['pricing']['prompt']) * 60 for e in stt) < RESERVES['stt']
assert Decimal('.000001') * 8192 + Decimal('.000002') * 128 < RESERVES['llm']
return {'budget_usd': '1', 'total_reserved_usd': str(sum(RESERVES.values())),
'tts_full_endpoint_maxima_usd': str(full), 'requests_max': 3,
'provider_enforced_test_cap': False,
'basis': 'Published endpoint limits/prices, bounded input, fixed requests and no client retries; shared key retains its existing $5 cap.'}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true')
parser.add_argument('--resume-pcm', action='store_true', help='Explicit format correction after the sole WAV HTTP400; not an automatic retry.')
args = parser.parse_args()
budget = validate_budget()
if args.check:
print(json.dumps(budget))
return
if args.resume_pcm:
state = json.loads(LEDGER.read_text())
assert state['status']=='failed_stopped_no_retry' and state['paid_attempts']==1
assert state['stages'][0]['http_status']==400 and state['reserved_usd']=='0.25'
state['format_correction']='Explicit PCM request matching native engine after WAV HTTP400; initial error body was not retained.'
state['budget'].update(requests_max=4, maximum_execution_reserved_usd='0.56')
else:
state = dict(budget=budget, stages=[], status='started', paid_attempts=0,
reserved_usd='0', speech_text=TEXT)
with LEDGER.open('x') as f:
json.dump(state, f, indent=2)
key = (ROOT / 'openrouter-test.key').read_text().strip()
def save():
temporary = LEDGER.with_suffix('.tmp')
temporary.write_text(json.dumps(state, indent=2, ensure_ascii=False)+'\n')
temporary.replace(LEDGER)
def metadata(client):
response = client.get(API+'key')
response.raise_for_status()
data = response.json()['data']
return {k: data.get(k) for k in ('usage', 'limit', 'limit_remaining', 'limit_reset')}
def request(client, stage, endpoint, max_bytes, **kwargs):
amount = RESERVES['tts'] if stage == 'tts_pcm' else RESERVES[stage]
assert stage not in [s['stage'] for s in state['stages']]
reserved = Decimal(state['reserved_usd']) + amount
assert reserved <= Decimal('1') and state['paid_attempts'] < state['budget']['requests_max']
row = dict(stage=stage, reserved_usd=str(amount), status='in_flight')
state['stages'].append(row)
state.update(reserved_usd=str(reserved), paid_attempts=state['paid_attempts']+1)
save() # persist admission before sending, including failures/timeouts
began = time.monotonic()
try:
with client.stream('POST', API+endpoint, **kwargs) as response:
row['http_status'] = response.status_code
row['headers'] = {k: v for k,v in response.headers.items() if
k in ('content-type','content-length','x-request-id','x-generation-id',
'x-openrouter-request-id','x-audio-sample-rate')}
if response.status_code != 200:
error_body = bytearray()
for chunk in response.iter_bytes(1024):
error_body.extend(chunk)
if len(error_body) > 8192:
break
try:
error = json.loads(error_body).get('error', {})
row['provider_error'] = {k: str(error[k]).replace(key, '[redacted]')[:1000]
for k in ('code','message') if k in error}
except (ValueError, AttributeError, TypeError):
row['provider_error'] = 'unparseable'
response.raise_for_status()
body = bytearray()
for part in response.iter_bytes(8192):
assert time.monotonic()-began <= 30, 'stage wall deadline'
assert len(body)+len(part) <= max_bytes, 'response capacity'
body.extend(part)
row.update(status='received', bytes=len(body), elapsed_seconds=round(time.monotonic()-began, 3))
return bytes(body), response.headers.get('content-type','').split(';')[0]
except BaseException as exc:
row.update(status='failed', error_type=type(exc).__name__)
raise
finally:
save()
transport = httpx.HTTPTransport(retries=0)
with httpx.Client(transport=transport, timeout=30, trust_env=False,
follow_redirects=False, headers={'Authorization': 'Bearer '+key}) as client:
try:
if args.resume_pcm:
state['resume_key_preflight'] = metadata(client)
else:
state['key_before'] = metadata(client)
save()
assert state['key_before']['limit_remaining'] is not None
assert Decimal(str(state['key_before']['limit_remaining'])) >= sum(RESERVES.values())
raw, media = request(client, 'tts_pcm' if args.resume_pcm else 'tts', 'audio/speech', 484096,
json=dict(model='google/gemini-3.8-flash-lite-tts', voice='Kore',
input=TEXT, response_format='pcm' if args.resume_pcm else 'wav'))
native_header = raw.startswith(b'RIFF')
if args.resume_pcm and not native_header:
assert media in ('audio/pcm','application/octet-stream','audio/l16')
assert raw and len(raw) % 2 == 0 and len(raw) <= 480000
output = BytesIO()
with wave.open(output,'wb') as audio:
audio.setnchannels(1); audio.setsampwidth(2); audio.setframerate(24000)
audio.writeframes(raw)
raw = output.getvalue()
else:
assert media in ('audio/wav','audio/x-wav','audio/wave'), 'self-describing WAV required'
with wave.open(BytesIO(raw), 'rb') as audio:
channels, width, rate, frames = audio.getnchannels(), audio.getsampwidth(), audio.getframerate(), audio.getnframes()
assert channels == 1 and width == 2 and rate == 24000 and audio.getcomptype() == 'NONE'
assert 0 < frames <= 240000, 'audio duration exceeds 10s'
pcm = audio.readframes(frames)
assert len(pcm) == frames * 2 and any(pcm)
path = ROOT / 'persian-real-tts-one-dollar.wav'
with path.open('xb') as f:
f.write(raw)
state['tts_artifact'] = dict(path=str(path), header_rate=rate,
frames=frames, seconds=frames/rate,
rate_independently_verified=native_header,
pcm_native_path_tested=args.resume_pcm and not native_header)
save()
raw, media = request(client, 'stt', 'audio/transcriptions', 65536,
files={'file': ('generated-persian.wav', path.read_bytes(), 'audio/wav')},
data={'model': 'openai/whisper-large-v3', 'language': 'fa', 'response_format': 'json'})
assert media == 'application/json'
stt = json.loads(raw)
text = stt['text']
assert isinstance(text,str) and 0 < len(text) <= 1024
state['stt_result'] = stt
save()
raw, media = request(client, 'llm', 'chat/completions', 65536,
json=dict(model='openai/gpt-4.1-mini', stream=False, max_tokens=128,
provider={'allow_fallbacks': False, 'max_price': {'prompt': 1, 'completion': 2}},
messages=[dict(role='system', content='Reply with one short Persian greeting. No factual or document claims.'),
dict(role='user', content=text)]))
assert media == 'application/json'
llm = json.loads(raw)
assert llm['choices'][0]['finish_reason'] == 'stop'
state['llm_result'] = llm
state['status'] = 'components_completed_listening_pending'
state.pop('error_type', None)
except BaseException as exc:
state.update(status='failed_stopped_no_retry', error_type=type(exc).__name__)
finally:
try:
state['key_after'] = metadata(client)
state['observed_key_usage_delta_usd'] = str(Decimal(str(state['key_after']['usage']))-Decimal(str(state['key_before']['usage'])))
except Exception as exc:
state['usage_check_error_type'] = type(exc).__name__
save()
print(json.dumps({'status':state['status'],'paid_attempts':state['paid_attempts'],
'reserved_usd':state['reserved_usd'],
'observed_key_usage_delta_usd':state.get('observed_key_usage_delta_usd')}))
if state['status'] != 'components_completed_listening_pending':
raise SystemExit(1)
if __name__ == '__main__':
main()
@@ -0,0 +1,137 @@
"""Evaluation-only admission guard; never imported by the operational engine.
Persistent reservations include failed requests. Exactly two attempts per component
cover construction probes and one turn. No retries or ledger reset are supported.
"""
from decimal import Decimal
import base64
from io import BytesIO
import json
from pathlib import Path
import time
import wave
from email.parser import BytesParser
from email.policy import default
import httpx
RESERVES = {'speech': Decimal('.205'), 'transcriptions': Decimal('.004'),
'completions': Decimal('.01')}
MODELS = {'speech': 'google/gemini-3.8-flash-lite-tts',
'transcriptions': 'openai/whisper-large-v3',
'completions': 'openai/gpt-4.1-mini'}
def require(condition):
if not condition:
raise ValueError('EVALUATION_BUDGET_ADMISSION_DENIED')
def validate_prices(root):
tts = json.loads((root/'endpoints-google-gemini-3.8-flash-lite-tts.json').read_text())['data']['endpoints']
stt = json.loads((root/'endpoints-openai-whisper-large-v3.json').read_text())['data']['endpoints']
require(0 < len(tts) <= 2 and 0 < len(stt) <= 3)
full = Decimal(0)
for e in tts:
require(e['max_prompt_tokens'] == 8192 and e['max_completion_tokens'] == 16384)
require(Decimal(e['pricing']['prompt']) <= Decimal('.0000005') and
Decimal(e['pricing']['completion']) <= Decimal('.000006'))
require(Decimal(str(e['pricing'].get('request', 0))) == 0)
full += Decimal(e['pricing']['prompt'])*8192 + Decimal(e['pricing']['completion'])*16384
require(full < RESERVES['speech'])
require(all(Decimal(e['pricing']['prompt']) <= Decimal('.000031') and
Decimal(str(e['pricing'].get('request', 0))) == 0 for e in stt))
require(sum(Decimal(e['pricing']['prompt'])*60 for e in stt) < RESERVES['transcriptions'])
require(Decimal('.000001')*8192 + Decimal('.000002')*128 < RESERVES['completions'])
return full
def validate_request(request):
stage = request.url.path.rsplit('/', 1)[-1]
require(request.method == 'POST' and request.url.host == 'openrouter.ai' and
request.url.scheme == 'https' and request.url.path in (
'/api/v1/audio/speech', '/api/v1/audio/transcriptions', '/api/v1/chat/completions'))
if stage == 'transcriptions':
if request.headers.get('content-type','').startswith('application/json'):
from app.modules.voice.local_s2s import RESPONSIVE_ASR_PROMPT
data=json.loads(request.content)
require(set(data)=={'model','language','response_format','temperature','input_audio','provider'} and
data['model']==MODELS[stage] and data['language']=='fa' and data['response_format']=='json' and
type(data['temperature']) is int and data['temperature']==0 and
data['provider']=={'options':{'groq':{'prompt':RESPONSIVE_ASR_PROMPT}}} and
set(data['input_audio'])=={'data','format'} and data['input_audio']['format']=='wav')
fields={'file':base64.b64decode(data['input_audio']['data'],validate=True)}
else:
message = BytesParser(policy=default).parsebytes(
('Content-Type: '+request.headers['content-type']+'\r\nMIME-Version: 1.0\r\n\r\n').encode()+request.content)
fields = {p.get_param('name', header='content-disposition'): p.get_payload(decode=True)
for p in message.iter_parts()}
require(fields['model'].decode() == MODELS[stage] and fields['language'] == b'fa')
with wave.open(BytesIO(fields['file']), 'rb') as audio:
require(audio.getnchannels() == 1 and audio.getsampwidth() == 2 and
audio.getcomptype() == 'NONE' and
0 < audio.getnframes()/audio.getframerate() <= 10)
else:
data = json.loads(request.content)
require(data['model'] == MODELS[stage])
if stage == 'speech':
require(data['voice'] == 'Kore' and data['response_format'] == 'pcm' and
0 < len(data['input'].encode()) <= 4096)
else:
require(0 < data['max_tokens'] <= 128 and
len(json.dumps(data, ensure_ascii=False).encode()) <= 8192)
# Price caps are enforced on the actual provider-bound request only.
data['provider'] = {'allow_fallbacks': False, 'max_price': {'prompt': 1, 'completion': 2}}
request = httpx.Request('POST', request.url,
headers={k:v for k,v in request.headers.items() if k != 'content-length'},
content=json.dumps(data).encode())
return stage, request
class BudgetTransport(httpx.AsyncBaseTransport):
def __init__(self, root, previous, *, upstream=None):
validate_prices(root)
self.path = root/'native-paid-ledger.json'
prior = json.loads(previous.read_text())
# Preserve the original run's entire reservation, even unknown TTS cost.
require(prior['reserved_usd'] == '0.56' and prior['paid_attempts'] == 4)
self.state = {'previous_reserved_usd': prior['reserved_usd'], 'reserved_usd': '0.56',
'maximum_cumulative_reserved_usd': '0.998', 'attempts': []}
require(Decimal('.56') + 2*sum(RESERVES.values()) == Decimal('.998'))
with self.path.open('x') as output:
json.dump(self.state, output, indent=2)
self.upstream = upstream or httpx.AsyncHTTPTransport(retries=0, trust_env=False)
def save(self):
temporary = self.path.with_suffix('.tmp')
temporary.write_text(json.dumps(self.state, indent=2)+'\n')
temporary.replace(self.path)
async def handle_async_request(self, request):
stage, request = validate_request(request)
require(sum(row['stage'] == stage for row in self.state['attempts']) < 2)
total = Decimal(self.state['reserved_usd']) + RESERVES[stage]
require(total <= Decimal('1'))
row = {'stage': stage, 'reserved_usd': str(RESERVES[stage]), 'status': 'in_flight'}
self.state['attempts'].append(row)
self.state['reserved_usd'] = str(total)
self.save() # Synchronous admission on the single gateway event loop.
began = time.monotonic()
try:
response = await self.upstream.handle_async_request(request)
row.update(status='headers_received', http_status=response.status_code,
generation_id=response.headers.get('x-generation-id'))
return response
except BaseException as exc:
row.update(status='failed', error_type=type(exc).__name__)
raise
finally:
row['headers_elapsed_seconds'] = round(time.monotonic()-began, 3)
self.save()
async def aclose(self):
# One shared transport belongs to the whole test, not each HTTP client.
pass
async def close_owned(self):
await self.upstream.aclose()
@@ -0,0 +1,28 @@
# Current Linux host: append after the Phase 1 and browser overrides.
# Cached dependency runtime only; current app/migrations remain read-only mounts.
# No engine build or local_s2s activation. Do not apply to operational Compose.
services:
candidate_db:
image: sha256:f1447071e6c8449dcf4056aa0994c81d3566ce5ee232de36b04dc25696a116dd
candidate_migrations:
image: sha256:0390c6c5a4a279f22e86bbc3bf06ca9cfe1a958656dc3b0ca4f1c229db2a2763
volumes:
- /dev/null:/app/.env:ro
candidate_api:
image: sha256:0390c6c5a4a279f22e86bbc3bf06ca9cfe1a958656dc3b0ca4f1c229db2a2763
environment:
LIVE_SESSION_SECONDS: "60"
LIVE_DIAGNOSTIC_TRACE_ENABLED: "1"
MAX_PROVIDER_SESSIONS: "1"
# Validation-only transport profile. Inference stays disabled at port 9;
# these conservative byte caps do not describe a real hosted endpoint.
INGEST_EMBEDDING_LIMITS: '{"unit":"utf8_bytes","max_input_units":4096,"max_batch_units":4096,"max_batch_inputs":1}'
OPENAI_REALTIME_SPEED: ${OPENAI_REALTIME_SPEED:-1.0}
# Preserve the established generation limit; never lower it for a smoke.
OPENAI_REALTIME_MAX_OUTPUT_TOKENS: ${OPENAI_REALTIME_MAX_OUTPUT_TOKENS:-2048}
OPENAI_REALTIME_REASONING_EFFORT: ${OPENAI_REALTIME_REASONING_EFFORT:-null}
OPENAI_REALTIME_ASR_MODEL: ${OPENAI_REALTIME_ASR_MODEL:-whisper-1}
OPENAI_REALTIME_ASR_LANGUAGE: ${OPENAI_REALTIME_ASR_LANGUAGE:-fa}
OPENAI_REALTIME_ASR_LANGUAGES: ${OPENAI_REALTIME_ASR_LANGUAGES:-[]}
volumes:
- /dev/null:/app/.env:ro
@@ -0,0 +1,244 @@
# Phase 1 isolated Linux preparation — 2026-10-15
Status: **Phase 1 accepted on the isolated Linux candidate**, following the final
user-run listening test and matching native diagnostics below. Phase 2 remains
in_progress / not accepted. No local engine built or enabled. Earlier pending
statements below are historical preparation checkpoints, superseded by the final
acceptance record.
**Current configuration:** response cap restored to the established **2048**
after user feedback. The 256-token values below describe the initial test only.
No additional paid session was opened after restoration.
The artificial three-intent override has also now been removed; baseline
capacity is 256 intents. This restores runtime tuning, not permission for 256
paid requests. No further real test was run during this configuration correction.
The user authorized the proposed one-session OpenAI test, up to 60 seconds,
three response intents and 256 output tokens per response. These are usage
bounds, not an enforced monetary ceiling. Do not open extra sessions or retry
paid failures under this authorization.
## Isolation and current host
The Windows-era image IDs and `rag-api-mini` / `rag-api` containers are absent
here. Cached Linux images were inspected and explicitly selected. Historical
rollback restoration is not established by this preparation.
- Dependency runtime: `sha256:0390c6c5a4a279f22e86bbc3bf06ca9cfe1a958656dc3b0ca4f1c229db2a2763`.
- PostgreSQL: `sha256:f1447071e6c8449dcf4056aa0994c81d3566ce5ee232de36b04dc25696a116dd`.
- Project `rag-local-s2s-test`; DB `rag_local_s2s_test` on `candidate_db`.
- New project-only DB/original/extraction volumes; current app/migrations mounted
read-only, inherited `/app/data` masked with tmpfs and `/app/.env` with `/dev/null`.
- API `http://127.0.0.2:8091`; Angular `http://127.0.0.2:4201`.
- API container `9309d1458044f3fa0a14956aa05f258dc13c186b48ec2db2e6bc85f588448a1e`.
- DB container `3281173e1fb089e2be900a19ff1f7c9b21aea552cf1ce73d03bf857c637ba73c`.
- Source base `8d348f0`; no runtime source changes during this preparation.
- Existing `rag-postgres`, other acceptance DB and Angular port 4200 untouched.
Frontend source and its original proxy are unchanged.
## Executed checks
Used `docker compose` with these four `-f` arguments, in order, from repo root:
1. `docker-compose.local-s2s-test.yml`
2. `docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml`
3. `docs/evaluation/local-s2s/phase-02-browser.override.yml`
4. `docs/evaluation/local-s2s/phase-01-linux-acceptance.override.yml`
Commands: `config --quiet`, then
`up --pull never -d candidate_db candidate_migrations candidate_api`.
Private config assertions verified provider, candidate DB, read-only source,
loopback binding, no OpenRouter key in API and 60s/3-intent/256-token limits.
OpenAI settings/key were supplied server-side without printing credentials.
The cached runtime's dependencies were inspected in a disposable read-only,
network-disabled container: FastAPI 0.143.0, Pydantic 2.14.0,
pydantic-settings 2.15.0, SQLAlchemy 2.0.54, psycopg 3.3.6, Alembic 1.20.0,
websockets 17.2 and uvicorn 0.54.0. No app/provider connection during that check.
Migrations exited **0**. An actual API DB connection returned
`current_database() = rag_local_s2s_test` before bootstrap. Created a separate
organization/admin using `python -m app.bootstrap --password-stdin`. Random
credentials were passed privately over stdin and stored with mode 0600 in
`/tmp/local-s2s-test-login.txt`, outside Git.
Started the existing Angular CLI without installing dependencies, from the
sibling frontend checkout:
```sh
./node_modules/.bin/ng serve --host 127.0.0.2 --port 4201 --proxy-config /home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-browser.proxy.json --no-open
```
Angular compiled successfully. Actual HTTP checks used `trust_env=False`:
| Check | Result |
| --- | --- |
| API `/health/ready` | 200, ready / ingestion available |
| Angular `/` | 200, HTML |
| Proxied `/api/v1/auth/login` | 200, new test account |
| Proxied `/api/v1/auth/me` | 200, correct identity |
| Logout with untrusted Origin | 403 |
| Logout with trusted Origin and valid CSRF | 204 |
Exploratory `/api/v1/config` returned 404; this is not a verified endpoint or a
product defect. Effective API settings were checked without opening a provider:
OpenAI `gpt-realtime-2.1` / `marin`, 256 tokens, 60 seconds, three intents,
transport testing true. Real-provider attempts **0**; no voice reservation or
stream created and no speech saved. Browser control reported no available
browsers. No UI, microphone or human listening acceptance is claimed.
Before handoff, enabled existing `LIVE_DIAGNOSTIC_TRACE_ENABLED=1` numeric
runtime traces for interruption/terminal/truncate/next-turn inspection. Recreated
only candidate_api with `up --pull never --no-deps -d candidate_api`; readiness
returned 200 again. Auth checks were
performed before this diagnostic-only recreation; test account/data retained.
### First browser attempt: capability configuration correction
User reported initial identity/login 401s, legacy dark-mode 404s and immediate
voice-mode exit. Candidate access logs show a subsequent successful login,
identity and configuration request, with no conversation/voice creation request.
An authenticated configuration probe confirmed `voice=false` despite readiness
200. Validation-only preflight isolated missing `INGEST_EMBEDDING_LIMITS` as the
cause (`EmbeddingError`); voice settings, credentials and DB profile all passed.
Initial handoff had not checked voice capability, so readiness/auth checks alone
were insufficient to establish that the UI could start this transport test.
Added explicit conservative byte limits only in the Linux candidate API override:
4096 bytes/input and batch, one input/batch. These describe the disabled test
endpoint at loopback port 9, not supported limits of any real embedding service.
No calibration bypass, runtime code, schema, old snapshot or real endpoint changed.
Recreated only candidate_api, retaining the account/DB/volumes. The API container
ID above reflects this correction.
Actual post-correction checks: readiness 200, proxied login 200, configuration 200
with `voice=true`, `captions=true`, `voice_transport_testing=true`, and
`calibration_status=uncalibrated`; identity and valid-CSRF logout succeeded.
No voice reservation, stream or provider call was made during diagnosis/checks.
The failed browser start did not consume the authorized provider session. Legacy
dark-mode routes remain 404; they are unrelated to the observed voice gate.
Human listening and native cleanup evidence still remain pending.
### Established response cap restored after the real test
One real session was observed in existing numeric traces: one cancelled terminal,
two token-limited terminals, matching truncate acknowledgements at played
positions 6602ms and 6581ms, and HTTP close 200 / WebSocket close. User reported
audible speech and interruption but objected to the shortened responses.
This is partial real evidence, not acceptance of the changed generation profile.
No extra provider probe or retry was performed to inspect these logs.
The user instructed that established buffer/speed/timing settings must be preserved.
Restored only `OPENAI_REALTIME_MAX_OUTPUT_TOKENS` from 256 to the configured 2048
in the Linux candidate override, then recreated only candidate_api. Effective
settings compared before/after: model `gpt-realtime-2.1`, voice `marin`, speed 1.30,
OpenAI-repair backlog 5,760,000 bytes, credit window 72,000 bytes, input transport
queue 96,000 bytes / 2 seconds all unchanged. Existing test-session limits remain
60 seconds / three response intents. Readiness returned 200. No application code,
buffer, speed, timeout, original reservation or operational service was changed.
Additional real testing has not been executed after restoration; the earlier
one-session authorization must not be silently expanded to repeated sessions.
### Subsequent user-run session: response-intent test ceiling
User supplied a subsequent session's frontend failure trace after restoration.
Existing candidate logs identify the exact close branch as
`RESPONSE_INTENT_CAPACITY`, occupancy_count=3 / limit_count=3, surfaced publicly
as `LIVE_BUFFER_OVERFLOW`. This is the explicitly configured test intent ceiling,
not exhaustion of audio storage: peak backlog was 302,704 bytes versus the
unchanged 5,760,000-byte limit. The third turn's generation completed successfully
(`terminal_completed=1`, `terminal_limited=0`) before the capacity failure.
`VoiceRuntime.create_response` counts every generation intent, including a
continuation after a tool result (`origin=response`), so three intents do not
guarantee three complete spoken exchanges. Mapping the proposed small test budget
to `LIVE_MAX_INTENTS=3` therefore prevented this tool-using conversation from
finishing. This artificial test ceiling is not evidence of an audio-buffer
regression. Two prior interrupted turns have matching native truncation receipts;
the session still fails normal-conversation acceptance because of the cap.
No fresh provider calls, buffer/speed/timeout changes or intent-cap expansion
were performed during diagnosis. Any next test must explicitly account for tool
continuations in its bounded usage; do not enlarge the audio buffers to mask this
response-intent ceiling. Historical statement above that no post-restoration test
had run describes that earlier checkpoint only.
### Artificial intent override removed
Following the user's request to proceed, removed only `LIVE_MAX_INTENTS=3` from
the Linux override, restoring the actual configured/default capacity of 256.
Checked the real candidate DB before recreation: one closed and one failed
session, none active. Two initial read-only inspection queries used an incorrect
table/column name and failed; the corrected `live_sessions.status` query passed.
No schema or data change was used to bypass those errors.
Recreated only candidate_api and verified readiness 200 and actual effective
settings: 256 intents, 2048 output tokens, speed 1.30, backlog 5,760,000 bytes,
credit 72,000 bytes, transport queue 96,000 bytes / 2 seconds, session expiry
60 seconds. No buffer/speed/timeout or operational service changed. No provider
request, reservation, live smoke or new listening acceptance performed. A future
bounded test must count tool continuations separately from spoken exchanges.
These are preparation checks, not a fresh provider-free/PostgreSQL suite run.
## Human test and remaining gate
### Final Phase 1 listening and native cleanup acceptance
Date: 2026-10-15. User reported a real greeting, two interruptions, a final spoken
answer and no error. Correlated candidate session:
`66aae0b7-3abb-4e93-b25a-c4be0fc98c3d`. No new provider probe was initiated to
verify it; existing numeric diagnostics and the isolated DB row were inspected.
No audio or user speech text was retained in this report.
| Turn | Observed terminal | Native repair receipt | First next-turn audio |
| --- | --- | --- | --- |
| 1 | cancelled at 6450ms | truncate acknowledged at 7423ms, played 1045ms | turn 2 at 8515ms |
| 2 | completed at 10420ms, interrupted while audio remained unplayed | truncate acknowledged at 11943ms, played 1610ms | turn 3 at 13009ms |
| 3 | completed at 15558ms | no further interruption required | normal close |
Times are elapsed from backend runtime trace start, not browser elapsedMs.
Both active-generation interruption and completed-but-unplayed interruption have
matching native acknowledgements before subsequent output. This is OpenAI native
repair evidence; it does not prove any local engine history mutation.
Session-specific diagnostics: **0 warning diagnostics, 0 limited terminals,
0 error events**. Peak output backlog 342,088 bytes, below the established
5,760,000-byte capacity. Actual HTTP close returned 200; persisted status
`closed`, close_reason `user_requested`, error_code null. Frozen stored profile
verified: OpenAI `gpt-realtime-2.1` / `marin`, speed 1.30, max_output_tokens 2048,
backlog 5,760,000 bytes and input/output mono PCM24k. The earlier successful
offline boundary/preservation coverage remains separate from this real evidence.
Verdict: **Phase 1 accepted for the provider-boundary/OpenAI preservation scope**.
The missing real listening gate is now closed. No fresh full-suite or DB-suite
pass is claimed; previously recorded baseline/timing failures remain disclosed.
Historical Windows rollback images are absent here; restoration remains unproved
and must not be inferred from the cached Linux dependency runtime. The complete
pinned engine source, reviewed Linux dependency lock, asset compatibility,
engine/SDK/POSIX conformance and Phase 2 real components/browser remain open.
Build/download authorization and bounded later provider usage are independent;
this successful session does not authorize unbounded calls or a provider switch.
### Historical human test instructions
Open `http://127.0.0.2:4201/login` in a fresh browser profile, use the login file,
allow the microphone, and start **one** voice session. Say a short Persian
greeting, interrupt the answer once, ask one short follow-up, and close normally.
Stay within three responses and 60 seconds. Do not reconnect after a failure.
No real document content is needed; candidate embedding inference is disabled.
Observe speech, both transcripts, interruption stop, next answer and normal
close. Inspect correlated native stop/truncate acknowledgement and next-turn
release before accepting Phase 1; a human report alone does not prove repair.
Report provider/model errors without silently changing the baseline model.
Phase 2 engine/SDK/POSIX/component/browser gates and rollback remain unverified.
Stop only the owned API/DB after the test, retaining volumes:
```sh
docker stop rag-local-s2s-test-candidate_api-1 rag-local-s2s-test-candidate_db-1
```
Stop the port-4201 Angular process separately; retain port 4200. Do not use
`compose down`, remove volumes or prune images.
+5 -1
View File
@@ -1,6 +1,10 @@
# Local S2S Phase 1 report # 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. Date: 2026-10-15. Current status: **accepted for the provider-boundary/OpenAI
preservation scope**, following [real Linux listening and native cleanup
acceptance](phase-01-linux-preparation.md). The report below preserves the earlier
offline checkpoint; its live-pending/Phase-2-not-started statements are historical.
Phase 2 is in progress; engine build/live acceptance and rollback remain unproved.
The internal provider boundary is implemented. OpenAI cancellation and truncation The internal provider boundary is implemented. OpenAI cancellation and truncation
keep their native requests, identities, acknowledgement checks, deadlines and keep their native requests, identities, acknowledgement checks, deadlines and
@@ -1,5 +1,15 @@
# Local S2S Phase 2 acceptance checklist # Local S2S Phase 2 acceptance checklist
Current verdict (2026-10-16): **Phase 2 accepted for isolated development-only
normal Persian browser voice**. [Final evidence](phase-02-accepted-20261016.md)
and [machine-readable results](phase-02-accepted-20261016.json):
125 local + 258 preservation + 63 PostgreSQL tests passed; actual browser response
fully played and closed normally. Conservative cost exposure $0.420504399, below
the same $1 cap; final invoice details remain unresolved with full reserves held.
Paid engine stopped normally. No buffer/speed change or operational promotion.
Phase 3/4 remain not_started. Earlier checkpoints below are historical and are
superseded where they describe open Phase 2 gates.
Checkpoint: 2026-10-15, source HEAD `872e5f25cbe2870d3fc3c66c8a4ab9c697d3d894` Checkpoint: 2026-10-15, source HEAD `872e5f25cbe2870d3fc3c66c8a4ab9c697d3d894`
plus the preserved working tree. Engine pin `619e3fe4f71d1c6f35c15870d588a3638de34722`, plus the preserved working tree. Engine pin `619e3fe4f71d1c6f35c15870d588a3638de34722`,
patch `rag-local-s2s-phase2-v3`, private shape v1. **Not accepted.** patch `rag-local-s2s-phase2-v3`, private shape v1. **Not accepted.**
@@ -0,0 +1,373 @@
{
"date": "2026-10-16",
"phase": 2,
"status": "accepted",
"scope": "Isolated development-only normal Persian browser voice; no operational promotion or interruption continuation",
"tests": {
"local_adapter": {
"passed": 125,
"seconds": 13.8,
"log_sha256": "79f7c13cb6a0850950823fe820c84e19642feb03b223dab237d62784938bfb7a"
},
"openai_preservation": {
"passed": 258,
"seconds": 61.48,
"log_sha256": "748bc08057c555bb24f90e76d21d453ae485a9ea835db317f580d6f1a63ee423"
},
"postgres": {
"passed": 63,
"seconds": 116.02,
"log_sha256": "147e57d13ba6f5ec5d01ae9b0524de26045846b4d2bce3d6e8096677f08c1edf"
},
"citation_regression": {
"passed": 6,
"seconds": 17.0,
"log_sha256": "990e4e854569f33f2fff8e307f416cac5e3cfbad4760fe7a0613e7598f4bbe9b"
},
"runner_smoke": {
"passed": 2,
"seconds": 3.36,
"log_sha256": "7164a2c91721a671bbb45ff5dcfae252347871d3e10f82f5f9e1dad2ad9fc2df"
}
},
"unique_primary_tests_passed": 446,
"budget_regressions": "browser, native transport and native runner scripts passed",
"real_browser": {
"session_id": "4445c984-c56b-4269-a7a2-49556c0902d2",
"user_reported_input": "سلام چطوریم",
"user_reported_reply": "سلام ممنونم. شما چطورید چطور میتونم در زمینه امور شرکت شهرکهای صنعتی اصفهان کمکتون کنم",
"terminal_completed": 1,
"terminal_limited": 0,
"terminal_cancelled": 0,
"generated_bytes": 350208,
"sent_bytes": 350208,
"played_ms": 7296,
"final_backlog_bytes": 0,
"persisted_close": {
"status": "closed",
"close_reason": "user_requested",
"error_code": null
},
"evidence": "Actual API diagnostics and read-only isolated live_sessions query, matched to user-reported browser result.",
"asr_ground_truth_accuracy": "not_scored",
"phase_2_status": "accepted; final invoice accounting remains a disclosed nonblocking follow-up"
},
"cost": {
"method": "read_only_GET_no_inference",
"ledgers": {
"native": [
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792161394-vJMHFfdwTmHBDSBW48aH",
"status": "headers_received",
"reserved_usd": "0.004",
"lookup_http_status": 200,
"billing": {
"id": "gen-stt-1792161394-vJMHFfdwTmHBDSBW48aH",
"total_cost": 2.5e-05,
"usage": 2.5e-05,
"tokens_prompt": null,
"tokens_completion": null,
"native_tokens_prompt": null,
"native_tokens_completion": null
}
},
{
"stage": "completions",
"generation_id": "gen-1792161398-BRPNxd79tYYoQZdg43Ce",
"status": "headers_received",
"reserved_usd": "0.01",
"lookup_http_status": 404
},
{
"stage": "speech",
"generation_id": "gen-tts-1792161399-3YAyVlL5MSSKbqaZWnIz",
"status": "headers_received",
"reserved_usd": "0.205",
"lookup_http_status": 200,
"billing": {
"id": "gen-tts-1792161399-3YAyVlL5MSSKbqaZWnIz",
"total_cost": 0.000175,
"usage": 0.000175,
"tokens_prompt": 2,
"tokens_completion": 29,
"native_tokens_prompt": 2,
"native_tokens_completion": 29
}
},
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792161402-nvlLMzXrx1QdjtVT6Nuu",
"status": "headers_received",
"reserved_usd": "0.004",
"lookup_http_status": 200,
"billing": {
"id": "gen-stt-1792161402-nvlLMzXrx1QdjtVT6Nuu",
"total_cost": 0.000308333,
"usage": 0.000308333,
"tokens_prompt": null,
"tokens_completion": null,
"native_tokens_prompt": null,
"native_tokens_completion": null
}
},
{
"stage": "completions",
"generation_id": "gen-1792161403-FNP9pxaRHEq63J0h1qbo",
"status": "headers_received",
"reserved_usd": "0.01",
"lookup_http_status": 200,
"billing": {
"id": "gen-1792161403-FNP9pxaRHEq63J0h1qbo",
"total_cost": 0.000248,
"usage": 0.000248,
"tokens_prompt": 874,
"tokens_completion": 22,
"native_tokens_prompt": 584,
"native_tokens_completion": 9
}
},
{
"stage": "speech",
"generation_id": "gen-tts-1792161415-n472pZcpHCoMng79OO5S",
"status": "headers_received",
"reserved_usd": "0.205",
"lookup_http_status": 200,
"billing": {
"id": "gen-tts-1792161415-n472pZcpHCoMng79OO5S",
"total_cost": 0.0003815,
"usage": 0.0003815,
"tokens_prompt": 6,
"tokens_completion": 63,
"native_tokens_prompt": 7,
"native_tokens_completion": 63
}
}
],
"browser": [
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792162309-6uGLT2gkPHgtKOWXxMTe",
"status": "headers_received",
"reserved_usd": "0.004",
"lookup_http_status": 200,
"billing": {
"id": "gen-stt-1792162309-6uGLT2gkPHgtKOWXxMTe",
"total_cost": 0.000308333,
"usage": 0.000308333,
"tokens_prompt": null,
"tokens_completion": null,
"native_tokens_prompt": null,
"native_tokens_completion": null
}
},
{
"stage": "completions",
"generation_id": "gen-1792162310-PefNVi4EfXsUHh17bpno",
"status": "headers_received",
"reserved_usd": "0.02",
"lookup_http_status": 200,
"billing": {
"id": "gen-1792162310-PefNVi4EfXsUHh17bpno",
"total_cost": 2.28e-05,
"usage": 2.28e-05,
"tokens_prompt": 9,
"tokens_completion": 9,
"native_tokens_prompt": 17,
"native_tokens_completion": 10
}
},
{
"stage": "speech",
"generation_id": "gen-tts-1792162311-EvL82g6AOq2uUg0tV49F",
"status": "headers_received",
"reserved_usd": "0.035",
"lookup_http_status": 200,
"billing": {
"id": "gen-tts-1792162311-EvL82g6AOq2uUg0tV49F",
"total_cost": 0.0001575,
"usage": 0.0001575,
"tokens_prompt": 2,
"tokens_completion": 26,
"native_tokens_prompt": 3,
"native_tokens_completion": 26
}
},
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792162562-uzf1ExC8XXA2ojtKmzHQ",
"status": "headers_received",
"reserved_usd": "0.004",
"lookup_http_status": 404
},
{
"stage": "completions",
"generation_id": "gen-1792162563-v2xXCeyWczaO6N6sDGYO",
"status": "headers_received",
"reserved_usd": "0.02",
"lookup_http_status": 200,
"billing": {
"id": "gen-1792162563-v2xXCeyWczaO6N6sDGYO",
"total_cost": 0.0007596,
"usage": 0.0007596,
"tokens_prompt": 2570,
"tokens_completion": 27,
"native_tokens_prompt": 1839,
"native_tokens_completion": 15
}
},
{
"stage": "speech",
"generation_id": null,
"status": "failed",
"reserved_usd": "0.035"
}
],
"repair": [
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792164932-yowwJIs8FCVLhZsAPZCS",
"status": "headers_received",
"reserved_usd": "0.004",
"lookup_http_status": 404
},
{
"stage": "completions",
"generation_id": "gen-1792164934-Xzi45DRGAMNPQMKF6PtM",
"status": "headers_received",
"reserved_usd": "0.02",
"lookup_http_status": 404
},
{
"stage": "speech",
"generation_id": "gen-tts-1792164935-lFnqxFlbFB9oZtwUw99p",
"status": "headers_received",
"reserved_usd": "0.035",
"lookup_http_status": 404
},
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792165118-S7omIdaVRJTE9KadsXLE",
"status": "headers_received",
"reserved_usd": "0.004",
"lookup_http_status": 404
},
{
"stage": "completions",
"generation_id": "gen-1792165121-GmxoMAiyn8570Tg4mqfE",
"status": "headers_received",
"reserved_usd": "0.02",
"lookup_http_status": 404
},
{
"stage": "speech",
"generation_id": "gen-tts-1792165122-xAsR1xzOCcq0dqYyHJkh",
"status": "headers_received",
"reserved_usd": "0.035",
"lookup_http_status": 404
}
]
},
"key_lookup_status": 200,
"key_usage": {
"usage": 0.136937669,
"usage_daily": 0.003504399,
"limit": 5,
"limit_remaining": 4.863062331
},
"reconciliation": {
"confirmed_cost_usd": "0.003504399",
"unknown_reservations_usd": "0.417",
"conservative_exposure_usd": "0.420504399",
"unknown_attempts_including_initial_failed_wav": 10,
"unresolved": [
{
"ledger": "native",
"stage": "completions",
"generation_id": "gen-1792161398-BRPNxd79tYYoQZdg43Ce"
},
{
"ledger": "browser",
"stage": "transcriptions",
"generation_id": "gen-stt-1792162562-uzf1ExC8XXA2ojtKmzHQ"
},
{
"ledger": "browser",
"stage": "speech",
"generation_id": null
},
{
"ledger": "repair",
"stage": "transcriptions",
"generation_id": "gen-stt-1792164932-yowwJIs8FCVLhZsAPZCS"
},
{
"ledger": "repair",
"stage": "completions",
"generation_id": "gen-1792164934-Xzi45DRGAMNPQMKF6PtM"
},
{
"ledger": "repair",
"stage": "speech",
"generation_id": "gen-tts-1792164935-lFnqxFlbFB9oZtwUw99p"
},
{
"ledger": "repair",
"stage": "transcriptions",
"generation_id": "gen-stt-1792165118-S7omIdaVRJTE9KadsXLE"
},
{
"ledger": "repair",
"stage": "completions",
"generation_id": "gen-1792165121-GmxoMAiyn8570Tg4mqfE"
},
{
"ledger": "repair",
"stage": "speech",
"generation_id": "gen-tts-1792165122-xAsR1xzOCcq0dqYyHJkh"
}
],
"ledger_files_unchanged": true,
"paid_tests_restarted": false
}
},
"paid_engine_shutdown": {
"repair": true,
"stage": "stopped",
"minimum_host_available_bytes": 4494655488,
"startup_seconds": 50.411,
"elapsed_seconds": 894.304,
"reason": "operator_stop"
},
"new_paid_inference_this_completion": 0,
"remaining_phase2_acceptance_gates": [],
"nonblocking_followups": [
"Final per-request invoice lookups remain unresolved; all unknown attempts retain full reservations.",
"Phase 3 interruption/history/shared RAG and declared-source integration remain not started.",
"Phase 4 quality/latency/cost benchmarking and controlled switch/rollback remain not started.",
"Repository-wide ordinary suite not rerun; earlier unrelated cancellation-diagnostic failures are retained in historical reports."
],
"historical_initial_results": {
"disk_backed_postgres": "11 passed then deliberately interrupted at 113.09s; test-owned database removed",
"old_citation_fixture_postgres": "57 passed, 6 failed in 212.44s; all 6 source cases subsequently corrected and passed",
"old_transcript_fixture_preservation": "257 passed, 1 failed in 61.18s; deterministic first-delivery synchronization then 258 passed"
},
"source_sha256": {
"services/local_s2s/engine.py": "b6c6f938109efed30e438b87c361a90aae5ec5d0ff9db47d8e92fa8c1957e003",
"tests/integration/test_phase2_postgres.py": "4ddc3c170e7a3d3c3813df4c9962ad05b1e8e481764bcf2ace52bbb6b60e09e3",
"tests/unit/test_openai_speech_configuration.py": "61f8b6f1c9c71ffa4974c09a9d019d37edcffb582b2afd71cf9a81b94c129c08",
"docs/evaluation/local-s2s/phase-02-final-postgres.py": "ebf0ea3df080f072d96b20b40b1e01147f94dd9fd32fdc4c73f020af7340ff38"
},
"final_resource_verification": {
"paid_engine": {
"status": "exited",
"exit_code": 0,
"oom_killed": false
},
"owned_disposable_test_containers_remaining": 0,
"owned_disk_test_databases_remaining": 0,
"candidate_database": "running and retained",
"operational_database_container": "same preexisting exited state; not started or modified"
},
"final_document_checks": "JSON/counts/source hashes/Python syntax/local links/provider-secret scan/git diff --check passed"
}
@@ -0,0 +1,111 @@
# Phase 2 accepted — 2026-10-16
**Accepted for isolated development-only normal Persian browser voice.** The
required Phase 2 implementation, real component/audio evidence, human browser
round trip and applicable PostgreSQL acceptance are complete. This does not
promote local_s2s or accept interruption continuation. Phase 3/4 have not started.
[Machine-readable results](phase-02-accepted-20261016.json) record hashes, billing
lookups and exact scoped outcomes. Earlier checkpoints remain historical.
## Acceptance evidence
| Required gate | Actual evidence |
| --- | --- |
| Phase 1 / OpenAI preservation | Prior accepted [real OpenAI interaction](phase-01-linux-preparation.md); 258 focused preservation tests now pass |
| Pinned source, dependencies, image and assets | [Reviewed lock](phase-02-dependency-lock.md), [source acquisition](phase-02-source-checkout.json), [Linux image](phase-02-image-build-20261016.md), [assets](phase-02-linux-assets-20261016.md) |
| Actual native engine / setup / shutdown | [Native fixture conformance and cleanup](phase-02-native-session-20261016.md); actual engine image and first-turn repair below |
| Actual STT, LLM and TTS | [Component evidence](phase-02-real-components-20261016.md), [native round trip](phase-02-real-native-20261016.md); user previously accepted pronunciation |
| Existing browser, transcripts, full audio and normal close | [Repaired real browser exchange](phase-02-browser-first-turn-repair-20261016.md): all 350208 PCM bytes / 7.296s played, completed terminal without limitation/cancellation; isolated DB confirms closed/user_requested and no error |
| Setup mismatch, HTTP, adapter and frozen profile behavior | 125 focused local tests pass, including existing pinned-source/fixture coverage; actual native setup mismatch evidence retained |
| Isolated DB profile/replay/admission/owner/revocation and ASGI behavior | 63 PostgreSQL tests pass with --require-postgres, zero skips |
| Budget authorization | No new inference during completion; all unresolved attempts retain reservations; conservative exposure remains below $1 |
The repaired engine is immutable image
`sha256:a51167d1952a8947efe1c9048311b549a1998ab8cfaf41371228b6c326781ff9`.
Upstream remains `619e3fe4f71d1c6f35c15870d588a3638de34722`, extension
`rag-local-s2s-phase2-v3`, private shape v1. The same language detector now warms
before listener readiness. No model, buffer, speed, public event, PCM or timeout
change was needed to finish acceptance.
## Final checks and test repairs
| Check | Result |
| --- | --- |
| Local boundary/engine/Phase2/repair unit tests | 125 passed in 13.80s |
| OpenAI/provider/context/audio/style/source preservation | 258 passed in 61.48s |
| Local + expanded PostgreSQL acceptance | 63 passed in 116.02s, zero skips |
| Six corrected citation scenarios alone | 6 passed in 17.00s; included in the 63 |
| Final RAM-database runner smoke | 2 passed in 3.36s; repeats local cases |
| Browser/native budget guards and native runner | All three scripts passed |
| Recorded running-source fingerprints, Python syntax and secret scan | Passed |
The **446 primary tests** are 383 unit plus 63 integration tests. Subset reruns
are not counted again. The broader ordinary suite was not rerun; historical
unrelated cancellation-diagnostic failures remain disclosed in the Phase 1 report.
Two existing fixtures needed correction, without changing production runtime:
- The six ASGI cases waited for public sources immediately after retrieval, then
timed out on the next response acknowledgement. The API's existing
[declared-source amendment](../../specifications/RAG-Phase1-API-Catalog.md)
requires report_used_sources. Tests now complete that real tool round trip,
acknowledge each OpenAI response and verify exact public references and
document/chunk identities. No-evidence/errors publish no citations; reporting
creates no extra durable retrieval. Existing persistence assertions are retained.
- The transcript test assumed two adjacent unsent deltas would produce separate
frames, although existing control delivery may concatenate them. It now waits
for first-frame delivery before testing identity replay and a legitimate repeated
word. All original text/order/release assertions and deadlines remain intact.
The old fixtures were actually rerun before correction: PostgreSQL produced
57 passed / 6 failed in 212.44s, and preservation produced 257 passed / 1 failed
in 61.18s. These results are retained, superseded by the complete green reruns.
An initial disk-backed DB run was deliberately interrupted after 11 passes in
113.09s because of slow disk synchronization. Its test-owned database was removed.
Reproduction from the repository root, with the existing cached image/network:
```sh
TRUSTED_HOSTS='["localhost:8000","127.0.0.1:8000"]' .venv/bin/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_local_s2s_engine.py tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_repairs.py -q --tb=short
TRUSTED_HOSTS='["localhost:8000","127.0.0.1:8000"]' .venv/bin/python -m pytest tests/unit/test_realtime_phase1.py tests/unit/test_live_context_sync.py tests/unit/test_phase2_provider_selection.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_voice_output_capacity.py tests/unit/test_openai_output_limit.py tests/unit/test_openai_persian_style.py tests/unit/test_openai_speech_configuration.py -q --tb=short
.venv/bin/python docs/evaluation/local-s2s/phase-02-final-postgres.py
.venv/bin/python docs/evaluation/local-s2s/check-browser-budget.py
.venv/bin/python docs/evaluation/local-s2s/check-native-budget.py
.venv/bin/python docs/evaluation/local-s2s/check-native-runner.py
```
The [DB runner](phase-02-final-postgres.py) creates a fresh 512MiB/no-swap,
two-CPU PostgreSQL/pgvector container from the verified cached image. Data is tmpfs;
PostgreSQL durability settings are not disabled. No published port, operational
volume, .env or provider credential is attached. The existing harness migrates and
drops random schemas; the owned container stops and auto-removes on completion.
No operational container/image/database was modified.
## Cost accounting and handoff
Read-only OpenRouter GET lookups confirmed **$0.003504399** across known billed
requests. All still-unresolved calls, the initial failed WAV and the cancelled TTS
retain their full reserves: **$0.417**. Combined conservative exposure is therefore
**$0.420504399**, below the original $1 authorization. The provider key's unrelated
$5 limit was not changed. A 404 is not treated as free.
Final per-request billing, including the successful browser greeting, remains
unavailable from some generation lookups. Thus no exact browser-turn cost or final
invoice total is claimed. Phase 2's bounded-cost compliance is verified; delayed
invoice reconciliation remains a disclosed accounting follow-up, not an unrun
functional acceptance test. Phase 4 cost/quality evaluation remains separate.
Original exclusive ledgers were neither reset nor rewritten. The live repair
ledger still records $0.925118333 and its $0.995118333 ceiling; the reconciliation
above is a separate accounting snapshot and grants no additional inference.
The paid engine watchdog was stopped normally after acceptance, releasing RAM.
Final inspect confirms engine exit0, OOMKilled=false, no retained task-owned
disposable acceptance container and no leftover disk-test database.
Its image, candidate DB/account, API, frontend and private login file are retained.
Do not restart its existing exclusive ledger or repeat paid browser tests.
Remaining work belongs to Phase 3 (interruption and real history repair, shared
RAG, used sources) and Phase 4 (quality/latency/cost evaluation, controlled switch
and proven rollback). Native fixture source/tool tests are not real-provider RAG
acceptance. Operational OpenAI remains preserved; this phase performs no promotion
or rollback rehearsal and claims no production parity.
@@ -0,0 +1,215 @@
{
"date": "2026-10-16",
"phase": 2,
"status": "first_turn_prewarm_fixed_human_browser_round_trip_passed",
"user_failed_session": "331b8eed-21ba-423a-ad21-237986846ef9",
"root_cause": {
"native_stack": [
"pipeline/language_detection.py:51 build_language_detector",
"pipeline/language_detection.py:57 warm_language_detector",
"LLM/lm_output_processor.py:97 _observe_assistant_language",
"LLM/lm_output_processor.py:261 process"
],
"description": "First-response all-language Lingua initialization in native output processing; move the same cached warmup before exposing the listener."
},
"image": "sha256:a51167d1952a8947efe1c9048311b549a1998ab8cfaf41371228b6c326781ff9",
"base_image": "sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"provider_free_full_path_regression": [
{
"iteration": 0,
"exit_code": 0,
"stdout": "{\"conversation_id\": \"5003ed68-1d46-4f92-8f6f-ce0abb6e994b\", \"session_id\": \"aa9a67d5-2673-4f67-8270-328f046d8f59\", \"events\": [\"session_ready\", \"user_speech_started\", \"transcript\", \"transcript\", \"audio_started\", \"transcript\", \"audio_ended\"], \"binary_bytes\": 10752, \"session_ready\": true, \"close\": {\"session_id\": \"aa9a67d5-2673-4f67-8270-328f046d8f59\", \"status\": \"closed\", \"close_reason\": \"user_requested\"}, \"component_attempts_before\": 6, \"component_attempts_after\": 6}\n",
"stderr": ""
},
{
"iteration": 1,
"exit_code": 0,
"stdout": "{\"conversation_id\": \"457da308-8231-4b8a-9e47-cafad7335032\", \"session_id\": \"5261eb72-5991-41bd-b4de-60e294911965\", \"events\": [\"session_ready\", \"user_speech_started\", \"transcript\", \"transcript\", \"audio_started\", \"transcript\", \"audio_ended\"], \"binary_bytes\": 10752, \"session_ready\": true, \"close\": {\"session_id\": \"5261eb72-5991-41bd-b4de-60e294911965\", \"status\": \"closed\", \"close_reason\": \"user_requested\"}, \"component_attempts_before\": 6, \"component_attempts_after\": 6}\n",
"stderr": ""
},
{
"iteration": 2,
"exit_code": 0,
"stdout": "{\"conversation_id\": \"a58cf721-5694-405d-849b-4e40e331d6a0\", \"session_id\": \"82d00373-bd4e-499d-a649-d65723ff0496\", \"events\": [\"session_ready\", \"user_speech_started\", \"transcript\", \"transcript\", \"audio_started\", \"transcript\", \"audio_ended\"], \"binary_bytes\": 10752, \"session_ready\": true, \"close\": {\"session_id\": \"82d00373-bd4e-499d-a649-d65723ff0496\", \"status\": \"closed\", \"close_reason\": \"user_requested\"}, \"component_attempts_before\": 6, \"component_attempts_after\": 6}\n",
"stderr": ""
}
],
"focused_tests": {
"passed": 98,
"seconds": 8.51,
"files": [
"tests/unit/test_local_s2s_phase2.py",
"tests/unit/test_local_s2s_repairs.py"
]
},
"real_fixed_connection": {
"conversation_id": "2ee01d73-6a52-4d4b-85dc-aff6e74cb541",
"session_id": "2fdd2e77-29d6-4f30-9240-dded88a8de31",
"events": [
"session_ready"
],
"session_ready": true,
"close": {
"session_id": "2fdd2e77-29d6-4f30-9240-dded88a8de31",
"status": "closed",
"close_reason": "user_requested"
},
"component_attempts_before": 3,
"component_attempts_after": 3
},
"real_fixed_watchdog": {
"repair": true,
"stage": "ready",
"minimum_host_available_bytes": 4984836096,
"startup_seconds": 50.411
},
"real_fixed_budget": {
"previous_reserved_and_billed_usd": "0.807118333",
"reserved_usd": "0.866118333",
"maximum_cumulative_usd": "0.995118333",
"reconciled_successful_components_usd": "0.001118333",
"failed_wav_retained_usd": ".25",
"unbilled_native_retained_usd": ".438",
"previous_browser_retained_usd": ".118",
"maximum_attempts": {
"speech": 4,
"transcriptions": 2,
"completions": 2
},
"attempts": [
{
"stage": "transcriptions",
"reserved_usd": "0.004",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-stt-1792164932-yowwJIs8FCVLhZsAPZCS",
"headers_elapsed_seconds": 1.199
},
{
"stage": "completions",
"reserved_usd": "0.02",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-1792164934-Xzi45DRGAMNPQMKF6PtM",
"headers_elapsed_seconds": 0.761
},
{
"stage": "speech",
"reserved_usd": "0.035",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-tts-1792164935-lFnqxFlbFB9oZtwUw99p",
"headers_elapsed_seconds": 2.001
}
]
},
"original_browser_ledger_retained": true,
"native_ledger_retained": true,
"no_additional_paid_user_audio_test": false,
"settings_changed": {
"buffers": false,
"speed": false,
"timeouts": false,
"provider_models": false,
"public_api": false
},
"human_browser_acceptance": "single_greeting_round_trip_observed_and_reported_by_user",
"source_sha256": {
"services/local_s2s/engine.py": "b6c6f938109efed30e438b87c361a90aae5ec5d0ff9db47d8e92fa8c1957e003",
"docs/evaluation/local-s2s/browser-budget.py": "58f3fe7e9984445748488c2aab2b4362066346858bf392d65f6c42b10d4eb0e6",
"docs/evaluation/local-s2s/browser-engine.py": "12a819253860c94c22a830c027d1b15f62b2c1327db6cc999d3d9182e7d2fd9a",
"docs/evaluation/local-s2s/browser-fixture-engine.py": "8c04c75fb99f5d4fe8a399abd530ae75cd4b3a5393b17575b0d063057e5f9801",
"docs/evaluation/local-s2s/watch-browser-engine.py": "ec8fbca95ce7e4101066527f5d112fc5f5331689e9cd7dd7c9bf3910d42dd6b5",
"docs/evaluation/local-s2s/check-browser-budget.py": "7be851fe31b3a37bc5a67a1e3d89d882a5f1cdc8078b277b135f2c8bbbbdf867",
"docs/evaluation/local-s2s/check-browser-connection.py": "28514a95ce72c1719f4d41422b3ac7354d028111b478690930ba952d4f9e8ccc",
"docs/evaluation/local-s2s/check-browser-duplex.py": "2848bd26936f7ffbc63b74ebe523fd80ee082aae112199c1f023d384f8bb68aa",
"docs/evaluation/local-s2s/image-session-smoke.py": "1c72866c4a8c5f2b4dd3eaab31767d156ed5246f1072b7aa4676c99ff28934ca",
"docs/evaluation/local-s2s/run-image-session-smoke.py": "66dcb1441d01e1bfa176cdf25c68e2bc01aa6161f02119f6fc72b7e18a104fdb",
"docs/evaluation/local-s2s/phase-02-browser-fixture.override.yml": "9cd72b33f78e215d5985a5380b8988793ed5727013ae627377758579be712623",
"docs/evaluation/local-s2s/phase-02-browser-repair.override.yml": "6530bed5da2f29abcec05f147a32b7b952a1553aa530f00ffec9c5fe2fc2c21e"
},
"real_fixed_budget_after_human_turn": {
"previous_reserved_and_billed_usd": "0.807118333",
"reserved_usd": "0.925118333",
"maximum_cumulative_usd": "0.995118333",
"reconciled_successful_components_usd": "0.001118333",
"failed_wav_retained_usd": ".25",
"unbilled_native_retained_usd": ".438",
"previous_browser_retained_usd": ".118",
"maximum_attempts": {
"speech": 4,
"transcriptions": 2,
"completions": 2
},
"attempts": [
{
"stage": "transcriptions",
"reserved_usd": "0.004",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-stt-1792164932-yowwJIs8FCVLhZsAPZCS",
"headers_elapsed_seconds": 1.199
},
{
"stage": "completions",
"reserved_usd": "0.02",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-1792164934-Xzi45DRGAMNPQMKF6PtM",
"headers_elapsed_seconds": 0.761
},
{
"stage": "speech",
"reserved_usd": "0.035",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-tts-1792164935-lFnqxFlbFB9oZtwUw99p",
"headers_elapsed_seconds": 2.001
},
{
"stage": "transcriptions",
"reserved_usd": "0.004",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-stt-1792165118-S7omIdaVRJTE9KadsXLE",
"headers_elapsed_seconds": 3.139
},
{
"stage": "completions",
"reserved_usd": "0.02",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-1792165121-GmxoMAiyn8570Tg4mqfE",
"headers_elapsed_seconds": 0.965
},
{
"stage": "speech",
"reserved_usd": "0.035",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-tts-1792165122-xAsR1xzOCcq0dqYyHJkh",
"headers_elapsed_seconds": 2.518
}
]
},
"human_browser_result": {
"session_id": "4445c984-c56b-4269-a7a2-49556c0902d2",
"user_reported_input": "سلام چطوریم",
"user_reported_reply": "سلام ممنونم. شما چطورید چطور میتونم در زمینه امور شرکت شهرکهای صنعتی اصفهان کمکتون کنم",
"terminal_completed": 1,
"terminal_limited": 0,
"terminal_cancelled": 0,
"generated_bytes": 350208,
"sent_bytes": 350208,
"played_ms": 7296,
"final_backlog_bytes": 0,
"persisted_close": {
"status": "closed",
"close_reason": "user_requested",
"error_code": null
},
"evidence": "Actual API diagnostics and read-only isolated live_sessions query, matched to user-reported browser result.",
"asr_ground_truth_accuracy": "not_scored",
"phase_2_status": "in_progress; applicable database acceptance gates and final billing reconciliation remain"
}
}
@@ -0,0 +1,124 @@
# Browser first-turn stall repair — 2026-10-16
Follow-up: [Phase 2 accepted](phase-02-accepted-20261016.md). Required database and preservation checks are now green; delayed invoice accounting retains full reserves. The handoff descriptions below are historical; the paid engine has been stopped normally.
The user's real session `331b8eed-21ba-423a-ad21-237986846ef9` reached
`session_ready`, detected speech and delivered the recognized transcript, then
failed with `LIVE_TRANSPORT_FAILED` / close1011 before audible output. This was
not a successful Phase2 microphone acceptance. Login succeeded; the initial
identity401 was before login. The legacy dark-mode404 is separate from the voice
transport failure.
## Cause and change
The pinned native output processor calls `_observe_assistant_language()` whenever
there is a session configuration, even when `detect_llm_output_language` is false.
Its first call lazily invokes `warm_language_detector()`, whose Lingua builder
preloads models for all supported languages. Native thread snapshots captured this
work in `pipeline/language_detection.py:51` via `lm_output_processor.py:97` at the
first LLM-to-speech handoff. The expensive native initialization can hold the GIL
and prevents timely servicing of live microphone traffic. A separately running API
reaches its unchanged five-second provider-send bound; shutdown then also has
pending transport work. Same-process native-only tests had not exposed the same
cross-process deadline failure.
[The launcher](../../../services/local_s2s/engine.py) now primes **the same existing
cached language detector during construction**, before the listener is exposed.
The existing startup deadline owns this work. Automatic detection semantics and
language models are preserved. No buffer, queue capacity, speed, PCM rate, provider
send/cleanup timeout, public API or frontend source changes were made. Operational
OpenAI is untouched. The added language-prewarm step is provider-free and adds no dependency or
download. Restarting the engine still performs its usual three paid component
probes, all counted in the carried-forward budget.
## Evidence
- Actual native duplex fixture test sent580 continuous microphone frames while
a controlled LLM streamed with12 seconds of delay; normal output/close passed.
This isolated native-only success was insufficient to certify browser behavior.
- The full Angular proxy → actual authenticated API → native fixture engine path
reproduced the user's failure repeatedly with no provider fees. A single pass
during diagnosis was retained as an intermittent outcome, not acceptance.
- API coroutine traces showed an open provider socket waiting for its write buffer
to drain. Native receive queues were empty/read-enabled, and SQL connections
showed no lock wait. Plain TCP and raw-WebSocket probes between these same
containers passed. Explicit native legacy-WebSocket backend selection also
failed and was discarded; no such backend switch remains in production code.
- Native watchdog thread snapshots at the LLM/TTS boundary identified the lazy
Lingua preload. After moving it to startup, **three sequential full-path duplex
fixture sessions passed**, including the first response from a cold fixed engine.
Each delivered10752 test PCM bytes, `audio_ended`, and explicit
`closed / user_requested`. Microphone input continued during the delayed reply.
These were synthetic fixture audio/sink tests, not human listening evidence.
- **98 focused tests passed** in8.51s:
`tests/unit/test_local_s2s_phase2.py` and `tests/unit/test_local_s2s_repairs.py`.
Browser budget regression covers both original and repair ledgers. Fixture audio
testing now refuses an engine whose entrypoint is not fixture-only or which
mounts a provider credential. No broad PostgreSQL suite rerun is claimed.
The [duplex regression](check-browser-duplex.py) requires the explicit
[fixture override](phase-02-browser-fixture.override.yml), which mounts no provider
key. The [fixture engine](browser-fixture-engine.py) uses actual handlers/assets
and intercepts all component HTTP. Do not apply that override to a human quality
test; the corrected real handoff uses the repair override instead.
## Fixed image and real handoff
New COPY-only image:
`sha256:a51167d1952a8947efe1c9048311b549a1998ab8cfaf41371228b6c326781ff9`
(tag `rag-local-s2s-candidate:phase2-prewarm-fix`). Its verified base is89c7295e5219;
only the launcher file is replaced. Original images are retained. A first build
using bare `FROM sha256:...` was rejected as an invalid registry reference; the
successful build used the verified local tag with no dependency installation.
Append [repair override](phase-02-browser-repair.override.yml) after the standalone
candidate base and Linux browser override. Its fresh evidence directory is
`.local-s2s-build/browser-repair-paid`; previous ledgers remain intact. The real
engine is owned by `watch-browser-engine.py --repair`, with the same3GiB/no-swap,
two-CPU, >5GiB pre-start and2500MiB runtime headroom gates and30-minute handoff
expiry. API/Angular/test account and URL are unchanged.
Retained exposure before this restart is **$0.807118333**: every earlier unbilled
attempt, the initial failed WAV and the cancelled browser TTS reservation remain
included. The new guard permits at most two STT, two LLM and four TTS attempts,
including the three startup probes. Its **cumulative ceiling is$0.995118333** under
the original$1 authorization. This is not an actual bill. No old ledger was reset,
no failed attempt was treated as free and no operational/shared-key cap changed.
The one-greeting browser handoff below has now completed. Earlier WAV listening
approvals are retained. No complete Phase2 acceptance is claimed.
## Actual repaired handoff check
The real repaired engine reached startup in **50.411s** and its three actual
component probes returnedHTTP200. Current cumulative reservation after probes is
**$0.866118333**; ceiling remains$0.995118333. The running launcher hash matches
the reviewed source. An actual proxied API/native connection again reached
`session_ready` and persisted `closed / user_requested`; admissions remained3→3.
No additional user-audio inference was run during that final connection check.
The fixture-audio test was verified to refuse this real engine before login/audio.
[Machine-readable evidence](phase-02-browser-first-turn-repair-20261016.json)
records exact hashes, test results, budget and watchdog state.
## Actual human browser result
The user reported this real browser exchange after the repair:
> سلام چطوریم
>
> سلام ممنونم. شما چطورید چطور میتونم در زمینه امور شرکت شهرکهای صنعتی اصفهان کمکتون کنم
Session `4445c984-c56b-4269-a7a2-49556c0902d2` completed one response with
`terminal_completed=1`, `terminal_limited=0`, and `terminal_cancelled=0`.
All **350208 PCM bytes / 7.296 seconds** were sent and acknowledged as played;
final backlog, queued and reserved bytes were zero. The close endpoint returned200.
A read-only query of the isolated database confirmed **closed / user_requested**
with `error_code=null`. This verifies the single real browser greeting round trip;
it does not score transcription accuracy or certify interruption/RAG behavior.
The three new component requests all returnedHTTP200. Cumulative retained
reservation is now **$0.925118333**, against the unchanged **$0.995118333** ceiling;
these reservations are not actual billed costs. Startup plus this greeting exhaust
the current STT/LLM admission counts. Do not run another paid conversation under
this ledger. Final billing reconciliation and applicable database acceptance
checks remain before complete Phase2 acceptance. No buffer or speed was changed.
@@ -0,0 +1,10 @@
# Diagnostic only: no real-provider credential or external HTTP.
services:
local-s2s-engine:
entrypoint: [python, /checks/browser-fixture-engine.py]
volumes: !override
- ./.local-s2s-build/assets-linux/nltk:/assets/nltk:ro
- ./.local-s2s-build/assets-linux/silero-vad:/vad/silero-vad:ro
- ./docs/evaluation/local-s2s/phase-02-linux-assets.json:/assets/assets.json:ro
- ./docs/evaluation/local-s2s/browser-fixture-engine.py:/checks/browser-fixture-engine.py:ro
- ./services/local_s2s/engine.py:/app/services/local_s2s/engine.py:ro
@@ -0,0 +1,57 @@
# Standalone candidate stack only. No operational .env/provider is changed.
x-live-settings: &live-settings
LOCAL_S2S_ENABLED: "true"
LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:?Private browser environment required}
LOCAL_S2S_MAX_OUTPUT_TOKENS: "128"
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"]'
LIVE_SESSION_SECONDS: "60"
LIVE_DIAGNOSTIC_TRACE_ENABLED: "1"
MAX_PROVIDER_SESSIONS: "1"
INGEST_EMBEDDING_LIMITS: '{"unit":"utf8_bytes","max_input_units":4096,"max_batch_units":4096,"max_batch_inputs":1}'
services:
candidate_db:
image: sha256:f1447071e6c8449dcf4056aa0994c81d3566ce5ee232de36b04dc25696a116dd
mem_limit: 512m
memswap_limit: 512m
candidate_migrations:
image: sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b
environment: *live-settings
volumes:
- /dev/null:/app/.env:ro
mem_limit: 512m
memswap_limit: 512m
candidate_api:
image: sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b
environment: *live-settings
volumes:
- /dev/null:/app/.env:ro
mem_limit: 768m
memswap_limit: 768m
local-s2s-engine:
image: sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b
user: "${LOCAL_S2S_TEST_UID:?}:${LOCAL_S2S_TEST_GID:?}"
entrypoint: [python, /checks/browser-engine.py]
command: [--allow-paid-startup]
environment:
<<: *live-settings
OPENROUTER_API_KEY: ""
LOCAL_S2S_ALLOW_PAID_STARTUP: "true"
PYTHONPATH: /app
OMP_NUM_THREADS: "1"
OPENBLAS_NUM_THREADS: "1"
volumes:
- /dev/null:/app/.env:ro
- ./.local-s2s-build/openrouter-test.key:/secret/openrouter-test.key:ro
- ./.local-s2s-build/browser-paid:/evidence:rw
- ./docs/evaluation/local-s2s/browser-engine.py:/checks/browser-engine.py:ro
- ./docs/evaluation/local-s2s/browser-budget.py:/checks/browser-budget.py:ro
- ./docs/evaluation/local-s2s/native-budget-transport.py:/checks/native-budget-transport.py:ro
read_only: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
tmpfs: ["/tmp:rw,noexec,nosuid,size=64m"]
mem_limit: 3g
memswap_limit: 3g
cpus: 2
pids_limit: 128
@@ -0,0 +1,73 @@
{
"date": "2026-10-16",
"phase": 2,
"status": "browser_ready_human_test_pending",
"url": "http://127.0.0.2:4201/login",
"credentials_path": ".local-s2s-build/browser-login.txt",
"credentials_in_report": false,
"watchdog": {
"stage": "ready",
"minimum_host_available_bytes": 6291255296,
"startup_seconds": 21.303
},
"connection_check": {
"conversation_id": "83dd690b-3462-4dec-ae60-8e791b8bace3",
"session_id": "26b4a826-fd8c-4a95-8e6a-cec634aa0204",
"events": [
"session_ready"
],
"session_ready": true,
"close": {
"session_id": "26b4a826-fd8c-4a95-8e6a-cec634aa0204",
"status": "closed",
"close_reason": "user_requested"
},
"component_attempts_before": 3,
"component_attempts_after": 3
},
"budget": {
"previous_reserved_and_billed_usd": "0.689118333",
"reserved_usd": "0.748118333",
"maximum_cumulative_usd": "0.901118333",
"reconciled_successful_components_usd": "0.001118333",
"failed_wav_retained_usd": ".25",
"unbilled_native_retained_usd": ".438",
"attempts": [
{
"stage": "transcriptions",
"reserved_usd": "0.004",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-stt-1792162309-6uGLT2gkPHgtKOWXxMTe",
"headers_elapsed_seconds": 2.036
},
{
"stage": "completions",
"reserved_usd": "0.02",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-1792162310-PefNVi4EfXsUHh17bpno",
"headers_elapsed_seconds": 0.661
},
{
"stage": "speech",
"reserved_usd": "0.035",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-tts-1792162311-EvL82g6AOq2uUg0tV49F",
"headers_elapsed_seconds": 1.752
}
]
},
"operational_changes": false,
"frontend_source_changes": false,
"audio_tuning_changes": false,
"source_sha256": {
"docs/evaluation/local-s2s/browser-budget.py": "a328ec7c73365df025d5f7d95d09db570dd25d4941aae05677f8b866260dcd90",
"docs/evaluation/local-s2s/browser-engine.py": "12a819253860c94c22a830c027d1b15f62b2c1327db6cc999d3d9182e7d2fd9a",
"docs/evaluation/local-s2s/watch-browser-engine.py": "f987466502543c1be47604442a49fc00add3d7e3f35043147b54c006af5fa2d1",
"docs/evaluation/local-s2s/check-browser-budget.py": "40f343d6e70a4718fea877a7800160df147e5066b4cdf7fc8a3a69e8757ce8be",
"docs/evaluation/local-s2s/check-browser-connection.py": "91ef4b39b224f56692b9ddd6176a71d0681d7f0768b907f949b4d0e5d3fe2035",
"docs/evaluation/local-s2s/phase-02-browser-linux.override.yml": "bfbffbfb1765b760134e163fbe3685895ba9c05292e86f5fc74618ee12cea932"
}
}
@@ -0,0 +1,83 @@
# Isolated browser handoff — 2026-10-16
Superseded by [first-turn repair and renewed real handoff](phase-02-browser-first-turn-repair-20261016.md).
The initial human test failed; use the repaired engine and carried-forward budget,
not the old startup/ledger. URL and private test-account file remain the same.
The candidate is running at **http://127.0.0.2:4201/login**. Use a fresh/private
browser window. Test-account username/password are only in the ignored private
file `.local-s2s-build/browser-login.txt` (mode0600). No original account was reset.
1. Open the page and log in using that file.
2. Start voice mode and allow microphone access.
3. Say one short greeting, e.g. «سلام، حالت چطوره؟», then remain silent while the
reply plays. Verify your transcript and the assistant's text/audio.
4. End voice mode normally. Report whether the full reply played and whether
any error appeared. This is the Phase2 normal-session acceptance, not a test
of interruption or document retrieval.
The engine watchdog stops **only the candidate engine** after30minutes from its
launch, or earlier if host MemAvailable drops below2500MiB. Sessions have the
isolated test's60-second limit. If this handoff has expired, request continuation;
do not restart the engine directly or delete a paid ledger. It would repeat paid
constructor probes. Frontend and API remain independently running.
## Actual preparation and checks
- Existing sibling Angular checkout compiled successfully in19.580s and serves
the existing separate proxy. No frontend source or original proxy was edited;
its development-server heap is capped at1GiB. No dependencies were installed.
- Existing isolated candidate DB/storage reused; migrations exited0. API readiness,
frontend HTML, proxied login and identity all returned200; valid Origin/CSRF
logout returned204. A new disposable ordinary user was provisioned through the
existing trusted maintenance CLI; previous accounts remain intact.
- Corrected immutable image89c7295e5219 runs API and engine. The standalone
[Linux override](phase-02-browser-linux.override.yml) mounts no operational.env
and supplies the OpenRouter credential only as a private engine file. Engine
process UID/GID matches that file's owner; its0600 mode is unchanged.
- Engine constructor made exactly three real HTTP200 probes (STT/LLM/TTS) and
reached startup in21.303s. The [watchdog](watch-browser-engine.py) enforces a
>5GiB pre-start gate,3GiB/no-swap engine cap, two CPUs and memory-floor stop.
- The [actual connection check](check-browser-connection.py) used proxied login,
created an owned conversation/voice session, connected through Angular's
WebSocket proxy to the API and received **session_ready** from the real engine.
Explicit close persisted **closed / user_requested**. Component admissions were
**3 before and3 after**: no audio/inference was sent during that check.
- [Budget regressions](check-browser-budget.py), script parse checks, Compose
validation and `git diff --check` passed. An initial YAML flow-sequence typo in
tmpfs options prevented container creation before any paid request; quoting the
mount fixed it. No broad app/PostgreSQL suite was rerun for this preparation.
## Budget: same original $1 authorization
Only the three individually billed, successful older component reservations were
released. Their actual total is$0.001118333. The first failed WAV retains$0.25;
all six unbilled native attempts retain$0.438. Thus previous reserved-plus-billed
exposure is **$0.689118333**, not zero and not a reset of either old ledger.
[The browser-only transport](browser-budget.py) validates models, voice, mono
PCM16 input duration<=10s and LLM input/output. It persists admission before
network I/O, counts failures, allows no retry and refuses an existing browser
ledger on restart. New ceilings: four TTS attempts at$0.035, three STT at$0.004,
three LLM at$0.02. Total new maximum$0.212; cumulative ceiling **$0.901118333**.
After the three startup probes, cumulative reservation is **$0.748118333**. These
figures are reservations, not actual invoices or the shared key's provider cap.
For this evaluation only, each Google TTS endpoint receives
`provider.options[endpoint_tag].maxOutputTokens=2048`. Full prompt maxima and this
output cap at both published routes together bound one TTS attempt at$0.032768,
below$0.035. This does not change buffer sizes or speech speed. The isolated
LLM's128-token cap is unchanged from the preceding native evaluation; actual
provider-bound LLM requests use price caps/no fallback and <=16384 input JSON
UTF8 bytes. The operational OpenAI2048-token/speed1.30/audio profile is untouched.
Official basis: [OpenRouter TTS provider options](https://openrouter.ai/docs/guides/overview/multimodal/tts)
forward remaining Google options as generation config; provider routing `only`
is explicitly unsupported for speech, so it is not used as a cost guarantee.
[Google GenerationConfig](https://ai.google.dev/api/generate-content#v1beta.GenerationConfig)
defines `maxOutputTokens`. Both currently listed tags are covered; price/tag drift
fails preparation. Per-endpoint prices are captured in ignored browser evidence.
Phase2 is still **in_progress** until human browser/microphone acceptance and
applicable final checks. Earlier accepted WAV listening is retained. RAG and
advanced interruption are Phase3. No operational switch, buffer or speed change.
@@ -0,0 +1,7 @@
# Append to candidate base + Linux browser overrides only.
# Fresh ledger carries all earlier paid attempts, including the cancelled TTS.
services:
local-s2s-engine:
image: sha256:a51167d1952a8947efe1c9048311b549a1998ab8cfaf41371228b6c326781ff9
volumes:
- ./.local-s2s-build/browser-repair-paid:/evidence:rw
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,104 @@
# Phase 2 Linux CPU dependency lock — 2026-10-15
Status: **hash lock resolved and wheel-only installation dry run passed**.
This is dependency preparation, not image build, native import or engine acceptance.
Phase 2 remains in_progress. No voice configuration or operational service changed.
## Artifacts and target
- [Complete dependency input](../../../services/local_s2s/requirements-linux-cpu.in)
retains every dependency from the pinned upstream manifest, application base
manifest and existing api/voice/embedding extras. No upstream branch was removed.
- [CPU constraints](../../../services/local_s2s/cpu-constraints.txt) use exact
official CPython 3.11 Linux x86_64 wheel URLs and SHA-256 for both
`torch==2.11.0+cpu` and `torchaudio==2.11.0+cpu`.
- [Final lock](../../../services/local_s2s/requirements-linux-cpu.lock): **134
packages**, each with hashes; no NVIDIA/CUDA/triton package requirements.
- [Machine-readable review](phase-02-dependency-lock.json): input/lock/resolver
fingerprints, commands, registry manifest, package license metadata and size estimates.
- Resolver **uv 0.9.7**, host CPython 3.13.7, cross-resolution target **Python 3.11,
x86_64-manylinux_2_40**. Actual Python 3.11 imports are not yet tested.
- Registry-verified amd64 base:
`python:3.11-slim@sha256:e529028263dbe6910a2d96f7d2b8f5266385e917fd45d286ef166977c094a51e`.
Manifest annotations identify Python 3.11.17 and Debian trixie-slim. Its layers
were **not** pulled. Debian documents trixie's [glibc 2.41](https://packages.debian.org/trixie/libc6),
which is consistent with the selected manylinux floor; verify inside the actual
image before claiming native compatibility.
The earlier recorded base digest was absent locally and failed remote verification.
It is not the base for this lock. The new manifest was inspected by exact digest;
multi-platform registry traversal also had a timeout, not an image-build failure.
## Commands and checks
Prepared source/inputs with the existing helper, using the clean pinned checkout.
The helper applied only its existing v3 NLTK downloader patch to the disposable
build copy; the original Git checkout remained clean. The generated build manifest
was updated to the newly verified base and final lock fingerprint.
Final resolution (uv 0.9.7; use a writable isolated cache and an existing Python
interpreter; no managed Python download):
```sh
uv --no-config pip compile services/local_s2s/requirements-linux-cpu.in \
-c services/local_s2s/cpu-constraints.txt \
--python-version 3.11 --python-platform x86_64-manylinux_2_40 \
--no-python-downloads --no-build --default-index https://pypi.org/simple \
--generate-hashes --emit-index-url --emit-index-annotation \
-o services/local_s2s/requirements-linux-cpu.lock
```
Final wheel-only, hash-required dry run:
```sh
uv --no-config pip install --dry-run --target .local-s2s-build/dryrun-target \
--python-version 3.11 --python-platform x86_64-manylinux_2_40 \
--no-python-downloads --only-binary :all: --require-hashes \
-r services/local_s2s/requirements-linux-cpu.lock
```
Actual commands additionally selected the existing `.venv/bin/python` explicitly,
isolated the cache under `.local-s2s-build/uv-cache` and cleared ambient UV/PIP
configuration variables. Exact argument lists are in the JSON report. Final dry
run: **exit 0, 134 packages resolved, would download 132 / install 134**; nothing
installed. Structural checks confirmed all 134 requirements have SHA-256 hashes,
both CPU wheels share a release and other dependencies use only PyPI.
Earlier attempts were retained in ignored build logs:
- Generic Linux target defaults to an older manylinux floor; full upstream
`faster-qwen3-tts[ggml]` needs a qwentts-cpp-python wheel requiring glibc 2.39.
Target changed to manylinux_2_40; no dependency removed and no source build allowed.
- Unconstrained CPU selection chose different torch/torchaudio releases; corrected
to the same official 2.11.0 CPU release. See [PyTorch version guidance](https://pytorch.org/get-started/previous-versions/).
- A broad extra CPU index shadowed unrelated PyPI packages; using only the
implicit `--torch-backend` index then exporting a broad extra index caused the
uv dry run to fail on certifi. Final direct CPU wheel constraints eliminate that
ambiguity; no unsafe index strategy or fallback was enabled. See [uv guidance](https://docs.astral.sh/uv/guides/integration/pytorch/).
- An initial dry-run invocation combined mutually exclusive `--no-build` and
`--only-binary`; corrected to wheel-only before the final successful check.
## Size, license inventory and execution boundaries
Published release metadata reviewed for all 134 pins, including license fields.
Estimated compatible compressed wheel total: **647.5 MiB**, including CPU torch
190,218,265 bytes and torchaudio 341,288 bytes. This estimate is not measured image
size or a model download; the full upstream graph includes unused local-model
branches such as faster-qwen/nano-parakeet. Registry base layers total 45,594,562
compressed bytes separately. No runtime footprint or performance claim follows.
The inventory records existing LGPL metadata for psycopg/psycopg-binary/soxr and
PyMuPDF's AGPL/commercial dual-license metadata. This is an inventory of published
metadata, not legal clearance or a bundled-binary license audit. No dependency
was removed to suppress a license or compatibility issue.
Resolution downloaded registry metadata and cached wheel artifacts, including
the CPU torch wheel (181.4 MiB) and setuptools. It **did not install libraries**,
download model weights, execute the upstream engine, pull image layers, build an
image or open any provider connection. Existing virtualenv, buffers, speed,
generation limits and active test/operational services were not changed.
Next gate: an explicitly authorized isolated image build from the verified base
and this lock, followed by actual Python 3.11/native library and complete-engine
conformance checks. Models/assets, paid component startup and browser acceptance
remain separate; a successful resolver dry run does not close those gates.
@@ -0,0 +1,53 @@
"""Provider-free acceptance on a fresh RAM-backed PostgreSQL/pgvector container."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
ROOT = Path(__file__).resolve().parents[3]
IMAGE = 'sha256:f1447071e6c8449dcf4056aa0994c81d3566ce5ee232de36b04dc25696a116dd'
name = 'rag-phase2-acceptance-' + uuid4().hex
container = None
try:
# No published port, inherited .env, provider key, bind mount or durable volume.
container = subprocess.check_output([
'docker', 'run', '-d', '--rm', '--name', name,
'--label', 'rag.phase2.disposable=true', '--network', 'rag-local-s2s-test_default',
'--memory', '512m', '--memory-swap', '512m', '--cpus', '2', '--pids-limit', '128',
'--tmpfs', '/var/lib/postgresql/data:rw,nosuid,size=384m',
'-e', 'POSTGRES_DB=phase2_acceptance_local_s2s_test', '-e', 'POSTGRES_USER=phase2_test',
'-e', 'POSTGRES_PASSWORD=disposable-test-only', IMAGE,
], text=True).strip()
row = json.loads(subprocess.check_output(['docker', 'inspect', container]))[0]
assert row['Image'] == IMAGE and row['Name'] == '/' + name
assert not row['HostConfig']['PortBindings']
assert all(m['Type'] != 'volume' for m in row['Mounts'])
for _ in range(30):
ready = subprocess.run(['docker', 'exec', container, 'pg_isready', '-h', '127.0.0.1', '-U', 'phase2_test',
'-d', 'phase2_acceptance_local_s2s_test'], capture_output=True)
if ready.returncode == 0:
break
time.sleep(1)
else:
raise RuntimeError('Disposable PostgreSQL startup deadline')
ip = next(v['IPAddress'] for v in row['NetworkSettings']['Networks'].values() if v['IPAddress'])
env = os.environ.copy()
env['TEST_DATABASE_URL'] = f'postgresql+psycopg://phase2_test:disposable-test-only@{ip}:5432/phase2_acceptance_local_s2s_test'
env['TRUSTED_HOSTS'] = '["localhost:8000","127.0.0.1:8000"]'
tests = sys.argv[1:] or ['tests/integration/test_local_s2s_phase2.py',
'tests/integration/test_phase2_postgres.py']
print(json.dumps(dict(container=container, image=IMAGE, storage='tmpfs',
database='phase2_acceptance_local_s2s_test', require_postgres=True)), flush=True)
result = subprocess.run([str(ROOT/'.venv/bin/python'), '-m', 'pytest', *tests,
'-m', 'postgres', '--require-postgres', '-q', '--tb=short', '-p', 'no:cacheprovider'],
cwd=ROOT, env=env, timeout=600)
finally:
if container:
subprocess.run(['docker', 'stop', '--time', '5', container],
check=True, stdout=subprocess.DEVNULL)
print('Disposable acceptance container stopped and auto-removed.', flush=True)
if result.returncode:
raise SystemExit(result.returncode)
@@ -0,0 +1,216 @@
{
"date": "2026-10-16",
"status": "image_built_basic_native_sdk_and_focused_checks_passed_phase2_not_accepted",
"image": {
"Id": "sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1",
"RepoTags": [
"rag-local-s2s-candidate:phase2"
],
"RepoDigests": [],
"Size": 2349831100,
"Created": "2026-10-16T05:19:05.512978492-04:00",
"Os": "linux",
"Architecture": "amd64"
},
"build": {
"exit_code": 0,
"stopped_for_disk": false,
"minimum_free_bytes": 22656344064,
"elapsed_seconds": 775.34,
"engine_started": false,
"provider_calls": 0
},
"build_command": [
"docker",
"build",
"--pull=false",
"--progress=plain",
"-f",
"services/local_s2s/Dockerfile",
"--build-arg",
"ENGINE_BASE_IMAGE=python:3.11-slim@sha256:e529028263dbe6910a2d96f7d2b8f5266385e917fd45d286ef166977c094a51e",
"-t",
"rag-local-s2s-candidate:phase2",
"."
],
"inputs": {
"services/local_s2s/Dockerfile": "bff71138703f23e7379567fde47262c592a761756090fe561f13211d03347254",
"services/local_s2s/Dockerfile.dockerignore": "2499ac41aee4813ac262ceb0029c38bf7565e88e69a579a29d22f320cabf628b",
"services/local_s2s/requirements-linux-cpu.lock": "fdcd9ad5d520012d9a31fa6b89492f69c39454339c6766172bde2df0bf0bd19a",
"services/local_s2s/engine.py": "497d034b3fd974c8d01db3bbc8af0df7295faa770c70d3294307d7af5a485f79",
"services/local_s2s/extension.py": "30f1435241284e2c5233cc6f45c703e10873454c77295f8bc97ee0b76ae83430",
"services/local_s2s/request_policy.py": "0d4d322cf596e2b690699f77a1ab509c82688c9e44795ce42e0bdd5b3e21ba9f",
"services/local_s2s/assets.py": "a16ae47b5fe196883662333cc849d0d4c301a9339b480926a721a436cb60b8cb",
"app/infrastructure/local_s2s.py": "2847552df0407949007c55ac1bc6a4558fae6b20a2b875af882a55bc2491f218",
"app/modules/voice/runtime.py": "81bece5d52ef086a9a7caa961643199dfc54e2528a40a5ee20fa2b142fa03b7d",
"app/modules/voice/configuration.py": "b3b8be699748c7bef094dc189282370e2146fee9e63385ac66143ec624f44c7e",
"docs/evaluation/local-s2s/image-sdk-smoke.py": "a02b78ae106be607c573358d6f9103aa816fdebf358a91668a5fc4dc4d3aef37"
},
"prepared_manifest": {
"upstream": "619e3fe4f71d1c6f35c15870d588a3638de34722",
"base_image": "python:3.11-slim@sha256:e529028263dbe6910a2d96f7d2b8f5266385e917fd45d286ef166977c094a51e",
"upstream_pyproject_sha256": "87ace2c683f2625f998b2852ae25ccceead5e55ed73fafd5d731d88662e450ff",
"patch_revision": "rag-local-s2s-phase2-v3",
"built": false,
"python_version": "3.11",
"python_platform": "x86_64-manylinux_2_40",
"lock_sha256": "fdcd9ad5d520012d9a31fa6b89492f69c39454339c6766172bde2df0bf0bd19a",
"resolver_version": "uv 0.9.7",
"resolver_binary_sha256": "6583a1d002bf6165be0a38366538268e028bbcbb8802880ca09cce80d5505447"
},
"checks": {
"pip_check": {
"exit_code": 0,
"message": "No broken requirements found."
},
"native_imports": {
"exit_code": 0,
"passed_modules": [
"torch",
"torchaudio",
"onnxruntime",
"nltk",
"openai",
"speech_to_speech.config",
"speech_to_speech.configured_runtime",
"speech_to_speech.backend_registry",
"speech_to_speech.STT.openai_compatible_handler",
"speech_to_speech.LLM.base_openai_compatible_language_model",
"speech_to_speech.LLM.chat_completions_language_model",
"speech_to_speech.TTS.openai_compatible_handler",
"speech_to_speech.VAD.vad_handler",
"speech_to_speech.api.openai_realtime.server",
"services.local_s2s.engine"
],
"python": "3.11.17",
"libc": [
"glibc",
"2.41"
],
"torch": "2.11.0+cpu",
"torchaudio": "2.11.0+cpu",
"cuda_available": false,
"tensor_operation": "passed",
"dotenv_absent": true,
"originals_absent": true
},
"actual_sdk_controlled_io": {
"exit_code": 0,
"script": "docs/evaluation/local-s2s/image-sdk-smoke.py",
"http_io": "HTTPX MockTransport, actual pinned handler construction/warmup/_request and installed OpenAI 2.28.0 SDK",
"cases": [
{
"limit": 17,
"outcome": "ok",
"attempts": 2,
"passed": true
},
{
"limit": 17,
"outcome": "http503",
"attempts": 1,
"passed": true
},
{
"limit": 17,
"outcome": "connect",
"attempts": 1,
"passed": true
},
{
"limit": 83,
"outcome": "ok",
"attempts": 2,
"passed": true
},
{
"limit": 83,
"outcome": "http503",
"attempts": 1,
"passed": true
},
{
"limit": 83,
"outcome": "connect",
"attempts": 1,
"passed": true
}
]
},
"startup_guards": {
"startup_without_opt_in": "refused_before_initialization",
"missing_assets": "refused_before_component_probes",
"provider_calls": 0
},
"focused": {
"tests": 423,
"failures": 0,
"errors": 0,
"skipped": 0,
"seconds": 69.65,
"junit": ".local-s2s-build/focused-20261016.xml",
"command": [
".venv/bin/python",
"-m",
"pytest",
"tests/unit/test_local_s2s_repairs.py",
"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",
"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",
"--junitxml=.local-s2s-build/focused-20261016.xml"
],
"test_only_environment": {
"TRUSTED_HOSTS": "[\"localhost:8000\",\"127.0.0.1:8000\"]"
}
}
},
"artifact_hashes": {
"image-build-20261016.log": "d21a6ac0417481e71fdd991795b200f6c7273b938df608fed297a33eb1b0aa2c",
"focused-20261016.xml": "2e15c0b213f88dd01b40286e5d1f27532b9393dbc1acd26210ceb56822a2b5c8"
},
"isolation": {
"network": "none for all smoke containers",
"read_only": true,
"no_host_secret_or_data_mounts": true,
"temporary_containers_removed": true
},
"observations": [
"Expected optional DeepFilterNet import warning; enhancement disabled, no dependency added.",
"ONNX runtime could not persist telemetry ID in read-only container and used memory; network disabled.",
"Build warning InvalidDefaultArgInFrom because the recipe intentionally requires an explicit pinned ENGINE_BASE_IMAGE; actual build supplied and verified it.",
"Full unchanged upstream dependency graph includes qwentts_cpp_python-0.5.0-1cu128 wheel for an unused local TTS backend; torch/torchaudio are CPU, but the full image is not asserted free of CUDA-tagged binaries."
],
"operations": {
"new_runtime_code_changes": false,
"voice_configuration_changed": false,
"provider_calls": 0,
"engine_pipeline_started": false,
"models_downloaded": false,
"operational_services_started_or_restarted": false,
"database_acceptance_executed": false,
"images_or_volumes_pruned": false
},
"remaining": [
"Provisioned fingerprinted NLTK and Silero VAD assets on Linux",
"Complete engine/SDK controlled-I/O and actual POSIX signals with assets",
"Actual component speech format/rate/Persian and isolated local_s2s browser acceptance",
"Real interruption/history mutation and shared RAG Phase 3",
"Historical rollback restoration and Phase 4 quality/cost"
]
}
@@ -0,0 +1,110 @@
# Phase 2 image build and checks — 2026-10-16
Status: **image built; basic native/SDK and focused regression checks passed**.
Phase 2 remains **in_progress / not accepted**: full engine initialization,
asset validation, actual signal handling and real Persian components/browser
have not been proved by these checks. This supersedes the 2026-10-15 disk-blocked
build checkpoint. [Machine-readable evidence](phase-02-image-build-20261016.json).
## Built artifact
- Local tag: `rag-local-s2s-candidate:phase2`.
- Image ID: `sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1`.
- Size: **2,349,831,100 bytes**; Linux/amd64. No registry push or RepoDigest.
- Exact upstream: `619e3fe4f71d1c6f35c15870d588a3638de34722`, existing extension v3.
- Reviewed lock SHA-256: `fdcd9ad5d520012d9a31fa6b89492f69c39454339c6766172bde2df0bf0bd19a`.
- Exact base: `python:3.11-slim@sha256:e529028263dbe6910a2d96f7d2b8f5266385e917fd45d286ef166977c094a51e`.
- Build exit **0**, elapsed **775.34 seconds**, disk guard did not fire;
minimum sampled free disk **22,656,344,064 bytes**. About 22 GB free afterward.
The user freed disk before this attempt. Verified the clean upstream checkout,
prepared v3 source patch, source manifest and lock identities before retrying.
No new runtime source or Docker recipe changes were needed today. The embedded
`engine-build-manifest.json` is the preserved pre-build input manifest and retains
`built=false`; this external record supplies the actual completed image identity.
```sh
docker build --pull=false --progress=plain -f services/local_s2s/Dockerfile \
--build-arg ENGINE_BASE_IMAGE=python:3.11-slim@sha256:e529028263dbe6910a2d96f7d2b8f5266385e917fd45d286ef166977c094a51e \
-t rag-local-s2s-candidate:phase2 .
```
Actual command/result and full log are retained in ignored
`.local-s2s-build/image-build-20261016-{command,result}.json` and
`.local-s2s-build/image-build-20261016.log`. Evidence JSON records fingerprints.
## Executed checks
Every image check used the immutable image ID, `--rm --network none --read-only`,
capabilities dropped, no-new-privileges, memory/PID limits, and no host credential
or document mounts. Checks requiring temporary files received a small tmpfs.
No ports published, engine service started or paid request sent.
| Check | Actual result |
| --- | --- |
| `python -m pip check` | exit 0, no broken requirements |
| Native/runtime imports | **15 passed**, full list in JSON |
| Python/glibc | **3.11.17 / 2.41** inside actual image |
| Torch/Torchaudio | both **2.11.0+cpu**, CUDA unavailable, tensor operation passed |
| Image data boundaries | `/app/.env` and original-document directory absent |
| Actual pinned LLM handler + installed OpenAI SDK | **6 scenarios passed** with controlled HTTPX I/O |
| Startup without explicit opt-in | refused before initialization, expected exit 2 |
| Opt-in with missing assets | fixed asset-validation failure before probes, expected exit 1 |
| Existing provider-free local/runtime/OpenAI/Gemini regressions | **423 passed in 69.65s**, zero failures/errors/skips |
Native imports covered torch, torchaudio, onnxruntime, nltk, openai, upstream
configuration/configured-runtime/backend registry, STT/LLM/TTS handlers, VAD,
Realtime server and the local launcher. Modules imported successfully; this does
not mean that an asset-backed engine instance was constructed or audio processed.
[Reproducible native SDK smoke](image-sdk-smoke.py) imports the actual installed
upstream classes and OpenAI **2.28.0** SDK. Only provider HTTP I/O is replaced by
HTTPX fixtures; it is not the earlier AST/RecordingSDK harness. At both 17 and 83
synthetic token caps, real handler construction invokes warmup and a normal
`_request` sends the configured cap. HTTP 503 and connection failures each make
exactly **one** attempt despite upstream warmup requesting six retries. These
synthetic settings are confined to the smoke process and do not alter voice tuning.
```sh
docker run --rm -i --network none --read-only \
--tmpfs /tmp:rw,noexec,nosuid,size=128m \
--cap-drop ALL --security-opt no-new-privileges --memory 2g --pids-limit 128 \
-e OMP_NUM_THREADS=1 -e OPENBLAS_NUM_THREADS=1 --entrypoint python \
sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1 - \
< docs/evaluation/local-s2s/image-sdk-smoke.py
```
Focused tests used the same 16 existing test files as the earlier 423-case review;
exact arguments and JUnit fingerprint are in the evidence JSON. Test-only
`TRUSTED_HOSTS` overrides the invalid ambient host configuration, not deployment
configuration. JUnit is `.local-s2s-build/focused-20261016.xml`. The earlier
capacity test also passed in this combined run; no assertion was relaxed.
Broader provider-free and PostgreSQL suites were not run or implied green.
## Observations and open gates
- Docker warns that the required base ARG has no default. The exact reviewed
digest was supplied; no floating fallback was introduced.
- Optional DeepFilterNet is absent and VAD import warns; enhancement remains
disabled. ONNX uses an in-memory telemetry ID because the container is read-only.
Neither warning caused a failed check or led to another dependency installation.
- **CPU scope correction:** the full retained upstream dependency graph includes
`qwentts_cpp_python-0.5.0-1cu128` for an unused local TTS branch. The image is not
certified free of CUDA-tagged binaries. Selected orchestration uses CPU Torch
and HTTP STT/LLM/TTS; no GPU inference or model-weight download occurred. Earlier
absence of NVIDIA-named package requirements did not establish binary contents.
- Fingerprinted NLTK/Silero assets have not been provisioned at the required Linux
paths. Checked standard host resource roots were absent; missing-assets guard
correctly closes before component initialization. No synthetic asset fixture
was substituted for real resources.
- Complete engine/SDK controlled-I/O, actual Linux SIGINT/SIGTERM cleanup,
real component format/rate/Persian and isolated local_s2s browser acceptance
remain open. Native imports and this SDK subset do not close those gates.
- No voice setting, buffer, speed, output cap, profile or reservation was changed.
No database/migration acceptance was run. Existing API/DB containers were already
stopped at the start of this host session and were not restarted. The unrelated
pre-existing `fastapi_db` restart loop was left unchanged. All temporary check
containers were removed; no existing images/volumes/cache were pruned.
Next: provision and verify the real local assets, then initialize the full pinned
engine in controlled-I/O/network-isolated tests before authorizing paid stages.
@@ -0,0 +1,75 @@
{
"date": "2026-10-15",
"status": "not_built_disk_capacity_guard_cancelled",
"command": [
"docker",
"build",
"--pull=false",
"--progress=plain",
"-f",
"services/local_s2s/Dockerfile",
"--build-arg",
"ENGINE_BASE_IMAGE=python:3.11-slim@sha256:e529028263dbe6910a2d96f7d2b8f5266385e917fd45d286ef166977c094a51e",
"-t",
"rag-local-s2s-candidate:phase2",
"."
],
"result": {
"exit_code": 130,
"stopped_for_disk": true,
"minimum_free_bytes": 392171520,
"provider_calls": 0,
"engine_started": false
},
"image_tag": "rag-local-s2s-candidate:phase2",
"image_id": null,
"build_context_bytes_approx": 6640000,
"disk": {
"root_free_before_cache_move_bytes_approx": 1051721728,
"root_free_after_cache_move_MiB": 1768,
"root_free_after_cancel_bytes": 1858625536,
"cancellation_threshold_bytes": 402653184,
"cache_moved_from": ".local-s2s-build/uv-cache",
"cache_moved_to": "/tmp/local-s2s-resolver-cache-20261015",
"cache_path_preserved_by_symlink": true,
"unrelated_data_pruned": false
},
"stopped_stage": "Dockerfile dependency install RUN (step 4/12), after wheel downloads, during pip installation.",
"inputs": {
"services/local_s2s/Dockerfile": "bff71138703f23e7379567fde47262c592a761756090fe561f13211d03347254",
"services/local_s2s/Dockerfile.dockerignore": "2499ac41aee4813ac262ceb0029c38bf7565e88e69a579a29d22f320cabf628b",
"services/local_s2s/requirements-linux-cpu.lock": "fdcd9ad5d520012d9a31fa6b89492f69c39454339c6766172bde2df0bf0bd19a"
},
"prepared_manifest": {
"upstream": "619e3fe4f71d1c6f35c15870d588a3638de34722",
"base_image": "python:3.11-slim@sha256:e529028263dbe6910a2d96f7d2b8f5266385e917fd45d286ef166977c094a51e",
"upstream_pyproject_sha256": "87ace2c683f2625f998b2852ae25ccceead5e55ed73fafd5d731d88662e450ff",
"patch_revision": "rag-local-s2s-phase2-v3",
"built": false,
"python_version": "3.11",
"python_platform": "x86_64-manylinux_2_40",
"lock_sha256": "fdcd9ad5d520012d9a31fa6b89492f69c39454339c6766172bde2df0bf0bd19a",
"resolver_version": "uv 0.9.7",
"resolver_binary_sha256": "6583a1d002bf6165be0a38366538268e028bbcbb8802880ca09cce80d5505447"
},
"log_sha256": "8dff37c915b008971a27b1a2544aeb80268ad7e53fa8991ce6366f3b29c9cc0d",
"checks": {
"input_lock_matches_reviewed": true,
"context_excludes_resolver_cache": true,
"source_checkout_clean": true,
"preexisting_services_still_running": true,
"final_image_absent": true,
"native_imports": "not_run"
},
"operations": {
"operational_services_changed": false,
"voice_configuration_changed": false,
"models_downloaded": false,
"provider_calls": 0,
"engine_started": false,
"existing_images_deleted": false,
"volumes_deleted": false,
"build_cache_pruned": false
},
"next_gate": "Provide adequate free space on Docker storage, preferably at least 4 GiB free, then rerun the same reviewed build. No cleanup authorization inferred."
}
@@ -0,0 +1,53 @@
# Phase 2 image build attempt — 2026-10-15
Historical disk-blocked checkpoint. **Superseded by the successful 2026-10-16
build and checks:** [current result](phase-02-image-build-20261016.md). The failure
record below is preserved unchanged as evidence of the first attempt.
Status: **not built: cancelled by disk-capacity guard**. Phase 2 remains
in_progress. No final `rag-local-s2s-candidate:phase2` image exists; native imports,
engine startup and engine/browser acceptance were not run.
User authorized building the isolated image from the reviewed lock. Inputs matched
the exact source/base/lock recorded in the dependency review. The only recipe edits
were `--only-binary=:all:` for the hash-verified dependency install and narrowing
Dockerfile-specific context exclusions to omit resolver cache and scratch logs.
The actual transferred context was **6.64 MB**. No runtime code or voice settings
changed. [Machine-readable evidence](phase-02-image-build.json) records commands,
fingerprints, cancellation result and disk observations.
Command from the repository root:
```sh
docker build --pull=false --progress=plain -f services/local_s2s/Dockerfile \
--build-arg ENGINE_BASE_IMAGE=python:3.11-slim@sha256:e529028263dbe6910a2d96f7d2b8f5266385e917fd45d286ef166977c094a51e \
-t rag-local-s2s-candidate:phase2 .
```
Before build, root and Docker storage (`/var/lib/docker`) had only approximately
1,003 MiB available. Moved **only this task's** approximately 780 MiB resolver
cache to `/tmp/local-s2s-resolver-cache-20261015` (tmpfs), preserving the original
cache path via a symlink. This freed approximately 1,768 MiB on root. Cache artifacts
are retained; no unrelated files/images/volumes were deleted and no pruning occurred.
The temporary cache is disposable across host reboot and is not a build input.
Build reached dependency installation (Dockerfile step 4/12) after downloading
the pinned wheels. A task-owned monitor sampled root free space every 0.5 seconds
and cancelled the owned build when it dropped below **384 MiB**. Recorded
minimum sample: **392,171,520 bytes**. Build client exit **130**,
`stopped_for_disk=true`. This was intentional resource cancellation, not proof of
a dependency/import incompatibility. Full build log remains in ignored
`.local-s2s-build/image-build.log`; its SHA-256 is in the evidence JSON.
After cancellation and disposable-step cleanup, root free space returned to
approximately **1.8 GiB**. Candidate tag inspection returned no image. Existing
test API/database, earlier acceptance database and `rag-postgres` remained running;
the PostgreSQL health checks remained healthy. No engine process, model-weight
download, provider call, native conformance or operational switch occurred.
Next prerequisite: sufficient Docker-disk space for downloaded wheels, unpacked
dependencies and layer export. Prefer **at least 4 GiB free** before retrying;
this is a working-space target, not a measured final image size. The build command
and verified inputs are ready to retry. No authorization to delete unrelated
build cache/images/volumes is inferred from the image-build request. No additional
build retry was attempted after the disk guard cancellation.
@@ -0,0 +1,140 @@
{
"authorized_by": "User: \u062f\u0627\u0646\u0644\u0648\u062f \u06a9\u0646",
"date": "2026-10-16",
"silero_commit": "1e261b036686cd0017d500ee96acd1c4ba572a9d",
"nltk_data_commit": "550b6625bcef1f2abff2ff770a5a0d272c9c6b2a",
"silero_bundle_scope": "Unmodified minimal JIT hub runtime source, JIT weight and LICENSE; ONNX/sequence/audio examples omitted",
"downloads": [
{
"path": "vad/LICENSE",
"url": "https://raw.githubusercontent.com/snakers4/silero-vad/1e261b036686cd0017d500ee96acd1c4ba572a9d/LICENSE",
"bytes": 1075,
"sha256": "2e63e9a38b6e8fc0c7bc37ce174caca1862870856c6daf5697cfb785e925520b",
"matches_historical_manifest": true
},
{
"path": "vad/hubconf.py",
"url": "https://raw.githubusercontent.com/snakers4/silero-vad/1e261b036686cd0017d500ee96acd1c4ba572a9d/hubconf.py",
"bytes": 1978,
"sha256": "2637a3a91d061a6e921853f5de5430f873c292662b46e5fd61edaf648b4ae5bd",
"matches_historical_manifest": true
},
{
"path": "vad/src/silero_vad/__init__.py",
"url": "https://raw.githubusercontent.com/snakers4/silero-vad/1e261b036686cd0017d500ee96acd1c4ba572a9d/src/silero_vad/__init__.py",
"bytes": 1288,
"sha256": "45fcf7e268eb0ba83ccee737b1a86cc94d7cf7487e2a1c0a31b9b72b899201f1",
"matches_historical_manifest": true
},
{
"path": "vad/src/silero_vad/data/__init__.py",
"url": "https://raw.githubusercontent.com/snakers4/silero-vad/1e261b036686cd0017d500ee96acd1c4ba572a9d/src/silero_vad/data/__init__.py",
"bytes": 0,
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"matches_historical_manifest": true
},
{
"path": "vad/src/silero_vad/data/silero_vad.jit",
"url": "https://raw.githubusercontent.com/snakers4/silero-vad/1e261b036686cd0017d500ee96acd1c4ba572a9d/src/silero_vad/data/silero_vad.jit",
"bytes": 2272526,
"sha256": "e1122837f4154c511485fe0b9c64455f7b929c96fbb8d79fbdb336383ebd3720",
"matches_historical_manifest": true
},
{
"path": "vad/src/silero_vad/model.py",
"url": "https://raw.githubusercontent.com/snakers4/silero-vad/1e261b036686cd0017d500ee96acd1c4ba572a9d/src/silero_vad/model.py",
"bytes": 1504,
"sha256": "40762a80d1278605480f75f90c6510c1a4ab71bd230f45c334e4f9c5e402181d",
"matches_historical_manifest": true
},
{
"path": "vad/src/silero_vad/utils_vad.py",
"url": "https://raw.githubusercontent.com/snakers4/silero-vad/1e261b036686cd0017d500ee96acd1c4ba572a9d/src/silero_vad/utils_vad.py",
"bytes": 31474,
"sha256": "7e0f9b3334ee4feb79abcf2251be12458329077bce28c8540878ed9d35e5aa6b",
"matches_historical_manifest": true
},
{
"path": "downloads/averaged_perceptron_tagger_eng.zip",
"url": "https://raw.githubusercontent.com/nltk/nltk_data/550b6625bcef1f2abff2ff770a5a0d272c9c6b2a/packages/taggers/averaged_perceptron_tagger_eng.zip",
"bytes": 1539115,
"sha256": "6025f530624335c67d6547d44757b357b4e79bae030a0383e9887a92c1718f0b",
"matches_historical_manifest": true
}
],
"manifest_path": "docs/evaluation/local-s2s/phase-02-linux-assets.json",
"manifest_sha256": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"file_count": 14,
"paid_calls": 0,
"runtime_downloads": 0,
"download_bytes": 3848960,
"image_id": "sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1",
"asset_image_check": {
"manifest_sha256": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"nltk_version": "3.10.3",
"nltk_sentence_pos": "passed",
"nltk_download_block": "passed",
"torch_version": "2.11.0+cpu",
"silero_local_jit_load": "passed",
"inference": [
{
"sample_rate": 8000,
"windows": 8,
"probabilities": [
0.01736745983362198,
0.017466764897108078,
0.022407179698348045,
0.014889121055603027,
0.011104934848845005,
0.009810141287744045,
0.00883372500538826,
0.007873174734413624
],
"silence_segments": [],
"passed": true
},
{
"sample_rate": 16000,
"windows": 8,
"probabilities": [
0.0016697795363143086,
0.006883786991238594,
0.008910676464438438,
0.007857130840420723,
0.005906581878662109,
0.005960718262940645,
0.005853211507201195,
0.005640285089612007
],
"silence_segments": [],
"passed": true
}
],
"paid_calls": 0,
"external_network": "none",
"scope": "real local assets and silence inference; no speech quality claim"
},
"asset_image_exit_code": 0,
"all_staged_assets_match_historical_manifest": true,
"phase_status": "in_progress",
"construction_check": {
"exit_code": 1,
"passed": false,
"script": "docs/evaluation/local-s2s/image-construction-smoke.py",
"image_runtime_source": "unmodified",
"phase": "handler context declaration during native pipeline construction",
"exception": "TypeError: function object is not subscriptable",
"location": "speech_to_speech/s2s_pipeline.py:490",
"cause": "services/local_s2s/engine.py replaces pipeline.Queue with a lambda; upstream evaluates Queue[Any] in a nested function annotation",
"outer_exception": "ConfiguredRuntimeError: Configured pipeline local construction failed.",
"provider_io": "controlled HTTPX fixture gateway; external networking disabled",
"paid_calls": 0,
"fix_applied": false
},
"source_fingerprints": {
"services/local_s2s/engine.py": "497d034b3fd974c8d01db3bbc8af0df7295faa770c70d3294307d7af5a485f79",
"services/local_s2s/pipeline.yaml": "50c3fa906b0096db01dfdc8380cef72d6136eda10c699cb3cee317899ab25947",
"docs/evaluation/local-s2s/image-assets-smoke.py": "7551fe4660dd7215a063f136349bd56cea4114ca4cc7cc7947cac3208f5e0cfb",
"docs/evaluation/local-s2s/image-construction-smoke.py": "245379e61b6bdaa15bbecea68d63238ba7545b7db48c9ea998d2b143d280b192"
}
}
@@ -0,0 +1,105 @@
# Phase 2 authorized Linux resource acquisition — 2026-10-16
Later [Queue repair and actual construction evidence](phase-02-queue-repair-20261016.md)
resolve the constructor defect recorded below. This acquisition checkpoint and
its failure observations are retained; complete native/live acceptance stays open.
The missing NLTK tagger and Silero JIT resources were downloaded following the
user's explicit authorization. Both now load successfully in the existing
immutable engine image with networking disabled. The missing-assets prerequisite
from the [earlier preflight](phase-02-offline-preflight-20261016.md) is resolved.
Phase 2 remains **in_progress**; these checks do not establish Persian speech
quality or complete native-session conformance.
## Provenance and local paths
- Official NLTK data revision: `550b6625bcef1f2abff2ff770a5a0d272c9c6b2a`.
Downloaded `averaged_perceptron_tagger_eng.zip` and safely unpacked its three
JSON files. Archive and extracted files match the prior Windows manifest.
- Official Silero revision: `1e261b036686cd0017d500ee96acd1c4ba572a9d`.
Downloaded the unmodified minimal JIT hub runtime: `hubconf.py`, package/data
markers, `model.py`, `utils_vad.py`, JIT weight and MIT license. Every downloaded
file also matches the earlier Windows manifest. Unused ONNX/sequence weights
and examples were not downloaded; this is a JIT runtime subset, not a full repo.
- Total downloaded response bodies: **3,848,960 bytes**, eight files including
the NLTK archive. The four existing punkt files were reused, not downloaded.
- Ignored host paths: `.local-s2s-build/assets-linux/nltk` and
`.local-s2s-build/assets-linux/silero-vad`. No host package installation.
The new Linux [asset manifest](phase-02-linux-assets.json) lists **14 files**.
Its SHA-256 is
`869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26`.
It deliberately differs from the historical 201-file manifest because unused
resources are omitted. All 14 retained file hashes match their old entries.
Do not substitute the old manifest digest for this Linux subset.
[Machine-readable evidence](phase-02-linux-assets-20261016.json) records each
immutable source URL, size, hash, authorization, and actual image check result.
Downloaded artifacts remain outside Git; manifests and evaluation scripts are
reviewable repository artifacts. No operational configuration was changed.
## Actual image validation
Image: `sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1`.
It was reused without rebuilding. Read-only resource mounts, `--network none`,
read-only root, dropped capabilities, no-new-privileges, 2 GiB memory and 128 PID
limits were applied. No real API credential was supplied.
[Asset check](image-assets-smoke.py), exit **0**:
- Complete manifest validation passed against the read-only mounted resources.
- NLTK **3.10.3** sentence tokenizer and original English POS tagger loaded.
An attempted NLTK download was rejected by the runtime guard.
- Torch **2.11.0+cpu** loaded the actual Silero JIT with `source='local'`.
- Eight inference windows each at **8 kHz and 16 kHz** produced finite
probabilities within [0, 1]. One second of silence at each rate yielded no
speech segments. These are real model computations on synthetic silence,
not a speech-detection accuracy measurement or a change to browser PCM24k.
Repeat from the repository root:
```sh
docker run --rm -i --network none --read-only --cap-drop ALL \
--security-opt no-new-privileges --memory 2g --pids-limit 128 \
--tmpfs /tmp:rw,noexec,nosuid,size=64m \
-e OMP_NUM_THREADS=1 -e OPENBLAS_NUM_THREADS=1 \
-v "$PWD/.local-s2s-build/assets-linux/nltk:/assets/nltk:ro" \
-v "$PWD/.local-s2s-build/assets-linux/silero-vad:/vad/silero-vad:ro" \
-v "$PWD/docs/evaluation/local-s2s/phase-02-linux-assets.json:/assets/assets.json:ro" \
--entrypoint python \
sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1 \
- < docs/evaluation/local-s2s/image-assets-smoke.py
```
No paid requests, STT/LLM/TTS weight downloads, application runtime edits, voice
speed/buffer changes, database operations, image rebuild or operational restart
occurred. The local Silero VAD weight was downloaded under this authorization.
## Additional actual construction attempt: failed
After resource validation, [the construction check](image-construction-smoke.py)
called the unmodified image's actual `build_runtime` with the real local assets
and a real local component gateway backed only by HTTPX fixtures. It used the
same isolated Docker command above, substituting this script on stdin; the
script uses fixture model IDs and a 17-token cap in its own process only.
The process exited **1** before successful construction:
```text
speech_to_speech/s2s_pipeline.py:490
def handler_context(queue_in: Queue[Any], queue_out: Queue[Any]) -> HandlerContext:
TypeError: 'function' object is not subscriptable
ConfiguredRuntimeError: Configured pipeline local construction failed.
```
Root cause: `services/local_s2s/engine.py` replaces upstream `pipeline.Queue`
with a lambda returning a bounded queue. The real upstream handler builder also
evaluates `Queue[Any]` as a type in a nested function annotation; the lambda does
not support that operation. Earlier offline fixtures/imports did not execute this
path. Missing resources are resolved, but the current image cannot construct the
complete pipeline successfully.
No application fix was applied during this resource-download task. Next scoped
repair: retain a type-compatible queue factory without changing the existing
256-item capacity or stop behavior, add regression coverage for construction,
and rerun the real image check. Then complete native session/audio/POSIX checks
before any paid component or Persian browser acceptance.
@@ -0,0 +1,19 @@
{
"files": {
"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/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",
"vad/LICENSE": "2e63e9a38b6e8fc0c7bc37ce174caca1862870856c6daf5697cfb785e925520b",
"vad/hubconf.py": "2637a3a91d061a6e921853f5de5430f873c292662b46e5fd61edaf648b4ae5bd",
"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/model.py": "40762a80d1278605480f75f90c6510c1a4ab71bd230f45c334e4f9c5e402181d",
"vad/src/silero_vad/utils_vad.py": "7e0f9b3334ee4feb79abcf2251be12458329077bce28c8540878ed9d35e5aa6b"
},
"schema": 1
}
@@ -0,0 +1,54 @@
{
"date": "2026-10-16",
"phase": 2,
"status": "prepared_real_native_blocked_host_headroom",
"sample_listening": {
"result": "accepted",
"scope": "single generated 5.16-second sample"
},
"budget": {
"authorized_usd": "1",
"previous_reserved_usd": "0.56",
"maximum_additional_reserve_usd": "0.438",
"maximum_cumulative_reserve_usd": "0.998",
"new_attempts_per_component_max": 2,
"new_paid_attempts": 0,
"provider_enforced_test_cap": false
},
"native_fixture": {
"mode": "normal",
"exit_code": 0,
"elapsed_seconds": 27.011,
"minimum_host_available_bytes": 5147222016
},
"real_native": {
"completed": false,
"first_failure": "private credential permission before gateway/admission",
"fix": "container uses credential owner UID/GID; mode0600 retained",
"resume_blocker": "host MemAvailable below 5120MiB; approximately4871MiB observed",
"native_paid_ledger_exists": false,
"latest_prestart_gate": {
"mode": "real",
"minimum_host_available_bytes": 5155991552,
"aborted": "insufficient_host_headroom_before_start",
"exit_code": null,
"elapsed_seconds": 0.0
}
},
"remaining": [
"restore host headroom",
"real native round trip and listening",
"isolated browser/microphone acceptance within cumulative budget",
"final speech billing"
],
"operational_changes": false,
"audio_tuning_changes": false,
"source_sha256": {
"docs/evaluation/local-s2s/native-budget-transport.py": "506830f949ba62ab637ebe06c589dc4ecff131bb87ab083feeb7381f256ced0a",
"docs/evaluation/local-s2s/check-native-budget.py": "a2f3aea7b3598774fc145ad93f49931def80348e081313a6d10c5e9816d542c0",
"docs/evaluation/local-s2s/check-native-runner.py": "85f6d845198a542dae7f5232e1e549eff0b60ec9502ee61688ac62138bc0745e",
"docs/evaluation/local-s2s/image-session-smoke.py": "c7448f766e03c34321b495c86c6da06e95b369f2078ef69c4b527e97476fc2b4",
"docs/evaluation/local-s2s/run-image-session-smoke.py": "9995e61a5488164a9be0afbc95c612c042da00e9d2729001349b7d2c45905e7f"
},
"superseded_by": "phase-02-real-native-20261016.json"
}
@@ -0,0 +1,91 @@
# Bounded real native session preparation — 2026-10-16
Superseded continuation: [real native round trip passed](phase-02-real-native-20261016.md).
The native paid ledger now exists; do not rerun the command below. Current cumulative
reservation is $0.998. Memory/credential blockers below are historical.
Phase 2 remains **in_progress**. The user accepted pronunciation of the existing
5.16-second Persian sample («تلفظ خوب و قابل قبول بود»). This acceptance applies
only to that sample; the recorded کوتاه/کتاه recognition mismatch remains.
## Implemented
The existing [native session harness](image-session-smoke.py) now has an explicit
`real` mode. It uses the actual native pipeline, assets, adapter setup attestation,
input transcription, manual response, correlated audio/transcript terminal and
normal session release. Input is the already approved generated sample, checked
against its previous SHA-256; the earlier prerecorded reference voice is not sent
to real providers. A response-specific greeting instruction keeps this a transport
evaluation, not production policy or RAG acceptance. Output, if successful, is
saved as ignored `.local-s2s-build/native-paid/native-real-output.wav`.
[The evaluation-only transport](native-budget-transport.py) reserves before every
provider request, including initialization warmups. It validates model, voice,
format, request body size and STT duration, forces bounded LLM tokens and provider
prices, and uses no client retry. The exclusive ledger cannot be overwritten by
running again. The source is mounted only into this evaluation; operational engine
code, configuration, frontend, audio speed and buffer limits are unchanged.
Fresh public endpoint metadata was retrieved directly from OpenRouter before
preparation. Each new TTS attempt reserves $0.205, exceeding the full token maxima
at both published routes combined ($0.2048). Each STT attempt reserves $0.004,
exceeding a full minute across all three listed routes while allowing at most ten
seconds of mono PCM16 input. Each LLM attempt reserves $0.01, bounding its input,
128 output tokens, route price and fallback policy. At most **two attempts per
component** cover one construction probe and one turn. Extra sentences, extra
transcription work or any SDK repeat are denied before another paid request.
The old **$0.56 reservation is retained in full**. The maximum additional reserve
is `2 × (0.205 + 0.004 + 0.01) = $0.438`; cumulative maximum is **$0.998** under the
user's existing $1 authorization. These are conservative reservations, not actual
charges or a provider-enforced account cap. The existing shared key cap remains $5.
Do not delete either paid ledger, automatically rerun the test after admission,
or start an unguarded Compose engine with the same credential.
[The owned-container runner](run-image-session-smoke.py) preserves one container,
3 GiB memory, no swap, two CPUs, >5 GiB host MemAvailable before start, a 2500 MiB
runtime floor and 180-second wall deadline. It now records pre-start refusal,
propagates child failure and cleans up its owned container on interruption.
Credential access uses the file owner's UID/GID while preserving mode 0600.
No database, unrelated container or operational application is stopped or changed.
## Actual validation and remaining gate
- Provider-free [budget regression checks](check-native-budget.py) passed normally
and with optimized Python: failed-attempt reservation retention, admission count,
cumulative overflow, exclusive ledger, input/model limits and LLM price routing.
Budget rejection uses explicit conditions, independent of Python assertions.
- Provider-free [runner checks](check-native-runner.py) passed: insufficient memory
prevents container launch, low headroom stops the owned container and nonzero
child status cannot be reported as success.
- Extended native harness **normal fixture** mode passed in the actual corrected
image in **27.011 s**, minimum available host memory **5,147,222,016 bytes**.
This is fixture evidence, not real-provider session acceptance.
- The first `real` invocation failed on the private credential's filesystem access
before gateway construction or any paid request. Its logs were archived. The
UID/GID correction preserves private permissions; it has not yet passed a real
run. An intervening approval-service usage-limit failure did not execute a run.
- On resumption there was no owned evaluation container and no native paid ledger.
The next launch was refused before Docker startup: MemAvailable was about
**4871 MiB**, below the unchanged **5120 MiB** pre-start requirement. No new paid
request was made. Final TTS billing remains unresolved; a read-only follow-up
confirmed the earlier LLM charge ($0.00003), while speech generation lookups
still returned 404. The key's usage delta alone does not finalize speech billing.
Once host headroom is restored, continue from the repository root using:
```sh
.venv/bin/python docs/evaluation/local-s2s/run-image-session-smoke.py real
```
This command intentionally refuses an existing native paid ledger. Reconcile any
admitted attempts before a subsequent run; do not remove the ledger to bypass it.
The generated output then needs listening, followed by separately bounded isolated
browser/microphone acceptance. This preparation does not start the browser/API
stack, switch providers or accept Phase 2. If the full reserve is consumed, browser
requests need reconciled released reservations or renewed user authorization.
Final headroom recheck: **5,155,991,552 bytes** (about 4917 MiB), still below
5 GiB. The runner recorded `insufficient_host_headroom_before_start` and exited
nonzero without launching Docker. Budget, runner, links, fingerprints and secret
scan passed; `git diff --check` passed. No native paid ledger was created.
@@ -0,0 +1,694 @@
{
"date": "2026-10-16",
"phase": 2,
"status": "in_progress",
"image_id": "sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"image_tag": "rag-local-s2s-candidate:phase2-session-fix-v2",
"image_recipe": "FROM rag-local-s2s-candidate:phase2-queue-fix\nCOPY services/local_s2s/lifecycle.py /app/services/local_s2s/lifecycle.py\nCOPY services/local_s2s/components.py /app/services/local_s2s/components.py\n",
"cases": {
"normal": {
"stage": "session_result",
"mode": "normal",
"lifecycle_outcome": 0,
"client_done": true,
"client_error": null,
"events": {
"session.created": 1,
"session.updated": 3,
"input_audio_buffer.speech_started": 1,
"input_audio_buffer.speech_stopped": 1,
"input_audio_buffer.committed": 1,
"conversation.item.created": 1,
"conversation.item.input_audio_transcription.completed": 1,
"response.created": 1,
"response.output_item.added": 1,
"response.content_part.added": 1,
"response.output_audio_transcript.delta": 1,
"response.output_audio.delta": 3,
"response.output_audio.done": 1,
"response.output_audio_transcript.done": 1,
"response.content_part.done": 1,
"response.output_item.done": 1,
"response.done": 1
},
"fixture_attempts": {
"/api/v1/audio/transcriptions": 2,
"/api/v1/chat/completions": 2,
"/api/v1/audio/speech": 2
},
"final_cleanup": {
"stage": "close",
"cleanup": {
"gateway_shutdown": 0,
"gateway_close": 0,
"runtime_stop": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 6,
"/v1/audio/transcriptions": 2,
"released": 6,
"/v1/chat/completions": 2,
"/v1/audio/speech": 2,
"close_errors": 1,
"shutdown_pending": 0
}
},
"manifest_sha256": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"audio_result": {
"bytes": 10752,
"samples": 5376,
"sha256": "cae27dc0b5dc8cebb95531de41096371a2c091b291820f257b3f62f479df7875"
},
"normal_complete": true,
"unit_released": true,
"fixture_cancelled": false,
"failure_verified": false,
"mismatch_rejected": true,
"intent_correlated": true,
"runtime_state": "stopped",
"paid_calls": 0,
"external_network": "none",
"trace_sha256": "4ca29eb3dbaab97ed7a9530ec10ae70bd34ae03c87338b7b3ab34358d0cfc277",
"fixture_llm_caps": [
17,
17
],
"native_correlations": {
"user_item_id": "item_4d7ba81533754c1e91476bbff5ff4541",
"response_id": "resp_3f4283938b584ae1b3880aa16fec918e",
"assistant_item_id": "item_008aab18bdb44c37a704507b7178fd6a",
"passed": true
},
"actual_output_format": {
"rate": 24000,
"type": "audio/pcm"
}
},
"sigint": {
"stage": "session_result",
"mode": "sigint",
"lifecycle_outcome": 0,
"client_done": true,
"client_error": null,
"events": {
"session.created": 1,
"session.updated": 1,
"input_audio_buffer.speech_started": 1,
"input_audio_buffer.speech_stopped": 1,
"input_audio_buffer.committed": 1,
"conversation.item.created": 1,
"conversation.item.input_audio_transcription.completed": 1,
"response.created": 1
},
"fixture_attempts": {
"/api/v1/audio/transcriptions": 2,
"/api/v1/chat/completions": 2,
"/api/v1/audio/speech": 1
},
"final_cleanup": {
"stage": "close",
"cleanup": {
"gateway_shutdown": 0,
"gateway_close": 0,
"runtime_stop": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 5,
"/v1/audio/transcriptions": 2,
"released": 5,
"/v1/chat/completions": 2,
"/v1/audio/speech": 1,
"cancelled": 1,
"shutdown_pending": 0
}
},
"manifest_sha256": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"audio_result": null,
"normal_complete": false,
"unit_released": false,
"fixture_cancelled": true,
"failure_verified": false,
"runtime_state": "stopped",
"paid_calls": 0,
"external_network": "none",
"signal_to_cleanup_seconds": 0.1072,
"trace_sha256": "41b63c45c48099b5c5ffb83cc2c4d722bfc7f91327ea1f0fc65854ddf0b5f898",
"fixture_llm_caps": [
17,
17
]
},
"sigterm": {
"stage": "session_result",
"mode": "sigterm",
"lifecycle_outcome": 0,
"client_done": true,
"client_error": null,
"events": {
"session.created": 1,
"session.updated": 1,
"input_audio_buffer.speech_started": 1,
"input_audio_buffer.speech_stopped": 1,
"input_audio_buffer.committed": 1,
"conversation.item.created": 1,
"conversation.item.input_audio_transcription.completed": 1,
"response.created": 1
},
"fixture_attempts": {
"/api/v1/audio/transcriptions": 2,
"/api/v1/chat/completions": 2,
"/api/v1/audio/speech": 1
},
"final_cleanup": {
"stage": "close",
"cleanup": {
"gateway_shutdown": 0,
"gateway_close": 0,
"runtime_stop": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 5,
"/v1/audio/transcriptions": 2,
"released": 5,
"/v1/chat/completions": 2,
"/v1/audio/speech": 1,
"cancelled": 1,
"shutdown_pending": 0
}
},
"manifest_sha256": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"audio_result": null,
"normal_complete": false,
"unit_released": false,
"fixture_cancelled": true,
"failure_verified": false,
"runtime_state": "stopped",
"paid_calls": 0,
"external_network": "none",
"signal_to_cleanup_seconds": 0.203,
"trace_sha256": "0c9a9e4621e0b3eff4b5008febc778b20ce5c218d87cecff2a5007b2a11ff689",
"fixture_llm_caps": [
17,
17
]
},
"failure": {
"stage": "session_result",
"mode": "failure",
"lifecycle_outcome": 0,
"client_done": true,
"client_error": null,
"events": {
"session.created": 1,
"session.updated": 1,
"input_audio_buffer.speech_started": 1,
"input_audio_buffer.speech_stopped": 1,
"input_audio_buffer.committed": 1,
"conversation.item.created": 1,
"conversation.item.input_audio_transcription.completed": 1,
"response.created": 1,
"response.output_item.added": 1,
"response.content_part.added": 1,
"response.output_audio_transcript.delta": 1,
"response.output_audio.delta": 2,
"response.output_audio.done": 1,
"error": 1,
"response.output_audio_transcript.done": 1,
"response.content_part.done": 1,
"response.output_item.done": 1,
"response.done": 1
},
"fixture_attempts": {
"/api/v1/audio/transcriptions": 2,
"/api/v1/chat/completions": 2,
"/api/v1/audio/speech": 2
},
"final_cleanup": {
"stage": "close",
"cleanup": {
"gateway_shutdown": 0,
"gateway_close": 0,
"runtime_stop": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 6,
"/v1/audio/transcriptions": 2,
"released": 6,
"/v1/chat/completions": 2,
"/v1/audio/speech": 2,
"shutdown_pending": 0
}
},
"manifest_sha256": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"audio_result": null,
"normal_complete": false,
"unit_released": true,
"fixture_cancelled": false,
"failure_verified": true,
"runtime_state": "stopped",
"paid_calls": 0,
"external_network": "none",
"trace_sha256": "b9b251201d1160bc7caf8bb19ad77fd7be05e136f53191703dcdd830a4d10d29",
"fixture_llm_caps": [
17,
17
]
}
},
"tests": {
"name": "pytest",
"errors": "0",
"failures": "0",
"skipped": "0",
"tests": "110",
"time": "6.894",
"timestamp": "2026-10-16T06:17:31.284950-04:00",
"hostname": "kali"
},
"test_command": "TRUSTED_HOSTS='[\"localhost:8000\",\"127.0.0.1:8000\"]' .venv/bin/python -m pytest tests/unit/test_local_s2s_repairs.py tests/unit/test_local_s2s_engine.py tests/unit/test_local_s2s_phase2.py -q --tb=short -p no:cacheprovider --junitxml=.local-s2s-build/native-session-tests.xml",
"first_guarded_pass": [
{
"mode": "normal",
"command": [
"docker",
"run",
"--rm",
"--name",
"rag-s2s-offline-normal-50204",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--memory",
"3g",
"--memory-swap",
"3g",
"--cpus",
"1",
"--pids-limit",
"128",
"--tmpfs",
"/tmp:rw,noexec,nosuid,size=64m",
"-e",
"PYTHONPATH=/app",
"-e",
"OMP_NUM_THREADS=1",
"-e",
"OPENBLAS_NUM_THREADS=1",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/nltk:/assets/nltk:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/silero-vad:/vad/silero-vad:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-linux-assets.json:/assets/assets.json:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/session-input-24k.pcm:/checks/input.pcm:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/image-session-smoke.py:/checks/session.py:ro",
"--entrypoint",
"python",
"sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"/checks/session.py",
"normal"
],
"minimum_host_available_bytes": 6658875392,
"aborted": null,
"exit_code": 1,
"elapsed_seconds": 128.08
},
{
"mode": "sigint",
"command": [
"docker",
"run",
"--rm",
"--name",
"rag-s2s-offline-sigint-50204",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--memory",
"3g",
"--memory-swap",
"3g",
"--cpus",
"1",
"--pids-limit",
"128",
"--tmpfs",
"/tmp:rw,noexec,nosuid,size=64m",
"-e",
"PYTHONPATH=/app",
"-e",
"OMP_NUM_THREADS=1",
"-e",
"OPENBLAS_NUM_THREADS=1",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/nltk:/assets/nltk:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/silero-vad:/vad/silero-vad:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-linux-assets.json:/assets/assets.json:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/session-input-24k.pcm:/checks/input.pcm:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/image-session-smoke.py:/checks/session.py:ro",
"--entrypoint",
"python",
"sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"/checks/session.py",
"sigint"
],
"minimum_host_available_bytes": 6616719360,
"aborted": null,
"exit_code": 0,
"elapsed_seconds": 26.014
},
{
"mode": "sigterm",
"command": [
"docker",
"run",
"--rm",
"--name",
"rag-s2s-offline-sigterm-50204",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--memory",
"3g",
"--memory-swap",
"3g",
"--cpus",
"1",
"--pids-limit",
"128",
"--tmpfs",
"/tmp:rw,noexec,nosuid,size=64m",
"-e",
"PYTHONPATH=/app",
"-e",
"OMP_NUM_THREADS=1",
"-e",
"OPENBLAS_NUM_THREADS=1",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/nltk:/assets/nltk:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/silero-vad:/vad/silero-vad:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-linux-assets.json:/assets/assets.json:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/session-input-24k.pcm:/checks/input.pcm:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/image-session-smoke.py:/checks/session.py:ro",
"--entrypoint",
"python",
"sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"/checks/session.py",
"sigterm"
],
"minimum_host_available_bytes": 6637899776,
"aborted": null,
"exit_code": 0,
"elapsed_seconds": 20.008
},
{
"mode": "failure",
"command": [
"docker",
"run",
"--rm",
"--name",
"rag-s2s-offline-failure-50204",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--memory",
"3g",
"--memory-swap",
"3g",
"--cpus",
"1",
"--pids-limit",
"128",
"--tmpfs",
"/tmp:rw,noexec,nosuid,size=64m",
"-e",
"PYTHONPATH=/app",
"-e",
"OMP_NUM_THREADS=1",
"-e",
"OPENBLAS_NUM_THREADS=1",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/nltk:/assets/nltk:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/silero-vad:/vad/silero-vad:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-linux-assets.json:/assets/assets.json:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/session-input-24k.pcm:/checks/input.pcm:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/image-session-smoke.py:/checks/session.py:ro",
"--entrypoint",
"python",
"sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"/checks/session.py",
"failure"
],
"minimum_host_available_bytes": 5513785344,
"aborted": null,
"exit_code": 1,
"elapsed_seconds": 37.015
}
],
"two_cpu_runs": [
{
"mode": "normal",
"command": [
"docker",
"run",
"--rm",
"--name",
"rag-s2s-offline-normal-52375",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--memory",
"3g",
"--memory-swap",
"3g",
"--cpus",
"2",
"--pids-limit",
"128",
"--tmpfs",
"/tmp:rw,noexec,nosuid,size=64m",
"-e",
"PYTHONPATH=/app",
"-e",
"OMP_NUM_THREADS=1",
"-e",
"OPENBLAS_NUM_THREADS=1",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/nltk:/assets/nltk:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/silero-vad:/vad/silero-vad:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-linux-assets.json:/assets/assets.json:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/session-input-24k.pcm:/checks/input.pcm:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/image-session-smoke.py:/checks/session.py:ro",
"--entrypoint",
"python",
"sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"/checks/session.py",
"normal"
],
"minimum_host_available_bytes": 5346463744,
"aborted": null,
"exit_code": 0,
"elapsed_seconds": 28.011
},
{
"mode": "failure",
"command": [
"docker",
"run",
"--rm",
"--name",
"rag-s2s-offline-failure-52375",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--memory",
"3g",
"--memory-swap",
"3g",
"--cpus",
"2",
"--pids-limit",
"128",
"--tmpfs",
"/tmp:rw,noexec,nosuid,size=64m",
"-e",
"PYTHONPATH=/app",
"-e",
"OMP_NUM_THREADS=1",
"-e",
"OPENBLAS_NUM_THREADS=1",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/nltk:/assets/nltk:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/silero-vad:/vad/silero-vad:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-linux-assets.json:/assets/assets.json:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/session-input-24k.pcm:/checks/input.pcm:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/image-session-smoke.py:/checks/session.py:ro",
"--entrypoint",
"python",
"sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"/checks/session.py",
"failure"
],
"minimum_host_available_bytes": 5443026944,
"aborted": null,
"exit_code": 0,
"elapsed_seconds": 28.013
}
],
"final_normal_run": [
{
"mode": "normal",
"command": [
"docker",
"run",
"--rm",
"--name",
"rag-s2s-offline-normal-53200",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--memory",
"3g",
"--memory-swap",
"3g",
"--cpus",
"2",
"--pids-limit",
"128",
"--tmpfs",
"/tmp:rw,noexec,nosuid,size=64m",
"-e",
"PYTHONPATH=/app",
"-e",
"OMP_NUM_THREADS=1",
"-e",
"OPENBLAS_NUM_THREADS=1",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/nltk:/assets/nltk:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/assets-linux/silero-vad:/vad/silero-vad:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-linux-assets.json:/assets/assets.json:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/.local-s2s-build/session-input-24k.pcm:/checks/input.pcm:ro",
"-v",
"/home/moz/Projects/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/image-session-smoke.py:/checks/session.py:ro",
"--entrypoint",
"python",
"sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"/checks/session.py",
"normal"
],
"minimum_host_available_bytes": 5381197824,
"aborted": null,
"exit_code": 0,
"elapsed_seconds": 29.012
}
],
"source_sha256": {
"services/local_s2s/lifecycle.py": "1dd6a9750dbb3b62d00629c8f14514a8d84b23012d60dcd9d6153ce2f794d59e",
"services/local_s2s/components.py": "7c703ef4263908fbf5fcff65395f978b6eefb35cf6d6a3cf500f6818a0ccbb12",
"services/local_s2s/engine.py": "91e613aa17e7dee66cf28864317021e99c233bd30591f11cd19b85dc7880eca6",
"services/local_s2s/pipeline.yaml": "50c3fa906b0096db01dfdc8380cef72d6136eda10c699cb3cee317899ab25947",
"tests/unit/test_local_s2s_repairs.py": "ba390ac1a03e445dece8a70bd65e5b39fe4446e8fb5ca2dfb8c1a2cbd276d8bc",
"docs/evaluation/local-s2s/image-session-smoke.py": "48a7d150a26f961f79f90308fe050de9840581e21ffaaa7368d51963db7da5ba",
"docs/evaluation/local-s2s/run-image-session-smoke.py": "670565115bdb0c8289567bff5cd93305caad70e07a0ef3df6303b11a92ffc377"
},
"input_fixture": {
"origin": "pinned upstream src/speech_to_speech/TTS/ref_audio.wav; first 3 seconds locally decoded with ffmpeg",
"source_sha256": "c8f3be0d4e32aa3ab4bbc859bb5c2ae176d2170853661edc65c94f232ecca232",
"pcm_sha256": "9fa6882785d1fa6585a05295f60391ff319571968ee00033c403b828d1785513",
"pcm_bytes": 144000,
"rate": 24000,
"channels": 1,
"format": "PCM16LE",
"appended_silence_seconds": 1
},
"incident": {
"time": "2026-10-16 06:07:57 America/New_York",
"evidence": "systemd-oomd killed app-code-12270.scope after user-slice pressure 70.57% > 50% for >20s",
"scope_memory": "about 2 GiB",
"cause": "userspace OOM-manager termination of VS Code; no kernel-panic or reboot evidence for this incident",
"contributing_inference": "two concurrent 4GiB-capped engine tests overlapped; actual usage attribution was not established",
"journal_sha256": "e359249e685e34ebff45240607f6541af123b040be277811897ee76aee2e887f"
},
"limitations": [
"Normal/cert context work timed out under a one-core test limit; cold import exceeded unchanged startup90s once. Two-core sequential normal/failure passed; cold-start performance not accepted.",
"Signal traces preceded the added setup mismatch/intent assertions; only final normal run exercised those new assertions. Earlier harness variants were not separately source-snapshotted.",
"No application database/browser/microphone/RAG acceptance in these native sessions.",
"No real STT/LLM/TTS quality, billing or voice-quality acceptance."
],
"paid_calls": 0,
"downloads": 0,
"changed_runtime": "shutdown ordering only; budgets and voice/queue settings unchanged",
"remaining": [
"bounded authorized real component audio and Persian browser listening",
"cold-start performance under target machine resources",
"existing isolated-database baseline failures and rollback gates remain separate"
],
"actual_image_runtime_hashes": {
"services/local_s2s/engine.py": "91e613aa17e7dee66cf28864317021e99c233bd30591f11cd19b85dc7880eca6",
"services/local_s2s/lifecycle.py": "1dd6a9750dbb3b62d00629c8f14514a8d84b23012d60dcd9d6153ce2f794d59e",
"services/local_s2s/components.py": "7c703ef4263908fbf5fcff65395f978b6eefb35cf6d6a3cf500f6818a0ccbb12"
},
"actual_image_source_match": "passed"
}
@@ -0,0 +1,163 @@
# Native session conformance and memory incident — 2026-10-16
Four controlled native cases now pass: normal audio/close, SIGINT, SIGTERM and
provider failure. **110 targeted tests pass**. Phase 2 remains **in_progress**;
real component audio, browser listening and cold-start performance are not accepted.
[Machine-readable evidence](phase-02-native-session-20261016.json).
This checkpoint tests the actual pinned local pipeline, real NLTK/Silero assets,
native WebSocket server and application adapter setup verification. Only upstream
provider HTTP is replaced with fixtures. No paid request, real-provider quality
claim, operational change or audio tuning is part of these checks.
## IDE termination: observed cause
The current boot's `systemd-oomd` journal records a kill at **06:07:57 America/New_York**:
the VS Code scope `app-code-12270.scope` was killed after user-slice memory pressure
was **70.57% > 50% for over 20 seconds** with reclaim activity. That application
scope used about 2 GiB. Current-boot kernel logs also record repeated memory-pressure
cache flushing. The boot started around 04:49; the previous boot ended the day
before. Evidence establishes a userspace OOM-manager kill of the IDE, not a kernel
panic or a new system boot at the incident time.
Two native engine tests had been launched concurrently with 4 GiB limits each.
Those limits are ceilings, not measurements of actual usage. Their concurrency
coincided with the incident and plausibly contributed to host pressure; the
journal does not attribute the pressure exclusively to them. They should have
been run sequentially. Interrupted runs are not accepted as successful evidence.
After resumption no owned engine test container was running. Unrelated containers
and stopped operational services were not restarted or cleaned up.
## Safer continuation
[The guarded runner](run-image-session-smoke.py) runs one engine at a time with:
- 3 GiB container memory, swap disabled, two CPUs and 128 PIDs;
- external network disabled, read-only root/resources, dropped capabilities;
- more than 5 GiB available host memory required before starting each case;
- host available-memory sampling once per second; below 2500 MiB, stop only the
owned test container;
- a 180-second wall deadline per test and recorded commands/outcomes/headroom.
These are evaluation-container resource controls. Existing application audio
buffers, credits, speed, pipeline queue capacity and runtime deadlines are unchanged.
The runner's generated PCM fixture and local assets must already exist. Invoke
from the repository root; it does not download resources or launch operational
Compose services.
## Discovered shutdown defects and scoped correction
The earlier queue-fixed image passed a normal native speech turn, but actual
SIGINT/SIGTERM during a held fixture LLM request produced `runtime_stop=2` and
lifecycle outcome 1. Cleanup waited for native workers before cancelling the
provider I/O those workers awaited. Cleanup now closes the component gateway
before waiting for runtime stop; independent cleanup and existing budgets remain.
A lightweight regression also exposed a Python 3.13 shutdown issue: the gateway
awaited `asyncio.Server.wait_closed()` before closing accepted clients. New Python
waits for those transports, delaying request cancellation. Accepted writers/tasks
are now closed/cancelled before awaiting server closure. This changes cleanup
ordering only. The final scoped suite passed **110 tests** in 6.90 seconds;
the new regression also rejected the original lifecycle cleanup order.
Files: `services/local_s2s/lifecycle.py`, `services/local_s2s/components.py`, and
`tests/unit/test_local_s2s_repairs.py`. No provider/profile contract was changed.
The corrected image adds those two runtime files to preserved queue-fixed image
`6ad4a6a418ef`, using an offline COPY-only build. Its immutable ID is:
```text
sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b
```
Tag: `rag-local-s2s-candidate:phase2-session-fix-v2`. Earlier candidate tags/images
remain intact; Compose defaults and operational selection are unchanged. The
inherited embedded build-input manifest still describes the earlier base inputs;
the correction-layer provenance is recorded separately.
## Input and evidence boundaries
[The session check](image-session-smoke.py) uses the first three seconds of the
pinned source's existing `src/speech_to_speech/TTS/ref_audio.wav`, decoded locally
by ffmpeg to mono PCM16LE at 24 kHz; one second of silence is appended in memory.
The clip stays entirely in the offline test container. It is not the user's
voice, a new recording or Persian ASR accuracy evidence. STT returns a fixed Persian
fixture transcript; LLM returns fixed Persian SSE text; TTS returns a 440 Hz test
tone. No synthesized-Persian listening claim is made.
Earlier unguarded normal runs: the first 2 GiB run timed out after response.create;
a single 4 GiB run passed. A subsequent concurrent run had provider expiry/close
errors, and its paired SIGINT run was interrupted. These are reported rather than
treated as reliable performance or successful shutdown evidence. Final acceptance
below must come only from the guarded sequential runs on the corrected image.
## Guarded native outcomes
| Case | Observed result | Outcome |
| --- | --- | --- |
| Normal session | Real Silero detects sample speech; committed input and fixture transcript share item ID; explicit response emits nonzero audio, completed transcript and successful terminal; unit releases after close | passed |
| Applied setup mismatch | Actual native model change fails application adapter attestation; restoring the correct session passes | passed in final normal run |
| Intent/item correlation | `voice_intent` preserved in created/done response; response ID and assistant item ID agree across audio/transcript events | passed in final normal run |
| SIGINT while fixture LLM is pending | Actual OS signal to engine PID; provider fixture cancelled, all cleanup counters zero, runtime stopped | passed, 0.1072 s to final cleanup |
| SIGTERM while fixture LLM is pending | Same real native path and cancellation/cleanup checks | passed, 0.2030 s to final cleanup |
| Provider HTTP 503 | Exactly one admitted generation attempt (plus constructor warmup), failed response terminal, no successful-answer terminal, unit releases and cleanup succeeds | passed |
The final normal session observed **10,752 PCM bytes / 5,376 samples**, SHA-256
`cae27dc0b5dc8cebb95531de41096371a2c091b291820f257b3f62f479df7875`.
Native setup acknowledged 24 kHz PCM. The fixture TTS tone starts with 4,800
samples; pipeline resampling/block padding changes the delivered sample count.
This establishes actual nonzero PCM transport with correlation, not natural
Persian speech or a real provider's independently verified raw sample rate.
Exactly six fixture attempts occurred in a normal turn: three constructor warmups
and one STT/LLM/TTS request. Caps were 17 tokens in this fixture process only;
operational generation limits were not changed. No response was generated before
the explicit create command. Signals observed five attempts each, because TTS was
not reached before cancellation. Failure also retained the failed terminal rather
than disguising the provider failure as a completed answer.
### Resource-dependent failures retained
The guarded one-CPU first pass had a cold-start deadline failure while lazily
importing OpenAI resource modules; actual startup's **90 s** limit was preserved.
One-core normal and provider-failure response runs later timed out while a TTS
worker was creating an SSL context. A separate SSL-only check completed in
**0.0208 s**, so these observations do not establish an intrinsically slow or
corrupt certificate bundle. With **two CPUs**, unchanged 3 GiB/no-swap/headroom
guards and unchanged application deadlines, normal/failure cases passed in
28.011/28.013 s total. The final normal run with extra mismatch/intent assertions
passed in 29.012 s. No application timeout was increased to obtain those results.
Signal cases passed under the earlier one-CPU sequential limit. Their harness
predated the additional mismatch/intent assertions; those assertions were executed
only in the final normal session. Earlier harness variants were not independently
source-snapshotted; their immutable runtime image, raw trace hashes, commands and
observed results remain recorded. The JSON fingerprints the final runnable scripts.
Minimum host available memory across the guarded first pass was about **5.14 GiB**;
the final normal run retained about **5.01 GiB**. No guard abort or newer OOM-manager
kill was observed. All owned containers were removed; unrelated services remain
untouched. These are available-host-memory measurements, not per-container peak
RAM measurements or a capacity benchmark.
Repeat from the root, only with existing resources/input/image and sufficient
host headroom:
```sh
.venv/bin/python docs/evaluation/local-s2s/run-image-session-smoke.py normal sigint sigterm failure
```
The runner writes generated logs/results under `.local-s2s-build/`; archive old
outputs before rerunning comparisons. To regenerate the local acoustic input:
```sh
ffmpeg -hide_banner -loglevel error \
-i tmp/local-s2s-upstream-619e3fe4/src/speech_to_speech/TTS/ref_audio.wav \
-t 3 -ac 1 -ar 24000 -c:a pcm_s16le -f s16le \
.local-s2s-build/session-input-24k.pcm
```
No broad/database test rerun, actual Angular/microphone session, real-provider
request, measured quality/cost acceptance or operational switch is claimed.
The next live gates require separately bounded paid-call authorization and human
Persian listening. Cold-start behavior under target deployment resources remains
an explicit qualification, not a passed reliability/performance check.
@@ -0,0 +1,253 @@
{
"date": "2026-10-16",
"phase": 2,
"status": "in_progress",
"image_id": "sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1",
"linux_lifecycle_subset": {
"cases": [
{
"signal": "SIGINT",
"stop_fails": false,
"signal_to_exit_seconds": 0.114,
"passed": true,
"observations": [
{
"stage": "startup",
"request_counts": {}
},
{
"stage": "inflight"
},
{
"stage": "close",
"cleanup": {
"runtime_stop": 0,
"gateway_shutdown": 0,
"gateway_close": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 1,
"/v1/audio/speech": 1,
"cancelled": 1,
"released": 1,
"shutdown_pending": 0
}
},
{
"stage": "verified",
"stop_fails": false,
"signal_handlers_restored": true,
"fixture_io_cancelled": true
}
]
},
{
"signal": "SIGINT",
"stop_fails": true,
"signal_to_exit_seconds": 0.1144,
"passed": true,
"observations": [
{
"stage": "startup",
"request_counts": {}
},
{
"stage": "inflight"
},
{
"stage": "close",
"cleanup": {
"runtime_stop": 1,
"gateway_shutdown": 0,
"gateway_close": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 1,
"/v1/audio/speech": 1,
"cancelled": 1,
"released": 1,
"shutdown_pending": 0
}
},
{
"stage": "verified",
"stop_fails": true,
"signal_handlers_restored": true,
"fixture_io_cancelled": true
}
]
},
{
"signal": "SIGTERM",
"stop_fails": false,
"signal_to_exit_seconds": 0.1143,
"passed": true,
"observations": [
{
"stage": "startup",
"request_counts": {}
},
{
"stage": "inflight"
},
{
"stage": "close",
"cleanup": {
"runtime_stop": 0,
"gateway_shutdown": 0,
"gateway_close": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 1,
"/v1/audio/speech": 1,
"cancelled": 1,
"released": 1,
"shutdown_pending": 0
}
},
{
"stage": "verified",
"stop_fails": false,
"signal_handlers_restored": true,
"fixture_io_cancelled": true
}
]
},
{
"signal": "SIGTERM",
"stop_fails": true,
"signal_to_exit_seconds": 0.1141,
"passed": true,
"observations": [
{
"stage": "startup",
"request_counts": {}
},
{
"stage": "inflight"
},
{
"stage": "close",
"cleanup": {
"runtime_stop": 1,
"gateway_shutdown": 0,
"gateway_close": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 1,
"/v1/audio/speech": 1,
"cancelled": 1,
"released": 1,
"shutdown_pending": 0
}
},
{
"stage": "verified",
"stop_fails": true,
"signal_handlers_restored": true,
"fixture_io_cancelled": true
}
]
}
],
"paid_calls": 0,
"scope": "real lifecycle and gateway; fixture runtime and upstream HTTP"
},
"assets": {
"source": "/home/moz/Projects/venv/olm/lib/python3.13/site-packages/llama_index/core/_static/nltk_cache",
"staging": ".local-s2s-build/assets-linux/nltk",
"files": [
{
"file": "tokenizers/punkt_tab/english/abbrev_types.txt",
"present": true,
"sha256": "92a3e070f43d9b4c5534758ca40ad7343b04e7e29bfe0c2eb658a39445a4f779",
"matches_prior_manifest": true
},
{
"file": "tokenizers/punkt_tab/english/collocations.tab",
"present": true,
"sha256": "8e2da1225e4dd2cc9dba261ee231ccb134859e21b46006e7f472c5ee269af0cf",
"matches_prior_manifest": true
},
{
"file": "tokenizers/punkt_tab/english/sent_starters.txt",
"present": true,
"sha256": "f3f8535483e1dba487241b764945168123bca3209a9645e59acd1225dc76edac",
"matches_prior_manifest": true
},
{
"file": "tokenizers/punkt_tab/english/ortho_context.tab",
"present": true,
"sha256": "4bbcca25ed3d3f06c02402abf8419b9f033b8adc06e7b482eca4e45f81a5dc4c",
"matches_prior_manifest": true
},
{
"file": "taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.weights.json",
"present": false
},
{
"file": "taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.classes.json",
"present": false
},
{
"file": "taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.tagdict.json",
"present": false
}
],
"copied": 4,
"downloads": 0
},
"nltk_image_check": {
"nltk_version": "3.10.3",
"punkt_sentence_load": "passed",
"sentence_count": 2,
"complete_configure_nltk": "expected_rejection_missing_tagger",
"exit_code": 1,
"category": "LOCAL_ENGINE_ASSET_VALIDATION_FAILED",
"downloads": 0
},
"fingerprints": {
"services/local_s2s/engine.py": "497d034b3fd974c8d01db3bbc8af0df7295faa770c70d3294307d7af5a485f79",
"services/local_s2s/lifecycle.py": "5e59a4194d13fc4399464734403ee6355b9d8558ef0663f5cf0b66a48b3a2225",
"services/local_s2s/components.py": "b2f153e0ca9c230a62363dce4bdee10ca5da4e7b6367e3c525ca3cceeb623cea",
"services/local_s2s/pipeline.yaml": "50c3fa906b0096db01dfdc8380cef72d6136eda10c699cb3cee317899ab25947",
"services/local_s2s/requirements-linux-cpu.lock": "fdcd9ad5d520012d9a31fa6b89492f69c39454339c6766172bde2df0bf0bd19a",
"docs/evaluation/local-s2s/image-lifecycle-smoke.py": "5f5f1c4f940db17092004cebc3c3395f1cf885d08c0418ce92b82230a9fa7c96"
},
"not_run": [
"real Silero JIT load/inference",
"complete NLTK POS load",
"asset-backed build_runtime",
"native pipeline session/audio conformance",
"full-engine POSIX cleanup",
"real component audio",
"Persian browser acceptance"
],
"unchanged": [
"application runtime source",
"candidate image",
"OpenAI/Gemini settings",
"voice speed and buffers",
"operational containers and database"
],
"downloads": 0,
"paid_calls": 0,
"initial_harness_attempt": {
"exit_code": 1,
"reason": "mounted script lacked /app on sys.path; rerun with PYTHONPATH=/app passed"
},
"asset_search_scope": [
"standard nltk_data and torch/hub roots",
"project trees and Hugging Face cache",
"old llama_index static nltk cache"
],
"other_cached_vad": "faster_whisper/assets/silero_vad_v6.onnx exists; not the required hub source/JIT bundle and not substituted"
}
@@ -0,0 +1,142 @@
# Phase 2 offline assets and Linux lifecycle follow-up — 2026-10-16
Current verdict (2026-10-16): **Phase 2 accepted for isolated development-only
normal Persian browser voice**. [Final evidence](phase-02-accepted-20261016.md)
and [machine-readable results](phase-02-accepted-20261016.json):
125 local + 258 preservation + 63 PostgreSQL tests passed; actual browser response
fully played and closed normally. Conservative cost exposure $0.420504399, below
the same $1 cap; final invoice details remain unresolved with full reserves held.
Paid engine stopped normally. No buffer/speed change or operational promotion.
Phase 3/4 remain not_started. Earlier checkpoints below are historical and are
superseded where they describe open Phase 2 gates.
Current incident follow-up: [first browser-turn initialization stall repaired](phase-02-browser-first-turn-repair-20261016.md).
User session failed after transcription. Native snapshots identified first-reply
Lingua model preload; same cache now warms before listener readiness. Three full
proxy/API/native continuous-input fixture sessions and98 focused tests pass.
Fixed image a51167d1952a; no buffer/speed/timeout change. Repair handoff carries all
prior attempts; cumulative reservation ceiling $0.995118333 of the same$1. Human
browser greeting passed: 7.296s fully played, closed/user_requested, no persisted error.
Current reserved exposure is $0.925118333; final billing and applicable DB gates
remain. Earlier ready checkpoints below are historical.
Current browser handoff (2026-10-16): [isolated browser is ready](phase-02-browser-ready-20261016.md).
Angular/API/login and actual proxied WebSocket session_ready/normal close passed;
no inference in connection check. Three real startup probes passed. Human microphone/
reply/transcript acceptance remains open. Same $1 authorization; reconciled prior
exposure $0.689118333, cumulative ceiling $0.901118333, startup reserve $0.748118333.
Private login file and 30-minute engine watchdog documented. No tuning/operational change.
Latest actual run (2026-10-16): [real native Persian round trip passed](phase-02-real-native-20261016.md).
Six actual requests succeeded, 2.528s reply audio, successful terminal/normal
release and clean shutdown. Cumulative reservation is $0.998 of the same $1;
final billing remains unresolved, so no further paid request. User accepted native output; browser/microphone remains open; earlier memory blocker below is historical.
No operational switch or audio tuning change.
Latest preparation (2026-10-16): [bounded real native session](phase-02-native-paid-preparation-20261016.md).
Single-sample pronunciation accepted by the user. Cumulative reservation ceiling
is $0.998 including the retained $0.56; no new paid request. Real launch awaits
>5GiB host headroom. Budget/runner checks and actual native fixture pass; browser
and real session acceptance remain open. Audio tuning and operations unchanged.
Latest real-stage checkpoint: [Persian component tests under $1 authorization](phase-02-real-components-20261016.md).
PCM TTS, STT and LLM succeeded; generated audio awaits listening and final TTS
billing remains unverified. Earlier no-paid-call statements below are historical.
Newest: [actual native sessions, signals, cleanup repair and OOM recovery](phase-02-native-session-20261016.md).
Normal native audio/close, signals and fixture-provider failure now pass; target
cold start and real component/browser listening remain unaccepted.
Later checkpoints: [resources acquired and validated](phase-02-linux-assets-20261016.md),
then [Queue repair and actual constructor success](phase-02-queue-repair-20261016.md).
Missing-resource and constructor blockers below are historical; full native
session/audio/POSIX and real-provider acceptance remain open.
Phase 2 remains **in_progress**. Four real POSIX signal checks passed against the
built image's actual lifecycle and HTTP component gateway. Full asset-backed
engine construction is still blocked by missing local NLTK tagger and Silero
source/JIT resources. No runtime source, image, provider configuration, audio
speed/buffer setting or operational service changed. No download or paid request.
Machine-readable observations and source/script fingerprints are in
[the JSON report](phase-02-offline-preflight-20261016.json).
## Existing local resources
Standard Linux `nltk_data` and Torch Hub roots were absent. Project/cache searches
located a real `punkt_tab` cache under
`/home/moz/Projects/venv/olm/lib/python3.13/site-packages/llama_index/core/_static/nltk_cache`.
The four required English tokenizer files match the SHA-256 values in the earlier
201-file [Windows resource manifest](phase-02-local-assets.json). Copies were
staged under ignored `.local-s2s-build/assets-linux/nltk`; originals were preserved.
These English resources retain the upstream tokenizer behavior; this check does
not assess Persian sentence splitting or speech quality.
In the immutable image, NLTK **3.10.3** loaded those files and split the two-sentence
English check correctly with downloading blocked. The complete `configure_nltk`
call then rejected the missing POS tagger with
`LOCAL_ENGINE_ASSET_VALIDATION_FAILED` (expected exit 1). No full asset manifest
was created because the bundle is incomplete.
Still needed:
- Three `averaged_perceptron_tagger_eng` JSON files listed in
`services/local_s2s/assets.py`.
- A complete local Silero hub source bundle, including `hubconf.py` and
`src/silero_vad/data/silero_vad.jit` with its source dependencies.
The cached faster-whisper `silero_vad_v6.onnx` is a different artifact and was not
substituted. Historical Windows paths are not mounted on this Linux machine.
Transfer the old resources or separately authorize their acquisition before full
engine testing. Fingerprint the complete supplied bundle and validate it inside
Linux before initializing handlers.
## Actual Linux signal subset
[Runnable check](image-lifecycle-smoke.py) uses the image's unmodified `run_owned`
and `ComponentServer`, real loopback HTTP, and real `os.kill` delivery to a fresh
owned child process per case. The runtime object and upstream HTTP transport are
fixtures; no speech pipeline or real provider is constructed. This is stronger
than manually invoking installed signal handlers, but does **not** close the
full-engine POSIX gate or prove container PID-1/native-worker cleanup.
| OS signal | Fixture runtime stop | Result | Signal to child exit |
| --- | --- | --- | --- |
| SIGINT | succeeds | passed | 0.1140 s |
| SIGINT | raises | passed | 0.1144 s |
| SIGTERM | succeeds | passed | 0.1143 s |
| SIGTERM | raises | passed | 0.1141 s |
Each check observed one accepted in-flight fixture request, one cancellation and
one release; zero pending requests and zero transport close errors; a closed
listening socket, joined gateway thread and restored signal handlers. Numeric
final cleanup counters were emitted even when runtime stop raised. That controlled
error made `run_owned` return 1 as required; the checking child itself exited 0.
Run from the repository root with the existing image (no image build or package
installation required):
```sh
docker run --rm --network none --read-only --cap-drop ALL \
--security-opt no-new-privileges --memory 512m --pids-limit 128 \
--tmpfs /tmp:rw,noexec,nosuid,size=32m -e PYTHONPATH=/app \
-v "$PWD/docs/evaluation/local-s2s/image-lifecycle-smoke.py:/checks/image-lifecycle-smoke.py:ro" \
--entrypoint python \
sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1 \
/checks/image-lifecycle-smoke.py
```
Initial harness launch omitted `PYTHONPATH=/app` and failed to import `services`
from the externally mounted script; the corrected command above passed all four
cases. No image or application change was needed. All owned check containers were
removed. The pre-existing unrelated `fastapi_db` restart loop was left untouched.
No broad regression rerun was needed for this evaluation-only change; the earlier
423 passing checks remain historical evidence, not a new execution claim.
## Remaining gate and next action
Provision the missing real resources, generate/review a complete fingerprint
manifest, validate NLTK POS and Silero JIT in the immutable image, then construct
the complete engine with controlled provider I/O and test native sessions/audio
and POSIX shutdown. Actual provider requests and a Persian browser/listening run
remain separate bounded-authorized steps. No Phase 2 acceptance is claimed here.
@@ -0,0 +1,94 @@
{
"date": "2026-10-16",
"phase": 2,
"status": "in_progress",
"repair": "Preserve Queue type subscription while binding the existing fail-closed queue to its owner stop event",
"queue_capacity_before": 256,
"queue_capacity_after": 256,
"overflow_behavior": "unchanged: set stop event and raise LOCAL_ENGINE_QUEUE_CAPACITY",
"base_image_id": "sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1",
"corrected_image_id": "sha256:6ad4a6a418ef3122923724760b9b2fa8e55cd7db10189614492f5e2b1dc23a74",
"corrected_image_tag": "rag-local-s2s-candidate:phase2-queue-fix",
"corrected_image_bytes": 2349835421,
"build_recipe": "FROM rag-local-s2s-candidate:phase2\nCOPY services/local_s2s/engine.py /app/services/local_s2s/engine.py\n",
"build_command": "docker build --pull=false --network none --progress=plain -f .local-s2s-build/queue-fix.Dockerfile -t rag-local-s2s-candidate:phase2-queue-fix .",
"build_exit_code": 0,
"construction_exit_code": 0,
"construction_observations": [
{
"stage": "construction",
"passed": true,
"manifest_sha256": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"handlers": [
"VADHandler",
"OpenAICompatibleSTTHandler",
"TranscriptionNotifier",
"ChatCompletionsApiModelHandler",
"LMOutputProcessor",
"OpenAICompatibleTTSHandler"
],
"fixture_requests": [
"/api/v1/audio/transcriptions",
"/api/v1/chat/completions",
"/api/v1/audio/speech"
],
"counts": {
"accepted": 3,
"/v1/audio/transcriptions": 1,
"released": 3,
"/v1/chat/completions": 1,
"/v1/audio/speech": 1
},
"paid_calls": 0,
"queue_generic_and_capacity": "passed",
"queue_capacity": 256
},
{
"stage": "construction_cleanup",
"passed": true,
"runtime_state": "stopped",
"counts": {
"accepted": 3,
"/v1/audio/transcriptions": 1,
"released": 3,
"/v1/chat/completions": 1,
"/v1/audio/speech": 1,
"shutdown_pending": 0
}
}
],
"tests": {
"name": "pytest",
"errors": "0",
"failures": "0",
"skipped": "0",
"tests": "109",
"time": "9.741",
"timestamp": "2026-10-16T05:51:28.420746-04:00",
"hostname": "kali"
},
"test_command": "TRUSTED_HOSTS='[\"localhost:8000\",\"127.0.0.1:8000\"]' .venv/bin/python -m pytest tests/unit/test_local_s2s_engine.py tests/unit/test_local_s2s_repairs.py tests/unit/test_local_s2s_phase2.py -q --tb=short -p no:cacheprovider --junitxml=.local-s2s-build/queue-fix-tests.xml",
"fingerprints": {
"services/local_s2s/engine.py": "91e613aa17e7dee66cf28864317021e99c233bd30591f11cd19b85dc7880eca6",
"docs/evaluation/local-s2s/image-construction-smoke.py": "203b64546ea51a413dac011d2c945568ffd8483102deff9b3e6432261619c5cf",
"services/local_s2s/pipeline.yaml": "50c3fa906b0096db01dfdc8380cef72d6136eda10c699cb3cee317899ab25947",
"services/local_s2s/requirements-linux-cpu.lock": "fdcd9ad5d520012d9a31fa6b89492f69c39454339c6766172bde2df0bf0bd19a"
},
"initial_test_attempt": "22 loopback failures and 1 socket-validation setup error under restricted sandbox; 86 passed. Same tests passed 109/109 with loopback access; no assertions or config files changed.",
"initial_full_recipe_attempt": "network-none invalidated dependency RUN cache; pip could not resolve its pinned wheel URL, build exit 1. Reused verified image instead; no dependency or model downloads.",
"unchanged": [
"OpenAI/Gemini",
"audio buffers, playback credit and speed",
"pipeline settings",
"lock and dependencies",
"operational services and database",
"original candidate image tag"
],
"paid_calls": 0,
"downloads": 0,
"remaining": [
"native server start and session/audio controlled-I/O conformance",
"native pipeline Linux signal cleanup",
"authorized real components and Persian browser acceptance"
]
}
@@ -0,0 +1,70 @@
# Phase 2 Queue construction repair — 2026-10-16
The actual engine constructor now succeeds. The launcher binds the existing
`FailClosedQueue` through a local subclass instead of a lambda, so upstream
`Queue[Any]` annotations remain valid. Capacity remains **256 items**, FIFO order
is preserved, and overflow still sets the owner stop event and raises
`LOCAL_ENGINE_QUEUE_CAPACITY`. No audio tuning, pipeline settings, provider
contract, dependency or operational service changed.
This supersedes the construction blocker in the
[resource acquisition report](phase-02-linux-assets-20261016.md).
Phase 2 remains **in_progress**: construction is not a running native session,
speech-quality acceptance or native-worker signal test.
## Verified checks
- **109 targeted tests passed**, zero failures/errors/skips. Command and timing
are in the [machine-readable evidence](phase-02-queue-repair-20261016.json).
Initial restricted-sandbox execution blocked local sockets (22 failures and
one setup error); the unchanged suite passed with local socket access.
- The enhanced [construction regression](image-construction-smoke.py) passed in
the corrected image with real local NLTK/Silero resources and actual pinned
handlers/SDK. Only upstream HTTP responses were fixtures; external networking
was disabled and no provider credential was supplied.
- Constructed handlers: VAD, OpenAI-compatible STT, transcription notifier,
Chat Completions LLM, LM output processor and OpenAI-compatible TTS. Attestation
checked the initialized components. Exactly **three fixture warmup requests**,
one per STT/LLM/TTS route, were accepted and released.
- The regression instantiated the installed `pipeline.Queue[int]`, filled its
256 slots, observed the expected overflow error/owner stop, and drained every
item in FIFO order. Final runtime state was `stopped`; the component gateway
joined with zero pending requests. No native server or browser session started.
- `git diff --check` passed. No PostgreSQL test or broad-suite pass is claimed.
## Corrected candidate image
The preserved original image is
`sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1`.
The corrected image is tagged `rag-local-s2s-candidate:phase2-queue-fix`:
```text
sha256:6ad4a6a418ef3122923724760b9b2fa8e55cd7db10189614492f5e2b1dc23a74
```
It adds only the corrected launcher to the verified old image, without dependency
installation, using this generated recipe after verifying the old tag's ID:
```dockerfile
FROM rag-local-s2s-candidate:phase2
COPY services/local_s2s/engine.py /app/services/local_s2s/engine.py
```
Actual build used `--pull=false --network none`. The initial full-recipe offline
attempt could not reuse the dependency-install RUN cache and failed on DNS, so
the minimal correction layer avoided any new downloads. No operational image was
retagged or container restarted. The inherited embedded build-input manifest still
describes the original base preparation; the new image identity and corrected
source hashes are recorded externally in this report's JSON, not represented as
an original full-recipe build.
To repeat the construction check, use the resource report's exact Docker command,
substituting the corrected image ID above and
`docs/evaluation/local-s2s/image-construction-smoke.py` as stdin. Resources and
manifest mounts remain the same. No source overlay is needed in the corrected
image. The normal service Dockerfile also copies the corrected launcher on future
full builds; default Compose selection was not changed by this repair.
Next: controlled native server/session/audio execution and native pipeline POSIX
cleanup, followed by separately authorized real components and Persian listening.
No real provider call, model download or Phase 2 acceptance occurred here.
@@ -0,0 +1,209 @@
{
"date": "2026-10-16",
"phase": 2,
"status": "real_components_sample_listening_accepted_integration_pending",
"authorization_usd": "1",
"provider_key_cap_usd": "5",
"provider_key_cap_changed": false,
"provider_enforced_test_cap": false,
"attempts": 4,
"stage_observations": [
{
"stage": "tts",
"reserved_usd": "0.25",
"status": "failed",
"http_status": 400,
"headers": {
"content-type": "application/json"
},
"error_type": "HTTPStatusError"
},
{
"stage": "tts_pcm",
"reserved_usd": "0.25",
"status": "received",
"http_status": 200,
"headers": {
"content-type": "audio/pcm;rate=24000;channels=1",
"x-generation-id": "gen-tts-1792147214-vtWNLNMAyxlzEM87Oz23"
},
"bytes": 247680,
"elapsed_seconds": 2.73
},
{
"stage": "stt",
"reserved_usd": "0.05",
"status": "received",
"http_status": 200,
"headers": {
"content-type": "application/json",
"x-generation-id": "gen-stt-1792147218-l61CrhLNYq2tgkQjV8TS"
},
"bytes": 152,
"elapsed_seconds": 1.946
},
{
"stage": "llm",
"reserved_usd": "0.01",
"status": "received",
"http_status": 200,
"headers": {
"content-type": "application/json",
"x-generation-id": "gen-1792147219-rEyCmMLKSrqpXjdZyj4I"
},
"bytes": 842,
"elapsed_seconds": 0.784
}
],
"reserved_usd": "0.56",
"reserve_basis": {
"budget_usd": "1",
"total_reserved_usd": "0.31",
"tts_full_endpoint_maxima_usd": "0.2048000",
"requests_max": 4,
"provider_enforced_test_cap": false,
"basis": "Published endpoint limits/prices, bounded input, fixed requests and no client retries; shared key retains its existing $5 cap.",
"maximum_execution_reserved_usd": "0.56"
},
"first_error": "WAV speech HTTP400; original error response body not retained. Stopped, then explicit PCM-format correction; no automatic retry or model substitution.",
"models": {
"tts": "google/gemini-3.8-flash-lite-tts",
"voice": "Kore",
"stt": "openai/whisper-large-v3",
"llm": "openai/gpt-4.1-mini"
},
"tts": {
"path": ".local-s2s-build/persian-real-tts-one-dollar.wav",
"header_rate": 24000,
"frames": 123840,
"seconds": 5.16,
"rate_independently_verified": false,
"pcm_native_path_tested": true,
"sha256": "1edd8a6ef0182664f58dc6a37464bcfee3ab434e225c161aab3890930fda0998",
"rate_basis": "provider Content-Type audio/pcm;rate=24000;channels=1; saved WAV header is locally constructed",
"independent_physical_sample_rate_measurement": false
},
"reference_text": "سلام، این یک آزمایش کوتاه برای بررسی صدای فارسی است.",
"transcript": " سلام، این یک آزمایش کتاه برای بررسی صدای فارسی است.",
"transcript_observation": "Expected کوتاه; STT returned کتاه. User accepted pronunciation of this single generated sample; the written ASR mismatch is retained.",
"stt_usage": {
"seconds": 10,
"cost": 0.000308333333333
},
"llm": {
"model_returned": "openai/gpt-4.1-mini",
"answer": "سلام! حالت چطوره؟ 😊",
"finish_reason": "stop",
"usage": {
"prompt_tokens": 39,
"completion_tokens": 9,
"total_tokens": 48,
"cost": 3e-05,
"is_byok": false,
"prompt_tokens_details": {
"cached_tokens": 0,
"cache_write_tokens": 0,
"audio_tokens": 0,
"video_tokens": 0
},
"cost_details": {
"upstream_inference_cost": 3e-05,
"upstream_inference_prompt_cost": 1.56e-05,
"upstream_inference_completions_cost": 1.44e-05
},
"completion_tokens_details": {
"reasoning_tokens": 0,
"image_tokens": 0,
"audio_tokens": 0
}
}
},
"cost": {
"reported_stt_plus_llm_usd": "0.000338333333333",
"tts_actual_cost": "0.00078",
"total_final_cost": null,
"observed_key_usage_delta_usd": "0",
"generation_billing_lookups": [
{
"stage": "tts_pcm",
"generation_id": "gen-tts-1792147214-vtWNLNMAyxlzEM87Oz23",
"status": 404
},
{
"stage": "stt",
"generation_id": "gen-stt-1792147218-l61CrhLNYq2tgkQjV8TS",
"status": 404
},
{
"stage": "llm",
"generation_id": "gen-1792147219-rEyCmMLKSrqpXjdZyj4I",
"status": 404
}
],
"verdict": "Later read-only billing confirms $0.001118333 for the three successful calls. The failed initial WAV attempt is excluded; the newer native-turn cost remains separate and unresolved.",
"latest_successful_three_call_total_usd": "0.001118333",
"latest_generation_billing": [
{
"stage": "tts_pcm",
"generation_id": "gen-tts-1792147214-vtWNLNMAyxlzEM87Oz23",
"http_status": 200,
"billing": {
"total_cost": 0.00078,
"native_tokens_prompt": 12,
"native_tokens_completion": 129,
"provider_name": "Google",
"created_at": "2026-10-16T10:40:14.709Z"
}
},
{
"stage": "stt",
"generation_id": "gen-stt-1792147218-l61CrhLNYq2tgkQjV8TS",
"http_status": 200,
"billing": {
"total_cost": 0.000308333,
"native_tokens_prompt": null,
"native_tokens_completion": null,
"provider_name": "Groq",
"created_at": "2026-10-16T10:40:18.23Z"
}
},
{
"stage": "llm",
"generation_id": "gen-1792147219-rEyCmMLKSrqpXjdZyj4I",
"http_status": 200,
"billing": {
"total_cost": 3e-05,
"native_tokens_prompt": 39,
"native_tokens_completion": 9,
"provider_name": "OpenAI",
"created_at": "2026-10-16T10:40:19.452Z"
}
}
]
},
"source_sha256": {
"docs/evaluation/local-s2s/live-components-one-dollar.py": "b538fb04f032e086e328b0a98527ebf8a7fa893158e81fe8014f879e978da859"
},
"runtime_changes": false,
"heavy_containers_started": false,
"operational_changes": false,
"settings_changes": false,
"remaining": [
"real native engine/component integration and isolated browser acceptance",
"final provider billing confirmation",
"broader Persian/noise/domain vocabulary comparison"
],
"sources": [
"https://openrouter.ai/api/v1/models?output_modalities=all",
"https://openrouter.ai/api/v1/models/google/gemini-3.8-flash-lite-tts/endpoints",
"https://openrouter.ai/api/v1/models/openai/whisper-large-v3/endpoints",
"https://openrouter.ai/docs/client-sdks/python/sdks/tts/README.md",
"https://openrouter.ai/docs/client-sdks/python/sdks/stt/README.md"
],
"human_listening": {
"date": "2026-10-16",
"result": "accepted",
"user_observation": "تلفظ خوب و قابل قبول بود",
"scope": "The single 5.16-second generated Persian sample; not full conversation or a broad Persian benchmark."
}
}
@@ -0,0 +1,103 @@
# Phase 2 real components under a $1 authorization — 2026-10-16
Later billing follow-up: the three successful calls below now have provider
records: TTS $0.00078 + STT $0.000308333 + LLM $0.00003 = **$0.001118333**.
The failed WAV attempt is excluded. Earlier pending-billing observations below
are historical; the newer native-turn bill remains unresolved.
Three actual component calls succeeded: Gemini 3.8 Flash-Lite TTS/Kore produced
Persian PCM, Whisper large-v3 transcribed it, and GPT-4.1 mini replied in Persian.
There was also one earlier failed WAV-format speech attempt, HTTP400. No automatic
retry or model substitution occurred. Phase 2 is **in_progress**: the user accepted pronunciation of the single saved sample. Real native-engine/
browser integration and final billing remain unaccepted.
[Machine-readable evidence](phase-02-real-components-20261016.json) records the
actual request headers/IDs, usage, stage timing and qualifications. Audio is in
ignored `.local-s2s-build/persian-real-tts-one-dollar.wav`, SHA-256
`1edd8a6ef0182664f58dc6a37464bcfee3ab434e225c161aab3890930fda0998`.
## Authorization, cost and containment
The user authorized starting real testing with a **$1 total limit** and supplied
an OpenRouter key. Read-only metadata showed that key's existing provider cap was
$5, not $1; it was not a management key. No key cap or operational credential was
changed. The supplied secret was stored only in ignored local storage with 0600
permissions and is absent from these reports and scripts.
[The bounded runner](live-components-one-dollar.py) reserves cost before sending
each request, persists failed/in-flight admissions, uses no client retries, and
refuses accidental re-execution of an existing ledger. The initial sequence
reserved $0.25 TTS + $0.05 STT + $0.01 LLM. After the sole WAV HTTP400 it stopped.
An explicitly announced PCM-format correction matching the native engine retained
that first reservation and added $0.31, for **$0.56 total reserved** across four
attempts. This is below the authorization; it is not a provider-enforced $1 key cap.
The reservation is based on captured [official model metadata](https://openrouter.ai/api/v1/models?output_modalities=all)
and [TTS endpoints](https://openrouter.ai/api/v1/models/google/gemini-3.8-flash-lite-tts/endpoints):
both TTS endpoints list 8192 maximum prompt tokens and 16384 completion tokens at
$0.0000005/$0.000006 per token. Even both full endpoint maxima total $0.2048,
below the $0.25 reservation for one TTS attempt. STT is limited to ten seconds;
its $0.05 reservation exceeds a full minute at every listed route. LLM input is
bounded and output capped at 128 tokens, with provider price limits and fallback
disabled. These caps apply to this evaluation only; operational voice limits stay.
Actual reported STT cost is **$0.000308333333333**, with ten billed seconds for
5.16 seconds of audio. LLM reported **$0.00003**, 39 prompt and nine completion
tokens. Their combined reported cost is **$0.000338333333333**.
**TTS cost and the final total are not yet verified.** Read-only generation lookups
for the three returned IDs yielded404, and the key usage total had not changed
at the final lookup. That zero delta is not proof the calls were free. Keep the
entire $0.56 reservation; no further paid requests were made and no final cost
acceptance is claimed.
No ML engine/container, startup probes, database, browser, user microphone or
operational service was launched. The small HTTP runner ran stages sequentially,
avoiding the earlier native-test memory pressure. No models were downloaded and
no audio buffers, speed or provider selection were modified.
## Actual observations
| Stage | Outcome |
| --- | --- |
| Initial TTS/WAV | HTTP400; original error body was not retained, so its precise cause is not established |
| Explicit TTS/PCM correction | HTTP200 in 2.730 s; 247680 raw bytes; provider Content-Type declares `audio/pcm;rate=24000;channels=1` |
| STT/multipart, language fa | HTTP200 in 1.946 s; Persian text returned |
| LLM | HTTP200 in 0.784 s; Persian greeting; successful stop terminal |
The saved WAV contains **123840 PCM16 mono samples**, 5.16 seconds using the
provider-declared 24 kHz rate. Its WAV header was constructed locally; it is not
independent measurement of the physical sample rate. The real PCM endpoint now
has compatibility evidence; the rejected WAV request is not hidden or classified
as a proven format-specific provider defect without its missing error body.
TTS source text:
> سلام، این یک آزمایش کوتاه برای بررسی صدای فارسی است.
Actual STT:
> سلام، این یک آزمایش کتاه برای بررسی صدای فارسی است.
The transcript differs at «کوتاه/کتاه». The user listened and reported
«تلفظ خوب و قابل قبول بود» on 2026-10-16. This accepts pronunciation of the
single saved sample; the written recognition mismatch is retained. This one synthetic example is
not a Persian accuracy benchmark, naturalness score, accent/noise test or RAG
answer-quality evaluation. Actual LLM reply was «سلام! حالت چطوره؟ 😊» under a
small greeting-only test instruction; production policy adherence was not tested.
The single generated sample has passed user listening; the LLM reply has not yet been synthesized here.
The run order was **TTS → STT → LLM** to avoid sending an unconsented existing
voice clip to a provider. Only the fixed test text and its generated audio were
sent. A full browser conversation and synthesis of the LLM reply were not run.
## Validation and next gate
Offline budget check and a negative authorization-overflow check passed before
execution; `git diff --check` passed. No broad application tests were rerun for
this standalone evaluation. Existing 110-test/native evidence remains separate.
The ledger is exclusive and intentionally prevents repeating paid requests by
running the command again. Do not delete it to bypass the cumulative budget.
Next: reconcile billing and prepare bounded real-engine/browser acceptance
within the remaining authorization. Single-sample listening is accepted.
No spending beyond the retained reservation or Phase 2 acceptance is implied.
@@ -0,0 +1,306 @@
{
"date": "2026-10-16",
"phase": 2,
"status": "real_native_round_trip_passed_browser_pending",
"image": "sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b",
"runner": {
"mode": "real",
"minimum_host_available_bytes": 5393440768,
"aborted": null,
"exit_code": 0,
"elapsed_seconds": 130.096
},
"native": {
"lifecycle_outcome": 0,
"client_done": true,
"client_error": null,
"events": {
"session.created": 1,
"session.updated": 3,
"input_audio_buffer.speech_started": 1,
"input_audio_buffer.speech_stopped": 1,
"input_audio_buffer.committed": 1,
"conversation.item.created": 1,
"conversation.item.input_audio_transcription.completed": 1,
"response.created": 1,
"response.output_item.added": 1,
"response.content_part.added": 1,
"response.output_audio_transcript.delta": 1,
"response.output_audio.delta": 21,
"response.output_audio.done": 1,
"response.output_audio_transcript.done": 1,
"response.content_part.done": 1,
"response.output_item.done": 1,
"response.done": 1
},
"audio_result": {
"bytes": 121344,
"samples": 60672,
"sha256": "e1c422f753c4ce4c9f0d3f88d1559fc938c0e2e703ddaa7ec34e0902d99682f9"
},
"normal_complete": true,
"unit_released": true,
"mismatch_rejected": true,
"intent_correlated": true,
"runtime_state": "stopped",
"paid_calls": 6,
"manifest_sha256": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"final_cleanup": {
"stage": "close",
"cleanup": {
"gateway_shutdown": 0,
"gateway_close": 0,
"runtime_stop": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 6,
"/v1/audio/transcriptions": 2,
"released": 6,
"/v1/chat/completions": 2,
"/v1/audio/speech": 2,
"shutdown_pending": 0
}
}
},
"transcripts": [
{
"type": "conversation.item.input_audio_transcription.completed",
"text": " سلام، این یک آزمایش کتاه برای بررسی صدای فارسی است."
},
{
"type": "response.output_audio_transcript.done",
"text": "سلام صدای شما دریافت شد."
}
],
"terminal": {
"status": "completed",
"usage": {
"input_token_details": {
"audio_tokens": 0,
"cached_tokens": 0,
"cached_tokens_details": null,
"image_tokens": 0,
"text_tokens": 584
},
"input_tokens": 584,
"output_token_details": {
"audio_tokens": 0,
"text_tokens": 9
},
"output_tokens": 9,
"total_tokens": 593
},
"metadata": {
"voice_intent": "fixture-intent-1",
"speech_to_speech.turn_latency": "{\"e2e_s\":15.251953101003892,\"hold_s\":null,\"llm_s\":0.9196348260011291,\"response_key\":\"e4a1ac43052b421299908c73eb8addfb\",\"smart_status\":null,\"source\":\"speech\",\"status\":\"completed\",\"stt_s\":null,\"tts_ttfa_s\":1.9715482209976471,\"turn_id\":\"turn_1\",\"turn_revision\":0,\"vad_decision_s\":null,\"version\":2}"
}
},
"budget": {
"previous_reserved_usd": "0.56",
"reserved_usd": "0.998",
"maximum_cumulative_reserved_usd": "0.998",
"attempts": [
{
"stage": "transcriptions",
"reserved_usd": "0.004",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-stt-1792161394-vJMHFfdwTmHBDSBW48aH",
"headers_elapsed_seconds": 3.536
},
{
"stage": "completions",
"reserved_usd": "0.01",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-1792161398-BRPNxd79tYYoQZdg43Ce",
"headers_elapsed_seconds": 0.703
},
{
"stage": "speech",
"reserved_usd": "0.205",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-tts-1792161399-3YAyVlL5MSSKbqaZWnIz",
"headers_elapsed_seconds": 1.236
},
{
"stage": "transcriptions",
"reserved_usd": "0.004",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-stt-1792161402-nvlLMzXrx1QdjtVT6Nuu",
"headers_elapsed_seconds": 1.267
},
{
"stage": "completions",
"reserved_usd": "0.01",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-1792161403-FNP9pxaRHEq63J0h1qbo",
"headers_elapsed_seconds": 0.841
},
{
"stage": "speech",
"reserved_usd": "0.205",
"status": "headers_received",
"http_status": 200,
"generation_id": "gen-tts-1792161415-n472pZcpHCoMng79OO5S",
"headers_elapsed_seconds": 1.937
}
]
},
"billing_read_only_followup": {
"generation_lookups": [
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792161394-vJMHFfdwTmHBDSBW48aH",
"http_status": 404
},
{
"stage": "completions",
"generation_id": "gen-1792161398-BRPNxd79tYYoQZdg43Ce",
"http_status": 404
},
{
"stage": "speech",
"generation_id": "gen-tts-1792161399-3YAyVlL5MSSKbqaZWnIz",
"http_status": 404
},
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792161402-nvlLMzXrx1QdjtVT6Nuu",
"http_status": 404
},
{
"stage": "completions",
"generation_id": "gen-1792161403-FNP9pxaRHEq63J0h1qbo",
"http_status": 404
},
{
"stage": "speech",
"generation_id": "gen-tts-1792161415-n472pZcpHCoMng79OO5S",
"http_status": 404
}
],
"key_http_status": 200,
"key": {
"usage": 0.134551603,
"limit": 5,
"limit_remaining": 4.865448397
}
},
"observed_shared_key_usage_delta_since_initial_components_usd": "0.001118333",
"billing_verdict": "Earlier three successful standalone component calls now total $0.001118333 in provider generation records. All six newer native-test generation records still return404; newest turn and warmup costs are not finalized. Retain reservation; no new paid call.",
"audio": {
"path": ".local-s2s-build/native-paid/native-real-output.wav",
"sha256": "106d419d45eaa67e334489a2be18a78dba705da4de55914178cba46bef1f1e9e",
"human_listening": "accepted",
"rate_basis": "native declared 24000Hz PCM16 mono; WAV header constructed locally",
"frames": 60672,
"rate": 24000,
"channels": 1,
"seconds": 2.528,
"human_acceptance": {
"date": "2026-10-16",
"user_observation": "تاییدش میکنم",
"scope": "the 2.528-second native output WAV"
}
},
"operational_changes": false,
"audio_tuning_changes": false,
"owned_containers_remaining": false,
"remaining": [
"isolated backend/browser/microphone acceptance within reconciled authorization",
"final component billing",
"broader Persian/noise/domain vocabulary quality",
"cold-start qualification, prior DB and rollback gates"
],
"source_sha256": {
"docs/evaluation/local-s2s/image-session-smoke.py": "c7448f766e03c34321b495c86c6da06e95b369f2078ef69c4b527e97476fc2b4",
"docs/evaluation/local-s2s/native-budget-transport.py": "506830f949ba62ab637ebe06c589dc4ecff131bb87ab083feeb7381f256ced0a",
"docs/evaluation/local-s2s/run-image-session-smoke.py": "9995e61a5488164a9be0afbc95c612c042da00e9d2729001349b7d2c45905e7f",
"docs/evaluation/local-s2s/check-native-budget.py": "a2f3aea7b3598774fc145ad93f49931def80348e081313a6d10c5e9816d542c0",
"docs/evaluation/local-s2s/check-native-runner.py": "85f6d845198a542dae7f5232e1e549eff0b60ec9502ee61688ac62138bc0745e"
},
"latest_billing_followup": {
"native": [
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792161394-vJMHFfdwTmHBDSBW48aH",
"http_status": 404
},
{
"stage": "completions",
"generation_id": "gen-1792161398-BRPNxd79tYYoQZdg43Ce",
"http_status": 404
},
{
"stage": "speech",
"generation_id": "gen-tts-1792161399-3YAyVlL5MSSKbqaZWnIz",
"http_status": 404
},
{
"stage": "transcriptions",
"generation_id": "gen-stt-1792161402-nvlLMzXrx1QdjtVT6Nuu",
"http_status": 404
},
{
"stage": "completions",
"generation_id": "gen-1792161403-FNP9pxaRHEq63J0h1qbo",
"http_status": 404
},
{
"stage": "speech",
"generation_id": "gen-tts-1792161415-n472pZcpHCoMng79OO5S",
"http_status": 404
}
],
"earlier_components": [
{
"stage": "tts_pcm",
"generation_id": "gen-tts-1792147214-vtWNLNMAyxlzEM87Oz23",
"http_status": 200,
"billing": {
"total_cost": 0.00078,
"native_tokens_prompt": 12,
"native_tokens_completion": 129,
"provider_name": "Google",
"created_at": "2026-10-16T10:40:14.709Z"
}
},
{
"stage": "stt",
"generation_id": "gen-stt-1792147218-l61CrhLNYq2tgkQjV8TS",
"http_status": 200,
"billing": {
"total_cost": 0.000308333,
"native_tokens_prompt": null,
"native_tokens_completion": null,
"provider_name": "Groq",
"created_at": "2026-10-16T10:40:18.23Z"
}
},
{
"stage": "llm",
"generation_id": "gen-1792147219-rEyCmMLKSrqpXjdZyj4I",
"http_status": 200,
"billing": {
"total_cost": 3e-05,
"native_tokens_prompt": 39,
"native_tokens_completion": 9,
"provider_name": "OpenAI",
"created_at": "2026-10-16T10:40:19.452Z"
}
}
],
"key_http_status": 200,
"key": {
"usage": 0.134551603,
"limit": 5,
"limit_remaining": 4.865448397
}
}
}
@@ -0,0 +1,100 @@
# Real native Persian round trip — 2026-10-16
**The actual native S2S round trip passed. Phase 2 remains in progress** pending
isolated backend/browser/microphone acceptance and the other open gates. This supersedes the memory-blocked checkpoint in
[preparation](phase-02-native-paid-preparation-20261016.md). The user accepted pronunciation of the separate source sample and has now
also accepted this native output on 2026-10-16.
[Machine-readable evidence](phase-02-real-native-20261016.json) records the image,
script hashes, native event counts, transcripts, budget ledger and billing checks.
The corrected candidate image is
`sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b`.
No operational image, provider selection, database, frontend or audio tuning changed.
## Observed result
After an initial refusal below the unchanged 5 GiB host-headroom threshold, a
bounded one-minute wait observed sufficient memory and invoked the existing guarded
runner. The test completed with exit code **0 in 130.096 seconds**, including
imports, construction, probes and the session. Minimum observed host MemAvailable
was **5,393,440,768 bytes**. Only one container ran with 3 GiB/no-swap, two CPUs,
128 PIDs and the existing 180-second wall guard. It was removed on exit. No unrelated
service was stopped; the earlier credential-access issue is now runtime verified
fixed by matching the credential owner's UID/GID while retaining mode0600.
Actual models were Whisper large-v3, GPT-4.1 mini and Gemini3.8 Flash-Lite TTS/Kore,
all through OpenRouter. All six admitted requests returned HTTP200: three actual
constructor probes and three turn requests. The approved generated source sample
was used; no prerecorded third-party reference voice or user microphone was sent.
The response-specific test instruction requested a fixed greeting and disabled
tools. This validates transport/integration, not production policy or RAG behavior.
Actual recognized input:
> سلام، این یک آزمایش کتاه برای بررسی صدای فارسی است.
The earlier کوتاه/کتاه mismatch is still present. Actual LLM/output transcript:
> سلام صدای شما دریافت شد.
The output contains **21 native audio delta events**, **121344 PCM bytes**,
**60672 samples** and a successful `response.done` terminal. Saved WAV duration
is **2.528 seconds** at the native-declared 24 kHz mono PCM16 rate; the locally
constructed header is not an independent sample-rate measurement.
Ignored output: `.local-s2s-build/native-paid/native-real-output.wav`, SHA-256
`106d419d45eaa67e334489a2be18a78dba705da4de55914178cba46bef1f1e9e`.
Raw PCM SHA-256: `e1c422f753c4ce4c9f0d3f88d1559fc938c0e2e703ddaa7ec34e0902d99682f9`.
Setup attestation, actual model-mismatch rejection/restoration, no automatic
response before explicit create, intent/response correlation, normal session-slot
release and complete runtime stop passed. Cleanup counters were all zero; all six
gateway requests were released and no shutdown work remained. Native timing metadata
reported about15.252s end-to-end, 0.920s LLM and 1.972s TTS first audio. Input was
submitted as a synthetic clip rather than real-time browser speech, so these are
native test metadata, not measured user-perceived browser latency. Startup and
quality are not accepted solely from this one successful run.
## Cost and next step
The exclusive native ledger admitted exactly two requests per component and kept
the previous **$0.56** reservation. New reservation was **$0.438**, bringing the
cumulative reserved maximum to **$0.998**, under the existing $1 authorization.
This is a conservative reservation, **not the final bill**. No retry, model
substitution, extra utterance or subsequent paid request was performed.
Read-only billing returned HTTP200 for key metadata; shared-key usage was
$0.134551603, a $0.001118333 increase from the initial component baseline. That
shared-key delta is not independently attributed final cost. All six immediate
new generation lookups returned404. Final TTS/component charges remain unresolved;
retain the entire $0.998 reservation. Neither the paid ledgers nor the existing
shared key's $5 cap was reset or changed. The runner refuses another real execution
because its native ledger now exists.
Next: reconcile charges before any additional paid work, then complete isolated
backend/browser/microphone acceptance with a bounded budget. Human listening of
the native reply has passed. The current reservation leaves insufficient room for another full
engine startup. Do not launch ordinary candidate Compose with the key or remove a
ledger to bypass this condition. Phase 3/4 are not accepted or started here.
Validation: actual native run passed; existing provider-free budget/runner checks
passed. No broad application/PostgreSQL suite was rerun for this evaluation-only
change. Earlier baseline database and rollback gates remain disclosed.
## User acceptance and later billing follow-up
The user accepted the native reply («تاییدش میکنم») on2026-10-16. Read-only
reconciliation now returns the earlier standalone TTS $0.00078, STT $0.000308333
and LLM $0.00003, summing to **$0.001118333 for those three successful calls**.
This matches the observed shared-key usage delta but is not the bill for the newer
native turn. The initial failed WAV attempt is not included in this successful-call
sum. All six native generation records still return404; their costs and the price
of the new input→output turn remain unconfirmed. Keep reservation bookkeeping
separate from actual charges. No paid request was made during this follow-up.
The main Phase2 gate now is a normal isolated browser/API/microphone session with
transcripts, audible reply and normal close, plus completion/reconciliation of
applicable configuration/security and PostgreSQL acceptance checks. The documented
existing expanded-DB failures remain unresolved. Advanced interruption/RAG belongs
to Phase3; broad quality benchmarking and operational switch/rollback to Phase4.
No percentage or fixed completion-time claim is inferred from offline test counts.
@@ -0,0 +1,106 @@
{
"date": "2026-10-15",
"repository": "https://github.com/huggingface/speech-to-speech",
"commit": "619e3fe4f71d1c6f35c15870d588a3638de34722",
"tree": "b8bcffdb364f248e97ef62d597d2626d4a108303",
"checkout": "tmp/local-s2s-upstream-619e3fe4",
"clean": true,
"detached_head": true,
"fetch_depth": 1,
"git_fsck": "passed",
"verified_input_count": 17,
"inputs": [
{
"path": "pyproject.toml",
"git_blob": "06d1b6ec6e662d01a67c1e84f7fffe026535ad25",
"sha256": "87ace2c683f2625f998b2852ae25ccceead5e55ed73fafd5d731d88662e450ff"
},
{
"path": "Dockerfile",
"git_blob": "99d58f7bd9dc30f5e0eb139909608b4b3c8f86cb",
"sha256": "1d23587e48dc063b6ddc436b958acf9aa78e6e7f22c833d665bc0365b3e143b0"
},
{
"path": "src/speech_to_speech/api/openai_realtime/README.md",
"git_blob": "ab9cfc85e3d2c99852fcb7fce1f1037cc9bf7281",
"sha256": "6cab7c906ad307deaebf72890e982be4908765b4f3f5aee5bbd5d8b5fc311b23"
},
{
"path": "src/speech_to_speech/api/openai_realtime/websocket_router.py",
"git_blob": "368a0001455e395629e86f40ed7b3fb52a8d1455",
"sha256": "5b449bb1a774e187f50e99f4db6105281c791bbe4dd6a4810d41e6758b734469"
},
{
"path": "src/speech_to_speech/api/openai_realtime/service.py",
"git_blob": "52cdbc3e0a2de50683a07550475a859be5c7068a",
"sha256": "9c105a9f05790b250f18273edfeddf768625cea0d047e42eb5827bd405aecf49"
},
{
"path": "src/speech_to_speech/api/openai_realtime/runtime_config.py",
"git_blob": "123a9e41f0c1d1113aedd5c2c08af25911cf54f4",
"sha256": "a5a03cd24435a242c1c77107e94c6db7bd7f63ae70b12a89e7da41e304b27c27"
},
{
"path": "src/speech_to_speech/api/openai_realtime/handlers/session.py",
"git_blob": "67b4d65fab209b25b2639c176653bd5918ba07b0",
"sha256": "e8fe23105354276fb115550d3954e5b7108480ddb22b2b89da62003d648bb713"
},
{
"path": "src/speech_to_speech/api/openai_realtime/handlers/audio.py",
"git_blob": "11a9b9f396cb80b90fb29e08ff9abc63fe33a9d2",
"sha256": "f8de10b81a9f86f8a25c3bfe707687efe98f269f87bc8a840f74ae958fcc7b57"
},
{
"path": "src/speech_to_speech/api/openai_realtime/handlers/response.py",
"git_blob": "44fce432470071276463347579720662ee06e3ba",
"sha256": "dbae7e84d274d3dd6010ca3c14c417246a424d18a99318dcfb390b4f0c5c48c0"
},
{
"path": "src/speech_to_speech/api/openai_realtime/handlers/conversation.py",
"git_blob": "0e1abf3945957ca4b33e8a4d48f62338de12b999",
"sha256": "4e6f3cf7860d911a631a15e9c25ac715353f501a50847169a7f4b17808a0438b"
},
{
"path": "src/speech_to_speech/api/openai_realtime/handlers/history.py",
"git_blob": "4ebba270974c88ed6a54707413c17fbb4e1c24ca",
"sha256": "835e0ee2ea72a8b2c468e1364d798c7b02fbcf795217aa9345c6272fd8cd43fb"
},
{
"path": "src/speech_to_speech/STT/openai_compatible_handler.py",
"git_blob": "0605445e69112e4dc43e1c15d8b70e4d9f1f5fa0",
"sha256": "89393c8c26a9ad755e8db4da3020019f98ab094b9a5ad049bd9ed8a73d7a68c1"
},
{
"path": "src/speech_to_speech/TTS/openai_compatible_handler.py",
"git_blob": "d1eb738f2a380c8d3c08e36696b8b169ddb4a09a",
"sha256": "8723e77e9ba7ebe6e0ae9a3b746cdf87b1faefeeb0c7114aed24986c98c3d3a8"
},
{
"path": "tests/openai_realtime/test_realtime_protocol_contract.py",
"git_blob": "c95274c2b5d615cd4a0fff319a729909434e0468",
"sha256": "da1fe6724aeea3a9232c9dfe750e26d1887a1e44a99822183abffd98984d6a62"
},
{
"path": "tests/openai_realtime/test_response_input_identity.py",
"git_blob": "e30994bd3052b026d42eeafb232d6b268b4bfd5d",
"sha256": "581bfcbbff7b3d408044b8495811d0d964ce4ecd33c2fff604d43944116a1071"
},
{
"path": "docs/openai-compatible-stt.md",
"git_blob": "e54df2af12fbeadaa9c9972a1e204cc34c064d9d",
"sha256": "57ecb39cb3027145e80fba47b61562f81449d38fc6a47b2eccfe3d7c7fed3c2e"
},
{
"path": "docs/openai-compatible-tts.md",
"git_blob": "d7da52896b7c91e90c6fea2272cb19291d6b14b6",
"sha256": "3a18c99ac38bd26979aa421f73289e3cce55a1ec65a9097e422e7e50c48b26d3"
}
],
"dependencies_installed": false,
"models_downloaded": false,
"submodules_initialized": false,
"engine_built": false,
"provider_calls": 0,
"source_executed": false,
"next_gate": "Review and prepare Linux dependency lock; not executed by this checkout task."
}
+63
View File
@@ -1,11 +1,74 @@
# Local S2S Phase 2 implementation report # Local S2S Phase 2 implementation report
Current verdict (2026-10-16): **Phase 2 accepted for isolated development-only
normal Persian browser voice**. [Final evidence](phase-02-accepted-20261016.md)
and [machine-readable results](phase-02-accepted-20261016.json):
125 local + 258 preservation + 63 PostgreSQL tests passed; actual browser response
fully played and closed normally. Conservative cost exposure $0.420504399, below
the same $1 cap; final invoice details remain unresolved with full reserves held.
Paid engine stopped normally. No buffer/speed change or operational promotion.
Phase 3/4 remain not_started. Earlier checkpoints below are historical and are
superseded where they describe open Phase 2 gates.
Current incident follow-up: [first browser-turn initialization stall repaired](phase-02-browser-first-turn-repair-20261016.md).
User session failed after transcription. Native snapshots identified first-reply
Lingua model preload; same cache now warms before listener readiness. Three full
proxy/API/native continuous-input fixture sessions and98 focused tests pass.
Fixed image a51167d1952a; no buffer/speed/timeout change. Repair handoff carries all
prior attempts; cumulative reservation ceiling $0.995118333 of the same$1. Human
browser acceptance remains open; earlier ready checkpoints below are historical.
Current browser handoff (2026-10-16): [isolated browser is ready](phase-02-browser-ready-20261016.md).
Angular/API/login and actual proxied WebSocket session_ready/normal close passed;
no inference in connection check. Three real startup probes passed. Human microphone/
reply/transcript acceptance remains open. Same $1 authorization; reconciled prior
exposure $0.689118333, cumulative ceiling $0.901118333, startup reserve $0.748118333.
Private login file and 30-minute engine watchdog documented. No tuning/operational change.
Latest actual run (2026-10-16): [real native Persian round trip passed](phase-02-real-native-20261016.md).
Six actual requests succeeded, 2.528s reply audio, successful terminal/normal
release and clean shutdown. Cumulative reservation is $0.998 of the same $1;
final billing remains unresolved, so no further paid request. User accepted native output; browser/microphone remains open; earlier memory blocker below is historical.
No operational switch or audio tuning change.
**Current 2026-10-16 checkpoint:** [image built and basic native/SDK checks passed](phase-02-image-build-20261016.md),
plus **423 provider-free regressions passed**. Earlier unbuilt/disk-blocked
statements below are historical. Phase 2 remains in_progress: real Linux assets,
complete engine/signal conformance and actual components/Persian browser are open.
Date: 2026-10-15. Status: **in_progress; offline candidate delivered, build/live acceptance pending**. 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 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. provider switch, paid request, dependency/model download or engine build was performed.
## Delivered ## Delivered
Latest image-build attempt (2026-10-15): [disk-guard result](phase-02-image-build.md)
records actual build from reviewed source/base/lock, 6.64 MB context and binary-only
dependency installation. The root/Docker disk ran below the 384 MiB guard during
installation, so the owned build was cancelled (exit 130). No final image exists.
Moving only this task's resolver cache to tmpfs freed space; after cancellation
root returned to about 1.8 GiB free. Existing services/voice tuning preserved;
no pruning, model download or provider call. More Docker-disk space is required
before retry; Phase 2 remains in_progress, not accepted.
Latest Linux dependency checkpoint (2026-10-15): [reviewed hash lock and dry-run
report](phase-02-dependency-lock.md), [machine evidence](phase-02-dependency-lock.json).
134 packages resolved for Python 3.11/Linux x86_64, exact matching CPU torch/audio
2.11.0 wheels, verified trixie base manifest, wheel-only hash-required dry run
passed. No library installed, model downloaded, image built or voice setting
changed. Earlier missing-lock/base statements are historical; real native
imports, engine conformance and Phase 2 live acceptance remain open.
Latest Linux source-only checkpoint (2026-10-15): a clean, detached, depth-one
checkout of `619e3fe4f71d1c6f35c15870d588a3638de34722` now exists at
`tmp/local-s2s-upstream-619e3fe4` in this workspace. All 17 audited file SHA-256
and Git blob identities match `upstream-pin.json`; `git fsck --no-reflogs` passed.
See [source evidence](phase-02-source-checkout.json). This supersedes earlier
statements that the full pin is absent locally. No source executed, dependencies
installed, models downloaded, submodules initialized, engine built or provider
calls made during this step. Reviewed Linux lock/build/asset/conformance/live
gates remain open; Phase 2 stays in_progress.
- `local_s2s` configuration, factory and adapter alongside OpenAI/Gemini. It is - `local_s2s` configuration, factory and adapter alongside OpenAI/Gemini. It is
off by default and requires explicit development/transport-test opt-in. off by default and requires explicit development/transport-test opt-in.
- Immutable profile containing upstream/extension/contract revisions, component - Immutable profile containing upstream/extension/contract revisions, component
@@ -0,0 +1,11 @@
# Preparation only: append to the isolated Phase 2 candidate base + Linux override.
# No paid startup is authorized by this file. Existing exclusive ledgers refuse restart.
services:
candidate_api:
image: sha256:02518bed03e909ce9b8324ce7772902fb427ce55a6f0cef31ec0d6282f1506bc
environment:
LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS: "true"
local-s2s-engine:
image: sha256:02518bed03e909ce9b8324ce7772902fb427ce55a6f0cef31ec0d6282f1506bc
environment:
LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS: "true"
@@ -0,0 +1,208 @@
{
"status": "prepared_not_executed",
"source": "docs/calibration/phase4-cases.draft.json",
"annotation_caveat": "Original-derived draft transcriptions, not search output. Resolve literal rendering differences against originals before freezing; never weaken labels after retrieval. DOCX facts are pending human factual-corpus approval. Unsupported labels must be rechecked against complete approved unseen corpus before freeze.",
"cases": [
{
"id": "A01",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "مشوق دهه فجر کدام بخش قرارداد واگذاری حق بهره‌برداری زمین را کاهش می‌دهد و میزان کاهش چقدر است؟",
"evidence_groups": [
[
"کاهش بخش نقدی",
"پیش دریافت",
"قراردادهای واگذاری حق بهره برداری زمین",
"۱۰",
"درصد"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Reduction of cash advance only; no total-price discount inferred.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run_for_local_s2s_phase3",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision.",
"human_annotation_approval": "pending"
},
{
"id": "A02",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "برای برخورداری از مشوق دهه فجر، قرارداد واگذاری باید در چه بازه زمانی منعقد شود؟",
"evidence_groups": [
[
"از تاریخ",
"۱۲",
"بهمن تا پایان بهمن سال",
"۱۴۰۴",
"منعقد گردد"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Contract conclusion within the stated window; not upload date.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run_for_local_s2s_phase3",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision.",
"human_annotation_approval": "pending"
},
{
"id": "A03",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "آیا قراردادهای انصرافی مشمول مشوق دهه فجر هستند و قید زمانی استثنا چیست؟",
"evidence_groups": [
[
"قراردادهای انصرافی",
"از تاریخ ابلاغ این مصوبه",
"مشمول این مشوق نمی گردند"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Exclusion applies from notification date.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run_for_local_s2s_phase3",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision.",
"human_annotation_approval": "pending"
},
{
"id": "A04",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "آیا اراضی و مستحدثات واگذارشده به شیوه مزایده از مشوق دهه فجر برخوردارند؟",
"evidence_groups": [
[
"اراضی و مستحدثاتی",
"وفق مصوبه هیات مدیره شرکت استانی",
"به شیوه مزایده واگذار می شوند",
"مشمول این مشوق نمی گردند"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Preserve provincial board resolution qualifier and negation.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run_for_local_s2s_phase3",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision.",
"human_annotation_approval": "pending"
},
{
"id": "A05",
"answerable": true,
"original": "letter",
"original_sha256": "f5732a2eff7fec3e7827c5f25c9a9d50897363935101e46f631404c03ce6ef99",
"query": "قیمت و بازپرداخت اقساط قراردادهای مشمول مشوق دهه فجر تابع کدام ماده و مصوبه معتبر است؟",
"evidence_groups": [
[
"قیمت و بازپرداخت اقساط",
"ماده",
"۸",
"دستورالعمل بهره برداری"
],
[
"مصوبه هیات مدیره شرکت استانی",
"در شش ماه دوم سال جاری معتبر میباشد"
]
],
"locator": {
"page": 1
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Both article and valid provincial resolution; not a new instalment rate.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run_for_local_s2s_phase3",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision.",
"human_annotation_approval": "pending"
},
{
"id": "A09",
"answerable": true,
"original": "regulation",
"original_sha256": "42f7cbc0ad4a187f7d8a89b0ace484e936ab25c96820fe6ac18b25533e987096",
"query": "ماده ۸ پرداخت هزینه شرکت خدماتی را تا چه مدت مجاز می‌داند و کسر هزینه پس از تشکیل شرکت چگونه است؟",
"evidence_groups": [
[
"می توانند حداکثر دو ماه",
"هزینه های شرکت خدماتی"
],
[
"پس از تشکیل شرکت خدماتی",
"منطبق با اساسنامه شرکت",
"از هزینه های مشترک قابل پرداخت توسط شرکت کسر نمایند"
]
],
"locator": {
"page": 3,
"section": "ماده ۸ (اصلاحی ۱۳۹۶/۰۴/۱۸)"
},
"critical": true,
"unseen": false,
"annotation_method": "original visual reconstruction",
"qualifiers": "Maximum two months, permissible rather than mandatory.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run_for_local_s2s_phase3",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision.",
"human_annotation_approval": "pending"
},
{
"id": "A14",
"answerable": true,
"original": "docx",
"original_sha256": "6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23",
"query": "در فایل اصلی ساعت کاری شنبه تا چهارشنبه و پنجشنبه چیست و هنگام تعطیلی یا تغییر ساعات اداری چه ملاکی حاکم است؟",
"evidence_groups": [
[
"از شنبه تا چهارشنبه از ساعت 8 صبح الي 13",
"در روزپنجشنبه از 8 صبح الي 12"
],
[
"در روزهای تعطیل یا تغییر ساعات اداری، آخرین ابلاغ شرکت ملاک است."
]
],
"locator": {
"page": null,
"section": "سؤال ساعت کاری؛ پاسخ در بند ۳ فایل اصلی"
},
"critical": true,
"unseen": false,
"annotation_method": "original DOCX OOXML paragraph reconstruction",
"qualifiers": "Candidate factual group; human authority/inclusion approval absent. Latest official notice governs.",
"annotation_status": "draft_original_annotated",
"outcome": "not_run_for_local_s2s_phase3",
"repair_note": "Reconstructed independently from original content, not question-mark counts. Still draft; no approval or publication decision.",
"human_annotation_approval": "pending"
},
{
"id": "phase3-deputy",
"query": "نام معاون، سمت و سازمان او طبق نامه چیست؟",
"outcome": "not_run",
"expected_facts": null,
"blocker": "No approved deputy-name/organization annotation found; do not guess from citations."
}
],
"paid_calls": 0
}
+82
View File
@@ -0,0 +1,82 @@
{
"date": "2026-10-16",
"phase": 3,
"status": "implementation_live_pending",
"policy": "retain_unheard_draft_v1",
"user_revoked_deletion": true,
"raw_answer_retained_in_same_session": true,
"exact_heard_prefix_claim": false,
"image": "sha256:02518bed03e909ce9b8324ce7772902fb427ce55a6f0cef31ec0d6282f1506bc",
"native_fixture": {
"active_retention_verified": true,
"retention_verified": true,
"lifecycle_outcome": 0,
"paid_calls": 0,
"events": {
"session.created": 1,
"session.updated": 3,
"input_audio_buffer.speech_started": 1,
"input_audio_buffer.speech_stopped": 1,
"input_audio_buffer.committed": 1,
"conversation.item.created": 1,
"conversation.item.input_audio_transcription.completed": 1,
"response.created": 3,
"response.output_item.added": 3,
"response.content_part.added": 3,
"response.output_audio_transcript.delta": 3,
"response.output_audio.delta": 7,
"response.output_audio.done": 3,
"response.output_audio_transcript.done": 3,
"response.content_part.done": 3,
"response.output_item.done": 3,
"response.done": 3,
"s2s.history.retained": 2
},
"unit_released": true,
"final_cleanup": {
"stage": "close",
"cleanup": {
"gateway_shutdown": 0,
"gateway_close": 0,
"runtime_stop": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 10,
"/v1/audio/transcriptions": 2,
"released": 10,
"/v1/chat/completions": 4,
"/v1/audio/speech": 4,
"shutdown_pending": 0
}
}
},
"unit_tests": {
"passed": 411,
"seconds": 48.21,
"log_sha256": "dc03a867293d3a352e8d99057f52657791a4aca751561b68bdc9c71c8ebe9249"
},
"postgres": {
"passed": 31,
"seconds": 50.6,
"log_sha256": "654d8b982599ee70ccaf9a3198ddb090be08e7ce819ab386d209deb1cc0e6f8d"
},
"required_real_checks": "pending; see phase-03.md and phase-03-live-cases.json",
"native_chat_sdk_final_cases": [
{
"case": "completed_unplayed",
"next_actual_http_request_verified": true,
"raw_answer_retained": true,
"heard_delivery_claim": false,
"paid_calls": 0
},
{
"case": "cancelled_active",
"next_actual_http_request_verified": true,
"raw_answer_retained": true,
"heard_delivery_claim": false,
"paid_calls": 0
}
]
}
+99
View File
@@ -0,0 +1,99 @@
# Local S2S Phase 3 — retained interrupted answers
Status: **in_progress; real listening/RAG acceptance pending**. The user revoked
whole-response deletion and asked to retain interrupted answers for repeated
questions. The implementation preserves raw text in the current session and
marks its model-context representation as **not fully heard**. It does not
estimate a heard prefix, delete the saved answer, or represent the draft as a
completed spoken answer. This is the user-selected policy, not exact word/audio
alignment. No operational provider switch or new paid call occurred.
## Implementation
- Opt-in `LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS=true`; default false preserves
existing Phase 2 identities and fail-closed interruption. Phase 3 pins patch and
private contract `rag-local-s2s-phase3-retain-v1` and a different effective
configuration digest. Old reservations are not rewritten.
- The [native extension](../../../services/local_s2s/history.py) captures
response-owned text before native cancellation rolls provisional history back.
It preserves raw copies and annotates/restores the matching assistant items at
their original response anchor in the actual Chat used by the LLM. Valid prior
user/assistant/tool context is preserved. Raw drafts remain private memory,
bounded to 64 responses / 128KiB each / 512KiB total, and clear on unregister.
- Active cancellation marks its captured output before returning the actual
native terminal, including the case where every emitted audio sample was
already heard but text generation was ahead. Completed-but-unplayed responses
are annotated through the explicit synchronization operation.
- The [local adapter](../../../app/infrastructure/local_s2s.py) translates the
existing internal cleanup command to private `s2s.history.retain`; native
`s2s.history.retained` receipts attest an actual applied annotation and history
revision. Session/engine-session/generation/response/item/operation/position and
replay/revision checks remain mandatory. The native type and distinct
provenance survive private normalization. This is not a fabricated OpenAI
truncate acknowledgement. The upstream native truncate remains a no-op.
- Shared runtime cancellation, cleanup dispatch, playback barriers and deadlines
remain intact. Next response is blocked until the required real terminal,
playback cleanup and matching history receipt. No buffer, queue capacity,
speed, rate, operational model or browser event changes were made.
- Search/reuse/source reporting still runs through the existing dispatcher,
ToolContext, DurableTools and SearchService. The engine gets no DB authority.
Saved prose is never evidence; document facts require backend reuse/search
revalidation and current-turn source labels before answering.
This saves text for a subsequent model answer; it does not implement a separate
persistent question/answer database or byte-for-byte audio replay. A new topic
still requires fresh search. Retention ends with the live session. Exact repeat
answer quality and model compliance require the real checks below.
## Checks
[Machine-readable evidence](phase-03.json) records final counts and image/source
identities. HTTP fixture evidence is explicitly separate from real inference.
- Focused local/OpenAI/context/source/reuse tests: **411 passed in 48.21s**.
- PostgreSQL profile/replay + local/OpenAI/Gemini authenticated ASGI tools and
evidence reuse/revocation: **31 passed in 50.60s**, zero skips, on a test-owned
tmpfs database ending `_local_s2s_test`; disposable container removed.
- Both adapters run the same pending-search reuse and selected-source assertions.
Same-question searches coalesce; invalid reports stay private; no-evidence and
technical error remain distinct. Local ASGI tests use actual backend search,
owner/Origin/cookie/CSRF and durable persistence with fixture provider wire I/O.
- Actual native Chat + actual SDK HTTP request checks preserve valid previous
user/tool/assistant context and explicitly retained drafts. Invalid identities
do not mutate history. These use controlled HTTP, not model quality evidence.
- Full native worker/WebSocket cases cover completed-unplayed and active
cancellation, real mutation receipts and next SDK request inspection. Obsolete
late sentinel output must not enter that next request. Provider calls are zero.
Earlier failures were investigated and retained in ignored diagnostic logs:
local ASGI tests initially lacked the required isolated DB/storage naming; a
manual response without a new user item needed an immutable response-start anchor;
a one-sentence stalled stream did not reach the native three-sentence batching
threshold and timed out. The final fixture sends enough sentences, without
changing batching/timing, before cancelling. No failed fixture result is speech
quality acceptance. No broad ordinary suite or operational deployment was run.
## Candidate and remaining gates
Final COPY-only candidate:
`sha256:02518bed03e909ce9b8324ce7772902fb427ce55a6f0cef31ec0d6282f1506bc`.
The [prepared isolated override](phase-03-candidate.override.yml) is not launched;
[the flag](../../../.env.example) remains off by default. Original images,
operational provider and user .env are preserved. Original paid ledgers remain
exclusive and cannot be restarted. A fresh bounded, reconciled Phase 3 paid-test
ledger is required before real engine startup; no new inference was run here.
The original total authorization remains $1.
Required before Phase 3 acceptance:
1. Run real browser barge-in and repeat the question; listen and inspect the
subsequent model request for marked retained text and correct context.
2. Run real document answers for hours/fees, deputy name/organization and incentive
percentage/date/exclusions, including pending-search interruption/repeat.
Correct source identities do not prove factual correctness.
3. Review the [prepared factual cases](phase-03-live-cases.json): inherited corpus
annotations are still drafts, and no approved deputy-name/organization
annotation was located. Do not invent expected facts or claim corpus quality.
No complete Phase 3 acceptance, safe production promotion, exact heard-prefix
alignment, final real-provider factual score or Phase 4 work is claimed.
@@ -0,0 +1,24 @@
# Phase 3/4 isolated browser preparation checkpoint
2026-10-16. Partial Step 1 preparation, not phase acceptance or a complete paired-test handoff.
- Browser: http://127.0.0.2:4201/login. Existing private `.local-s2s-build/browser-login.txt` credentials remain valid; no account reset.
- Actual frontend selector compiled with Node 22.23.1. Candidate API uses immutable phase4 image `51d4b79825bc`; engine uses retained-history image `02518bed03e9`.
- Authenticated proxied login, metadata, explicitly selected local session, native `session_ready`, and persisted `closed/user_requested` passed. Admission count remained three: connection-only check sent no audio/inference.
- Three actual construction probes returned HTTP200. Prior confirmed/unknown exposure $0.420504399 carried forward unchanged; current reservation $0.479504399. Exclusive new ledger ceiling $0.774504399, including six attempts each STT/LLM/TTS. Startup has consumed one each; at most five further admissions each remain, not a guarantee of five complete turns.
- New budget regression verifies failed-attempt retention, quota rejection before network, exclusive ledger, carried exposure and endpoint price metadata. Endpoint metadata refreshed read-only before startup. Older paid ledgers were not restarted or reset.
- Watchdog owns only candidate engine: 30 minutes from startup, host preflight >5GiB, runtime floor2500MiB, 3GiB/no-swap, 2CPUs. Do not restart after expiry: this ledger is exclusive and startup calls would repeat. API/frontend may remain running after engine expiry.
## Remaining Step 1 gates
**OpenAI is deliberately unavailable in this candidate**, with metadata `not_configured`. Complete original `.env` was copied privately into `.local-s2s-build/phase4-preserved-profile.env`; candidate receives a separate copy with both OpenAI inference keys empty. Original `.env`, original tuning and operational PostgreSQL are unchanged. A dedicated bounded OpenAI admission mechanism within the same total $1 cap is still needed before enabling paid baseline voice; simply copying the unrestricted key would bypass the budget guard. Thus provider selector implementation is visible, but real two-provider switching/comparison is not ready.
**Real RAG preparation is pending.** This reuses the earlier isolated transport database/storage and embedding endpoint deliberately set to unreachable port9. No actual corpus/search/embedding capability is claimed. Preparing approved evidence and a bounded embedding path or validated compatible local embedding service is required before factual RAG tests.
Local microphone/barge-in/repeat tests may proceed during the live handoff window. Full combined Phase3/4 tests must wait for both gates above. No human microphone result, paired cost/latency result, rollback or operational promotion is claimed.
## Preparation issues corrected
Initial isolated API request failed because `PROVIDER=openai` conflicted with `VOICE_PROVIDER=local_s2s`. Both isolated aliases were aligned; API alone recreated, paid engine never restarted. Subsequent actual connection check passed. Test fixture initially copied the live ledger into its temp folder and correctly hit exclusive-create rejection; fixture now excludes it. No production assertions were weakened.
Private actual evidence: `.local-s2s-build/phase4-browser-connection-result.json`, `phase4-browser-watch.json`, `phase4-browser-paid/browser-paid-ledger.json`, frontend log. Do not publish private profile, credentials or raw provider keys.
@@ -0,0 +1,22 @@
# Isolated browser handoff: OpenAI inference disabled pending its own cost guard.
services:
candidate_api:
image: sha256:51d4b79825bc3b29abba692093ee879360def9530676755acfb27d63884424ad
env_file: [.local-s2s-build/phase4-browser-profile.env]
environment:
PROVIDER: local_s2s
VOICE_PROVIDER: local_s2s
VOICE_SELECTABLE_PROVIDERS: '["openai","local_s2s"]'
LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS: "true"
OPENAI_API_KEY: ""
OPENAI_REALTIME_API_KEY: ""
local-s2s-engine:
image: sha256:02518bed03e909ce9b8324ce7772902fb427ce55a6f0cef31ec0d6282f1506bc
entrypoint: [python, /checks/phase4-browser-engine.py]
environment:
LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS: "true"
volumes:
- ./.local-s2s-build/phase4-browser-paid:/evidence:rw
- ./docs/evaluation/local-s2s/phase4-browser-budget.py:/checks/phase4-browser-budget.py:ro
- ./docs/evaluation/local-s2s/phase4-browser-engine.py:/checks/phase4-browser-engine.py:ro
- ./services/local_s2s/components.py:/app/services/local_s2s/components.py:ro
@@ -0,0 +1,17 @@
# Preparation only. Append to the standalone disposable base + Linux override.
# Preserve the full server-only OpenAI profile instead of guessing tuned defaults.
services:
candidate_api:
image: sha256:51d4b79825bc3b29abba692093ee879360def9530676755acfb27d63884424ad
env_file:
- ${PHASE4_OPENAI_PROFILE_ENV:?Provide the preserved private OpenAI profile file}
environment:
PROVIDER: openai
VOICE_PROVIDER: openai
VOICE_SELECTABLE_PROVIDERS: '["openai","local_s2s"]'
LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS: "true"
local-s2s-engine:
image: sha256:02518bed03e909ce9b8324ce7772902fb427ce55a6f0cef31ec0d6282f1506bc
environment:
LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS: "true"
LOCAL_S2S_ALLOW_PAID_STARTUP: "false"
@@ -0,0 +1,11 @@
{
"thresholds_accepted": false,
"minimum_samples_per_provider": null,
"real_provider_observations": false,
"human_quality_accepted": false,
"rollback_verified": false,
"profile_sha256": {},
"billing_complete": {"openai": false, "local_s2s": false},
"samples": [],
"charges": []
}
@@ -0,0 +1,13 @@
{
"status": "prepared_provider_free_coverage_not_live_acceptance",
"cases": [
{"case": "disabled_or_unconfigured_provider", "expected": "Reject selected provider without fallback", "coverage": "tests/unit/test_voice_provider_choice.py", "live": "not_run"},
{"case": "concurrent_different_provider_same_request", "expected": "One frozen reservation and one 409 conflict", "coverage": "tests/integration/test_voice_provider_choice.py", "live": "not_run"},
{"case": "selected_provider_stream", "expected": "Connect the pinned provider, not the server default", "coverage": "tests/integration/test_voice_provider_choice.py", "live": "not_run"},
{"case": "unconfirmed_close", "expected": "Keep provider and request identity; refuse switch", "coverage": "frontend voice-stream.service.spec.ts", "live": "not_run"},
{"case": "component_failure_or_slow_response", "expected": "Bounded error/deadline/cleanup; no retry storm or false success", "coverage": "tests/unit/test_local_s2s_repairs.py; native Phase 2 failure evidence", "live": "not_run"},
{"case": "missing_wrong_or_late_history_receipt", "expected": "No new response before matching applied history and playback gates", "coverage": "tests/unit/test_local_s2s_history.py; shared context regressions", "live": "not_run"},
{"case": "quota_partial_stream_restart_saturation", "expected": "Record all failures, abandoned cost and cleanup; do not promote on fixture evidence", "coverage": "partial existing component/context fixtures; complete paired fault campaign pending", "live": "not_run"},
{"case": "restore_preserved_openai", "expected": "One API owns operational lifecycle; restore without rebuilding and verify fresh real session/data", "coverage": "prepared runbook only", "live": "not_run"}
]
}
@@ -0,0 +1,25 @@
# Browser interruption incident — 2026-10-16
User reported an error when interrupting speech. The attached console output contains an unexpanded server error Object, so its actual code is unavailable. Do not equate it with a proven retained-history defect.
Read-only API logs show two native cancellations acknowledged as cancelled terminals in session6319accb; a new user turn then started and a server error was emitted. Both browser sessions ultimately persisted `closed/user_requested`, which does not identify the transient error because V04 can win the finalization race. No audio existed at the two cancellation terminals in this session; this is not proof of heard-position repair.
The exclusive ledger has six STT and six LLM admissions (their exact caps), four TTS admissions, and cumulative reserve $0.704504399. Cancellation/failure holds are retained. A subsequent STT request would be refused before provider I/O. This is a plausible contributor, not conclusive identification of the unexpanded browser error.
## Scoped repair
The evaluation guard now persists a sanitized stage/count/attempt-limit denial and raises a distinct EvaluationBudgetExhausted exception. The local component gateway returns explicit HTTP429 on that evaluation-only exception, rather than closing the socket without any HTTP response. Other invalid/failed requests retain existing behavior. This does not promise that native SDK429 is nonfatal or eliminate legitimate budget stops. No budget increases, ledger reset, paid restart, audio timing/buffer/speed or history-policy changes.
Provider-free checks: 100 history/component tests passed, including a real loopback HTTP regression proving429, one budget-rejected count, zero generic failures and no sensitive response body. Exclusive guard regression passed, including persisted denial and unchanged number of provider calls after cap. Compose validation and diff whitespace checks passed.
Paid engine stopped; API and recorded owned frontend temporarily stopped to free RAM for network-disabled actual native replay. Operational PostgreSQL untouched. Candidate override mounts the reviewed gateway source read-only so a future authorized fresh-ledger launch includes the repair; existing exclusive ledger must never restart. No new paid request was made. Actual native reproduction outcome is recorded in private `.local-s2s-build/interruption-incident-native.log` and is not human/browser acceptance.
Remaining: collect expanded browser error code or reproduce the same error under controlled fixture conditions; do not declare this user incident fully resolved from unit tests alone. A new human test requires a newly carried-forward bounded admission handoff within the same $1 cap.
## Actual native replay
Network-disabled real native active-retention run passed in71.037s, exit0, minimum host headroom3821453312bytes. Active cancellation, two retained-history receipts, subsequent generation, stale-output exclusion and unit release verified; client_error null, paid_calls0. Fixture cleanup recorded close_errors1 (same diagnostic field, not suppressed); runtime/gateway stop/join all0 and shutdown_pending0. This verifies the existing interruption path under fixtures, not the exact unidentified browser error. Initial memory-preflight refusals performed no engine/provider work. The failed/exhausted browser runtime was not restarted.
## Restored UI and next bounded preparation
Frontend and isolated API restored after user requested continuation; actual `/login` and `/settings` return200. New exclusive next-run preparation carries the full $0.704504399 prior reserve, including every cancellation/failure, and permits four attempts per component (one each needed for startup), cumulative ceiling $0.940504399. Original and previous ledgers untouched; new live ledger not created. Temporary-copy regression confirms carry and ceiling; existing guard regression still passes. New override and watchdog are prepared, but not launched: actual host MemAvailable4723MiB is below the mandatory >5120MiB pre-start gate. Do not stop the restored UI again to claim browser readiness. No paid engine restart or new paid request. OpenAI/RAG preparation remains separately pending.
@@ -0,0 +1,5 @@
# Fresh carried-forward evidence; never reset or restart either older ledger.
services:
local-s2s-engine:
volumes:
- ./.local-s2s-build/phase4-next-paid:/evidence:rw
@@ -0,0 +1,99 @@
# Phase 4 provider selection and rollback preparation
Preparation only. Phase 3 real barge-in/RAG acceptance, paired evaluation and
restoration evidence are still required. Do not promote local_s2s from fixture
results or start paid engine initialization without a fresh bounded ledger under
the original $1 authorization. Operational services and user .env are unchanged.
## Selection inside one API
`VOICE_PROVIDER` keeps its existing default meaning. Additional session choices
are enabled explicitly with server-only `VOICE_SELECTABLE_PROVIDERS`, for example
`["openai","local_s2s"]`. Empty preserves default-only behavior. Both providers
use the same backend identity, authorization, canonical search and database.
There is no automatic fallback. Local selection retains the isolated
`*_local_s2s_test` database/dedicated storage requirement.
The UI reads authenticated `GET /api/v1/voice/sessions/providers`, displays
configuration eligibility and lets the user choose a provider. This request does
not connect to a provider; `connection_checked=false` explicitly records that
remote readiness has not been tested. Keys, component models, speed and buffers
remain server-owned. An unconfigured or disabled provider cannot be selected.
Changing the dropdown closes the current call and checks its terminal server
status. If closure is unknown, selection and request ids remain pinned and a
message explains that the change was not applied. A successful change takes
effect on the next microphone click, which creates new request/session ids.
No media is resumed across providers. An ambiguous creation attempt cannot be
reused with a different explicit provider. A request-id/provider conflict returns
409; an unenabled provider is unavailable, never silently replaced.
`GET /api/v1/configuration?provider=openai|local_s2s|gemini` evaluates the selected
provider through the same capability checks. Old clients may omit provider and
retain default behavior. A new frontend against an older backend hides the
unsupported selector; it does not rewrite a pending request's provider intent.
## Configuration review before a disposable test
1. Preserve the complete existing OpenAI effective profile/environment privately,
including model, voice, speed, token limits, ASR, VAD and delivery settings.
Do not recreate it from example defaults. Record its profile digest.
2. Use the standalone disposable candidate stack. Add the reviewed candidate API
image and the additional provider allowlist. Keep one API per database.
3. Keep the local engine fixed to its own model/voice and retained-draft revision.
Require authenticated engine setup proof. Never change global engine models
from frontend fields.
4. Supply a newly prepared, exclusive, carried-forward test ledger before paid
startup. Previous ledgers are exhausted/exclusive and must not be reset.
5. Confirm provider metadata, cookie/Origin/CSRF admission, frozen replay,
unavailable-provider rejection and normal session closure before human tests.
No operational compose up/down, container stop/start, volume cleanup or provider
switch is performed by this runbook or scorecard command.
## Controlled deployment and rollback (not executed)
After Phase 3 acceptance and explicit operational authorization:
- Record the actual current API/container/image identities, server profile digest,
mounts and database compatibility. Preserve the original container and image.
- Close/drain active sessions; stop the current API before a candidate is allowed
to reconcile that same operational database. Never run two APIs against it.
- Verify fresh-session Persian greeting, selected provider, real RAG, used sources,
interruption and normal close. A health response alone is insufficient.
- Actually stop the candidate and restore the preserved OpenAI API/image/profile
without rebuilding. Verify a fresh baseline voice session and preserved users,
documents and ingestion. Then leave the provider explicitly requested by user.
- If validation fails, preserve evidence and restore the known baseline. Container
rollback does not roll back the database/filesystem or resume a media session.
No database migration was added for provider selection. Applied migrations are
unchanged. Actual backward image compatibility/restoration remains unproved;
this document is not rollback acceptance and deliberately contains no guessed
operational container IDs or commands that could stop the wrong service.
## Paired evaluation input
Copy `phase-04-evaluation-template.json` to a new consent-controlled artifact.
Record stable OpenAI/local profile SHA-256 values and approve the provisional
thresholds and minimum sample counts before collecting live observations.
Each sample contains `provider`, `case_id`, booleans `success`, `critical_error`,
`persistent_underrun`, `duplicate`, `disconnected`, and observed
`first_audible_ms`; optionally `tool_ms` and `interruption_stop_ms`.
Record all billed charges with unique `id`, `provider`, `kind` and `cost_usd`.
Kinds are request/startup/failed/abandoned/session; avoid counting the same invoice
in both per-request and session totals. Unknown cost is null, never zero.
```sh
.venv/bin/python -m services.local_s2s.evaluation --input <observations.json> --output <new-scorecard.json>
```
The command is offline, refuses to overwrite an output and performs no provider
calls or deployment actions. It reports nearest-rank p95, paired case counts and
cost per successful task including all supplied overhead. It blocks acceptance
for missing samples, unknown costs, unpaired cases, failures, unaccepted thresholds,
missing profile identity, missing real/human evidence or missing rollback proof.
Targets remain provisional: zero critical/task failures, no persistent underruns
or duplicate/disconnected tasks, local p95 <= baseline + 1000ms and cost <= 70%
of baseline. Sample count is deliberately unset until accepted. A scorecard is
not authorization to switch services.
+127
View File
@@ -0,0 +1,127 @@
{
"date": "2026-10-16",
"phase": 4,
"status": "offline_prepared_live_pending",
"user_authorized_frontend_provider_selection": true,
"phase3_live_acceptance": "pending",
"api_image": "sha256:51d4b79825bc3b29abba692093ee879360def9530676755acfb27d63884424ad",
"engine_image": "sha256:02518bed03e909ce9b8324ce7772902fb427ce55a6f0cef31ec0d6282f1506bc",
"tests": {
"backend_suite": {
"passed": 207,
"seconds": 34.66,
"log_sha256": "77a23fdf66ec10f5fc1edef05e5919cc200b044ed4d7b3fbd180be11122fa8b7"
},
"final_targeted_faults_and_scorecard": {
"passed": 13,
"seconds": 1.15,
"log_sha256": "a58198245cff5a0522ce6c41b6ecda866f30ac718e51595dd875db2f166453e4"
},
"postgres": {
"passed": 14,
"seconds": 34.62,
"log_sha256": "3084de922b32e7a577dcf0785624544bbc9b6fa31fd672a8c4605d6cc1bd20c1"
}
},
"angular": {
"voice_service_tests_passed": 46,
"node_version": "22.23.1",
"initial_node20_jsdom_incompatibility": "failed before test collection; rerun with installed Node22 passed",
"development_build": "passed",
"build_seconds": 11.789,
"test_log_sha256": "bbce0baa9d27954d523f1f6d0cda33b031f850cb4c7289a93c2fa74a1d85585e",
"build_log_sha256": "1a60a97f77ce1dd5edb07ce4fdac6746775e027457a27bfd99f6e6981844dab7"
},
"candidate_image_smoke": {
"openapi": "passed",
"selection": "passed",
"unmeasured_scorecard": "blocked_as_required",
"provider_calls": 0
},
"compose_validation": "passed with fake private OpenAI profile; no containers started",
"unmeasured_scorecard": {
"status": "not_accepted",
"providers": {
"openai": {
"samples": 0,
"successful_tasks": 0,
"p95_first_audible_ms": null,
"p95_tool_ms": null,
"p95_interruption_stop_ms": null,
"total_cost_usd": null,
"cost_per_success_usd": null
},
"local_s2s": {
"samples": 0,
"successful_tasks": 0,
"p95_first_audible_ms": null,
"p95_tool_ms": null,
"p95_interruption_stop_ms": null,
"total_cost_usd": null,
"cost_per_success_usd": null
}
},
"blockers": [
"sample_threshold_not_set",
"openai:insufficient_samples",
"openai:billing_incomplete",
"local_s2s:insufficient_samples",
"local_s2s:billing_incomplete",
"thresholds_accepted:pending",
"real_provider_observations:pending",
"human_quality_accepted:pending",
"rollback_verified:pending",
"profile_identity_missing"
],
"thresholds": {
"latency_delta_ms": 1000,
"cost_ratio": ".70",
"minimum_samples_per_provider": null
},
"percentile_method": "nearest-rank",
"cost_method": "sum_all_supplied_charges_including_startup_failure_abandoned",
"authorization_to_switch": false
},
"new_paid_calls": 0,
"operational_switch": false,
"rollback_actual": "not_run",
"user_env_changed": false,
"audio_engine_and_worklet_changed": false,
"phase4_override_launched": false,
"source_sha256": {
"app/api/v1/live.py": "4a14099f3fb7c7ad7683dc2a3f933c7658fcce8277e71b94cc7baa365a9cd16e",
"app/api/v1/knowledge.py": "5439f08f1f63d74f8ac19ce19546382758763b9399b7da9e007e67f2948f7a6d",
"app/modules/voice/configuration.py": "3c720f73b81469e375fccf090b92e39aedb3d62a6f56f1bcbedf595d0c139e64",
"app/modules/voice/lifecycle.py": "4735e0a7fb9931383ce071ff4fab06b43bab23b524ecc253d1f399524bda2f6e",
"services/local_s2s/evaluation.py": "989a81a7ca6604dec000cd4d0d112ce68738952636cbd17105242bf3c402d241",
"tests/unit/test_voice_provider_choice.py": "c9ff258e1dd0710fc81427409bbc382614bd7ac96c6a8e1e82f158d66e00322d",
"tests/unit/test_local_s2s_evaluation.py": "f9a588d513dd575534ea99a0ebc99371293b2e63b843495d90bcbcfb8b0fc0de",
"tests/integration/test_voice_provider_choice.py": "5c4eb0d4c89b70d5f20b62102ceb229775a3f0243daaacd38a5b7e42130a9228"
},
"frontend_source_sha256": {
"src/app/pages/home/home.page.ts": "6ad0f1c6ea321cda0b88c40d6f13842f364933a7e82d210be0abe591a1ceb884",
"src/app/pages/home/home.page.html": "87228f9142a46f0dbdfcef47b2cb526b27d5135d979556be2d3109e64d92d433",
"src/app/pages/home/home.page.css": "32a87443d7c33a90be89f44690655af139e33b39cb9c4edb71eb16a0b84297db",
"src/app/services/voice-stream/voice-api.service.ts": "b5b0c41f7fce863680d16a0f36af86d68ca08bdcb5ae52759b53240dcc4257a1",
"src/app/services/voice-stream/voice-stream.service.ts": "d8db234b68038544bf6dea73133fd2575f3fa90af8524030ccd4c5c5c1554149",
"src/app/services/voice-stream/voice-stream.service.spec.ts": "54f796ef4297b1d7c7da71a57912d4014ab0e673c952fe5ce8f8414fd5caee73"
},
"not_run": [
"Real microphone/browser provider switch",
"Phase3 real barge-in/repeat/RAG/factual acceptance",
"Paired Persian quality/latency/cost and complete live fault campaign",
"Actual operational switch and restoration without rebuild"
],
"thresholds": {
"status": "provisional_not_accepted",
"minimum_samples": "unset",
"latency_delta_ms": 1000,
"cost_ratio": ".70"
},
"final_checks": [
"backend git diff --check passed",
"frontend git diff --check passed",
"disposable test database containers removed",
"no new paid inference or operational deployment"
]
}
+76
View File
@@ -0,0 +1,76 @@
# Phase 4 implementation preparation — 2026-10-16
Status: **offline_prepared; live evaluation and promotion not accepted**. The user
explicitly authorized preparation alongside unfinished real Phase 3 checks and
requested an OpenAI/local_s2s frontend selector. Neither phase is accepted from
these offline tests. No operational service/profile, audio buffering/speed,
provider key, paid ledger or document data was changed.
## Delivered
- Angular provider dropdown beside the composer. Standard choices are OpenAI and
«سیستم جدید»; legacy Gemini remains visible when current/enabled. Unavailable
choices are disabled. Changing provider closes the old call, checks terminal
status, and takes effect on the next microphone click with fresh request/session
ids. Unconfirmed closure keeps the old selection and ids.
- Authenticated metadata `/api/v1/voice/sessions/providers` reports configured
eligibility, not remote health. No paid probe is made. The server retains keys,
models, voices and tuned profiles. Frontend configuration eligibility for the
selected provider uses F01's optional provider query.
- V01 optionally selects an allowlisted provider. Omission preserves old clients;
replay keeps its frozen row. Conflicting explicit selection returns409 even
under concurrent creation. Stream setup uses the persisted provider and the
same authorization, profile, search and playback gates. No fallback is added.
- `VOICE_SELECTABLE_PROVIDERS=[]` defaults to the configured provider only.
Additional local choices still require isolated test DB/storage. No migration
or profile rewrite was introduced.
- Offline [paired scorecard](../../../services/local_s2s/evaluation.py),
[empty input template](phase-04-evaluation-template.json),
[fault matrix](phase-04-fault-matrix.json), and
[selection/rollback runbook](phase-04-switch-runbook.md). It reports nearest-rank
p95 and actual billed cost per successful task from all supplied charges;
unknown billing stays unknown. Missing paired samples, accepted thresholds,
real/human evidence or actual restoration blocks acceptance. No savings are
claimed from this implementation.
- Separate COPY-only API candidate
`sha256:51d4b79825bc3b29abba692093ee879360def9530676755acfb27d63884424ad`;
native engine remains pinned to the Phase 3 image. The
[prepared override](phase-04-candidate.override.yml) requires the preserved
private OpenAI profile and does not enable paid engine initialization. It was
syntax-validated with a fake profile fixture, not launched.
## Validation
The [machine-readable report](phase-04.json) records exact commands, hashes and
results. Results are provider-free unless explicitly marked otherwise.
- Backend selection/auth/lifecycle/local/history/scorecard: **207 passed in 34.66s**;
final targeted fault/scorecard checks **13 passed in 1.15s** (overlapping rerun).
- **14 PostgreSQL tests passed in 34.62s**, zero skips. They cover pinned provider, replay, competing choices,
close/new-session change, selected-provider WebSocket setup and existing
local/OpenAI/Gemini tool paths. Provider transport is controlled fixtures.
- **46 Angular voice service tests passed**. They cover switching, unconfirmed close, request-id
pinning and old-backend compatibility, alongside existing audio/teardown cases.
- Angular development build passed in **11.789s**. Tests require the installed Node22 runtime;
the frontend shell's Node20 failed to initialize the existing jsdom/undici
dependency before any tests ran. No dependencies or Node settings were changed.
- Actual candidate image passed OpenAPI/selection/empty-scorecard smoke with
network disabled. Compose config validation passed with a fake private profile.
- No real microphone/paired provider calls, browser visual acceptance, measured
cost saving, complete live fault campaign or operational restoration occurred.
## Use and remaining work
The UI/backend source and reviewable image are prepared. They are **not deployed**
to the user's running browser/API. Set the additional allowlist only in the
reviewed isolated environment and preserve the full existing OpenAI profile;
example defaults are not a substitute for its model/voice/input/tuning settings.
Both old and new clients are supported; pending identities are never rewritten
to make a provider switch succeed.
Before acceptance: complete real Phase 3 interruption/repeated-question/RAG and
critical factual cases; accept sample thresholds before paired measurements;
reconcile all startup/failure/abandoned costs; run resource/fault and human quality
checks; then, with separate operational authorization, actually demonstrate
restoration of preserved OpenAI without a rebuild. Keep one API per operational
DB and leave the final provider explicitly requested. Preparation is not promotion.
@@ -0,0 +1,120 @@
"""Exclusive Phase3/4 guard carrying every prior billed/unknown reservation."""
import importlib.util
import json
from decimal import Decimal
from pathlib import Path
import httpx
from services.local_s2s.components import EvaluationBudgetExhausted
path=Path('/checks/browser-budget.py')
if not path.exists():path=Path(__file__).with_name('browser-budget.py')
spec=importlib.util.spec_from_file_location('previous_browser_budget',path)
previous=importlib.util.module_from_spec(spec);spec.loader.exec_module(previous)
class BrowserBudget(previous.BrowserBudget):
def __init__(self,root,*,upstream=None):
previous.native.validate_prices(root)
checkpoint=root/'carried-budget-preparation.json'
if checkpoint.exists():
# Migration from another host: documentary carry, never invented bills.
prior=json.loads(checkpoint.read_text())
previous.require(prior['prior_conservative_exposure_usd']=='0.704504399' and
prior['total_cap_usd']=='1' and prior['paid_calls_on_this_host']==0 and
prior['prior_private_ledgers_available'] is False and
prior['source']=='docs/evaluation/local-s2s/phase-04-interruption-incident.md' and
prior['status']=='preparation_only_not_a_live_admission_ledger' and
not (root/'previous-phase4-ledger.json').exists() and
not (root/'prior-final-billing.json').exists())
carried=Decimal(prior['prior_conservative_exposure_usd'])
self.maximum_attempts={'speech':4,'transcriptions':4,'completions':4}
runs_path=root/'previous-windows-runs.json'
old_ledger=root/'previous-windows-ledger.json'
old_billing=root/'previous-windows-billing.json'
previous.require(old_ledger.exists()==old_billing.exists())
if runs_path.exists():
previous.require(not old_ledger.exists())
runs=json.loads(runs_path.read_text())
previous.require(isinstance(runs,list) and 0<len(runs)<=16)
files=[]
for run in runs:
previous.require(set(run)=={'ledger','billing'} and
all(Path(run[key]).name==run[key] for key in run))
files.append((root/run['ledger'],root/run['billing']))
self.maximum_attempts={'speech':5,'transcriptions':4,'completions':4}
else:
files=[(old_ledger,old_billing)] if old_ledger.exists() else []
generation_ids=set()
for ledger_file,billing_file in files:
ledger=json.loads(ledger_file.read_text())
bills=json.loads(billing_file.read_text())
attempts=ledger['attempts']
previous.require(ledger['previous_reserved_and_billed_usd']==str(carried) and
0<len(attempts)==len(bills) and
len({row['generation_id'] for row in bills})==len(bills))
reserved=Decimal(0)
billed=Decimal(0)
for attempt in attempts:
stage=attempt['stage']
previous.require(stage in previous.RESERVES and
sum(row['stage']==stage for row in attempts)<=ledger.get('maximum_attempts',{}).get(stage,4))
reserve=Decimal(attempt['reserved_usd'])
previous.require(reserve==previous.RESERVES[stage] and
attempt['status']=='headers_received' and attempt['http_status']==200 and
attempt['generation_id'] not in generation_ids)
generation_ids.add(attempt['generation_id'])
matches=[row for row in bills if row['generation_id']==attempt['generation_id']]
previous.require(len(matches)==1)
bill=matches[0]
previous.require(bill['stage']==stage and bill['http_status']==200)
cost=Decimal(str(bill['billing']['total_cost']))
previous.require(cost.is_finite() and 0<=cost<=reserve)
reserved+=reserve
billed+=cost
previous.require(Decimal(ledger['reserved_usd'])==carried+reserved)
carried+=billed # Release only exact-ID, successful, individually billed attempts.
else:
report=json.loads((root/'prior-final-billing.json').read_text())
reconciliation=report['reconciliation']
previous.require(reconciliation['confirmed_cost_usd']=='0.003504399' and
reconciliation['unknown_reservations_usd']=='0.417' and
reconciliation['conservative_exposure_usd']=='0.420504399')
carried=Decimal(reconciliation['confirmed_cost_usd'])+Decimal(reconciliation['unknown_reservations_usd'])
self.maximum_attempts={'speech':6,'transcriptions':6,'completions':6}
carry_path=root/'previous-phase4-ledger.json'
if carry_path.exists():
carry=json.loads(carry_path.read_text())
previous.require(Decimal(carry['previous_reserved_and_billed_usd'])==carried)
attempts=carry['attempts']
previous.require(all(row['stage'] in previous.RESERVES and
Decimal(row['reserved_usd'])==previous.RESERVES[row['stage']] for row in attempts))
used=sum((Decimal(row['reserved_usd']) for row in attempts),Decimal(0))
previous.require(carried+used==Decimal(carry['reserved_usd']))
carried+=used # Includes cancelled, failed and unknown invoices; no releases.
self.maximum_attempts={'speech':4,'transcriptions':4,'completions':4}
maximum=carried+sum(previous.RESERVES[k]*v for k,v in self.maximum_attempts.items())
previous.require(maximum<1)
endpoints=json.loads((root/'endpoints-google-gemini-3.8-flash-lite-tts.json').read_text())['data']['endpoints']
self.tags=[e['tag'] for e in endpoints]
previous.require(set(self.tags)=={'google-ai-studio','google-vertex/global'})
bound=sum(Decimal(e['pricing']['prompt'])*8192+Decimal(e['pricing']['completion'])*2048 for e in endpoints)
previous.require(bound<previous.RESERVES['speech'])
self.path=root/'browser-paid-ledger.json'
self.state={'previous_reserved_and_billed_usd':str(carried),'reserved_usd':str(carried),
'maximum_cumulative_usd':str(maximum),'maximum_attempts':self.maximum_attempts,
'unknown_prior_reservations_usd':'0.417','attempts':[],
'carry_basis':('documentary_checkpoint_with_local_bills' if (root/'previous-windows-ledger.json').exists() or (root/'previous-windows-runs.json').exists() else 'documentary_checkpoint') if checkpoint.exists() else 'private_ledgers',
'purpose':'phase3_4_local_browser_only_no_openai_inference'}
with self.path.open('x') as output:json.dump(self.state,output,indent=2)
self.upstream=upstream or httpx.AsyncHTTPTransport(retries=0,trust_env=False)
async def handle_async_request(self, request):
stage=request.url.path.rsplit('/',1)[-1]
# Budget exhaustion is distinct from malformed requests or a broken stream.
if stage in self.maximum_attempts:
used=sum(row['stage']==stage for row in self.state['attempts'])
if used >= self.maximum_attempts[stage]:
self.state['last_denial']={'stage':stage,'reason':'attempt_limit',
'admitted_attempts':used}
self.save()
raise EvaluationBudgetExhausted('Evaluation attempt limit reached')
return await super().handle_async_request(request)
@@ -0,0 +1,39 @@
"""Use the actual engine launcher with the browser-only admission transport."""
import importlib.util
from pathlib import Path
from threading import Thread
from services.local_s2s.components import ComponentServer
import services.local_s2s.lifecycle as lifecycle
from services.local_s2s.engine import main
spec=importlib.util.spec_from_file_location('browser_budget','/checks/phase4-browser-budget.py')
module=importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def start_components(key, timeout, **options):
if os.environ.get('LOCAL_S2S_TTS_MODEL') == 'google/gemini-3.8-flash-lite-tts':
transport=module.BrowserBudget(Path('/evidence'))
class OwnedGateway(ComponentServer):
async def _run(self):
try:
await super()._run()
finally:
await transport.close_owned()
gateway=OwnedGateway(key,port=8766,transport=transport,timeout=timeout,**options)
else:
gateway=ComponentServer(key,port=8766,timeout=timeout,**options)
thread=Thread(target=gateway.serve_forever,daemon=True)
thread.start()
if not gateway.ready.wait(5):
raise RuntimeError('BROWSER_GATEWAY_NOT_READY')
return gateway,thread
lifecycle.start_components=start_components
# The key is mounted only into this engine, never Compose environment/API/browser.
import os
os.environ['OPENROUTER_API_KEY']=Path('/secret/openrouter-test.key').read_text().strip()
if Path('/secret/openai-test.key').exists():
os.environ['OPENAI_API_KEY']=Path('/secret/openai-test.key').read_text().strip()
raise SystemExit(main())
@@ -0,0 +1,104 @@
{
"date": "2026-10-17",
"status": "candidate_live_human_comparison_pending",
"image": "sha256:ddbb90366f19f8077b1cb40a77e529393459485fb8ae0cb9d074ffea641c265f",
"unit_tests": {
"passed": 157,
"seconds": 8.51
},
"postgres": {
"passed": 3,
"seconds": 6.72,
"skips": 0
},
"native_fixture": {
"responsive": true,
"single_sentence_probe": true,
"active_retention_verified": true,
"retention_verified": true,
"client_error": null,
"normal_complete": true,
"unit_released": true,
"paid_calls": 0,
"final_cleanup": {
"stage": "close",
"cleanup": {
"gateway_shutdown": 0,
"gateway_close": 0,
"runtime_stop": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 10,
"/v1/audio/transcriptions": 2,
"released": 10,
"/v1/chat/completions": 4,
"/v1/audio/speech": 4,
"disconnected": 2,
"shutdown_pending": 0
}
}
},
"native_single_sentence_seconds": 18.272,
"connection": {
"conversation_id": "c4ad0ece-e0e4-42fd-b9c3-63eaab1f5494",
"session_id": "2931f6df-176c-4f95-8bb3-55f2c4920312",
"events": [
"session_ready"
],
"providers": {
"default_provider": "local_s2s",
"connection_checked": false,
"providers": [
{
"id": "openai",
"label": "OpenAI",
"can_start": false,
"reason": "not_configured"
},
{
"id": "local_s2s",
"label": "\u0633\u06cc\u0633\u062a\u0645 \u062c\u062f\u06cc\u062f",
"can_start": true,
"reason": null
},
{
"id": "gemini",
"label": "Gemini",
"can_start": false,
"reason": "disabled"
}
]
},
"session_ready": true,
"close": {
"session_id": "2931f6df-176c-4f95-8bb3-55f2c4920312",
"status": "closed",
"close_reason": "user_requested"
},
"component_attempts_before": 3,
"component_attempts_after": 3
},
"watch": {
"stage": "ready",
"memory_enforcement": false,
"minimum_windows_available_bytes": 4080177152,
"minimum_vm_available_bytes": 4225368064,
"startup_seconds": 24.639
},
"budget": {
"previous_reserved_and_billed_usd": "0.710884452",
"reserved_usd": "0.769884452",
"maximum_cumulative_usd": "0.981884452",
"maximum_attempts": {
"speech": 5,
"transcriptions": 4,
"completions": 4
},
"carry_basis": "documentary_checkpoint_with_local_bills"
},
"nominal_expiry_tehran": "2026-10-17T11:01:18.153111+03:30",
"human_asr_improvement": "not_measured",
"human_latency_improvement": "not_measured"
}
@@ -0,0 +1,36 @@
# Isolated responsiveness candidate ? 2026-10-17
Status: **implemented and live for human comparison; ASR/latency improvement not accepted**. User requested fixes after two real short-utterance transcription errors and server speech-start-to-audio delays5.6?10.5s. This candidate does not claim those errors are resolved without new real audio.
## Changes
`LOCAL_S2S_RESPONSIVE=true` opts into a separate frozen local profile; defaultfalse preserves old profiles. The LLM emits each complete sentence instead of waiting for3. Actual initialized handler attestation checks the applied value, and the profile digest/patch revision `rag-local-s2s-responsive-v1` distinguish old reservations. No old execution profile is rewritten.
ASR uses temperature0 and a generic conversational Persian transcription hint; neither known test utterance is embedded and returned transcripts are not rewritten. Native setup applies settings before warmup. The gateway preserves exact WAV bytes while translating multipart into documented JSON `input_audio` and `provider.options.groq.prompt`; `fa` stays explicit. OpenRouter documents plain multipart `prompt` as accepted but ignored and documents provider-specific options here: [STT contract](https://openrouter.ai/docs/guides/overview/multimodal/stt). The hint applies only when Groq serves the request; other routes still receive explicit language and temperature. No unsupported latency routing preference is claimed.
The gateway records numeric component header/first-body times without text, audio or keys, to separate provider delay from pipeline delay. Existing HTTP PCM streaming is retained; `openai_tts_stream` remainsfalse because its upstream flag is not a general HTTP-streaming switch. PCM format, audio speed, playback/queue capacity, silence/padding settings, models/voices and retained-answer policy remain unchanged. Smaller sentence requests may increase TTS call counts; budget caps still apply.
## Validation
-157 focused unit tests passed in8.51s: wire bytes/options, applied policy/attestation, profile mismatch, cancellation/history, budget/supervisor and baseline behavior.
-3 PostgreSQL profile/replay/revocation tests passed in6.72s, zero skips, `--require-postgres` on a fresh dedicated tmpfs PostgreSQL. Owned container removed; operational and browser DB unchanged. Responsive and baseline reservations both pin original profiles on replay.
-COPY-only image `sha256:ddbb90366f19f8077b1cb40a77e529393459485fb8ae0cb9d074ffea641c265f`, verified parent `66aceba8e58a`; no dependencies downloaded/changed and private inputs excluded from context.
-Actual pinned native engine with real assets, networknone and fixture provider I/O passed. Final stricter18.272s run supplies only one complete sentence and holds generation open; audio arrives before completion, active cancellation/retained drafts/next generation and stale-output exclusion pass. Client error null; cleanup/pending zero, paid calls0. Controlled duration is not a Persian latency benchmark.
-Actual candidate startup24.639s; STT/LLM/TTS probes all200. Authenticated proxied session_ready and closed/user_requested pass; connection check did not increase inference count. This proves setup/probe compatibility, not human accuracy or quality.
-Initial local test runs exposed a Windows BOM decoding issue in the edited engine file and a missing RuntimeSettings argument in the new test; both corrected before the passing runs. No assertion weakened.
## Live handoff and budget
Browser http://127.0.0.2:4201/login, same private account/password and ?????? ?????. API and engine use the new image and responsive flag in the isolated stack. Memory prevention remains OFF per user; Docker3GiB/no-swap, deadlines and30minute expiry remain. Nominal expiry (Tehran): 2026-10-17T11:01:18.153111+03:30.
New exclusive directory `.local-s2s-build/windows-responsive-paid-01` carries both previous local ledgers and exact-ID receipts in order. All prior$0.710884452 exposure remains accounted. Current reserve **$0.769884452**, maximum **$0.981884452**, below the original$1 total. Limits:4 STT,4 LLM,5 TTS attempts including startup. Extra TTS allowance covers sentence splitting; no unrestricted OpenAI. Failed/unknown attempts keep reserves, partial or discontinuous billing chains fail closed, old ledgers remain unchanged. No automatic restart.
Human next: repeat the same short Persian utterances, listen to response onset and interrupt/request the same answer. Exact acoustic timing needs browser/capture measurements; server timing alone excludes the final audible-output path. Same-answer compliance and factual RAG remain pending. [Sanitized actual results](responsive-candidate-20261017.json).
## Human retest: latency still high, evaluation quota failure
User reports high latency persists and supplied browser error `LIVE_PROVIDER_UNAVAILABLE` for session e67dea1c-74bc-427e-8143-8187546e7cd3. Exact evaluation ledger denial: speech attempt_limit,5 admitted. Sentence splitting increased TTS calls; the sixth speech call was refused before provider I/O.13 admitted requests all returned200 (4STT,4LLM,5TTS); reserved exposure$0.981884452 held pending billing. This is an evaluation quota failure, not proof of provider outage or a successful repair. Engine stopped; UI/API remain available. No new inference during diagnosis.
Measured user-request component first-body delays: STT2046/1553/2058ms; LLM765/768/767ms; TTS2491/1578/2036/3741ms. These server timings exclude user speech and final browser audible onset. Sentence-at-a-time alone has not established acceptable end-to-end latency. Do not repeat this capped handoff or claim the latency fix accepted. Next funded evaluation must account for per-answer sentence/TTS calls before admitting generation, or use a deliberately bounded small scenario after exact bill reconciliation. Budget stays$1; memory prevention staysoff.
User explicitly asks to minimize coding quota consumption: keep follow-up investigation/changes narrowly targeted, avoid broad test/build/document churn.
@@ -0,0 +1,100 @@
"""Run one owned native test at a time, with memory and paid-ledger guards."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
root = Path.cwd()
image = 'sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b'
records = []
duplex = '--duplex' in sys.argv
retention = '--retention' in sys.argv or '--retention-active' in sys.argv
active_retention = '--retention-active' in sys.argv
if retention:
image = 'rag-local-s2s-candidate:phase3-retain-v1'
modes = tuple(a for a in sys.argv[1:] if a not in ('--duplex','--retention','--retention-active')) or ('normal', 'sigint', 'sigterm', 'failure')
if any(mode not in ('normal', 'sigint', 'sigterm', 'failure', 'real') for mode in modes):
raise SystemExit('Unknown test mode')
def available():
return int(next(x.split()[1] for x in Path('/proc/meminfo').read_text().splitlines()
if x.startswith('MemAvailable:'))) * 1024
def stop_owned(name, process):
subprocess.run(['docker', 'stop', '--time', '3', name], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=8)
if process.poll() is None:
subprocess.run(['docker', 'kill', name], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=5)
for mode in modes:
if mode == 'real' and (root/'.local-s2s-build/native-paid/native-paid-ledger.json').exists():
raise SystemExit('Paid ledger exists; refusing repeat')
name = 'rag-s2s-evaluation-' + mode + '-' + str(os.getpid())
command = ['docker', 'run', '--rm', '--name', name,
'--network', 'bridge' if mode == 'real' else 'none',
'--read-only', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
'--memory', '3g', '--memory-swap', '3g', '--cpus', '2', '--pids-limit', '128',
'--tmpfs', '/tmp:rw,noexec,nosuid,size=64m', '-e', 'PYTHONPATH=/app',
'-e', 'OMP_NUM_THREADS=1', '-e', 'OPENBLAS_NUM_THREADS=1']
mounts = [('.local-s2s-build/assets-linux/nltk', '/assets/nltk'),
('.local-s2s-build/assets-linux/silero-vad', '/vad/silero-vad'),
('docs/evaluation/local-s2s/phase-02-linux-assets.json', '/assets/assets.json'),
('.local-s2s-build/session-input-24k.pcm', '/checks/input.pcm'),
('docs/evaluation/local-s2s/image-session-smoke.py', '/checks/session.py')]
if mode == 'real':
mounts = [(s, t) for s, t in mounts if t != '/checks/input.pcm']
mounts += [('.local-s2s-build/native-paid/input.pcm', '/checks/input.pcm'),
('docs/evaluation/local-s2s/native-budget-transport.py', '/checks/native-budget-transport.py'),
('.local-s2s-build/openrouter-test.key', '/secret/openrouter-test.key')]
# Match the owner of the private 0600 credential; do not broaden its mode.
command += ['--user', str(os.getuid()) + ':' + str(os.getgid()),
'-v', str(root/'.local-s2s-build/native-paid') + ':/evidence:rw']
for source, target in mounts:
command += ['-v', str(root/source) + ':' + target + ':ro']
command += ['--entrypoint', 'python', image, '/checks/session.py', mode]
if retention:
if mode != 'normal':raise SystemExit('Retention requires normal fixture mode')
command += ['--retention-active' if active_retention else '--retention']
if duplex:
if mode != 'normal':raise SystemExit('Duplex reproduction requires normal fixture mode')
command += ['--duplex']
report = {'mode': mode, 'command': command, 'minimum_host_available_bytes': available(),
'aborted': None, 'exit_code': None}
began = time.monotonic()
process = None
try:
if report['minimum_host_available_bytes'] <= 5*1024**3:
report['aborted'] = 'insufficient_host_headroom_before_start'
else:
with (root/('.local-s2s-build/guarded-'+mode+'.jsonl')).open('w') as output, \
(root/('.local-s2s-build/guarded-'+mode+'.stderr')).open('w') as error:
process = subprocess.Popen(command, stdout=output, stderr=error)
while process.poll() is None:
free = available()
report['minimum_host_available_bytes'] = min(report['minimum_host_available_bytes'], free)
if free < 2500*1024**2 or time.monotonic()-began > 180:
report['aborted'] = 'host_memory_headroom' if free < 2500*1024**2 else 'wall_deadline'
stop_owned(name, process)
break
time.sleep(1)
report['exit_code'] = process.wait(timeout=10)
except BaseException as exc:
report['aborted'] = type(exc).__name__
raise
finally:
try:
if process is not None and process.poll() is None:
stop_owned(name, process)
finally:
report['elapsed_seconds'] = round(time.monotonic()-began, 3)
records.append(report)
(root/('.local-s2s-build/guarded-native-retention-runs.json' if retention else '.local-s2s-build/guarded-native-runs.json')).write_text(json.dumps(records, indent=2)+'\n')
print(json.dumps({k:v for k,v in report.items() if k != 'command'}), flush=True)
if report['aborted'] or report['exit_code'] != 0:
raise SystemExit(1)
@@ -0,0 +1,66 @@
"""Own the candidate engine: startup, memory floor and 30-minute handoff expiry."""
import json
from pathlib import Path
import signal
import subprocess
import time
import sys
root=Path.cwd()
compose=['docker','compose','--env-file','.local-s2s-build/browser-test.env','-f','docker-compose.local-s2s-test.yml','-f','docs/evaluation/local-s2s/phase-02-browser-linux.override.yml']
repair='--repair' in sys.argv
if repair:compose+=['-f','docs/evaluation/local-s2s/phase-02-browser-repair.override.yml']
evidence='browser-repair-paid' if repair else 'browser-paid'
state={'repair':repair,'stage':'preflight','minimum_host_available_bytes':2**63}
report=root/'.local-s2s-build/browser-watch.json'
stop=False
def available():
return int(next(x.split()[1] for x in Path('/proc/meminfo').read_text().splitlines() if x.startswith('MemAvailable:')))*1024
def save():report.write_text(json.dumps(state,indent=2)+'\n')
def terminate(*args):
global stop
stop=True
for sig in (signal.SIGINT,signal.SIGTERM):signal.signal(sig,terminate)
if (root/'.local-s2s-build'/evidence/'browser-paid-ledger.json').exists():
raise SystemExit('Browser paid ledger exists; no automatic restart')
if available()<=5*1024**3:
state.update(stage='blocked',reason='insufficient_host_headroom_before_start');save()
raise SystemExit(1)
began=time.monotonic()
owned=False
try:
owned=True
subprocess.run(compose+['up','--pull','never','-d','local-s2s-engine'],check=True,timeout=30)
state['stage']='starting';save()
while not stop:
free=available()
state['minimum_host_available_bytes']=min(state['minimum_host_available_bytes'],free)
if free<2500*1024**2:
state['reason']='host_memory_headroom';break
if time.monotonic()-began>1800:
state['reason']='handoff_expired_30_minutes';break
status=subprocess.run(compose+['ps','--all','--format','json','local-s2s-engine'],capture_output=True,text=True,timeout=10)
rows=[json.loads(line) for line in status.stdout.splitlines() if line.startswith('{')]
if rows and rows[0].get('State') not in ('running','created'):
state['reason']='engine_exited';break
if state['stage']=='starting':
logs=subprocess.run(compose+['logs','--no-log-prefix','--tail','10','local-s2s-engine'],capture_output=True,text=True,timeout=10).stdout
if '"stage": "startup"' in logs:
state.update(stage='ready',startup_seconds=round(time.monotonic()-began,3))
print(json.dumps({'stage':'ready','startup_seconds':state['startup_seconds']}),flush=True)
elif time.monotonic()-began>180:
state['reason']='startup_wall_deadline';break
save()
time.sleep(2)
except BaseException as exc:
state['reason']=type(exc).__name__
raise
finally:
if owned:
subprocess.run(compose+['stop','--timeout','5','local-s2s-engine'],timeout=15)
state.update(stage='stopped',elapsed_seconds=round(time.monotonic()-began,3))
state.setdefault('reason','operator_stop');save()
@@ -0,0 +1,67 @@
"""Own the candidate engine: startup, memory floor and 30-minute handoff expiry."""
import json
from pathlib import Path
import signal
import subprocess
import time
import sys
root=Path.cwd()
compose=['docker','compose','--env-file','.local-s2s-build/browser-test.env','-f','docker-compose.local-s2s-test.yml','-f','docs/evaluation/local-s2s/phase-02-browser-linux.override.yml']
compose+=['-f','docs/evaluation/local-s2s/phase-04-browser.override.yml']
repair=False
if repair:compose+=['-f','docs/evaluation/local-s2s/phase-02-browser-repair.override.yml']
evidence='phase4-browser-paid'
state={'repair':repair,'stage':'preflight','minimum_host_available_bytes':2**63}
report=root/'.local-s2s-build/phase4-browser-watch.json'
stop=False
def available():
return int(next(x.split()[1] for x in Path('/proc/meminfo').read_text().splitlines() if x.startswith('MemAvailable:')))*1024
def save():report.write_text(json.dumps(state,indent=2)+'\n')
def terminate(*args):
global stop
stop=True
for sig in (signal.SIGINT,signal.SIGTERM):signal.signal(sig,terminate)
if (root/'.local-s2s-build'/evidence/'browser-paid-ledger.json').exists():
raise SystemExit('Browser paid ledger exists; no automatic restart')
if available()<=5*1024**3:
state.update(stage='blocked',reason='insufficient_host_headroom_before_start');save()
raise SystemExit(1)
began=time.monotonic()
owned=False
try:
owned=True
subprocess.run(compose+['up','--pull','never','-d','local-s2s-engine'],check=True,timeout=30)
state['stage']='starting';save()
while not stop:
free=available()
state['minimum_host_available_bytes']=min(state['minimum_host_available_bytes'],free)
if free<2500*1024**2:
state['reason']='host_memory_headroom';break
if time.monotonic()-began>1800:
state['reason']='handoff_expired_30_minutes';break
status=subprocess.run(compose+['ps','--all','--format','json','local-s2s-engine'],capture_output=True,text=True,timeout=10)
rows=[json.loads(line) for line in status.stdout.splitlines() if line.startswith('{')]
if rows and rows[0].get('State') not in ('running','created'):
state['reason']='engine_exited';break
if state['stage']=='starting':
logs=subprocess.run(compose+['logs','--no-log-prefix','--tail','10','local-s2s-engine'],capture_output=True,text=True,timeout=10).stdout
if '"stage": "startup"' in logs:
state.update(stage='ready',startup_seconds=round(time.monotonic()-began,3))
print(json.dumps({'stage':'ready','startup_seconds':state['startup_seconds']}),flush=True)
elif time.monotonic()-began>180:
state['reason']='startup_wall_deadline';break
save()
time.sleep(2)
except BaseException as exc:
state['reason']=type(exc).__name__
raise
finally:
if owned:
subprocess.run(compose+['stop','--timeout','5','local-s2s-engine'],timeout=15)
state.update(stage='stopped',elapsed_seconds=round(time.monotonic()-began,3))
state.setdefault('reason','operator_stop');save()
@@ -0,0 +1,68 @@
"""Own the candidate engine: startup, memory floor and 30-minute handoff expiry."""
import json
from pathlib import Path
import signal
import subprocess
import time
import sys
root=Path.cwd()
compose=['docker','compose','--env-file','.local-s2s-build/browser-test.env','-f','docker-compose.local-s2s-test.yml','-f','docs/evaluation/local-s2s/phase-02-browser-linux.override.yml']
compose+=['-f','docs/evaluation/local-s2s/phase-04-browser.override.yml']
compose+=['-f','docs/evaluation/local-s2s/phase-04-next-browser.override.yml']
repair=False
if repair:compose+=['-f','docs/evaluation/local-s2s/phase-02-browser-repair.override.yml']
evidence='phase4-next-paid'
state={'repair':repair,'stage':'preflight','minimum_host_available_bytes':2**63}
report=root/'.local-s2s-build/phase4-next-watch.json'
stop=False
def available():
return int(next(x.split()[1] for x in Path('/proc/meminfo').read_text().splitlines() if x.startswith('MemAvailable:')))*1024
def save():report.write_text(json.dumps(state,indent=2)+'\n')
def terminate(*args):
global stop
stop=True
for sig in (signal.SIGINT,signal.SIGTERM):signal.signal(sig,terminate)
if (root/'.local-s2s-build'/evidence/'browser-paid-ledger.json').exists():
raise SystemExit('Browser paid ledger exists; no automatic restart')
if available()<=5*1024**3:
state.update(stage='blocked',reason='insufficient_host_headroom_before_start');save()
raise SystemExit(1)
began=time.monotonic()
owned=False
try:
owned=True
subprocess.run(compose+['up','--pull','never','-d','local-s2s-engine'],check=True,timeout=30)
state['stage']='starting';save()
while not stop:
free=available()
state['minimum_host_available_bytes']=min(state['minimum_host_available_bytes'],free)
if free<2500*1024**2:
state['reason']='host_memory_headroom';break
if time.monotonic()-began>1800:
state['reason']='handoff_expired_30_minutes';break
status=subprocess.run(compose+['ps','--all','--format','json','local-s2s-engine'],capture_output=True,text=True,timeout=10)
rows=[json.loads(line) for line in status.stdout.splitlines() if line.startswith('{')]
if rows and rows[0].get('State') not in ('running','created'):
state['reason']='engine_exited';break
if state['stage']=='starting':
logs=subprocess.run(compose+['logs','--no-log-prefix','--tail','10','local-s2s-engine'],capture_output=True,text=True,timeout=10).stdout
if '"stage": "startup"' in logs:
state.update(stage='ready',startup_seconds=round(time.monotonic()-began,3))
print(json.dumps({'stage':'ready','startup_seconds':state['startup_seconds']}),flush=True)
elif time.monotonic()-began>180:
state['reason']='startup_wall_deadline';break
save()
time.sleep(2)
except BaseException as exc:
state['reason']=type(exc).__name__
raise
finally:
if owned:
subprocess.run(compose+['stop','--timeout','5','local-s2s-engine'],timeout=15)
state.update(stage='stopped',elapsed_seconds=round(time.monotonic()-began,3))
state.setdefault('reason','operator_stop');save()
@@ -0,0 +1,82 @@
"""One exclusive, bounded Windows browser handoff. Never restart its ledger."""
import argparse
import ctypes
import json
from pathlib import Path
import signal
import subprocess
import time
ROOT=Path(__file__).resolve().parents[3]
EVIDENCE=ROOT/'.local-s2s-build/windows-browser-paid'
REPORT=ROOT/'.local-s2s-build/windows-browser-watch.json'
COMPOSE=['docker','compose','--project-directory',str(ROOT),'--env-file',str(ROOT/'.local-s2s-build/windows-browser.env'),'-f',str(ROOT/'docs/evaluation/local-s2s/windows-browser.compose.yml')]
class Memory(ctypes.Structure):
_fields_=[('length',ctypes.c_ulong),('load',ctypes.c_ulong)]+[(name,ctypes.c_ulonglong) for name in ('total','available','page_total','page_available','virtual_total','virtual_available','extended')]
def available():
memory=Memory();memory.length=ctypes.sizeof(memory)
if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(memory)):raise OSError('Windows memory query failed')
return memory.available
def vm_available():
data=subprocess.check_output(COMPOSE+['exec','-T','candidate_db','cat','/proc/meminfo'],text=True,timeout=10)
return int(next(line.split()[1] for line in data.splitlines() if line.startswith('MemAvailable:')))*1024
def main(*, enforce_memory=False):
state={'stage':'preflight','memory_enforcement':enforce_memory,'minimum_windows_available_bytes':available(),'minimum_vm_available_bytes':vm_available()}
def save():REPORT.write_text(json.dumps(state,indent=2)+'\n',encoding='utf-8')
if (EVIDENCE/'browser-paid-ledger.json').exists():raise SystemExit('Exclusive ledger already exists; no restart allowed')
if enforce_memory:
# Admit using this host's measured native peak plus the floor and256MiB margin.
trial=json.loads((ROOT/'docs/evaluation/local-s2s/windows-native-retention-20261017.json').read_text())
observed=trial['supervisor']
if observed['exit_code']!=0 or observed['abort'] is not None:raise SystemExit('Missing successful native memory evidence')
required=2500*1024**2+(observed['start_windows_available_bytes']-observed['minimum_windows_available_bytes'])+256*1024**2
state['required_windows_start_bytes']=required
if state['minimum_windows_available_bytes']<required or state['minimum_vm_available_bytes']<=5*1024**3:
state.update(stage='blocked',reason='prestart_memory');save();raise SystemExit(1)
stop=False
def terminate(*args):
nonlocal stop
stop=True
for sig in (signal.SIGINT,signal.SIGTERM):signal.signal(sig,terminate)
began=time.monotonic();owned=False
try:
owned=True
subprocess.run(COMPOSE+['up','--pull','never','--no-deps','-d','local-s2s-engine'],check=True,timeout=40)
state['stage']='starting';save()
while not stop:
win=available();vm=vm_available()
state['minimum_windows_available_bytes']=min(win,state['minimum_windows_available_bytes'])
state['minimum_vm_available_bytes']=min(vm,state['minimum_vm_available_bytes'])
if enforce_memory and min(win,vm)<2500*1024**2:state['reason']='memory_floor';break
if time.monotonic()-began>1800:state['reason']='handoff_expired_30_minutes';break
status=subprocess.check_output(COMPOSE+['ps','--all','--format','json','local-s2s-engine'],text=True,timeout=10)
rows=[json.loads(line) for line in status.splitlines() if line.startswith('{')]
if rows and rows[0].get('State') not in ('running','created'):state['reason']='engine_exited';break
if state['stage']=='starting':
logs=subprocess.check_output(COMPOSE+['logs','--no-log-prefix','--tail','10','local-s2s-engine'],text=True,timeout=10)
if '"stage": "startup"' in logs:
state.update(stage='ready',startup_seconds=round(time.monotonic()-began,3));print('Browser engine ready',flush=True)
elif time.monotonic()-began>180:state['reason']='startup_deadline';break
save();time.sleep(2)
except BaseException as exc:
state['reason']=type(exc).__name__
raise
finally:
if owned:subprocess.run(COMPOSE+['stop','--timeout','5','local-s2s-engine'],timeout=15)
state.update(stage='stopped',elapsed_seconds=round(time.monotonic()-began,3));state.setdefault('reason','operator_stop');save()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--enforce-memory-floor',action='store_true',help='Opt in to host/VM memory admission and automatic low-memory stop')
parser.add_argument('--evidence',type=Path)
parser.add_argument('--report',type=Path)
parser.add_argument('--compose',type=Path)
args=parser.parse_args()
if args.evidence:EVIDENCE=args.evidence.resolve()
if args.report:REPORT=args.report.resolve()
if args.compose:COMPOSE[-1]=str(args.compose.resolve())
main(enforce_memory=args.enforce_memory_floor)
@@ -0,0 +1,61 @@
{
"date": "2026-10-17",
"status": "ready_for_human_test",
"memory_enforcement": false,
"budget": {
"previous_reserved_and_billed_usd": "0.704698199",
"reserved_usd": "0.763698199",
"maximum_cumulative_usd": "0.940698199",
"carry_basis": "documentary_checkpoint_with_local_bills"
},
"connection": {
"conversation_id": "a515ec75-1fb4-496d-879b-ed824df881e9",
"session_id": "991b5a14-07b6-4891-bd16-eebaeab35487",
"events": [
"session_ready"
],
"providers": {
"default_provider": "local_s2s",
"connection_checked": false,
"providers": [
{
"id": "openai",
"label": "OpenAI",
"can_start": false,
"reason": "not_configured"
},
{
"id": "local_s2s",
"label": "\u0633\u06cc\u0633\u062a\u0645 \u062c\u062f\u06cc\u062f",
"can_start": true,
"reason": null
},
{
"id": "gemini",
"label": "Gemini",
"can_start": false,
"reason": "disabled"
}
]
},
"session_ready": true,
"close": {
"session_id": "991b5a14-07b6-4891-bd16-eebaeab35487",
"status": "closed",
"close_reason": "user_requested"
},
"component_attempts_before": 3,
"component_attempts_after": 3
},
"watch": {
"stage": "ready",
"memory_enforcement": false,
"minimum_windows_available_bytes": 4233564160,
"minimum_vm_available_bytes": 4304089088,
"startup_seconds": 26.674
},
"nominal_expiry_tehran": "2026-10-17T10:40:19.606602+03:30",
"openai_comparison_ready": false,
"real_rag_ready": false,
"human_result": "pending"
}
@@ -0,0 +1,18 @@
# Second Windows browser handoff ? 2026-10-17
Status: **ready for human voice/interruption test; Phase3/4 not accepted**.
The user requested temporary disabling of memory prevention and an actual restart for testing. The engine is running with `memory_enforcement=false`; memory measurements alone no longer block/stop it. Docker3GiB/no-swap, startup/30minute deadlines and exclusive budget remain.
## Verified
-15 budget/supervisor tests passed in0.51s. Exact-ID billed carry replaces only the three verified old startup reservations with$0.0001938 actual costs, preserving the full$0.704504399 older exposure. Missing/mismatched/negative receipts fail closed; old live ledger is unchanged.
- New exclusive directory `.local-s2s-build/windows-browser-paid-02`; previous ledger and receipt copies retained. New baseline$0.704698199; three actual startup requests returned200; current conservative exposure$0.763698199; maximum$0.940698199 under the original$1 cap. At most three further admissions per component remain, not guaranteed complete turns.
- Engine startup26.674s; actual proxied login, selected local WebSocket `session_ready` and normal close passed. No audio sent; paid attempts remained3 before/after connection. API and static frontend are healthy. Existing account/password unchanged.
- Watcher now accepts evidence/report/compose paths for fresh exclusive runs; old defaults remain. [Sanitized actual handoff](windows-browser-handoff-02-20261017.json).
Browser http://127.0.0.2:4201/login; credentials `.local-s2s-build/windows-browser-login.txt`. Select ?????? ?????. First ask for a short three-sentence general answer; interrupt with a same-answer repeat, listen to its completion, then request a short continuation. Report audio/transcript behavior and exact errors. Keep prompts/answers short within the per-component caps. No document claims should be tested in this transport-only database.
Nominal expiry (Tehran): 2026-10-17T10:40:19.606602+03:30. Memory prevention remains off; time/budget/provider failures can still end a session. No automatic restart of this ledger.
Next gates: human microphone/interruption/repetition acceptance; approved factual corpus and bounded compatible embeddings/shared search; then bounded OpenAI admission, paired comparisons and restoration. Current fixture and connection successes close none of these acceptance gates.
@@ -0,0 +1,73 @@
{
"date": "2026-10-17",
"status": "ready_for_human_transport_interruption_test_not_phase_acceptance",
"browser_url": "http://127.0.0.2:4201/login",
"image": "sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1",
"connection": {
"conversation_id": "1ad9d329-7ca7-4280-a38f-3f12fc33c1d1",
"session_id": "5cad13f2-d1c0-486b-902f-0a1e2c74b868",
"events": [
"session_ready"
],
"providers": {
"default_provider": "local_s2s",
"connection_checked": false,
"providers": [
{
"id": "openai",
"label": "OpenAI",
"can_start": false,
"reason": "not_configured"
},
{
"id": "local_s2s",
"label": "\u0633\u06cc\u0633\u062a\u0645 \u062c\u062f\u06cc\u062f",
"can_start": true,
"reason": null
},
{
"id": "gemini",
"label": "Gemini",
"can_start": false,
"reason": "disabled"
}
]
},
"session_ready": true,
"close": {
"session_id": "5cad13f2-d1c0-486b-902f-0a1e2c74b868",
"status": "closed",
"close_reason": "user_requested"
},
"component_attempts_before": 3,
"component_attempts_after": 3
},
"budget": {
"previous_reserved_and_billed_usd": "0.704504399",
"reserved_usd": "0.763504399",
"maximum_cumulative_usd": "0.940504399",
"maximum_attempts": {
"speech": 4,
"transcriptions": 4,
"completions": 4
},
"carry_basis": "documentary_checkpoint"
},
"startup_http_statuses": [
200,
200,
200
],
"watch_at_handoff": {
"stage": "ready",
"minimum_windows_available_bytes": 3021164544,
"minimum_vm_available_bytes": 4236189696,
"required_windows_start_bytes": 3816460288,
"startup_seconds": 30.553
},
"watchdog_started_utc": "2026-10-17T06:06:40Z",
"nominal_expiry_tehran": "2026-10-17T10:06:40+03:30",
"rag_ready": false,
"openai_bounded_admission_ready": false,
"human_result": "pending"
}
@@ -0,0 +1,29 @@
# Windows browser handoff ? 2026-10-17
Status: **ready for human microphone/interruption checks; neither Phase3 nor Phase4 accepted**.
Browser: http://127.0.0.2:4201/login. Private account details are in `.local-s2s-build/windows-browser-login.txt`. Select ?????? ?????. This is an isolated voice transport environment; real document RAG and bounded OpenAI comparison are not ready.
## Actual evidence
- Separate project `rag-local-s2s-windows-test` owns a fresh PostgreSQL database, originals/extractions volumes and account; existing operational and prior test data unchanged. API8092 readiness200, new administrator bootstrap successful.
- Actual Angular source built in19.165s; Vite preview serves the generated bundle and proxies HTTP/WebSocket. Development server used553MiB; preview used64MiB at the observed sample. Existing frontend package.json changes preserved.
- Actual proxied login and metadata passed. Explicitly selected local session reached `session_ready`; close persisted `closed/user_requested`. No microphone data sent. Component attempts remained3 before/after the connection check.
- Three actual startup requests (STT/LLM/TTS) returned200. No manual retry/reset. Full documentary carry$0.704504399 retained; current reserved exposure$0.763504399; exclusive cumulative ceiling$0.940504399 below the original$1 cap. This is conservative exposure, not final invoicing. Four attempts per stage include startup, so at most three further admissions per stage remain; batching/failure/interruption may consume these earlier than three user turns.
- Key was available under existing legacy `API_KEY` with OpenRouter endpoint; copied privately to engine-only secret mount. API/browser receive neither it nor OpenAI inference keys. Preserved original profile remains private and unchanged. OpenAI metadata is `not_configured` in this test API until separate bounded admission exists.
- Watchdog uses the measured native Windows memory increase plus2500MiB runtime floor and256MiB margin for preflight (3,816,460,288 bytes), and >5GiB Docker VM availability. Both Windows and VM runtime floors remain2500MiB. Only its engine stops on low memory, startup failure or30minute expiry; no restart of the exclusive ledger is allowed. Nominal expiry **10:06:40 Tehran,2026-10-17**; memory/exit can end it earlier.
## Implementation and checks
The evaluation budget guard adds an explicit documentary carry mode. It validates the exact known checkpoint and rejects mixed private/documentary evidence; it does not fabricate historical requests or invoices. Existing private-ledger paths remain supported. Failures retain reservations; quota denial occurs before provider I/O. Guard code is mounted read-only into the candidate. The connection checker accepts optional account/ledger/report paths, retaining old defaults.
- Budget/history/evaluation/provider selection: **60 passed in9.14s**.
- Budget/supervisor checks: **10 passed in0.69s**, including six overlapping budget cases. They test exclusive-ledger rejection, changed-carry rejection, failure retention, low-memory no-launch and only-owned-engine shutdown on memory/expiry.
- Compose validation, Windows configuration-only no-inference run, real metadata validation in a disposable directory and final `git diff --check` passed.
- Actual startup and authenticated proxied native connection are real-provider evidence limited to the described checks. They do not establish human Persian quality, interrupted-answer compliance or factual correctness. [Sanitized handoff](windows-browser-handoff-20261017.json).
## Human action now required
Use short, non-document questions. Exercise interruption with a same-answer repeat and then a brief continuation, listening for stale audio/errors and retained answer behavior. Keep answers short because the budget has only three additional admissions per component. Report the exact error code if any. No phase closure from this handoff.
Approved corpus/factual annotations, compatible bounded embedding/search preparation, OpenAI admission, paired comparison and restoration remain pending. Do not enable unrestricted OpenAI or bypass calibration to call document retrieval ready. If this handoff expires, create a new carried ledger only after reconciliation; never rerun this ledger.
@@ -0,0 +1,24 @@
{
"date": "2026-10-17",
"cause": "watchdog_memory_floor_before_user_connections",
"watchdog": {
"stage": "stopped",
"minimum_windows_available_bytes": 2606247936,
"minimum_vm_available_bytes": 4236189696,
"required_windows_start_bytes": 3816460288,
"startup_seconds": 30.553,
"reason": "memory_floor",
"elapsed_seconds": 175.791
},
"failed_user_sessions": [
"a4a1f0b8-b5e0-4dcf-9707-6b177ef93a34",
"c542c2a6-81f9-486b-bc0a-18de0dec0453"
],
"api_error": "LIVE_SETUP_FAILED",
"api_exception": "gaierror",
"paid_attempts_after_user_connections": 3,
"new_billed_startup_usd": "0.0001938",
"prior_exposure_held_usd": "0.704504399",
"reconciled_conservative_exposure_usd": "0.704698199",
"human_voice_acceptance": "not_run_engine_unavailable"
}
@@ -0,0 +1,21 @@
# Windows browser startup failure ? 2026-10-17
The browser handoff is **no longer live**. The Windows watchdog stopped only its owned engine after175.791s with reason `memory_floor`; minimum Windows availability2,606,247,936 bytes, just below2500MiB. This was a guarded stop, not a proven OOM or interruption/history defect. The frontend/API stayed available.
The two user WebSocket attempts at06:29:54 and06:30:01 UTC occurred after that stop. API diagnostics show `stream_setup`, `gaierror`, `LIVE_SETUP_FAILED`; frontend close1011 corresponds to failed engine setup. Three login401s were followed by login200 and authenticated me/configuration/session requests; those login failures do not explain the later voice failures. Initial me401 before login is expected.
Engine logs show only the three startup requests and normal shutdown. Ledger still contains exactly three attempts; neither failed browser connection admitted inference. There is no microphone/barge-in quality result.
## Billing reconciliation
Read-only generation lookups for all three exact ledger IDs returned200. Actual costs: STT$0.0000075, LLM$0.0000228, TTS$0.0001635; total **$0.0001938**. The corresponding new$0.059 startup reserve can be replaced only in a new carry; the historical$0.704504399 remains held in full. Reconciled conservative exposure **$0.704698199**. Original exclusive ledger remains untouched and must not restart. Full billing receipts retained privately; [sanitized evidence](windows-browser-stop-20261017.json).
No new inference or engine restart was performed during diagnosis. The current host had3463MiB free after engine stop. Native fixture peak alone underestimated live handoff memory pressure; next admission must include the observed live decline and browser/UI headroom instead of silently reducing the runtime floor. Free memory with the actual browser open before another paid startup. A new carried-forward exclusive ledger is required; old documentary constructor currently accepts only its original checkpoint, so do not substitute the new exposure into it without implementing/verifying a billing-linked carry path.
Phase3/4 remain unaccepted. Next user dependency: free nonessential memory with the browser open; plan roughly4.5GiB available before another supervised trial. No unrelated process was terminated. The previous advertised handoff expiry was an upper bound; this earlier memory stop supersedes its ready state.
## User override: memory prevention disabled
The user explicitly requested disabling memory prevention temporarily. `watch-windows-browser.py` now defaults to observation only: neither Windows/VM pre-start thresholds nor the runtime2500MiB floor block or stop the engine. Memory samples are still recorded. `--enforce-memory-floor` explicitly restores both checks. The3GiB/no-swap Docker limit, exclusive-ledger rejection, budget admission, startup deadline and30minute expiry remain unchanged.
Validation:11 budget/supervisor tests passed in0.40s, including default low-memory launch continuing until the time limit and opt-in memory enforcement. No engine restart or paid call was made. The previously stopped engine remains stopped; any new paid launch still needs verified billing-linked carry. Earlier requests to free RAM are superseded by this explicit user override.
@@ -0,0 +1,206 @@
{
"name": "rag-local-s2s-windows-test",
"services": {
"candidate_db": {
"image": "pgvector/pgvector:pg16",
"environment": {
"POSTGRES_DB": "windows_local_s2s_test",
"POSTGRES_USER": "windows_s2s_test",
"POSTGRES_PASSWORD": "isolated-windows-only"
},
"volumes": [
"windows_postgres:/var/lib/postgresql/data"
],
"healthcheck": {
"test": [
"CMD-SHELL",
"pg_isready -U windows_s2s_test -d windows_local_s2s_test"
],
"interval": "3s",
"timeout": "3s",
"retries": 20
},
"mem_limit": "512m",
"memswap_limit": "512m"
},
"candidate_migrations": {
"image": "sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1",
"environment": {
"PROVIDER": "local_s2s",
"VOICE_PROVIDER": "local_s2s",
"VOICE_SELECTABLE_PROVIDERS": "[\"openai\",\"local_s2s\"]",
"LOCAL_S2S_ENABLED": "true",
"LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS": "true",
"VOICE_TRANSPORT_TESTING": "true",
"LOCAL_S2S_ENDPOINT": "ws://local-s2s-engine:8765/v1/realtime",
"LOCAL_S2S_TOKEN": "${LOCAL_S2S_TOKEN:?Private test token required}",
"LOCAL_S2S_STT_MODEL": "openai/whisper-large-v3",
"LOCAL_S2S_LLM_MODEL": "openai/gpt-4.1-mini",
"LOCAL_S2S_TTS_MODEL": "gpt-4o-mini-tts-2025-12-15",
"LOCAL_S2S_TTS_VOICE": "alloy",
"LOCAL_S2S_MAX_OUTPUT_TOKENS": "128",
"LOCAL_S2S_REQUEST_TIMEOUT_SECONDS": "30",
"LIVE_SESSION_SECONDS": "60",
"LIVE_DIAGNOSTIC_TRACE_ENABLED": "1",
"MAX_PROVIDER_SESSIONS": "1",
"TRUSTED_ORIGINS": "[\"http://127.0.0.2:4201\",\"http://127.0.0.2:8092\"]",
"TRUSTED_HOSTS": "[\"127.0.0.2:4201\",\"127.0.0.2:8092\"]",
"COOKIE_SECURE": "false",
"OPENAI_API_KEY": "",
"OPENAI_REALTIME_API_KEY": "",
"INGEST_DATABASE_URL": "postgresql+psycopg://windows_s2s_test:isolated-windows-only@candidate_db:5432/windows_local_s2s_test",
"INGEST_ORIGINAL_DIRECTORY": "/app/data/local-s2s-test/originals",
"INGEST_EXTRACTION_DIRECTORY": "/app/data/local-s2s-test/extractions",
"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-no-inference",
"INGEST_EMBEDDING_LIMITS": "{\"unit\":\"utf8_bytes\",\"max_input_units\":4096,\"max_batch_units\":4096,\"max_batch_inputs\":1}"
},
"command": [
"alembic",
"upgrade",
"head"
],
"volumes": [
"./.local-s2s-build/windows-empty.env:/app/.env:ro"
],
"depends_on": {
"candidate_db": {
"condition": "service_healthy"
}
},
"mem_limit": "512m",
"memswap_limit": "512m"
},
"candidate_api": {
"image": "sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1",
"environment": {
"PROVIDER": "local_s2s",
"VOICE_PROVIDER": "local_s2s",
"VOICE_SELECTABLE_PROVIDERS": "[\"openai\",\"local_s2s\"]",
"LOCAL_S2S_ENABLED": "true",
"LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS": "true",
"VOICE_TRANSPORT_TESTING": "true",
"LOCAL_S2S_ENDPOINT": "ws://local-s2s-engine:8765/v1/realtime",
"LOCAL_S2S_TOKEN": "${LOCAL_S2S_TOKEN:?Private test token required}",
"LOCAL_S2S_STT_MODEL": "openai/whisper-large-v3",
"LOCAL_S2S_LLM_MODEL": "openai/gpt-4.1-mini",
"LOCAL_S2S_TTS_MODEL": "gpt-4o-mini-tts-2025-12-15",
"LOCAL_S2S_TTS_VOICE": "alloy",
"LOCAL_S2S_MAX_OUTPUT_TOKENS": "128",
"LOCAL_S2S_REQUEST_TIMEOUT_SECONDS": "30",
"LIVE_SESSION_SECONDS": "60",
"LIVE_DIAGNOSTIC_TRACE_ENABLED": "1",
"MAX_PROVIDER_SESSIONS": "1",
"TRUSTED_ORIGINS": "[\"http://127.0.0.2:4201\",\"http://127.0.0.2:8092\"]",
"TRUSTED_HOSTS": "[\"127.0.0.2:4201\",\"127.0.0.2:8092\"]",
"COOKIE_SECURE": "false",
"OPENAI_API_KEY": "",
"OPENAI_REALTIME_API_KEY": "",
"INGEST_DATABASE_URL": "postgresql+psycopg://windows_s2s_test:isolated-windows-only@candidate_db:5432/windows_local_s2s_test",
"INGEST_ORIGINAL_DIRECTORY": "/app/data/local-s2s-test/originals",
"INGEST_EXTRACTION_DIRECTORY": "/app/data/local-s2s-test/extractions",
"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-no-inference",
"INGEST_EMBEDDING_LIMITS": "{\"unit\":\"utf8_bytes\",\"max_input_units\":4096,\"max_batch_units\":4096,\"max_batch_inputs\":1}"
},
"command": [
"python",
"-m",
"app.server",
"--host",
"0.0.0.0",
"--port",
"8000"
],
"volumes": [
"./.local-s2s-build/windows-empty.env:/app/.env:ro",
"windows_originals:/app/data/local-s2s-test/originals",
"windows_extractions:/app/data/local-s2s-test/extractions"
],
"ports": [
"127.0.0.2:8092:8000"
],
"depends_on": {
"candidate_migrations": {
"condition": "service_completed_successfully"
}
},
"mem_limit": "768m",
"memswap_limit": "768m"
},
"local-s2s-engine": {
"image": "sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1",
"entrypoint": [
"python",
"/checks/phase4-browser-engine.py"
],
"command": [
"--allow-paid-startup"
],
"environment": {
"LOCAL_S2S_ENABLED": "true",
"LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS": "true",
"LOCAL_S2S_ENDPOINT": "ws://local-s2s-engine:8765/v1/realtime",
"LOCAL_S2S_TOKEN": "${LOCAL_S2S_TOKEN:?Private test token required}",
"LOCAL_S2S_STT_MODEL": "openai/whisper-large-v3",
"LOCAL_S2S_LLM_MODEL": "openai/gpt-4.1-mini",
"LOCAL_S2S_TTS_MODEL": "gpt-4o-mini-tts-2025-12-15",
"LOCAL_S2S_TTS_VOICE": "alloy",
"LOCAL_S2S_MAX_OUTPUT_TOKENS": "128",
"LOCAL_S2S_REQUEST_TIMEOUT_SECONDS": "30",
"LOCAL_S2S_ALLOW_PAID_STARTUP": "true",
"OPENROUTER_API_KEY": "",
"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": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"OMP_NUM_THREADS": "1",
"OPENBLAS_NUM_THREADS": "1",
"PYTHONPATH": "/app",
"PROVIDER": "local_s2s",
"VOICE_PROVIDER": "local_s2s",
"VOICE_TRANSPORT_TESTING": "true"
},
"volumes": [
"./.local-s2s-build/windows-empty.env:/app/.env:ro",
"./.local-s2s-build/windows-openrouter-test.key:/secret/openrouter-test.key:ro",
"./.local-s2s-build/windows-openai-test.key:/secret/openai-test.key:ro",
"./.local-s2s-build/windows-browser-paid:/evidence:rw",
"./.local-s2s-build/assets-linux/nltk:/assets/nltk:ro",
"./.local-s2s-build/assets-linux/vad:/vad/silero-vad:ro",
"./.local-s2s-build/windows-continuation-20261017/assets-lf.json:/assets/assets.json:ro",
"./services/local_s2s/components.py:/app/services/local_s2s/components.py:ro",
"./docs/evaluation/local-s2s/phase4-browser-engine.py:/checks/phase4-browser-engine.py:ro",
"./docs/evaluation/local-s2s/phase4-browser-budget.py:/checks/phase4-browser-budget.py:ro",
"./docs/evaluation/local-s2s/browser-budget.py:/checks/browser-budget.py:ro",
"./docs/evaluation/local-s2s/native-budget-transport.py:/checks/native-budget-transport.py:ro"
],
"read_only": true,
"cap_drop": [
"ALL"
],
"security_opt": [
"no-new-privileges:true"
],
"tmpfs": [
"/tmp:rw,noexec,nosuid,size=64m"
],
"mem_limit": "3g",
"memswap_limit": "3g",
"cpus": 2,
"pids_limit": 128,
"restart": "no"
}
},
"volumes": {
"windows_postgres": {},
"windows_originals": {},
"windows_extractions": {}
}
}
@@ -0,0 +1,47 @@
# Windows continuation preparation — 2026-10-17
Status: isolated candidate image rebuilt; supervised native retention fixture passed; paid/browser preparation pending; Phase 3 and Phase 4 live acceptance remain pending.
The user confirmed that previous real tests ran on another computer and authorized continuation on this Windows host. Previous private ledgers and native candidate images are not present here. Existing test PostgreSQL/original/extraction volumes remain available and have not been reset. Docker Desktop was started; existing unrelated restart-policy containers started automatically and were left unchanged.
## Recovered inputs
- Clean upstream pin `619e3fe4f71d1c6f35c15870d588a3638de34722`, acquired in `tmp/local-s2s-upstream-619e3fe4`; all 17 recorded SHA-256 fingerprints match after disabling Git archive CRLF conversion.
- Reviewed 134-package Linux CPU lock copied unchanged into `.local-s2s-build/requirements.lock`; original pinned Python base retained.
- All 14 NLTK/Silero asset fingerprints match the existing Linux asset manifest, under `.local-s2s-build/assets-linux`. The Silero directory in this reconstruction is `vad`, not `silero-vad`; mounts must use the actual path.
- Existing Angular checkout `D:/raymand/projects/faq_chatbot_frontend` contains provider selection at commit `a26c597`. Its existing package.json modification was preserved.
- Build succeeded: `rag-local-s2s-candidate:windows-rebuild-20261017`, image ID `sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1`. Original base/lock were retained; native validation remains unrun. A Dockerfile warning about the unset default base ARG remains; the build supplied the explicit pinned base.
## Budget
Carry the full conservative exposure **$0.704504399** from `phase-04-interruption-incident.md`; no release based on missing invoices. Remaining headroom before new reservations is **$0.295495601**, within the original **$1** authorization. This is a documentary carry, not recovered per-request billing evidence or a functioning inference admission ledger.
Public endpoint metadata for all three component models was refreshed without inference. Existing `native-budget-transport.py` price validation passed. Private preparation evidence is `.local-s2s-build/windows-continuation-20261017/`. Do not fabricate old attempt rows to satisfy an old ledger constructor, reset old ledgers, or enable unguarded OpenAI. A fresh exclusive admission ledger must explicitly support this documentary carry before paid startup.
## Checks and remaining gates
- `.venv/Scripts/python -m pytest -q -p no:cacheprovider tests/unit/test_local_s2s_history.py tests/unit/test_local_s2s_evaluation.py tests/unit/test_phase2_provider_selection.py`: **54 passed in 9.63s**.
- `git diff --check`: passed before this report.
- No new paid provider request, engine startup, audio tuning or operational provider switch.
- Windows available physical RAM fell below 1GiB during dependency download; Linux VM MemAvailable alone is insufficient evidence of Windows host headroom. Do not start the native engine until host and VM memory admission is satisfied. Original Linux runners use `/proc/meminfo` and require a Windows-compatible supervisor before reuse here.
- Native fixture validation, bounded cost admission, Windows-specific Compose mounts/images, browser authentication/handoff, approved RAG corpus and bounded embeddings, paired provider measurements and actual restoration remain pending. Existing Linux overrides reference unavailable image digests and `/dev/null`; do not launch them unchanged on this host.
## Completed image check
`docker run --rm --pull never --network none --read-only --memory 128m --memory-swap 128m --pids-limit 64 --cap-drop ALL --security-opt no-new-privileges --entrypoint python rag-local-s2s-candidate:windows-rebuild-20261017 -m pip check`: exit 0, `No broken requirements found.` No key mounted and no engine initialized.
Final Windows physical memory available: **393MiB**; native/paid/browser startup was not attempted. User was asked to free nonessential applications. Build and asset downloads are complete and retained. No unrelated process or container was stopped.
## Supervised native retention run with 4.8GB reported RAM
The user authorized testing after freeing memory. Actual preflight: Windows 5,038,092,288 bytes available, Docker VM 6,191,755,264 bytes. One controlled Windows trial admitted at >=4500MiB Windows / >5GiB VM, with the original 3GiB/no-swap container limit, 2 CPUs, network disabled and no provider key. The supervisor sampled both memory domains and stopped only its owned container if either fell below2500MiB or180s elapsed. This trial does not change existing launch defaults or establish a universal minimum.
**Passed in35.555s, exit0**, no memory abort. Minimum available: Windows4,111,507,456 bytes; VM4,471,754,752 bytes. Active cancellation, two retained-history receipts, next generation, stale-output exclusion, intent correlation, normal completion and unit release passed. Client error null; all cleanup errors/pending requests zero; paid calls zero. See [sanitized result](windows-native-retention-20261017.json). No actual browser, Persian quality or original transient error acceptance follows from fixture I/O.
The Windows checkout's mounted asset manifest has CRLF bytes; its LF-normalized digest matches the historical869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26. A normalized private copy was prepared as `windows-continuation-20261017/assets-lf.json` for later pinned live startup; tracked manifest unchanged. All14 asset payload hashes matched before execution.
Next: a fresh exclusive inference budget guard supporting documentary carry (without fabricated old attempts), Windows Compose/profiles and browser handoff. No paid inference is enabled by this native success; OpenAI admission and real RAG preparation remain pending.
## Later browser preparation
Superseded for readiness by [actual browser handoff](windows-browser-handoff-20261017.md): startup and authenticated proxied connection passed, current reserve$0.763504399. Human microphone/interruption and Phase3/4 acceptance remain pending. Earlier missing-key and preparation-only statements describe their historical checkpoint.

Some files were not shown because too many files have changed in this diff Show More