Author SHA1 Message Date
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
amirhosein mazaheri 8d348f0ba1 feat(voice): add isolated Local S2S v3 candidate and acceptance evidence
Extract the provider boundary while retaining OpenAI/Gemini contracts. Add
an opt-in isolated Local S2S adapter, pinned engine extension, bounded
component gateway and frozen effective configuration profiles.

Enforce request token limits, zero retries, local asset validation,
connection deadlines, disconnect ownership, bounded cleanup and signals.
Include regression coverage, pinned source fixtures, operator guidance,
asset fingerprints and guarded disposable PostgreSQL acceptance tooling.
Preserve immutable fixture bytes across Git line-ending conversion.

Validation recorded in the reports:
- 74 repair, 107 combined and 242 preservation checks passed.
- Fresh PostgreSQL local checks: 2 passed.
- Expanded PostgreSQL: 57 passed, 6 documented baseline failures.
- Compose configurations, staged whitespace and fixture hashes passed.

Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component
audio and Persian browser acceptance remain pending. No operational switch,
paid call, model download or Phase 3 implementation is included.
2026-10-15 12:28:17 +03:30
amirhosein mazaheri 872e5f25cb docs(voice): consolidate local S2S roadmap into four phases 2026-10-15 09:26:39 +03:30
amirhosein mazaheri 22f29b8d58 docs(voice): plan phased local S2S adapter with execution prompts 2026-10-15 09:21:54 +03:30
amirhosein mazaheri 5a4786d0fe docs(presentation): align embedded architecture source 2026-10-14 15:20:28 +03:30
amirhosein mazaheri 7017024d3b docs(presentation): simplify system architecture diagram 2026-10-14 15:20:13 +03:30
amirhosein mazaheri 5337031d80 docs(presentation): normalize guide trailing newline 2026-10-14 15:07:51 +03:30
amirhosein mazaheri e9797309f9 docs(presentation): add system ingestion voice and RAG pipeline diagrams 2026-10-14 15:07:27 +03:30
amirhosein mazaheri 2e8c179efc fix(ingestion): accept observed OCR text alias in partial mode 2026-10-14 14:01:51 +03:30
amirhosein mazaheri 77b8205db6 chore(voice): restore full realtime model with concise delivery 2026-10-14 13:11:22 +03:30
amirhosein mazaheri d7b6d24465 fix(voice): prefer concise complete answers by default 2026-10-14 12:34:36 +03:30
amirhosein mazaheri 1f7c2bd195 fix(voice): decouple cancellation race handling from model and voice 2026-10-14 12:04:08 +03:30
188 changed files with 26000 additions and 89 deletions
+27
View File
@@ -83,6 +83,8 @@ INGEST_EMBEDDING_MAX_RESPONSE_BYTES=16777216
# Backend voice selection; Gemini is the temporary default. No automatic fallback.
# Legacy PROVIDER is accepted; do not set it differently from VOICE_PROVIDER.
VOICE_PROVIDER=gemini
# Additional per-session UI choices; empty preserves default-provider-only admission.
VOICE_SELECTABLE_PROVIDERS=[]
GEMINI_API_KEY=
GEMINI_MODEL=gemini-2.0-flash-exp
GEMINI_VOICE=Aoede
@@ -145,3 +147,28 @@ INGEST_OCR_REVIEW_REQUIRED=true
OPENAI_REALTIME_MAX_OUTPUT_TOKENS=2048
# Provider-side speech speed (0.25..1.5); frozen for each new Live session.
OPENAI_REALTIME_SPEED=1.30
# Local S2S Phase 2 candidate (off by default; isolated development only).
# See services/local_s2s/README.md. Do not change the operational VOICE_PROVIDER.
LOCAL_S2S_ENABLED=false
# Phase 3 development opt-in; saved interrupted text is not treated as heard.
LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS=false
LOCAL_S2S_ENDPOINT=ws://local-s2s-engine:8765/v1/realtime
LOCAL_S2S_ENGINE_REVISION=619e3fe4f71d1c6f35c15870d588a3638de34722
LOCAL_S2S_STT_MODEL=openai/whisper-large-v3
LOCAL_S2S_LLM_MODEL=openai/gpt-4.1-mini
# Candidate only: actual voice/rate/Persian compatibility is not accepted yet.
LOCAL_S2S_TTS_MODEL=google/gemini-3.8-flash-lite-tts
LOCAL_S2S_TTS_VOICE=Kore
LOCAL_S2S_MAX_OUTPUT_TOKENS=256
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS=30
LOCAL_S2S_TOKEN=
# Engine-only OpenRouter key: set at launch, never forward it to the API/browser.
# OPENROUTER_API_KEY=
# Local engine v2: provision these local bundles separately, never at startup.
# Compose host paths (see services/local_s2s/README.md):
# LOCAL_S2S_VAD_SOURCE=<local-silero-source-and-jit-bundle>
# LOCAL_S2S_NLTK_SOURCE=<local-unpacked-nltk-data>
# LOCAL_S2S_ASSET_MANIFEST_SOURCE=<local-assets.json>
# LOCAL_S2S_ASSET_MANIFEST_SHA256=<reviewed-manifest-sha256>
+4
View File
@@ -4,3 +4,7 @@
# Preserve calibration original bytes used by independently annotated hashes.
/data/calibration/phase2-source.md -text
/docs/calibration/phase2-cases.json text eol=lf
# Pinned upstream fixtures and historical repair patch have byte fingerprints.
/tests/fixtures/local_s2s_upstream/* -text whitespace=cr-at-eol
/docs/evaluation/local-s2s/phase-02-remaining-repairs.patch -text whitespace=-blank-at-eol,-blank-at-eof
+3
View File
@@ -86,3 +86,6 @@ temp/
# Immutable ingestion originals (may contain private uploaded content)
data/originals/
# Isolated local S2S generated source and dependency inputs
.local-s2s-build/
+9 -1
View File
@@ -1,5 +1,6 @@
"""K01/K02 and read-only F01, with backend-owned organization scope."""
from uuid import UUID
from typing import Literal
from app.infrastructure.blocking import blocking
from fastapi import APIRouter, Depends, Request
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.',
)
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:
with transaction(engine) as conn:
_, settings = authority(conn, user.id)
+43 -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.modules.auth.service import COOKIE_NAME, UserContext, check_origin
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.settings import RuntimeSettings
from app.modules.voice.durable_tools import DurableTools
@@ -36,8 +36,10 @@ class CreateLiveSessionRequest(BaseModel):
model_config = ConfigDict(extra='forbid')
conversation_id: UUID
client_request_id: UUID
provider: Literal['gemini', 'openai', 'local_s2s'] | None = None
class LiveSessionResponse(BaseModel):
provider: Literal['gemini', 'openai', 'local_s2s'] | None = None
session_id: str
conversation_id: str
status: str
@@ -52,6 +54,34 @@ class CloseLiveSessionResponse(BaseModel):
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):
config.require_voice()
try:
@@ -96,12 +126,17 @@ def create_voice_session(req: CreateLiveSessionRequest, response: Response,
if str(exc) != 'SESSION_NOT_FOUND':
raise
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')
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id)
response.status_code = 201 if result['status'] == 'connected' else 202
response.headers['Idempotency-Replayed'] = 'true'
return result
config = select_provider(config, req.provider)
if config.provider == 'local_s2s':
from app.modules.voice.local_s2s import require_isolated_candidate
require_isolated_candidate(config, IngestionSettings(), database_url=engine.url)
cutoff = capability(config)
profile = config.profile()
# Construct configured embedding transport only after replay recovery.
@@ -110,6 +145,8 @@ def create_voice_session(req: CreateLiveSessionRequest, response: Response,
profile["search"] = search_profile(cutoff, search_settings)
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id,
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:
raise error(str(exc)) from None
if result['replayed']:
@@ -166,6 +203,10 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
try:
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)
config = select_provider(config, info['provider'])
if config.provider == 'local_s2s':
from app.modules.voice.local_s2s import require_isolated_candidate
require_isolated_candidate(config, search_service.settings, database_url=engine.url)
config.require_voice()
if search_service.cutoff is None and not config.voice_transport_testing:
raise ValueError('CALIBRATION_REQUIRED')
+17 -1
View File
@@ -15,7 +15,8 @@ from uuid import uuid4
from app.modules.knowledge.service import SearchInput
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.serialization import bounded_json
from app.infrastructure.realtime import POLICY, strict_json, ProviderProtocolError
from app.infrastructure.realtime import POLICY
from app.modules.voice.provider import strict_json, ProviderProtocolError
class GeminiContextError(ProviderProtocolError):
context_sync = True
@@ -102,6 +103,21 @@ class GeminiLiveAdapter:
self._sent_samples = 0
self._resampler = PCM24To16()
def cancellation_request(self, response_id, operation_id=None):
event = dict(type="response.cancel", response_id=response_id)
if operation_id is not None:
event["event_id"] = operation_id
return event
def history_repair_request(self, repair):
# Preserve the existing send-path failure and its bounded cleanup.
return dict(type="conversation.item.truncate", event_id=repair.operation_id,
item_id=repair.item_id, content_index=repair.content_index,
audio_end_ms=repair.played_ms)
def confirm_history_repair(self, repair, event):
raise GeminiContextError('Gemini context cannot be safely truncated')
def setup(self):
return dict(type='session.update', session={'provider':'gemini'})
+120
View File
@@ -0,0 +1,120 @@
"""Pinned local engine GA transport; no invented native input/history receipts."""
from app.infrastructure.realtime import RealtimeAdapter
from app.modules.voice.provider import ProviderProtocolError
from app.modules.voice.local_s2s import setup_session, effective_identity
class LocalS2SContextError(ProviderProtocolError):
context_sync = True
class LocalS2SAdapter(RealtimeAdapter):
def __init__(self, transport, *, config, settings):
# The local text model is not an OpenAI Realtime model. Keep its config
# independent of OpenAI reasoning/transcription settings.
self.transport, self.config, self.settings = transport, config, settings
self.model, self.voice = config.selected_model, config.selected_voice
self._setup = setup_session(config)
self._identity = effective_identity(config.components(), self._setup)
self._confirmed = False
self._engine_session = None
self._history_revision = 0
self._repair_receipts = {}
def setup(self):
from copy import deepcopy
return dict(type='session.update', session=deepcopy(self._setup))
def acknowledged(self, session):
self._confirmed = False
self._engine_session = None
# A session echo cannot certify a fixed global engine's real components.
# The versioned engine extension derives this from initialized handlers.
if not isinstance(session, dict) or session.get('s2s_effective') != self._identity:
return False
def matches(actual, expected):
if isinstance(expected, dict):
return isinstance(actual, dict) and all(k in actual and matches(actual[k], v) for k, v in expected.items())
if isinstance(expected, list):
return isinstance(actual, list) and len(actual) == len(expected) and all(matches(a, b) for a, b in zip(actual, expected))
return type(actual) is type(expected) and actual == expected
self._confirmed = matches(session, self._setup)
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
def token_limited(self, response):
# No unverified local terminal signature is accepted as a successful answer.
return False
def is_no_active(self, error):
return False
def 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):
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):
from app.modules.voice.provider import strict_json
event=strict_json(wire)
if event.get('type') in ('response.cancel','conversation.item.truncate','s2s.history.retain'):
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)
async def connect_local(config, limits):
from websockets.asyncio.client import connect
token = config.local_s2s_token.get_secret_value()
return await connect(config.local_s2s_endpoint,
additional_headers={'Authorization': 'Bearer ' + token} if token else {},
proxy=None, compression=None, max_size=limits.max_provider_message_bytes, max_queue=16,
open_timeout=limits.connect_timeout_seconds, close_timeout=limits.send_timeout_seconds,
ping_interval=20, ping_timeout=20)
+11
View File
@@ -159,7 +159,16 @@ class OpenRouterVision:
raw_dict = json.loads(raw_text)
valid_types = {"paragraph", "heading", "table", "question", "answer", "visual_group", "caption"}
type_map = {"text": "paragraph", "body": "paragraph", "header": "heading", "title": "heading", "list": "paragraph"}
text_alias_used = False
for i, b in enumerate(raw_dict.get("blocks", [])):
# Observed provider field alias, only in explicit partial admission.
# Transfer verbatim text; conflicting fields must never be guessed.
if allow_partial_extraction(processing_profile) and "text_content" in b:
alias = b["text_content"]
if not isinstance(alias, str) or ("text" in b and b["text"] != alias):
raise ExtractionError("Conflicting vision text fields")
b["text"] = b.pop("text_content")
text_alias_used = True
if b.get("block_type") not in valid_types:
b["block_type"] = type_map.get(str(b.get("block_type", "")).lower(), "paragraph")
if b.get("method") not in ("ocr", "vision"):
@@ -190,6 +199,8 @@ class OpenRouterVision:
}))
# Recognition diagnostics belong to the exact review candidate.
warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",))
if text_alias_used:
warnings += ("Provider text_content field mapped verbatim to text",)
if warnings:
blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks]
if allow_partial_extraction(processing_profile):
+32 -27
View File
@@ -1,5 +1,4 @@
"""Private OpenAI Realtime wire adapter; no application/provider IDs cross to clients."""
import json
from urllib.parse import quote
from app.modules.knowledge.service import SearchInput
@@ -8,8 +7,9 @@ from app.modules.voice.configuration import OpenAIInputSettings
from app.modules.voice.serialization import bounded_json
from app.modules.voice.openai_style import effective_instructions
class ProviderProtocolError(ValueError):
pass
from app.modules.voice.provider import (
ProviderProtocolError, canonical_json, strict_json, HistoryRepair, HistoryRepairReceipt,
)
POLICY = """You are the official voice assistant for «شرکت شهرک‌های صنعتی اصفهان».
Your scope is strictly limited to answering questions regarding «شرکت شهرک‌های صنعتی اصفهان», including its regulations, industrial parks in Isfahan province, land allocations, contracts, permits, circulars, and official procedures.
@@ -52,21 +52,6 @@ When calling search_knowledge:
- Preserve the user's explicitly stated place names, person names, document titles and identifiers in query. Shortening the question must not replace them with different entities. If a name is unclear, ask for clarification rather than guessing.
- Set 'context' to null. Never write explanations or user intent in 'context'."""
def canonical_json(value):
return json.dumps(value, ensure_ascii=False, allow_nan=False,
separators=(",", ":"), sort_keys=True)
def strict_json(raw):
def pairs(items):
value = {}
for key, item in items:
if key in value:
raise ValueError("Duplicate JSON key")
value[key] = item
return value
return json.loads(raw, object_pairs_hook=pairs,
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")))
class RealtimeAdapter:
# Argument-done can precede a cut-off tool call: wait for terminal success.
defer_tool_execution = True
@@ -146,6 +131,30 @@ class RealtimeAdapter:
for key in empty_defaults
if key not in expected['audio']['input']['transcription'])
def cancellation_request(self, response_id, operation_id=None):
event = dict(type="response.cancel", response_id=response_id)
if operation_id is not None:
event["event_id"] = operation_id
return event
def history_repair_request(self, repair: HistoryRepair):
return dict(type="conversation.item.truncate", event_id=repair.operation_id,
item_id=repair.item_id, content_index=repair.content_index,
audio_end_ms=repair.played_ms)
def confirm_history_repair(self, repair: HistoryRepair, event):
# Native OpenAI ack has no request event_id/response_id. Runtime first
# matches exactly one dispatched item/part in this session; never invent
# additional upstream confirmation or infer a heard transcript prefix.
if (event.get("type") != "conversation.item.truncated"
or event.get("item_id") != repair.item_id
or type(event.get("content_index")) is not int
or event["content_index"] != repair.content_index
or type(event.get("audio_end_ms")) is not int
or event["audio_end_ms"] != repair.played_ms):
raise ProviderProtocolError("History repair acknowledgement mismatch")
return HistoryRepairReceipt(repair, event.get("event_id"), "openai.item_truncated")
def interrupted_tool_output(self, call_id):
# Resolve abandoned private tool calls without publishing stale evidence.
return dict(type="conversation.item.create", item=dict(
@@ -195,15 +204,11 @@ class RealtimeAdapter:
try:
if self.no_active_classifier is not None:
return self.no_active_classifier(error) is True
# Selected-profile probe: docs/guides/live-context-sync-repair.md.
# The runtime separately requires the cancellation intent event_id,
# terminal response confirmation, and heard-position truncation.
return ((self.model, self.voice) in {
("gpt-realtime-mini", "shimmer"),
("gpt-realtime-2.1", "shimmer"),
("gpt-realtime-2.1", "marin"),
}
and isinstance(error, dict)
# Captured structured OpenAI signature; independent of model/voice.
# Runtime still requires the cancellation intent event_id, terminal
# response confirmation, and heard-position truncation acknowledgements.
# Unknown signatures remain failures; never match provider message text.
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)
+12 -1
View File
@@ -1,11 +1,22 @@
"""Selected voice transport construction shared by the API and operator smoke."""
import asyncio
from app.modules.voice.provider import VoiceProvider
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
from app.infrastructure.realtime import RealtimeAdapter, connect as connect_openai
async def create_adapter(config, limits):
async def create_adapter(config, limits) -> VoiceProvider:
config.require_voice()
if config.provider == 'local_s2s':
from app.infrastructure.local_s2s import LocalS2SAdapter, connect_local
if limits.output_capacity_profile != 'standard':
raise ValueError('OpenAI output capacity cannot be used for local S2S')
transport = await asyncio.wait_for(connect_local(config, limits), limits.connect_timeout_seconds)
try:
return LocalS2SAdapter(transport, config=config, settings=limits)
except BaseException:
await asyncio.wait_for(transport.close(), limits.send_timeout_seconds)
raise
if config.provider == 'gemini' and limits.output_capacity_profile != 'standard':
raise ValueError('OpenAI output capacity cannot be used for Gemini')
input_settings = None
+149
View File
@@ -0,0 +1,149 @@
"""Explicit offline stage demonstration or bounded opt-in OpenRouter smoke.
Default stub output is a labelled test tone, never evidence of Persian speech.
"""
import argparse
import asyncio
import base64
from io import BytesIO
import json
import math
import os
from pathlib import Path
import struct
import wave
import httpx
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.provider import strict_json
MAX_PCM = 480000 # 10 seconds at 24 kHz, also bounds saved evaluation audio.
def wav_bytes(pcm):
output = BytesIO()
with wave.open(output, 'wb') as audio:
audio.setnchannels(1)
audio.setsampwidth(2)
audio.setframerate(24000)
audio.writeframes(pcm)
return output.getvalue()
def tone():
return b''.join(struct.pack('<h', round(1800 * math.sin(2 * math.pi * 440 * i / 24000)))
for i in range(9600))
async def bounded_response(client, endpoint, *, max_bytes, **kwargs):
async with asyncio.timeout(30):
async with client.stream('POST', 'https://openrouter.ai/api/v1/' + endpoint, **kwargs) as response:
if response.status_code != 200:
raise ValueError('LOCAL_STAGE_HTTP_FAILURE')
body = bytearray()
async for part in response.aiter_bytes(8192):
if len(body) + len(part) > max_bytes:
raise ValueError('LOCAL_STAGE_RESPONSE_CAPACITY')
body.extend(part)
return bytes(body), response.headers.get('content-type', '').split(';')[0]
async def stages(config, pcm, client, key, *, stt_format='multipart'):
if not pcm or len(pcm) % 2 or len(pcm) > MAX_PCM:
raise ValueError('LOCAL_STAGE_INPUT_CAPACITY')
headers = {'Authorization': 'Bearer ' + key}
audio = wav_bytes(pcm)
if stt_format == 'multipart':
payload = dict(files={'file': ('fixture.wav', audio, 'audio/wav')},
data={'model': config.local_s2s_stt_model, 'language': 'fa', 'response_format': 'json'})
elif stt_format == 'json':
payload = dict(json=dict(model=config.local_s2s_stt_model, language='fa', response_format='json',
input_audio=dict(data=base64.b64encode(audio).decode('ascii'), format='wav')))
else:
raise ValueError('LOCAL_STAGE_STT_FORMAT')
raw, media = await bounded_response(client, 'audio/transcriptions', headers=headers, max_bytes=65536, **payload)
if media != 'application/json':
raise ValueError('LOCAL_STAGE_STT_FORMAT')
text = strict_json(raw).get('text')
if not isinstance(text, str) or not text.strip() or len(text) > 1024:
raise ValueError('LOCAL_STAGE_STT_RESULT')
raw, media = await bounded_response(client, 'chat/completions', headers=headers, max_bytes=65536,
json=dict(model=config.local_s2s_llm_model, stream=False, max_tokens=128,
messages=[dict(role='system', content='Reply briefly in Persian. A greeting only; no document claims.'),
dict(role='user', content=text)]))
if media != 'application/json':
raise ValueError('LOCAL_STAGE_LLM_FORMAT')
result = strict_json(raw)
choices = result.get('choices')
if not isinstance(choices, list) or len(choices) != 1 or choices[0].get('finish_reason') != 'stop':
raise ValueError('LOCAL_STAGE_LLM_TERMINAL')
answer = choices[0].get('message', {}).get('content')
if not isinstance(answer, str) or not answer.strip() or len(answer) > 300:
raise ValueError('LOCAL_STAGE_LLM_RESULT')
raw, media = await bounded_response(client, 'audio/speech', headers=headers, max_bytes=MAX_PCM,
json=dict(model=config.local_s2s_tts_model, voice=config.local_s2s_tts_voice,
input=answer, response_format='pcm'))
if media != 'audio/pcm' or not raw or len(raw) % 2:
raise ValueError('LOCAL_STAGE_TTS_FORMAT')
return raw
def stub_response(request):
if request.url.path.endswith('/audio/transcriptions'):
return httpx.Response(200, json={'text': '\u0633\u0644\u0627\u0645'})
if request.url.path.endswith('/chat/completions'):
return httpx.Response(200, json={'choices': [{'finish_reason': 'stop', 'message': {'content': '\u0633\u0644\u0627\u0645'}}]})
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=tone())
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--live', action='store_true', help='Makes exactly 3 paid requests; no retries or startup probes.')
parser.add_argument('--input', type=Path, help='Consented PCM16 mono 24k WAV, at most 10 seconds.')
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--save-evaluation-audio', action='store_true', help='Consent to saving actual provider speech.')
parser.add_argument('--stt-format', choices=['multipart', 'json'], default='multipart')
args = parser.parse_args()
if args.output.exists():
parser.error('Output already exists; choose a new filename.')
if args.live and (not args.input or not args.save_evaluation_audio):
parser.error('--live requires consented --input and --save-evaluation-audio')
if args.live:
config = VoiceSettings(provider='local_s2s')
if not all((config.local_s2s_stt_model, config.local_s2s_llm_model, config.local_s2s_tts_model, config.local_s2s_tts_voice)):
parser.error('Explicit local model/voice settings are required.')
key = os.environ.get('OPENROUTER_API_KEY', '')
if not key:
parser.error('OPENROUTER_API_KEY is required.')
# Check size before reading/decompressing input.
if args.input.stat().st_size > MAX_PCM + 4096:
parser.error('Input is too large.')
with wave.open(str(args.input), 'rb') as audio:
if (audio.getnchannels(), audio.getsampwidth(), audio.getframerate(), audio.getcomptype()) != (1, 2, 24000, 'NONE'):
parser.error('Expected mono PCM16 24kHz WAV.')
pcm = audio.readframes(240001)
transport = httpx.AsyncHTTPTransport(retries=0)
else:
config = VoiceSettings(_env_file=None, provider='local_s2s',
local_s2s_stt_model='stub/stt', local_s2s_llm_model='stub/llm',
local_s2s_tts_model='stub/tts', local_s2s_tts_voice='stub')
key, pcm, transport = 'stub-only', tone(), httpx.MockTransport(stub_response)
async def run():
async with httpx.AsyncClient(transport=transport, timeout=30, follow_redirects=False) as client:
async with asyncio.timeout(90):
return await stages(config, pcm, client, key, stt_format=args.stt_format)
try:
output = asyncio.run(run())
with args.output.open('xb') as target:
target.write(wav_bytes(output))
except (ValueError, KeyError, TypeError, OSError, httpx.HTTPError, TimeoutError):
print(json.dumps(dict(status='failed', mode='live' if args.live else 'stub')))
return 1
print(json.dumps(dict(status='ok', mode='live' if args.live else 'stub-test-tone',
requests=3, paid_requests=3 if args.live else 0,
sample_rate=24000, samples=len(output)//2)))
return 0
if __name__ == '__main__':
raise SystemExit(main())
+4
View File
@@ -32,6 +32,10 @@ async def lifespan(app):
engine = None
startup_error = None
try:
from app.modules.voice.local_s2s import require_isolated_candidate
candidate_config = dependencies.get_voice_settings()
if candidate_config.provider == 'local_s2s':
require_isolated_candidate(candidate_config, dependencies.get_ingestion_settings())
engine = dependencies.get_engine()
lifecycle = dependencies.get_lifecycle_service(engine)
await blocking(dependencies.prepare_search_tools)
+1
View File
@@ -27,6 +27,7 @@ class ExtractionError(ValueError):
# Only fixed categories enter logs; never exception/provider payload text.
self.reason_code = {
"Invalid vision transcription response": "invalid_vision_schema",
"Conflicting vision text fields": "conflicting_vision_text_fields",
"Vision reports unreadable source regions": "unreadable_vision_regions",
"Vision evidence identity, location or readability mismatch": "invalid_vision_evidence",
"Vision transcription incomplete or blocked": "incomplete_or_blocked_vision",
+39 -2
View File
@@ -5,6 +5,7 @@ from typing import Literal
from urllib.parse import urlsplit
from pydantic import AliasChoices, BaseModel, Field, SecretStr, field_validator, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from app.modules.voice.local_s2s import LocalS2SSettings
class OpenAIInputSettings(BaseModel):
@@ -87,9 +88,10 @@ class OpenAIInputSettings(BaseModel):
dict(type=self.openai_realtime_noise_reduction))
class VoiceSettings(OpenAIInputSettings, BaseSettings):
class VoiceSettings(LocalS2SSettings, OpenAIInputSettings, BaseSettings):
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
provider: Literal['gemini', 'openai', 'local_s2s'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
voice_selectable_providers: tuple[Literal['gemini', 'openai', 'local_s2s'], ...] = ()
gemini_api_key: SecretStr = SecretStr('')
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)
@@ -184,26 +186,51 @@ class VoiceSettings(OpenAIInputSettings, BaseSettings):
@property
def selected_model(self):
if self.provider == 'local_s2s':
return self.local_s2s_llm_model
return self.gemini_model if self.provider == 'gemini' else self.openai_realtime_model
@property
def selected_voice(self):
if self.provider == 'local_s2s':
return self.local_s2s_tts_voice
return self.gemini_voice if self.provider == 'gemini' else self.openai_realtime_voice
@property
def selected_proxy(self):
if self.provider == 'local_s2s':
return None
return self.gemini_proxy if self.provider == 'gemini' else self.openai_realtime_proxy
@property
def selected_key(self):
if self.provider == 'local_s2s':
return self.local_s2s_token
return self.gemini_api_key if self.provider == 'gemini' else self.openai_realtime_api_key
def require_voice(self):
if self.provider == 'local_s2s':
if (not self.local_s2s_enabled or not self.voice_transport_testing
or not all((self.local_s2s_stt_model, self.local_s2s_llm_model,
self.local_s2s_tts_model, self.local_s2s_tts_voice))):
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
token = self.local_s2s_token.get_secret_value()
if len(token) > 512 or (token and (not token.isascii() or any(c.isspace() for c in token))):
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
return
key = self.selected_key.get_secret_value()
if not key or len(key) > 512 or not key.isascii() or any(c.isspace() for c in key):
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
def profile(self):
if self.provider == 'local_s2s':
from app.modules.voice.local_s2s import effective_identity, setup_session
return dict(provider='local_s2s', model=self.selected_model, voice=self.selected_voice,
input_sample_rate=24000, output_sample_rate=24000,
evidence_policy_revision='same-session-evidence-retained-v5',
development_only=True, interruption_policy=('retain_unheard_draft_v1'
if self.local_s2s_retain_interrupted_answers else 'close_until_phase3'),
local_s2s=effective_identity(self.components(), setup_session(self)))
profile = dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000,
evidence_policy_revision='same-session-evidence-retained-v5')
@@ -220,3 +247,13 @@ class VoiceSettings(OpenAIInputSettings, BaseSettings):
from app.modules.voice.openai_style import instruction_profile
profile.update(instruction_profile(POLICY))
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
@@ -120,7 +120,7 @@ NUMERIC_FIELDS = frozenset({
"received_elapsed_ms", "terminal_completed", "terminal_cancelled", "terminal_limited",
"terminal_failed", "terminal_incomplete", "terminal_tool_calls", "terminal_output_items",
"authority_ms", "emit_ms", "queued_controls",
"cancellation_type_match", "cancellation_code_match", "cancellation_param_match", "cancellation_profile_2_1_shimmer",
"cancellation_type_match", "cancellation_code_match", "cancellation_param_match", "cancellation_correlated",
"transport_limit_bytes", "transport_limit_messages", "occupancy_count", "limit_count", "occupancy_bytes", "limit_bytes", "transport_bytes", "transport_messages",
"speech_bytes", "elapsed_ms", "deadline_remaining_ms", "sent_bytes", "played_ms", "pending_commands",
"pending_responses", "pending_audio", "pending_tasks", "abort_succeeded", "input_bytes", "http_status",
+1 -1
View File
@@ -87,7 +87,7 @@ class LiveLifecycleService:
@staticmethod
def _shape(row, *, replayed=False, eligible=True):
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,
expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed,
calibration_status=LiveLifecycleService._calibration_status(row))
+99
View File
@@ -0,0 +1,99 @@
"""Frozen, credential-free identity for the development-only local engine."""
from hashlib import sha256
from urllib.parse import urlsplit
from typing import Literal
from pydantic import BaseModel, Field, SecretStr, field_validator
from app.modules.voice.provider import canonical_json
UPSTREAM_REVISION = '619e3fe4f71d1c6f35c15870d588a3638de34722'
CONTRACT_REVISION = 'rag-local-s2s-phase2-v1'
PATCH_REVISION = 'rag-local-s2s-phase2-v3'
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.')
class LocalS2SSettings(BaseModel):
local_s2s_enabled: bool = False
local_s2s_retain_interrupted_answers: bool = False
local_s2s_endpoint: str = 'ws://local-s2s-engine:8765/v1/realtime'
local_s2s_token: SecretStr = SecretStr('')
local_s2s_engine_revision: Literal[UPSTREAM_REVISION] = UPSTREAM_REVISION
local_s2s_stt_model: str = Field(default='', max_length=200)
local_s2s_llm_model: str = Field(default='', max_length=200)
local_s2s_tts_model: str = Field(default='', max_length=200)
local_s2s_tts_voice: str = Field(default='', max_length=80)
local_s2s_language: Literal['fa'] = 'fa'
local_s2s_max_output_tokens: int = Field(default=256, ge=1, le=1024)
local_s2s_request_timeout_seconds: float = Field(default=30, gt=0, le=60, allow_inf_nan=False)
@field_validator('local_s2s_endpoint')
@classmethod
def endpoint(cls, value):
try:
p = urlsplit(value)
p.port
if (len(value) > 512 or p.scheme not in ('ws', 'wss') or not p.hostname
or p.username or p.password or p.query or p.fragment or p.path != '/v1/realtime'):
raise ValueError()
except ValueError:
raise ValueError('Invalid local engine endpoint') from None
return value
@field_validator('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
@classmethod
def local_component_identifier(cls, value):
if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value):
raise ValueError('Invalid local component identifier')
return value
def components(self):
return dict(stt=dict(backend='openai', model=self.local_s2s_stt_model,
language='fa', response_format='json', final_only=True),
llm=dict(backend='chat-completions', model=self.local_s2s_llm_model,
max_output_tokens=self.local_s2s_max_output_tokens),
tts=dict(backend='openai', model=self.local_s2s_tts_model,
voice=self.local_s2s_tts_voice, response_format='pcm', sample_rate=24000),
request_timeout_seconds=self.local_s2s_request_timeout_seconds)
def setup_session(config):
# Reuse the existing backend tool schema/policy; no second retrieval path.
from app.infrastructure.realtime import RealtimeAdapter
session = RealtimeAdapter(None).setup()['session']
session.pop('reasoning', None)
session['model'] = config.local_s2s_llm_model
session['max_output_tokens'] = config.local_s2s_max_output_tokens
session['audio']['input']['transcription'] = dict(model=config.local_s2s_stt_model, language='fa')
session['audio']['output']['voice'] = config.local_s2s_tts_voice
session['audio']['output']['speed'] = 1.0
if config.local_s2s_retain_interrupted_answers:
session['instructions'] += '\n' + RETENTION_INSTRUCTIONS
return session
def effective_identity(components, session):
retention = session.get('instructions', '').endswith(RETENTION_INSTRUCTIONS)
return dict(engine_revision=UPSTREAM_REVISION, patch_revision='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())
def require_isolated_candidate(config, ingestion, *, database_url=None):
"""Run before startup reconciliation, never on the operational database."""
from sqlalchemy.engine import make_url
if config.provider != 'local_s2s':
return
config.require_voice()
url = make_url(database_url if database_url is not None else ingestion.database_url.get_secret_value())
if not url.database or not url.database.endswith('_local_s2s_test'):
raise ValueError('Local S2S requires an isolated *_local_s2s_test database')
for path in (ingestion.original_directory, ingestion.extraction_directory):
if 'local-s2s-test' not in path.resolve().parts:
raise ValueError('Local S2S requires dedicated local-s2s-test storage')
+12 -3
View File
@@ -1,10 +1,19 @@
"""Fixed OpenAI delivery revision; no document facts or unreviewed examples."""
from hashlib import sha256
STYLE_REVISION = 'iranian-persian-conversational-v6'
STYLE_REVISION = 'iranian-persian-conversational-v7'
STYLE = """Delivery style (subordinate to the grounding policy above):
Answer the specific question directly. For a simple factual question, use one or
two short complete sentences. Call evidence tools silently. If an acknowledgement is needed, say only «یه لحظه…»
Give the requested fact or answer in the first sentence. Default to the shortest
complete answer: one or two short sentences for a simple factual question, and a
few short sentences for a multi-part question. Answer all requested parts.
Do not restate the question, introduce your answer, repeat evidence disclaimers,
list unrelated services, or end every answer with an invitation to ask more.
For hours, state the days and times plus any material exception. For a person,
state the supported name and exact role/organization; if ambiguous, ask one
focused clarification instead of changing the role. For eligibility, retain
all conditions and exclusions needed for the user's case.
When the user explicitly asks for a full explanation, steps or detail, provide
the necessary detail; brevity is a default, not a fixed sentence or token cap. Call evidence tools silently. If an acknowledgement is needed, say only «یه لحظه…»
once per user turn; do not describe reviewing documents. Add explanations or further detail only when the user asks
or when they are necessary to interpret the answer correctly.
Preserve necessary numbers, conditions, exceptions and negation;
+74
View File
@@ -0,0 +1,74 @@
"""Private provider port; browser events and runtime safety policy stay unchanged.
Events retain their admitted native identities and replay fingerprints. A terminal
response proves generation stopped, never that unheard history was repaired.
"""
from dataclasses import dataclass
import json
from typing import Protocol
from app.modules.voice.settings import RuntimeSettings
class ProviderProtocolError(ValueError):
pass
def canonical_json(value):
return json.dumps(value, ensure_ascii=False, allow_nan=False,
separators=(",", ":"), sort_keys=True)
def strict_json(raw):
def pairs(items):
value = {}
for key, item in items:
if key in value:
raise ValueError("Duplicate JSON key")
value[key] = item
return value
return json.loads(raw, object_pairs_hook=pairs,
parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")))
@dataclass(frozen=True)
class HistoryRepair:
"""Runtime-frozen correlation, after terminal and final playback coordinates."""
session_id: str
generation: int
response_id: str
operation_id: str
item_id: str
content_index: int
played_ms: int
@dataclass(frozen=True)
class HistoryRepairReceipt:
repair: HistoryRepair
# Native provenance, not an invented provider history revision. OpenAI's
# truncate event supplies item/part/position, but no operation or revision.
native_event_id: str | None
provenance: str
class VoiceProvider(Protocol):
"""Required transport/setup/repair operations; no provider-name branching.
Native optional extensions (consumed/backlog/tool completion classification)
remain adapter-owned. Runtime owns all authority, deadlines and release gates.
"""
settings: RuntimeSettings
def setup(self) -> dict: ...
def acknowledged(self, session: dict) -> bool: ...
def serialize(self, event: dict) -> str: ...
async def send_serialized(self, wire: str) -> None: ...
async def send(self, event: dict) -> None: ...
async def receive(self) -> dict: ...
def cancellation_request(self, response_id: str, operation_id: str | None = None) -> dict: ...
def history_repair_request(self, repair: HistoryRepair) -> dict: ...
def confirm_history_repair(self, repair: HistoryRepair, event: dict) -> HistoryRepairReceipt: ...
def is_no_active(self, error: dict) -> bool: ...
def abort(self) -> bool: ...
async def close(self) -> None: ...
+19 -14
View File
@@ -13,7 +13,9 @@ from pydantic import ValidationError
from app.modules.knowledge.evidence import SearchExecution
from app.modules.knowledge.langchain_tool import ToolContext, create_search_tool
from app.modules.knowledge.service import SearchInput, authority, transaction
from app.infrastructure.realtime import canonical_json, strict_json, ProviderProtocolError
from app.modules.voice.provider import (
canonical_json, strict_json, ProviderProtocolError, VoiceProvider, HistoryRepair, HistoryRepairReceipt,
)
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.diagnostics import diagnostic, protocol_reason, terminal_failure_reason, trace
from app.modules.voice.serialization import bounded_json, json_size, bounded_json_digest
@@ -133,6 +135,8 @@ class Audio:
cleanup: str | None = None
cleanup_deadline: float | None = None
cleanup_dispatched: bool = False
repair: HistoryRepair | None = None
repair_receipt: HistoryRepairReceipt | None = None
@dataclass
class Command:
@@ -163,7 +167,7 @@ class VoiceRuntime:
authority_check is a trusted async backend callback that captures/revalidates
the session's persisted actor/epoch. It is never model input.
"""
def __init__(self, adapter, service, runner, user_id, emit, *,
def __init__(self, adapter: VoiceProvider, service, runner, user_id, emit, *,
authority_check=None, clock=time.monotonic, tool_seconds=None,
session_id=None, max_calls=None, settings=None, close_client=None, tool_store=None):
self.settings = settings or getattr(adapter, "settings", None) or RuntimeSettings()
@@ -423,8 +427,7 @@ class VoiceRuntime:
self.discard_pending_transcript(response)
if not response.terminal and not response.cancel_event:
response.cancel_event = identity()
self.command(dict(type="response.cancel", response_id=response.id,
event_id=response.cancel_event))
self.command(self.adapter.cancellation_request(response.id, response.cancel_event))
task = asyncio.create_task(self._finish_failure(writable))
self.tasks.add(task)
task.add_done_callback(self._failure_finished)
@@ -970,8 +973,7 @@ class VoiceRuntime:
audio.data.clear()
if not response.terminal and not response.cancel_event:
response.cancel_event = identity()
self.command(dict(type="response.cancel", response_id=response.id,
event_id=response.cancel_event))
self.command(self.adapter.cancellation_request(response.id, response.cancel_event))
if any(r.visible for r in affected):
self.control(dict(type="turn_interrupted", turn_ref=old.ref,
cancelled_tool_call_ids=[
@@ -1109,8 +1111,9 @@ class VoiceRuntime:
self.retire(audio)
continue
audio.cleanup = identity()
self.command(dict(type="conversation.item.truncate", event_id=audio.cleanup,
item_id=audio.item, content_index=audio.index, audio_end_ms=audio.played))
audio.repair = HistoryRepair(self.session_id, response.turn.token,
response.id, audio.cleanup, audio.item, audio.index, audio.played)
self.command(self.adapter.history_repair_request(audio.repair))
async def client_control(self, raw):
async with self.lock:
@@ -1492,7 +1495,7 @@ class VoiceRuntime:
intent = wire.get("metadata", {}).get("voice_intent")
if (self.pending_create is None or not self.intent_dispatched
or intent != self.pending_create[0]):
self.command(dict(type="response.cancel", response_id=wire["id"]))
self.command(self.adapter.cancellation_request(wire["id"]))
raise ValueError("Unsolicited response")
_, turn = self.pending_create
response = Response(wire["id"], turn, creation_intent=intent,
@@ -1504,8 +1507,7 @@ class VoiceRuntime:
response.interrupted = True
response.final_deadline = self.clock() + self.settings.final_progress_window_ms / 1000
response.cancel_event = identity()
self.command(dict(type="response.cancel", response_id=response.id,
event_id=response.cancel_event))
self.command(self.adapter.cancellation_request(response.id, response.cancel_event))
elif self.responses[wire["id"]].creation_intent != wire.get("metadata", {}).get("voice_intent"):
raise ValueError("Response creation identity conflict")
elif kind in ("response.output_item.added", "response.output_item.done"):
@@ -1733,6 +1735,11 @@ class VoiceRuntime:
event_type=kind, audio=matches[0] if len(matches) == 1 else None)
return
audio = matches[0]
receipt = self.adapter.confirm_history_repair(audio.repair, event)
if (not isinstance(receipt, HistoryRepairReceipt)
or receipt.repair != audio.repair):
raise ProviderProtocolError("Uncorrelated history repair receipt")
audio.repair_receipt = receipt
audio.cleanup_deadline = None
self.trace("truncate_acknowledged", audio=audio)
self.retire(audio)
@@ -1752,9 +1759,7 @@ class VoiceRuntime:
cancellation_type_match=int(error.get("type") == "invalid_request_error"),
cancellation_code_match=int(error.get("code") == "response_cancel_not_active"),
cancellation_param_match=int(error.get("param") is None),
cancellation_profile_2_1_shimmer=int(
getattr(self.adapter, "model", None) == "gpt-realtime-2.1"
and getattr(self.adapter, "voice", None) == "shimmer"))
cancellation_correlated=1)
self.sync_failed("CANCELLATION_PROVIDER_ERROR", turn=matches[0].turn, phase="provider_handle", event_type=kind)
elif cleanup:
self.sync_failed("TRUNCATION_PROVIDER_ERROR", turn=cleanup.response.turn, phase="provider_handle", event_type=kind, audio=cleanup)
+1 -1
View File
@@ -43,7 +43,7 @@ class RuntimeSettings(BaseSettings):
@classmethod
def for_provider(cls, provider):
if provider not in ('openai', 'gemini'):
if provider not in ('openai', 'gemini', 'local_s2s'):
raise ValueError('Unsupported voice provider')
return cls(output_capacity_profile='openai-repair' if provider == 'openai' else 'standard')
+104
View File
@@ -0,0 +1,104 @@
# Standalone file: never extend the operational compose stack.
name: rag-local-s2s-test
x-candidate-env: &candidate-env
PROVIDER: local_s2s
VOICE_PROVIDER: local_s2s
LOCAL_S2S_ENABLED: ${LOCAL_S2S_ENABLE_CANDIDATE:-false}
VOICE_TRANSPORT_TESTING: "true"
LOCAL_S2S_ENDPOINT: ws://local-s2s-engine:8765/v1/realtime
LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3}
LOCAL_S2S_LLM_MODEL: ${LOCAL_S2S_LLM_MODEL:-openai/gpt-4.1-mini}
LOCAL_S2S_TTS_MODEL: ${LOCAL_S2S_TTS_MODEL:-google/gemini-3.8-flash-lite-tts}
LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-Kore}
LOCAL_S2S_MAX_OUTPUT_TOKENS: "256"
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30"
LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-}
INGEST_DATABASE_URL: postgresql+psycopg://local_s2s_test:isolated-test-only@candidate_db:5432/rag_local_s2s_test
INGEST_ORIGINAL_DIRECTORY: /app/data/local-s2s-test/originals
INGEST_EXTRACTION_DIRECTORY: /app/data/local-s2s-test/extractions
# Greeting/transport-only profile; this endpoint deliberately cannot do inference.
INGEST_EMBEDDING_PROVIDER: openai
INGEST_EMBEDDING_ENDPOINT: http://127.0.0.1:9/v1
INGEST_EMBEDDING_MODEL: text-embedding-3-small
INGEST_EMBEDDING_DIMENSIONS: "1536"
INGEST_EMBEDDING_API_KEY: transport-test-no-inference
TRUSTED_ORIGINS: '["http://127.0.0.2:8091"]'
TRUSTED_HOSTS: '["127.0.0.2:8091"]'
COOKIE_SECURE: "false"
services:
candidate_db:
image: pgvector/pgvector:pg16
environment:
POSTGRES_DB: rag_local_s2s_test
POSTGRES_USER: local_s2s_test
POSTGRES_PASSWORD: isolated-test-only
volumes: [candidate_postgres:/var/lib/postgresql/data]
healthcheck:
test: [CMD-SHELL, pg_isready -U local_s2s_test -d rag_local_s2s_test]
interval: 3s
timeout: 3s
retries: 20
candidate_migrations:
image: rag-local-s2s-candidate:phase2
environment: *candidate-env
command: [alembic, upgrade, head]
depends_on:
candidate_db: {condition: service_healthy}
local-s2s-engine:
image: rag-local-s2s-candidate:phase2
environment:
PROVIDER: local_s2s
VOICE_PROVIDER: local_s2s
LOCAL_S2S_ENABLED: ${LOCAL_S2S_ENABLE_CANDIDATE:-false}
VOICE_TRANSPORT_TESTING: "true"
LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3}
LOCAL_S2S_LLM_MODEL: ${LOCAL_S2S_LLM_MODEL:-openai/gpt-4.1-mini}
LOCAL_S2S_TTS_MODEL: ${LOCAL_S2S_TTS_MODEL:-google/gemini-3.8-flash-lite-tts}
LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-Kore}
LOCAL_S2S_MAX_OUTPUT_TOKENS: "256"
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30"
LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-}
# No database URL or application identity is supplied to the engine.
# The inference key is sent only to the engine, never to the API/browser.
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
LOCAL_S2S_ALLOW_PAID_STARTUP: ${LOCAL_S2S_ALLOW_PAID_STARTUP:-false}
LOCAL_S2S_SILERO_SOURCE: /vad/silero-vad
LOCAL_S2S_NLTK_DATA: /assets/nltk
LOCAL_S2S_ASSET_MANIFEST: /assets/assets.json
LOCAL_S2S_ASSET_MANIFEST_SHA256: ${LOCAL_S2S_ASSET_MANIFEST_SHA256:-}
# Set to a separately provisioned local Silero source+asset bundle; no download.
volumes:
- type: bind
source: ${LOCAL_S2S_VAD_SOURCE:-./.local-s2s-build/vad-not-provisioned}
target: /vad/silero-vad
read_only: true
bind: {create_host_path: false}
- type: bind
source: ${LOCAL_S2S_NLTK_SOURCE:-./.local-s2s-build/nltk-not-provisioned}
target: /assets/nltk
read_only: true
bind: {create_host_path: false}
- type: bind
source: ${LOCAL_S2S_ASSET_MANIFEST_SOURCE:-./.local-s2s-build/assets.json}
target: /assets/assets.json
read_only: true
bind: {create_host_path: false}
mem_limit: 4g
cpus: 2
pids_limit: 128
candidate_api:
image: rag-local-s2s-candidate:phase2
command: [python, -m, app.server, --host, 0.0.0.0, --port, "8000"]
environment: *candidate-env
ports: ["127.0.0.2:8091:8000"]
volumes:
- candidate_originals:/app/data/local-s2s-test/originals
- candidate_extractions:/app/data/local-s2s-test/extractions
depends_on:
candidate_migrations: {condition: service_completed_successfully}
mem_limit: 2g
pids_limit: 128
volumes:
candidate_postgres:
candidate_originals:
candidate_extractions:
+12
View File
@@ -0,0 +1,12 @@
# Start only after stopping rag-api; both APIs share one database.
# Keep rag-api intact for rollback. Never use compose down for switching.
services:
api_candidate:
extends:
file: docker-compose.yml
service: api
image: rag-api-brief-answers:20261014
# Historical container name; the selected model below is authoritative.
container_name: rag-api-mini
environment:
OPENAI_REALTIME_MODEL: gpt-realtime-2.1
+155
View File
@@ -1,5 +1,144 @@
# Phase 1 agent reference map
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);
201 cached asset files fingerprinted, existing NLTK load verified, fresh disposable
PostgreSQL 2 local passed / expanded 57 passed and 6 documented baseline failures.
The guarded runner is `docs/evaluation/local-s2s/acceptance-postgres.py --suite local|expanded`
with `.venv/Scripts/python`; it verifies the target and restores its stopped state.
Phase 1 listening and Phase 2 real engine/SDK/POSIX, components and browser remain open.
No runtime edits, downloads/builds/paid calls or operational switch occurred.
Local S2S Phase 2 preparation (2026-10-15): guarded [local adapter](../app/infrastructure/local_s2s.py),
[engine/build/operator guide](../services/local_s2s/README.md) and standalone
[candidate Compose](../docker-compose.local-s2s-test.yml) now exist. Runtime startup
requires dedicated test DB/storage before reconciliation. [Evidence](evaluation/local-s2s/phase-02.md)
distinguishes offline fixtures/isolated PostgreSQL from unbuilt engine and unrun
real speech/browser checks. No phase acceptance or operational switch is implied.
Local S2S Phase 1 (2026-10-15): the private [provider port](../app/modules/voice/provider.py)
now owns the adapter interface and correlated native repair target/receipt. Runtime
retains generation-stop, playback, authority and next-turn gates. OpenAI/Gemini
selection, public events and frozen profiles are unchanged; local_s2s is not enabled.
See [Phase 1 evidence and offline replay](evaluation/local-s2s/phase-01.md).
Real OpenAI preservation acceptance remains pending.
Live repair diagnostics (2026-10-12): see [numeric trace guide](guides/live-conversation-traces.md)
for the opt-in runtime timeline, frontend consumed/discarded sample accounting,
and the provider-free fixed worklet trace command. Current Linux checks use
@@ -2278,3 +2417,19 @@ Source order, text and locations are preserved; strict mode remains unchanged.
This mode does not guarantee complete legal context within each chunk.
117 focused regression checks passed, including malformed legal identifiers
and bounded splitting.
## Planned local speech-to-speech provider (2026-10-15)
The [phased plan](plans/local-s2s-adapter-plan.md),
[execution ledger](plans/local-s2s-adapter-progress.md) and
[copy-ready prompts](plans/local-s2s-adapter-prompts/README.md) describe local_s2s
alongside OpenAI/Gemini, with initially remote OpenRouter STT/LLM/TTS stages.
Phase 1 is offline_complete_live_pending; Phase 2 is in_progress with the v2
five-defect offline repair checkpoint (31 new, 107 combined and 242 preservation
checks passed). See the evaluation reports linked from the ledger and
`services/local_s2s/README.md` for required local asset fingerprints and commands.
Real engine/SDK, component audio and Persian browser acceptance remain pending.
The original eight-stage plan is archived. OpenAI preservation, actual context-repair
proof, shared RAG authority, isolated acceptance and rollback are hard gates.
This planning record does not weaken existing browser/OpenAI contracts or claim
implementation, live validation or deployment.
+259
View File
@@ -1,5 +1,185 @@
# 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
- 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.
## 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
Supersedes the earlier uncommitted-frontend status: at the user's explicit
@@ -0,0 +1,84 @@
"""Guarded acceptance runner for the retained disposable DB; never uses .env."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
from sqlalchemy import create_engine, text
from sqlalchemy.engine import URL
from tests.support.postgres import validated_test_url
NAME = 'rag-local-s2s-postgres-test'
IDENTITY = 'e5da8c342ed59fc48a49856bfd76010feda45e4a221f640d34aa330a5cd8a7da'
IMAGE = 'sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a'
VOLUME = '9f19da047744737e9bc010ba69c2f22e347f898939d1d42f7bbbb97c4591a3b6'
def inspect(name):
return json.loads(subprocess.check_output(['docker', 'inspect', name]))[0]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--suite', choices=['local', 'expanded'], required=True)
args = parser.parse_args()
row, operational = inspect(NAME), inspect('rag-postgres')
values = dict(item.split('=', 1) for item in row['Config']['Env'] if '=' in item)
expected_ports = {'5432/tcp': [{'HostIp': '127.0.0.1', 'HostPort': '55439'}]}
if not (row['Id'] == IDENTITY and row['Image'] == IMAGE
and row['HostConfig']['PortBindings'] == expected_ports
and values.get('POSTGRES_DB') == 'rag_local_s2s_test'
and values.get('POSTGRES_USER') == 'local_s2s_test'
and row['State']['Status'] == 'exited'
and len(row['Mounts']) == 1 and row['Mounts'][0].get('Name') == VOLUME
and all(m.get('Name') != VOLUME for m in operational['Mounts'])
and values.get('POSTGRES_PASSWORD')):
raise SystemExit('DISPOSABLE_DATABASE_IDENTITY_MISMATCH')
url = validated_test_url(URL.create('postgresql+psycopg', username=values['POSTGRES_USER'],
password=values['POSTGRES_PASSWORD'], host='127.0.0.1', port=55439,
database=values['POSTGRES_DB']))
print(json.dumps(dict(stage='verified-container', container_id=IDENTITY,
database=url.database, host=url.host, port=url.port, volume=VOLUME)), flush=True)
started = False
try:
subprocess.run(['docker', 'start', IDENTITY], check=True, stdout=subprocess.DEVNULL)
started = True
for attempt in range(30):
ready = subprocess.run(['docker', 'exec', IDENTITY, 'pg_isready', '-U', 'local_s2s_test',
'-d', 'rag_local_s2s_test'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if ready.returncode == 0:
break
time.sleep(1)
else:
raise SystemExit('DISPOSABLE_DATABASE_STARTUP_DEADLINE')
engine = create_engine(url, hide_parameters=True)
try:
with engine.connect() as conn:
actual = tuple(conn.execute(text('SELECT current_database(), current_user')).one())
if actual != ('rag_local_s2s_test', 'local_s2s_test'):
raise SystemExit('DISPOSABLE_DATABASE_SERVER_MISMATCH')
finally:
engine.dispose()
env = os.environ.copy()
env['TEST_DATABASE_URL'] = url.render_as_string(hide_password=False)
tests = ['tests/integration/test_local_s2s_phase2.py']
if args.suite == 'expanded':
tests.append('tests/integration/test_phase2_postgres.py')
command = [sys.executable, '-m', 'pytest', *tests, '-m', 'postgres',
'--require-postgres', '-q', '--tb=short', '-p', 'no:cacheprovider']
print(json.dumps(dict(stage='acceptance', suite=args.suite, schemas='test_<random>; fixture creates/drops',
require_postgres=True)), flush=True)
return subprocess.run(command, cwd=ROOT, env=env, timeout=600).returncode
finally:
if started:
stopped = subprocess.run(['docker', 'stop', '--time', '5', IDENTITY], stdout=subprocess.DEVNULL)
print(json.dumps(dict(stage='test-container-restored', stopped=stopped.returncode == 0,
status=inspect(NAME)['State']['Status'])), flush=True)
if stopped.returncode:
raise SystemExit('DISPOSABLE_DATABASE_STOP_FAILED')
if __name__ == '__main__':
raise SystemExit(main())
+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,52 @@
"""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':'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=root/'phase4-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/'phase4-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,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,341 @@
"""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
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)
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+' 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)
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(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,126 @@
"""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
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':
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.
@@ -0,0 +1,33 @@
# Preparation only. Requires bounded OpenAI consent before launching the API.
# Paths resolve relative to the FIRST Compose file at repository root.
services:
candidate_db:
image: sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a
candidate_migrations:
image: sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3
environment:
PROVIDER: openai
VOICE_PROVIDER: openai
volumes:
- ./app:/app/app:ro
- ./migrations:/app/migrations:ro
- ./alembic.ini:/app/alembic.ini:ro
- ./pyproject.toml:/app/pyproject.toml:ro
tmpfs:
- /app/data:rw,noexec,nosuid,size=64m
candidate_api:
image: sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3
environment:
PROVIDER: openai
VOICE_PROVIDER: openai
OPENAI_REALTIME_API_KEY: ${OPENAI_REALTIME_API_KEY:-}
OPENAI_REALTIME_MODEL: ${OPENAI_REALTIME_MODEL:-gpt-realtime-mini}
OPENAI_REALTIME_VOICE: ${OPENAI_REALTIME_VOICE:-shimmer}
OPENAI_REALTIME_MAX_OUTPUT_TOKENS: "256"
volumes:
- ./app:/app/app:ro
- ./migrations:/app/migrations:ro
- ./alembic.ini:/app/alembic.ini:ro
- ./pyproject.toml:/app/pyproject.toml:ro
tmpfs:
- /app/data:rw,noexec,nosuid,size=64m
+206
View File
@@ -0,0 +1,206 @@
# Local S2S Phase 1 report
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
keep their native requests, identities, acknowledgement checks, deadlines and
replay fingerprints. Gemini still refuses unsupported history repair. No new
provider, browser event, schema, profile revision or dependency was introduced.
## Changes and responsibility split
- `app/modules/voice/provider.py`: small structural provider port, shared strict
JSON/error helpers, immutable history-repair target and native receipt.
- `app/modules/voice/runtime.py`: uses the port for cancellation and repair;
freezes session/turn-generation/response/operation/item/part/played coordinates
and rejects a receipt rebound to another target. Retains authorization,
playback accounting, deadlines, evidence lifetime and next-response release.
- `app/infrastructure/realtime.py`: owns native cancel/truncate framing and repair
confirmation. Existing imports of the JSON/error helpers remain compatible.
- `app/infrastructure/gemini_live.py`: implements the same repair operations while
preserving conservative failure. `voice_provider.py` types the existing factory.
- `tests/unit/test_local_s2s_boundary.py`: deterministic before/after replay and
native adapter conformance. Existing test assertions were not weakened.
Generation-stop proof remains the correlated native terminal response. A no-active
cancel error alone never releases a turn. History-repair proof is independent:
one dispatched, frozen item/part/position must match a native acknowledgement
before retirement. Fully played audio needs no mutation. Only runtime releases a
new response after these gates, playback settlement and authority revalidation.
OpenAI provides no operation echo or applied history revision in its truncate
acknowledgement: the receipt records that limitation, not a fabricated revision.
The local engine will need its own actual mutation receipt; flags cannot bypass it.
## Preserved deployment (observed, unchanged)
Repository base: `872e5f25cbe2870d3fc3c66c8a4ab9c697d3d894`; implementation is an
uncommitted working-tree diff. Unrelated `.gitignore` edits and extraction artifacts
were present before work and retained.
| Role | Container ID | Image identity |
| --- | --- | --- |
| Running `rag-api-mini`, port 8080 | `4130f6de6e2a94e66befcb334badb6790fd22a1cdb1ab1a7d8ccfd6e0cd45043` | `rag-api-brief-answers:20261014`, `sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3` |
| Stopped original `rag-api` | `65c9fa765c150467bde2d6336b09fb46d5ffe451d1117eb1ab93a7bacff1037d` | `rag-technical-docs-assistant-api`, `sha256:6f9b1bc3e0eeb76e0143fb33e2773f3fe3e639fbc3c4b2c11139aaabb58ea028` |
Read-only container configuration inspection confirmed OpenAI, `gpt-realtime-2.1`,
`marin`, speed 1.3, reasoning low, max output tokens 2048, standard capacity;
ASR `gpt-transcribe`, languages fa/en; server VAD threshold 0.5, prefix 300 ms,
silence 500 ms, automatic response and interruption both false, noise reduction
null. Browser/provider PCM remains mono 24 kHz. Effective setup SHA-256:
`c5ae10c57660c9d051bb04b18d1b0feb55f3eaf10ac913563ddcdf0fcfe88182`.
This was computed inside the existing image from settings and adapter setup,
without opening a provider connection; it is not a new live setup acknowledgement
or inspection of any active reservation. No credentials were recorded.
Containers/images were retained in place; no build, restart, switch, database
write or second API was performed. Container writable-layer inspection reported
only `/app/docs/calibration` additions beneath `/app/docs`. Rollback was not
exercised. Retaining these IDs does not prove a successful restoration.
## Pinned upstream audit
[Source/build-input manifest](upstream-pin.json) pins
`huggingface/speech-to-speech` at
[`619e3fe4f71d1c6f35c15870d588a3638de34722`](https://github.com/huggingface/speech-to-speech/tree/619e3fe4f71d1c6f35c15870d588a3638de34722),
with SHA-256 and Git blob fingerprints for 17 inspected source/build/test inputs.
Patch revision: none (audit only). This is static compatibility evidence, not
upstream test execution or a built/validated engine.
| Concern | Pinned source evidence | Compatibility / remaining work |
| --- | --- | --- |
| Setup | `handlers/session.py`, `runtime_config.py` deep-merge session settings | Compare authoritative effective configuration; request echo is insufficient |
| Input consumption | `handlers/audio.py` emits committed input items on speech lifecycle | Preserve native item/turn correlation; transcript alone is not commit proof |
| Manual turns | `runtime_config.py`, `handlers/response.py` expose create/interrupt flags and explicit response creation | Both automatic flags must be disabled; verify in engine conformance |
| Identities | `handlers/response.py` preserves response metadata and native response/item IDs | Carry runtime intent and raw fingerprints; no fabricated IDs/acks |
| Tools | conversation/response handlers accept function outputs and terminal output items | Use existing trusted backend dispatcher and terminal validation in Phase 3 |
| Audio | `handlers/audio.py`, `service.py`: 16 kHz internal pipeline, stateful input/output conversion | Verify configured 24 kHz PCM boundary and actual HTTP STT/TTS formats |
| Terminal | `handlers/response.py` handles cancel/finish and structured status | Generation completion differs from browser playback completion |
| History repair | `websocket_router.py` truncate branch logs acceptance without mutation or ack; Realtime README confirms this | **Incompatible** with our repair gate; requires a versioned real mutation and receipt |
| Completed, unplayed output | History/generation lifecycle finishes before playback; truncate performs no repair | Next real LLM request must exclude unheard sentinel while preserving valid context; unproven |
| Remote work | STT/TTS handler/docs show HTTP stage lifecycle, progressive cumulative STT and streaming conversion | Final-only STT initially; separately measure obsolete work/cost and late output suppression |
| Build inputs | Pinned `pyproject.toml` and Dockerfile; CUDA 12.8.1 Ubuntu 24.04 tag, mutable apt/uv, ranged dependencies, NLTK downloads | No upstream Python lockfile; dependency lock, base-image digest and asset hashes remain required **before Phase 2 build** |
No weights/dependencies were installed and no engine was built. No exact Persian
heard-prefix alignment, engine repair revision, OpenRouter model/voice support,
quality, latency or cost claim is established. The no-op truncate and
completed-but-unplayed cases remain explicit Phase 3 hard gates; no weaker
whole-turn or duration-ratio policy was adopted.
## Checks and evidence
Commands ran from the repository root with the existing Windows virtualenv.
`-p no:cacheprovider` avoids pytest cache writes. No real providers were called.
1. Focused baseline, before source changes:
`.venv/Scripts/python -m pytest tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py -q -p no:cacheprovider`
— **215 passed in 29.48 s**.
2. Same replay fixture before refactor:
`.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py -q -s -p no:cacheprovider`
— **12 passed in 2.73 s**. Active and completed-unplayed generation; correct,
duplicate, wrong-item, wrong-position, missing, late and conflicting acks.
3. After initial extraction, focused baseline plus the same 12 replay cases:
— **227 passed in 30.12 s**.
4. Final focused suite, adding `tests/unit/test_local_s2s_boundary.py` and
`tests/unit/test_gemini_live.py` to command 1:
— **242 passed in 32.52 s**. Includes Gemini refusal and wrong-generation receipt rejection.
5. `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider`
? **2,079 passed, 5 failed, 3 skipped, 465 deselected in 305.56 s**.
This run collected the initial 12 replay cases before the final three
conformance cases and cancellation-routing edit; check 4 covers that final edit.
Four underlying failures also reproduce against the original HEAD modules:
- `test_openai_speech_configuration.py::test_transcript_ordering_repeated_words_delayed_completion_and_release`: waits for two transcript delta emissions; times out.
- `test_voice_search_interruption.py::test_profile_cancellation_diagnostics[shimmer-False]` and `[coral-False]`: expect an absent profile-specific diagnostic field.
- The same test's `[coral-True]`: expects profile-specific cancellation rejection inconsistent with the existing classifier.
- `test_test_environment.py::test_ordinary_suite_ignores_ambient_ingestion_configuration` reruns the suite and fails because of those same cases.
These tests were not changed. The three skips are unavailable Windows symlink privileges, not database acceptance.
6. Targeted failure comparison (current source):
`.venv/Scripts/python -m pytest tests/unit/test_openai_speech_configuration.py::test_transcript_ordering_repeated_words_delayed_completion_and_release tests/unit/test_voice_search_interruption.py::test_profile_cancellation_diagnostics -q --tb=short -p no:cacheprovider`
? **4 failed, 1 passed in 4.65 s**. Immutable HEAD module comparison below:
**same 4 failed, 1 passed in 4.32 s**. No files were reverted or rewritten.
7. Final visible replay command below ? **15 passed in 2.84 s**.
8. `git diff --check -- app docs tests` ? passed. Repository-wide
`git diff --check` reports the pre-existing `.gitignore:91` blank line at EOF;
that unrelated edit is preserved. New files were inspected separately.
9. `docker inspect --format '{{.Id}} {{.Image}} {{.State.Status}}' rag-api-mini rag-api`
? original IDs/images unchanged; running/stopped state unchanged.
`Invoke-RestMethod http://localhost:8080/health/ready` ? **ready / available**;
this is readiness, not a voice acceptance check.
To reproduce the original-module comparison without changing the working tree:
```powershell
@'
import subprocess, sys, types
from pathlib import Path
for name, path in (
('app.infrastructure.realtime', 'app/infrastructure/realtime.py'),
('app.infrastructure.gemini_live', 'app/infrastructure/gemini_live.py'),
('app.infrastructure.voice_provider', 'app/infrastructure/voice_provider.py'),
('app.modules.voice.runtime', 'app/modules/voice/runtime.py'),
):
source = subprocess.check_output(['git', 'show', 'HEAD:' + path]).decode('utf-8')
module = types.ModuleType(name)
module.__file__ = str(Path(path).resolve())
module.__package__ = name.rpartition('.')[0]
sys.modules[name] = module
exec(compile(source, module.__file__, 'exec'), module.__dict__)
import pytest
raise SystemExit(pytest.main([
'tests/unit/test_openai_speech_configuration.py::test_transcript_ordering_repeated_words_delayed_completion_and_release',
'tests/unit/test_voice_search_interruption.py::test_profile_cancellation_diagnostics',
'-q', '--tb=short', '-p', 'no:cacheprovider',
]))
'@ | .venv/Scripts/python -
```
The replays are **simulated native events with a controlled clock**. They prove
runtime ordering and unchanged cleanup behavior, not actual engine history
mutation or successful real speech. The matching path releases exactly one next
response after cleanup; missing/wrong/late proof closes safely. A later conflicting
replay closes the session even if a previous valid proof already released work.
Not run: real OpenAI interaction/human listening against the changed source;
engine build/upstream tests; OpenRouter calls; PostgreSQL acceptance (no persistence
contract changed); operational switch/rollback. No bounded paid-call authorization
or consent-controlled speech fixture was supplied for this task.
## See the result
Run this offline, from the repository root:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py -q -s -p no:cacheprovider
```
The trace prints `generation stopped; repair matched at 100ms; duplicate ignored;
exactly one next response`, then safe-close outcomes for bad/missing receipts.
It covers both active and already-completed generation. All 15 final cases should pass.
The existing OpenAI UI/deployment is unchanged. This phase adds an internal
boundary, so there is no new local voice option to click. Do not start a second
API on the operational database to try the source changes. A real changed-source
OpenAI demonstration needs an isolated candidate DB/storage/browser identity or
a separately authorized operational switch; use a short greeting, interrupt it,
and verify the next answer and normal close. Paid usage must be bounded first.
Verdict: offline implementation and deterministic acceptance evidence are delivered.
Required real OpenAI preservation acceptance remains open. Phase 2 must wait for
Phase 1 acceptance, and its build must resolve the recorded dependency/image pins.
## Acceptance prerequisite recheck (2026-10-15)
Phase 1 remains **offline_complete_live_pending**, not accepted. The later Phase 2
v3 preparation found the sibling Angular checkout and prepared an isolated
changed-source OpenAI recipe with read-only app mounts on the cached immutable API
image, masked inherited data and dedicated candidate DB/storage. See the
[acceptance checklist](phase-02-acceptance-checklist.md#phase-1-gate-prepared-source-only-candidate-not-launched).
The recipe was parsed and its isolation checked, not launched. A server-side OpenAI
key is configured, but no bounded live approval/consented speech or actual
interaction/listening evidence was supplied. Historical replay results remain
unchanged and do not close the listening gate. No operational container/image,
provider selection, reservation or database was changed.
@@ -0,0 +1,266 @@
# 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`
plus the preserved working tree. Engine pin `619e3fe4f71d1c6f35c15870d588a3638de34722`,
patch `rag-local-s2s-phase2-v3`, private shape v1. **Not accepted.**
Commands below run from the backend repository root unless stated. Examples under
conditional sections are NOT execution records or authorization. Do not run a
later gate when an earlier mandatory gate is open.
## Authorization and current evidence
| Gate | Actual state | Required next prerequisite |
| --- | --- | --- |
| Offline preparation / isolated DB checks | Authorized by this task; executed below | Preserve unrelated files and operational identities |
| Phase 1 changed-source OpenAI listening | Not run; server configuration has a key, but no bounded live consent/fixture | Explicit bounded OpenAI run and consenting speaker/listener |
| Immutable base | Cached Linux amd64 Python digest inspected | Keep exact digest; no mutable base substitution |
| Pinned source | Full pin absent locally; sibling checkout is `30af00916da85efb053b539a040fd71cf392e7e2` and dirty | Authorized source transfer or supplied clean offline checkout of exact pin |
| Assets | 201 existing files fingerprinted; NLTK 3.10.3 sentence/POS load passed with downloads blocked in sibling Windows venv | Review bundle and validate again in actual Linux engine; no new model download |
| Linux lock / image | Neither exists | Source, reviewed Linux CPU dependency hash lock, explicit dependency/build authorization; Phase 1 acceptance before Phase 2 build |
| Complete engine/SDK controlled I/O / POSIX | Not run; complete engine conformance harness remains to be completed against the full pinned checkout | Actual pinned source and locked Linux SDK/engine environment; no external network |
| Paid OpenRouter components | No approval, key or consented fixture supplied for this run | Engine offline conformance first, then bounded approval and approved speech/key |
| Existing browser | Located sibling Angular checkout; no source edits or browser run | Isolated candidate and fresh browser identity, trusted Origin, listener and consent |
| PostgreSQL | 2 local passed; expanded 57 passed / 6 existing failures | Broad acceptance remains non-green; do not relax assertions |
The earlier proposed 6 OpenRouter requests / 2,000 tokens / 30 seconds was not
approved (the reply expressed lack of understanding). It is not an authorization.
The reviewed 74/107/242 offline baseline remains historical, not a fresh rerun in
this preparation checkpoint. No runtime implementation changed, so those repairs
were not repeated. No paid request, dependency/model/source download, image build,
operational write or Phase 3 work occurred.
## Isolation and immediate stop rules
- Operational `rag-api-mini` ID `4130f6de6e2a94e66befcb334badb6790fd22a1cdb1ab1a7d8ccfd6e0cd45043`
remains running on image `sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3`.
Original `rag-api` ID `65c9fa765c150467bde2d6336b09fb46d5ffe451d1117eb1ab93a7bacff1037d`
remains stopped on image `sha256:6f9b1bc3e0eeb76e0143fb33e2773f3fe3e639fbc3c4b2c11139aaabb58ea028`.
- Acceptance DB runner targets ONLY the recorded container at 127.0.0.1:55439,
database/user `rag_local_s2s_test` / `local_s2s_test`, and its independent volume.
It checks container/image/port/volume, checks server identity, creates/drops
fixture-owned random schemas, uses --require-postgres and restores stopped state.
Operational `rag-postgres` port 5432 and its volume are never test targets.
- Browser/engine stack uses only `docker-compose.local-s2s-test.yml`, project
`rag-local-s2s-test`, separate candidate DB/storage volumes and loopback API
127.0.0.2:8091. Engine gets no DB credential; provider key stays server-side.
Frontend Origin is 127.0.0.2:4201 with an entirely fresh browser profile and test
account. Ports alone do not isolate cookies or databases.
- Stop on any identity/origin/profile/rate mismatch, unauthorized provider/model,
failed probe, missing terminal, incomplete audio, unavailable budget metering,
download attempt, counter discrepancy, teardown survivor, or gate not satisfied.
No retries or silent fallback. Keep partial streams incomplete; never invent
commit/repair/history/terminal receipts. Preserve frozen reservations.
- Stop only owned candidate services. Never compose down, remove volumes, prune,
retag/rebuild operational images, start an API against the operational DB, or
change the existing frontend proxy. Retain raw native IDs/fingerprints privately;
publish numeric/redacted observations, not keys or unconsented audio.
## Preparation executed: exact commands and observations
```powershell
docker inspect --format '{{.Name}}|{{.Id}}|{{.Image}}|{{.State.Status}}' rag-api-mini rag-api
docker image inspect python:3.11-slim --format '{{json .RepoDigests}}|{{.Os}}|{{.Architecture}}|{{.Id}}'
git -C D:/raymand/projects/speech-to-speech-test rev-parse HEAD
git -C D:/raymand/projects/speech-to-speech-test status --short
git -C D:/raymand/projects/speech-to-speech-test cat-file -t 619e3fe4f71d1c6f35c15870d588a3638de34722
```
Recorded operational IDs/images matched. Cached base is
`python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce`
(linux/amd64). `cat-file` failed: required commit object absent. Sibling changes
were preserved; no checkout/fetch was attempted. Only hash-checked partial source
fixtures exist here; these are not a complete source tree.
```powershell
.venv/Scripts/python -m services.local_s2s.assets --nltk-root "$env:APPDATA/nltk_data" --vad-root D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master --output docs/evaluation/local-s2s/phase-02-local-assets.json
D:/raymand/projects/speech-to-speech-test/.venv/Scripts/python.exe -c "import json,os,nltk; from pathlib import Path; from services.local_s2s.assets import validate_assets,configure_nltk; root=Path(os.environ['APPDATA'])/'nltk_data'; vad=Path('D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master'); digest=validate_assets(root,vad,'docs/evaluation/local-s2s/phase-02-local-assets.json'); configure_nltk(nltk,root); print(json.dumps({'manifest_sha256':digest,'nltk_version':nltk.__version__,'sentence_and_pos_load':'passed','runtime_downloads':'blocked','environment':'existing Windows sibling virtualenv; not Linux engine'}))"
.venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite local
.venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite expanded
```
Manifest SHA-256 `8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8`,
201 files. Original assets unchanged; manifest refuses overwrite. NLTK 3.10.3
sentence/POS validation passed with download functions blocked. This validates
existing Windows resources, not Linux torch/JIT or complete engine compatibility.
Local DB: **2 passed in 5.18 s**. Expanded: **57 passed, 6 failed in 236.50 s**;
all six are `test_actual_asgi_tool_dispatch_persistence_and_public_sources`,
`ok|no_evidence|error` x `gemini|openai`, failing on RESPONSE_ACK_DEADLINE. They
match the earlier immutable-HEAD comparison in phase-02.md. That comparison was
not rerun here; no runtime changes were made. All assertions remain intact.
Runner restored the test container to exited after each suite. Expanded suite is
not acceptance-green; no broad DB pass is claimed.
## Phase 1 gate: prepared source-only candidate, NOT launched
No engine build is needed to test the changed API source: the prepared
`phase-01-openai-acceptance.override.yml` reuses the cached immutable API image
read-only as a dependency runtime, mounts current app/migrations read-only, masks
inherited /app/data with tmpfs, and uses only candidate volumes/DB. This does not
alter or retag that image or touch its operational container. Validate source
compatibility before proceeding. Preserve a source SHA-256 manifest at run time;
freeze edits during the observed session and record actual effective OpenAI profile.
After explicit bounded OpenAI consent and verification of test DB/storage:
```powershell
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml up --pull never -d candidate_db candidate_migrations candidate_api
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml exec -it candidate_api python -m app.bootstrap --organization-name Local-S2S-Test --username local-s2s-admin --assistant-name Local-S2S-Test --instruction "Answer briefly in Persian"
```
Use a new test password; do not copy an operational account. Listen to one short
OpenAI greeting, interrupt once, verify the next answer and normal close on the
changed source. Record audible output, native stop/repair correlation, actual
transcripts and human listening observations. Readiness/replay/test tone do not
close this gate. Source-mount recipe is prepared, not runtime-tested or accepted.
Do not run the engine service in this Phase 1 session. Stop candidate_api before
changing the candidate provider; do not rewrite the old OpenAI reservation.
## Immutable build gate: conditional commands, NOT run
Acquire a clean checkout of the exact pin through an explicitly authorized source
transfer (or supply it offline). Never repurpose the dirty sibling checkout.
With the clean checkout and reviewed cached base:
```powershell
.venv/Scripts/python services/local_s2s/prepare_build.py --checkout <clean-pinned-checkout> --base-image python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce
```
In an authorized Linux resolver environment, pin the resolver version, review CPU
PyTorch and all transitive packages/licenses, and produce a complete hash lock:
```text
uv pip compile .local-s2s-build/requirements.in --python-version 3.11 --python-platform x86_64-unknown-linux-gnu --generate-hashes -o .local-s2s-build/requirements.lock
```
Record requirements.in, lock and prepared-source hashes, resolver/Python/platform,
base digest and v3 build manifest. No lock or resolved dependency graph exists yet;
full review cannot be performed on hashes of four source fixtures. Ensure controlled
acceptance test dependencies are separately hash-locked; pytest availability in the
runtime image is not assumed. Revalidate NLTK/VAD manifests after transfer.
Only after Phase 1 acceptance plus explicit dependency-download/image-build approval:
```text
docker build --pull=false -f services/local_s2s/Dockerfile --build-arg ENGINE_BASE_IMAGE=python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce -t rag-local-s2s-candidate:phase2 .
docker image inspect rag-local-s2s-candidate:phase2 --format '{{.Id}}|{{json .RepoDigests}}'
```
No new weights are authorized; use only reviewed fingerprinted local VAD assets.
An image ID/digest and lock SHA must be actual outputs before provenance is filled.
## Complete engine/SDK controlled-I/O gate: NOT run
Use the complete pinned checkout and actual locked SDK, handler construction,
configured runtime, real local VAD and original NLTK. Replace only provider I/O with
controlled responses and isolate external networking. A full-engine conformance
runner does not yet exist here; completing it against that exact source is a
remaining prerequisite, not a fictitious executable command. Do not substitute the
AST/RecordingSDK harness as full-engine evidence. As a preliminary subset, with
hash-locked pytest and assets available inside the isolated Linux environment:
```text
python -m pytest /opt/speech-to-speech/tests/openai_realtime/test_realtime_protocol_contract.py /opt/speech-to-speech/tests/openai_realtime/test_response_input_identity.py -q -p no:cacheprovider
```
These paths were audited at the pin; that command has NOT been executed here and
upstream fixtures alone do not close the full-engine gate. The complete runner
must exercise and save observations for every row below before live activation:
| Trigger | Required actual observation |
| --- | --- |
| Constructor warmups, normal transcribed input, nondefault 17/83 token caps | Actual SDK outbound JSON caps, warmup attempts/counters; retryable HTTP and connect failure exactly once |
| Missing/corrupt local assets with downloader blocked | Fixed safe failure and zero provider operations |
| Session update and authoritative state | Models, voice, 24k rates, v3 profile and configured limits match initialized handlers/applied state; mismatch rejected |
| Input append/commit and manual create | Native input/item/turn correlation; no automatic response before explicit create; transcript alone is not commitment |
| Successful response, audio, transcripts | Native response/item/intent correlation and unchanged raw fingerprints; actual PCM and user/assistant completion semantics |
| Provider failure, empty/partial/trickled stream, peer close before headers/while silent | Accurate failure/incomplete framing; no invented terminal; zero retries, deadline limits, upstream cancellation/socket closure and slot release within v3 bounds |
| SIGINT and SIGTERM during in-flight request on Linux | Actual OS signal delivery to owned process, runtime stop, independent gateway/socket closure, joins and numeric final counters within bounded grace |
| Unsupported interruption | Safe close; no fabricated repair or continuation |
For each independently started, **owned offline** conformance container, actual
signal commands are `docker kill --signal=SIGINT <owned-conformance-container>`
and `docker kill --signal=SIGTERM <owned-conformance-container>`, followed by
`docker wait <owned-conformance-container>`. Start a fresh process for each signal.
Never target operational containers. Record complete runner command, mounts,
network isolation and SDK versions when the runner becomes executable.
## Real components and browser: conditional, NOT authorized or run
Proposed ceilings for approval (not a grant): Phase 1 one OpenAI Realtime session,
60 seconds wall time, at most three responses, 256 output tokens per response;
Phase 2 at most 12 OpenRouter HTTP attempts TOTAL including constructor warmups,
component smoke and browser, at most 2,000 aggregate LLM output tokens and 30 seconds
aggregate synthesized speech, 180 seconds live wall time. Input clips <=10 seconds.
Require a monetary ceiling and approved model/voice IDs before paid execution.
Actual startup counts must first come from complete controlled-I/O evidence. Count
in-flight attempts against the limit. If these aggregate bounds cannot be metered
and enforced, do not start. Split runs into separately budgeted stages; never assume
startup probes are free or add retries when a stage fails. Record provider usage
and request IDs privately; missing usage prevents a cost acceptance claim.
Supply a consented mono PCM16LE 24k Persian WAV and consent to retain the output;
no consented fixture was supplied here. Configure key only in server environment,
models/voice and the reviewed manifest paths/SHA. Existing component smoke executes
three sequential calls, zero retries, 128-token LLM cap, per-stage 30s and total90s;
its WAV header labels the requested rate and does not independently prove that the
provider's raw PCM really has that rate. Verify provider format/rate metadata and
actual audio with an independent listener/analyzer; ambiguous raw PCM fails the gate.
```powershell
.venv/Scripts/python -m app.local_s2s_smoke --live --input <consented-mono24k-PCM16.wav> --output <fresh-output.wav> --save-evaluation-audio
```
Stop on missing/incompatible STT/LLM/TTS or incomplete/oversized output; do not try a
replacement model. Record every attempted stage, even if smoke exits before its
success counters; use provider records for partial failures.
For the isolated engine/browser, after all gates and explicit live approval:
```powershell
$env:LOCAL_S2S_NLTK_SOURCE = "$env:APPDATA/nltk_data"
$env:LOCAL_S2S_VAD_SOURCE = 'D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master'
$env:LOCAL_S2S_ASSET_MANIFEST_SOURCE = (Resolve-Path docs/evaluation/local-s2s/phase-02-local-assets.json).Path
$env:LOCAL_S2S_ASSET_MANIFEST_SHA256 = '8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8'
# Enable flags only under the approved budget; secrets remain in the server environment.
$env:LOCAL_S2S_ENABLE_CANDIDATE = 'true'
$env:LOCAL_S2S_ALLOW_PAID_STARTUP = 'true'
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml up --pull never -d candidate_db candidate_migrations local-s2s-engine candidate_api
```
Frontend checkout found at `D:/raymand/projects/faq_chatbot_frontend`, HEAD
`815191588c59fc43434cc2454cab3a8b2f8c1648`, with pre-existing package.json edit.
Its original proxy targets a LAN service; do not edit/use that proxy for acceptance.
Existing ng.cmd is available, so this conditional launch requires no npm download:
```powershell
Push-Location D:/raymand/projects/faq_chatbot_frontend
.\node_modules\.bin\ng.cmd serve --host 127.0.0.2 --port 4201 --proxy-config D:/raymand/projects/rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-02-browser.proxy.json
Pop-Location
```
Use a new browser profile at http://127.0.0.2:4201, log into the disposable account,
send one consenting Persian greeting, listen to the answer, verify user/assistant
transcripts and normal close. Confirm request destinations and cookie/Origin/CSRF
checks belong to this candidate only. Record actual sample counts/rate and native
IDs privately with a human observation, not just readiness or a WAV header.
If testing interruption, acceptance is only the documented safe close; no Phase 3
barge-in/history repair is claimed. Use source/profile snapshots for each session.
Stop the owned candidate after observations (retain data):
```powershell
docker compose -f docker-compose.local-s2s-test.yml stop
```
No operational switch is part of this checklist. Acceptance can be marked only
when Phase 1 live evidence, complete engine/SDK/POSIX evidence, real components
and isolated Persian browser greeting/transcripts/normal close all exist.
@@ -0,0 +1,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
@@ -0,0 +1,8 @@
# Candidate only; never merge with operational Compose.
services:
candidate_db:
image: sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a
candidate_api:
environment:
TRUSTED_ORIGINS: '["http://127.0.0.2:4201","http://127.0.0.2:8091"]'
TRUSTED_HOSTS: '["127.0.0.2:4201","127.0.0.2:8091"]'
@@ -0,0 +1,4 @@
{
"/api": {"target": "http://127.0.0.2:8091", "secure": false, "changeOrigin": true, "ws": true},
"/users": {"target": "http://127.0.0.2:8091", "secure": false, "changeOrigin": true}
}
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,206 @@
{
"files": {
"nltk/taggers/averaged_perceptron_tagger_eng.zip": "6025f530624335c67d6547d44757b357b4e79bae030a0383e9887a92c1718f0b",
"nltk/taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.classes.json": "d152ffa69d45b8357276341a3d592c6c025911d52ec0d9068d4f382560dd48b6",
"nltk/taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.tagdict.json": "4c713731cb06727736962bc8cd94ad919217a040e76691059af99bc0c2c9c246",
"nltk/taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.weights.json": "789e8e35f6fac656d9b7eccea29ba4e8a137cbb5b525dd31f39e4291a9e80832",
"nltk/tokenizers/punkt_tab.zip": "e57f64187974277726a3417ca6f181ec5403676c717672eef6a748a7b20e0106",
"nltk/tokenizers/punkt_tab/README": "d3251cae66a9359bd68c039e3a46172a05ca9df0b27dcdfa23ae594d68d27ec4",
"nltk/tokenizers/punkt_tab/czech/abbrev_types.txt": "8eb1feb5a6a46f9bd8f6a5ae58e218428a65b459b5ebd61668d83fa80acfc329",
"nltk/tokenizers/punkt_tab/czech/collocations.tab": "fd58f549658c8389be32577e232187be9376c79708f66c60388a84916c8f3f3d",
"nltk/tokenizers/punkt_tab/czech/ortho_context.tab": "451cb1a68a03ba88ced1247e6bb48c442e87dce1c9f463104618fac509866cd4",
"nltk/tokenizers/punkt_tab/czech/sent_starters.txt": "42f1de18ab29f9842113b87ec020202c0c25316c97d37f968435a7c7ee3018ca",
"nltk/tokenizers/punkt_tab/danish/abbrev_types.txt": "4a358b26b7ba372cab3cedeb43b4e99a76ae9d01150493964141eb42a62e4a6e",
"nltk/tokenizers/punkt_tab/danish/collocations.tab": "b003d3b839afd47afa81d64620a1cf15b75b944212a7f3ee6a7571f041ae02ec",
"nltk/tokenizers/punkt_tab/danish/ortho_context.tab": "59d7ccda7b1eef6cbcddb6d2f1930c255a5d43600e66e32eff28eab8190c0727",
"nltk/tokenizers/punkt_tab/danish/sent_starters.txt": "f8dd41bdb1bb633574b22d38205e1c073639a0b80cb9591964bf92d84317527f",
"nltk/tokenizers/punkt_tab/dutch/abbrev_types.txt": "dcd4af07101692c986049ba07abcd6b7c1a2464ef4e46a932cf92d6e220388dd",
"nltk/tokenizers/punkt_tab/dutch/collocations.tab": "9a013563bce4637595a6db9d2eeb0ab3f68685d704ae20d97ad718aa91afbe4a",
"nltk/tokenizers/punkt_tab/dutch/ortho_context.tab": "e2077b5748564a9666e437c0a96ea9c5bed0fe3ab5c756535584785d3af20fc9",
"nltk/tokenizers/punkt_tab/dutch/sent_starters.txt": "734454acc5952d91a1dfaca8cdfdabb715d8cdd35789c749528639d80751f45c",
"nltk/tokenizers/punkt_tab/english/abbrev_types.txt": "92a3e070f43d9b4c5534758ca40ad7343b04e7e29bfe0c2eb658a39445a4f779",
"nltk/tokenizers/punkt_tab/english/collocations.tab": "8e2da1225e4dd2cc9dba261ee231ccb134859e21b46006e7f472c5ee269af0cf",
"nltk/tokenizers/punkt_tab/english/ortho_context.tab": "4bbcca25ed3d3f06c02402abf8419b9f033b8adc06e7b482eca4e45f81a5dc4c",
"nltk/tokenizers/punkt_tab/english/sent_starters.txt": "f3f8535483e1dba487241b764945168123bca3209a9645e59acd1225dc76edac",
"nltk/tokenizers/punkt_tab/estonian/abbrev_types.txt": "0307878fb32af1e21d8f3ba0644e39c89602f2f8aa4e4304943f7e9e0fd081b2",
"nltk/tokenizers/punkt_tab/estonian/collocations.tab": "f1400a7ebf3c82a3d5aac886eb5bf06a1a840946cf052bb1532da7c25094797f",
"nltk/tokenizers/punkt_tab/estonian/ortho_context.tab": "768b7e6e2ba93ff096e244af175c343b1a73463c4a1b99beebe6a9aa57ea1d78",
"nltk/tokenizers/punkt_tab/estonian/sent_starters.txt": "7ade7bb8ca7c527aac09517a6efbdf4f749e9a9fc0e43d2856c58be847030c83",
"nltk/tokenizers/punkt_tab/finnish/abbrev_types.txt": "7829baabcb5d69e26232839a1f5b6bc6d12b0e59b7f0a65f6ab1c163acbeb800",
"nltk/tokenizers/punkt_tab/finnish/collocations.tab": "4d717a1b4d1fb7108ca9c9ed2cc63f8b4813cfaf73819e96fce79495ddc48292",
"nltk/tokenizers/punkt_tab/finnish/ortho_context.tab": "43e55a8bfa977561337a09105c570036df11346c6f91e57d8631520eefb26167",
"nltk/tokenizers/punkt_tab/finnish/sent_starters.txt": "ab81cf3b774ef068ac98adb99fcb3b1a05caf0423bdfa302bdc285e15597567f",
"nltk/tokenizers/punkt_tab/french/abbrev_types.txt": "01747ecfed08830d582d8c94634b63a36da316c0a67feec2871cf03f0dd5c657",
"nltk/tokenizers/punkt_tab/french/collocations.tab": "8ddf150ef5a0d22694e7c4d807f80b6d55da731ca81ea139633f560b378af990",
"nltk/tokenizers/punkt_tab/french/ortho_context.tab": "7090ef4292647d4fe137159bd768a5304015d0614d59fdcfc30b2389634365ac",
"nltk/tokenizers/punkt_tab/french/sent_starters.txt": "b45a1ebdae9cdf46cf2e8be016b4718bf4f825445fc783d445faf0cfb2d569f8",
"nltk/tokenizers/punkt_tab/german/abbrev_types.txt": "259e5d78bc9d61a12d55ba47552c4e9c5ca08364d78a4669e864fd6de86818e3",
"nltk/tokenizers/punkt_tab/german/collocations.tab": "f77bd513f42e8179f5c932111c312be353d5913387d0bfe90a95c109111bca25",
"nltk/tokenizers/punkt_tab/german/ortho_context.tab": "023887e78cfb919f1a00f9a96a88f42131582748cf833fd469490ee66596307c",
"nltk/tokenizers/punkt_tab/german/sent_starters.txt": "fe4b63edbdd33f78ba0a755f035680a864948b145ae82fc99072440a62a77acd",
"nltk/tokenizers/punkt_tab/greek/abbrev_types.txt": "0d56253b7ebc83f0f2403479bcf2b8ea51ffdea89ee60e34018eb32e4750d683",
"nltk/tokenizers/punkt_tab/greek/collocations.tab": "0fd732534d56177c80874125ca894ae60aee7b052ee2865a405b454cfd737a6f",
"nltk/tokenizers/punkt_tab/greek/ortho_context.tab": "a87e4467791f974f808c0d396f6c82cd3a014d4fb4458a2287e2fcbce7084e9c",
"nltk/tokenizers/punkt_tab/greek/sent_starters.txt": "1a450aec85164e3fbfeb814768c9f120abd7139726af5bb5e2a577096739ca8e",
"nltk/tokenizers/punkt_tab/italian/abbrev_types.txt": "5d406f6bfb35e55f6bea282bf148bdcc9e4677860eb01a8e67c34b894274ac50",
"nltk/tokenizers/punkt_tab/italian/collocations.tab": "8167b58a049bb04de8d692ed33d72963503a061717cd37cacb33bb2d00669caf",
"nltk/tokenizers/punkt_tab/italian/ortho_context.tab": "462ffd48bc1c9b86efe66d04d826cd1e7a5745be871b8121759ed2920a967370",
"nltk/tokenizers/punkt_tab/italian/sent_starters.txt": "4dc2cdfda34d4f286e5875d6b62b148771a799a71f0d45b504da23cb61b59d51",
"nltk/tokenizers/punkt_tab/malayalam/abbrev_types.txt": "1ea2cd01629c8cbeac0799d39383e10c4d6948734c255d37e3ceda550ba62464",
"nltk/tokenizers/punkt_tab/malayalam/collocations.tab": "71bc38e42133f288c660a338169d8858944135282ad4166a2c5d23cc8a06ed73",
"nltk/tokenizers/punkt_tab/malayalam/ortho_context.tab": "5289e43f46ef3679f4ebbed95ef1fad5b64dd7aa8957042adb2b661cc6ae4425",
"nltk/tokenizers/punkt_tab/malayalam/sent_starters.txt": "918c902aa9d0b72700410258274ae335da51148fee7fc27095ab4114b23a245c",
"nltk/tokenizers/punkt_tab/norwegian/abbrev_types.txt": "beced74076edabe64f45effb823012d1396db41f35fa1d8be2ac6b69bf7bc40f",
"nltk/tokenizers/punkt_tab/norwegian/collocations.tab": "9c815b01e2f7518552b53f09012644df1fa0d8c7642baff9dc5f61e85e0be422",
"nltk/tokenizers/punkt_tab/norwegian/ortho_context.tab": "57ea2aa129de6ae414cd0cbecba8b2399c4fde775a2145776a7e8f1023f3f183",
"nltk/tokenizers/punkt_tab/norwegian/sent_starters.txt": "2b49ef0f0c2e1b4e8b06aee1172e4d88ce6ad01486fe4182cff6fc443a73ddeb",
"nltk/tokenizers/punkt_tab/polish/abbrev_types.txt": "426ea37ca486d0dcc3653653c613d853d0bb3929037f8ee6bf6c12ddae873aa1",
"nltk/tokenizers/punkt_tab/polish/collocations.tab": "961653f0606d85ecb8a760cad4f69df123f010bc4b35de0253feb2d7869666b4",
"nltk/tokenizers/punkt_tab/polish/ortho_context.tab": "f770804067012ee5707ffc65d90523180e09bab09230a49251777be821a1a4f6",
"nltk/tokenizers/punkt_tab/polish/sent_starters.txt": "8564076ae22be3d549a3f097a18458ac2967d65bd28dad7cc223c53f5ce27d1b",
"nltk/tokenizers/punkt_tab/portuguese/abbrev_types.txt": "cd5c3cf9c4c8b766bc9edbc96444b0e2189b837b26c583aa2cce83a18e4285f5",
"nltk/tokenizers/punkt_tab/portuguese/collocations.tab": "a150d2ca3b8bd9d87cd25f2e1d2142607cdf9344efe914bd034af6017a16d841",
"nltk/tokenizers/punkt_tab/portuguese/ortho_context.tab": "2d9c143f7b322fc74738a21e0b2b04feed1668245ac93e5a8e5399e6e0d8ed8a",
"nltk/tokenizers/punkt_tab/portuguese/sent_starters.txt": "7b7f4a1586b1df8592bf294c8dd0d19aaf90740d78ce3b40a31eff2b9669d15e",
"nltk/tokenizers/punkt_tab/russian/abbrev_types.txt": "75191526be516a9918948fe3ad46f6c2c4dee14314359a899b8c2ebf496cb631",
"nltk/tokenizers/punkt_tab/russian/collocations.tab": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"nltk/tokenizers/punkt_tab/russian/ortho_context.tab": "b296cba91006569d3ef79eb2cff2378bf5be5b75e9e83ea119b883d3c3ee69b6",
"nltk/tokenizers/punkt_tab/russian/sent_starters.txt": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"nltk/tokenizers/punkt_tab/slovene/abbrev_types.txt": "b1d6b16d1d2b3c0c4132c1528b9843d1557f7f544044db27f4e8d2d6985faf2b",
"nltk/tokenizers/punkt_tab/slovene/collocations.tab": "4c10daafdff496e369f3a8809bebf187abc851df630457ae93c7ca4fda350651",
"nltk/tokenizers/punkt_tab/slovene/ortho_context.tab": "3ba826bdd7e5543af7af8e317d4652ba8b47fd812157855a6274ec1387a46b3e",
"nltk/tokenizers/punkt_tab/slovene/sent_starters.txt": "85ae14dadef3c4c9f753491d84919abb10e09003adfe248794d4a597fabc5793",
"nltk/tokenizers/punkt_tab/spanish/abbrev_types.txt": "246a4b3efbad45b63eb9672b718574b535acef6d656f24dc17a46d13a38efba1",
"nltk/tokenizers/punkt_tab/spanish/collocations.tab": "fa5ea7dbf61f2b1c12180d660a3012c9faaf4962eb12549d77af95e2a40be65d",
"nltk/tokenizers/punkt_tab/spanish/ortho_context.tab": "1346ecfc57b26174987ffa9bd4a2558a66f46592a513da3859648790351df370",
"nltk/tokenizers/punkt_tab/spanish/sent_starters.txt": "4d4f7380ba16380b6158e9e8ead6973c52f27e3c9c88af63f15a41c490998319",
"nltk/tokenizers/punkt_tab/swedish/abbrev_types.txt": "1e1a78bd5e7fd6e7eb4b15b751a23d441cda845d5fc0b631958177b2f504da00",
"nltk/tokenizers/punkt_tab/swedish/collocations.tab": "bd2260433c94617ba7cf6102e4c1035099a72e5a2f6b60734639252e41633c04",
"nltk/tokenizers/punkt_tab/swedish/ortho_context.tab": "d48c5705d0570993628e539ca211f05cdb5aad7adfcc6ed7b24310941bfac9f8",
"nltk/tokenizers/punkt_tab/swedish/sent_starters.txt": "6f0f7a6773f7488a23bafc6c29e7d4554e792d89c6b7a89fbd6a83bec85ef767",
"nltk/tokenizers/punkt_tab/turkish/abbrev_types.txt": "de56078c5eeb3fe07e24eab67c4aaf44e2181cbe80edd976cb1622819599d6fd",
"nltk/tokenizers/punkt_tab/turkish/collocations.tab": "061ce2981776a8f875da4f24bebd7e138f8da1d9057b43d07f580148ec106a33",
"nltk/tokenizers/punkt_tab/turkish/ortho_context.tab": "fc214227f99d5ea3ee70d208df16b1984eab375d1946ed379061c6cf5c1718be",
"nltk/tokenizers/punkt_tab/turkish/sent_starters.txt": "93239fb55b5d2ae6d945a84a94e118ba8a816326b17cdc11ba8111bea0c97828",
"vad/.github/ISSUE_TEMPLATE/bug_report.md": "838e58d3039c5eade216dd8caac4ef7e823203f5686eaf39ed62817530ae746f",
"vad/.github/ISSUE_TEMPLATE/feature_request.md": "7de51a6efb528d29eaa7a0c6364c05849d518102c24eefcfdcaa11338b442eb9",
"vad/.github/ISSUE_TEMPLATE/questions---help---support.md": "061d6ca1262f97c9460b769f041a2d73b7eddd86733a1d2bd44b637c564d3c6a",
"vad/.github/workflows/python-publish.yml": "63f2a37d1f8f683ba9e3672ba48f5b81f277b35039d0bdf24c1937accf5203c8",
"vad/.github/workflows/test.yml": "d358f62320a79dd9b92b12efd50edae557841650ea88583f67a26b4e00302e29",
"vad/.gitignore": "9d3c43ecc95137fc4d1c88df4ceaae256fc7ba2d55a06c01e890d4e6b52214cb",
"vad/CITATION.cff": "dd9981387b59cf75853e0f2b7f7f79e8a694f3bf6aaa17dc9bcc72e70356477f",
"vad/CODE_OF_CONDUCT.md": "216247a1f9d0f9bd5daa7ba7f2957c42f3c8ea39a315dbc0a883f62ec8f17666",
"vad/LICENSE": "2e63e9a38b6e8fc0c7bc37ce174caca1862870856c6daf5697cfb785e925520b",
"vad/README.md": "cd0ee56c91b8042e62a714c0c94bc8b74dbea127a483e390f8033bb8ec8cec78",
"vad/datasets/README.md": "603353a37ec3351f0463307f0c5377eefb98547e2463defb889e5f5930a5536a",
"vad/examples/c++/README.md": "4874ad0ec4d21dc2e7d981d523ac98c95792d6ae57773c2da0d24e11f7185811",
"vad/examples/c++/aepyx.wav": "a622cb1cdd8a52db84b0d4bb524fa9a93f9ed387de40530f87c3a57d7493fd49",
"vad/examples/c++/aepyx_8k.wav": "3b36a5347bdad20ff72fb9e2613e4214d25f981c56b51ca17704f087b84fddc6",
"vad/examples/c++/main.cc": "b51075d99f6001449335b7f52f74fa3860d3d5c3e2cecbef9c1e73cdd0d32087",
"vad/examples/c++/silero.cc": "39aed6dce7a1c05000f4305134be07b6ee28e1ffad70ee3c996a37d3d8bc29a5",
"vad/examples/c++/silero.h": "ff37646d0aa859b7c96739bbfb6b4da7c53e945bda571d5fb1a4dbf0d6697687",
"vad/examples/c++/wav.h": "04bd8d3a8b849ad2dc099fcaff5dff0da76592cefd954cc17185331b180a2c45",
"vad/examples/colab_record_example.ipynb": "e9c994372b93e2032fb4e4341e44a6027439d78c44976fd75d3249e18ed486f1",
"vad/examples/cpp/README.md": "617379cfc84ef62d8cacf314314b30a922145eb5b39ec0ee3b5e970d90b69177",
"vad/examples/cpp/silero-vad-onnx.cpp": "dcd7ab46126d7201c495fae2349fb956e81aba00220dc185838df122104612c7",
"vad/examples/cpp/wav.h": "75e73e37f3f3e33d7239e51b529d5165f27bcc6273fb52710402d81c7b11dcae",
"vad/examples/cpp_libtorch/README.md": "11c49c5dace8473818aa3be9c5662abc8dff753dbe724dc4ae6250b83aff5288",
"vad/examples/cpp_libtorch/aepyx.wav": "d6aed597425ea4ce852db919912906e45471acd74e18ed3046360cbc3f06c27b",
"vad/examples/cpp_libtorch/main.cc": "af41235e0a4ec44cb8321d3793993cdc718118439362d7cefb1d046c0296b5b2",
"vad/examples/cpp_libtorch/silero": "f5b2fa15458ca5bf961042b2157f4b81481a6e9819c4b32f886f9251dc31563b",
"vad/examples/cpp_libtorch/silero_torch.cc": "a58aabc000caf6f190c55625d835ca0ae6f09a5dd2cac900b144cb3b174da8e3",
"vad/examples/cpp_libtorch/silero_torch.h": "c4f4d89723e065a4d4df5a7bda22f839eaa9af4b97f50a59817f82b2d69c94e5",
"vad/examples/cpp_libtorch/wav.h": "65a200886095c998eec13900973876572a08a2d0c5f9ea7b00bd35f2973fe6b6",
"vad/examples/cpp_libtorch_deprecated/README.md": "11c49c5dace8473818aa3be9c5662abc8dff753dbe724dc4ae6250b83aff5288",
"vad/examples/cpp_libtorch_deprecated/aepyx.wav": "d6aed597425ea4ce852db919912906e45471acd74e18ed3046360cbc3f06c27b",
"vad/examples/cpp_libtorch_deprecated/main.cc": "af41235e0a4ec44cb8321d3793993cdc718118439362d7cefb1d046c0296b5b2",
"vad/examples/cpp_libtorch_deprecated/silero": "f5b2fa15458ca5bf961042b2157f4b81481a6e9819c4b32f886f9251dc31563b",
"vad/examples/cpp_libtorch_deprecated/silero_torch.cc": "a58aabc000caf6f190c55625d835ca0ae6f09a5dd2cac900b144cb3b174da8e3",
"vad/examples/cpp_libtorch_deprecated/silero_torch.h": "c4f4d89723e065a4d4df5a7bda22f839eaa9af4b97f50a59817f82b2d69c94e5",
"vad/examples/cpp_libtorch_deprecated/wav.h": "65a200886095c998eec13900973876572a08a2d0c5f9ea7b00bd35f2973fe6b6",
"vad/examples/csharp/Program.cs": "863e88b3a1eb496fdedd22820bd8bcdc45369e0c63204b91a1afaa4386d7f9da",
"vad/examples/csharp/SileroSpeechSegment.cs": "5a9917e9c83021404b5a49cba4ef54a50468ae209bf8b9037487a4365db26cfb",
"vad/examples/csharp/SileroVadDetector.cs": "33f46cf85dd8108acb86da0744483ea3d23ec1cfd507eb2e369bfe042fa612ac",
"vad/examples/csharp/SileroVadOnnxModel.cs": "dca90558149d4be15184a80385e886a44dcb9e90ecade9da66ea93fd1c176455",
"vad/examples/csharp/VadDotNet.csproj": "881fd1d1647ea781e50d16c9bf8c0850a10bd8e6195a605a4a5bdfe883a283b1",
"vad/examples/csharp/VadDotNet.sln": "6e4cc97b9828a5b3a715ed6c6fe422690f4d309208f301faacbc8fe863b6d920",
"vad/examples/csharp/resources/put_model_here.txt": "576203b57768b84f12e4f8a137a2e084dbdf0b75fbd77f1a8358ab4305be319d",
"vad/examples/go/README.md": "c561f2f92d64bcf4a52b7e2e2de25266b62fc410fbed23925d8d7b72ac8aaafd",
"vad/examples/go/cmd/main.go": "cee81f9296f5baf491ce45469be361f6226172b3399fa88b9ab11e368959bda4",
"vad/examples/go/go.mod": "fa075afa55942727467ded19b540ddcf75db2a001d5f953e46f8c48a428f2b73",
"vad/examples/go/go.sum": "1d941ecfdb03b7a4f2f51012f928ef9b7c1938f3b5b6b3c840663aab44367a9b",
"vad/examples/haskell/README.md": "ac9065f5aedc0155c59a1f97d4f949cf313b74122567432f83d7c1feab2b5ae6",
"vad/examples/haskell/app/Main.hs": "cf7da6c2e5a7d73242b565e5aa24b637e038b9af6ff33f032565a6d52b95c99b",
"vad/examples/haskell/example.cabal": "3de0377572a072ac9233fef68113d657a8519853119bb14e30d549f61f9cb442",
"vad/examples/haskell/package.yaml": "21e7c7b96cf36203c1fe078b76d210ae7418bb1d4f9258e5b64c3fe12e8256a4",
"vad/examples/haskell/stack.yaml": "305887dc2d15d1178ad0275fcad4d33cbc5a74b6274cf4a551191e161820dc91",
"vad/examples/haskell/stack.yaml.lock": "62f31a1d3f9167e1f3627539dbfb7a46a1983f0d8e194b88904cf4c435dcb5b6",
"vad/examples/java-example/pom.xml": "1aaac050ffee4d97b30dfc70de202ba0bd06da337d80917e75cb6dee9b19eb76",
"vad/examples/java-example/src/main/java/org/example/App.java": "1089deb76157a6b0a35b7f1fd311ba86922bd3a6ead46279b12d96d70b4ac4d5",
"vad/examples/java-example/src/main/java/org/example/SlieroVadDetector.java": "81534ed59133a8118e8ab0dc08c03aaeace0fab0fb200ce92d78b872c13bb2b8",
"vad/examples/java-example/src/main/java/org/example/SlieroVadOnnxModel.java": "aa9159cf2219b018dd566aecd9e533bb811485bd0947750c2f89ead99a5267cf",
"vad/examples/java-wav-file-example/src/main/java/org/example/App.java": "d454f388ca1230c87d2480ad4913b7c91fd44e6f436e40ecf963d0448d2861e4",
"vad/examples/java-wav-file-example/src/main/java/org/example/SileroSpeechSegment.java": "69eecb8a7e033e6b1e971318bd2691da6ad82417b28e3d437d9c804c6b590299",
"vad/examples/java-wav-file-example/src/main/java/org/example/SileroVadDetector.java": "381a2a6b3b768b36e828979803d65ff02e8274506906bfdf9ebf93accaec7e39",
"vad/examples/java-wav-file-example/src/main/java/org/example/SileroVadOnnxModel.java": "0625123e9202542c017c26fe23087934b802e5dba94a3789d5ab5a59495b705d",
"vad/examples/microphone_and_webRTC_integration/README.md": "46374787966a54c80857b03bf9256fbe9cbf6b279c8a183bb3a78caa3552d839",
"vad/examples/microphone_and_webRTC_integration/microphone_and_webRTC_integration.py": "d1628b83eb8a1f84d038499a9c7eda962d6f2684b722bd2167a081fa3666d373",
"vad/examples/onnx_sequence/README.md": "970bae202a4ab5b3a90b47e1e82158238cbc7113709b3c2c1ba91d69c829eff9",
"vad/examples/onnx_sequence/export.py": "5e0889ac5a84d8b0bb0bee178e1febde50397484dc96bf2d93a66eb8eae973c3",
"vad/examples/onnx_sequence/run.py": "b45355bec6451b07043bc352b6f890fab72c203b3708318502f833dec4e80045",
"vad/examples/openvino/README.md": "afb6c97107fca4a028f22ada74ab01c8287b45277fdfbdf2916d2d8f572f9dce",
"vad/examples/openvino/convert.py": "4ed304326aebcffacfbbf9a342a0812953e89acfc76335299af39e5275c8cc6b",
"vad/examples/openvino/verify.py": "f211740338aa558220d194d8cb9dd1ed6c6be502657af5ae201f168647e5d29c",
"vad/examples/parallel_example.ipynb": "34a990d7b4aee8ab09469565034fce015772dcf9ba33c50ce6969254edb87592",
"vad/examples/pyaudio-streaming/README.md": "1ae63cbddfdc54a5a0af525b6dbb13d5dcbc1f36cc247c29feb0e6995f0185d7",
"vad/examples/pyaudio-streaming/pyaudio-streaming-examples.ipynb": "c885e43f025f4fe4c69e54b3956ef40d1290ca9425e33fd4a18374cfc992846c",
"vad/examples/rust-example/.gitignore": "87871cf70e846ad574df943e50f59d6ccfcdb501d6517ec228b714e4994fea09",
"vad/examples/rust-example/Cargo.lock": "a1415ffef47fa0d6254dba496e4b43df7f6b0fd6757e91737de45391b14300df",
"vad/examples/rust-example/Cargo.toml": "85aa11c75bdbd9e67fe868fe29e55f531b46c78c1de068711e7298f4316a5a70",
"vad/examples/rust-example/README.md": "46ecdf442525e4e912c8f349431d7787d3c0cc6d150ac4811cafcdb226eb4188",
"vad/examples/rust-example/src/main.rs": "1d4ff80632fc609ed99030e5af2b9c81d8a26bfdc79cb0af5c9e406c3c141091",
"vad/examples/rust-example/src/silero.rs": "8d1b00124206f96b1b0c18bab6c53c8ae6f90e94e7e93e310c5c5f9edcec5bcd",
"vad/examples/rust-example/src/utils.rs": "296eabc14c137d5575384b8bbfb81c3c754d667b926ff58f902751453832393a",
"vad/examples/rust-example/src/vad_iter.rs": "ae2b8799fcb89b800198d86b82f6b0f7cb70f81cc5645089c234aa18163fc0c0",
"vad/examples/rust-wav-processing-with-wavekat-vad/.gitignore": "5d77fbb6e90fb09e55e21161fd11333b862e409c994ee8593131ad3ae0a97401",
"vad/examples/rust-wav-processing-with-wavekat-vad/Cargo.lock": "1fdafd48875a6bd75ecbbe58ca81083bbbdae78b8e21416fa0e03660f67f661a",
"vad/examples/rust-wav-processing-with-wavekat-vad/Cargo.toml": "f43ce000cb1b7e923fe07eac64ea56b11a9d842bce89b2f3fa86aee11611c8b2",
"vad/examples/rust-wav-processing-with-wavekat-vad/README.md": "0d5ff7e0c34ec1b60c85233f2663a858de55360b691ce570874cad4d4f2731b1",
"vad/examples/rust-wav-processing-with-wavekat-vad/src/main.rs": "13b7cbec9d5d88691e89fcad64b31a085ff5aefeff1c0d584102b607d03a43c2",
"vad/files/silero_logo.jpg": "997ebb29131f24871c8299ffabbf168712f9ffffb0546f89be235a57efce4f96",
"vad/hubconf.py": "2637a3a91d061a6e921853f5de5430f873c292662b46e5fd61edaf648b4ae5bd",
"vad/pyproject.toml": "2aa7fecb20eb9c9feaf22ae31421f904f85d7b939c03d17d12c0113fea49e32f",
"vad/silero-vad.ipynb": "d11a53290f594af3a73ee203555bbc8a0dab8735e93736f708ff3bbd16f6e9a2",
"vad/src/silero_vad/__init__.py": "45fcf7e268eb0ba83ccee737b1a86cc94d7cf7487e2a1c0a31b9b72b899201f1",
"vad/src/silero_vad/data/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"vad/src/silero_vad/data/silero_vad.jit": "e1122837f4154c511485fe0b9c64455f7b929c96fbb8d79fbdb336383ebd3720",
"vad/src/silero_vad/data/silero_vad.onnx": "1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3",
"vad/src/silero_vad/data/silero_vad_16k.safetensors": "c59271c284ae9c8335d795d60e0bfdb71aaaceec578d9bd9ffc1b8153c319ea1",
"vad/src/silero_vad/data/silero_vad_16k_op15.onnx": "7ed98ddbad84ccac4cd0aeb3099049280713df825c610a8ed34543318f1b2c49",
"vad/src/silero_vad/data/silero_vad_16k_sequence.onnx": "9ccdacc4719d8aa7e45a77536bfabec45a03ba1f2fad5e241ab4060b24238a85",
"vad/src/silero_vad/data/silero_vad_half.onnx": "1e0b195ad4806595ef4466f419d16fca7e4afcfc6669b8c0b5f76ea87547c769",
"vad/src/silero_vad/data/silero_vad_op18_ifless.onnx": "7671cd04b004e9076da0d4a7b1a5aec36adf161c39230c1cb94a4fd5db6bbd28",
"vad/src/silero_vad/data/silero_vad_openvino_16k.onnx": "7776b81ad1b0350c15d7f1555943b9232eb53e9ca5d989c6d0cea9ebc8664d87",
"vad/src/silero_vad/model.py": "40762a80d1278605480f75f90c6510c1a4ab71bd230f45c334e4f9c5e402181d",
"vad/src/silero_vad/sequence_vad.py": "c8b6e1194e36a5721a8f1ac6674e07f78c8a892c7585c51c9f9b40068cf34fbd",
"vad/src/silero_vad/tinygrad_model.py": "79afb8aae28bb9d20735df4053bef1191a85b74a0db335a5fc16c302ddda7e86",
"vad/src/silero_vad/utils_vad.py": "7e0f9b3334ee4feb79abcf2251be12458329077bce28c8540878ed9d35e5aa6b",
"vad/tests/conftest.py": "c53caa3c7b0cc071b358d8a3e5a6529502ffcdcd299e47106f54fb453644509c",
"vad/tests/data/test.mp3": "65a63b8ab116e80078cfc700ebec6d496b769c33bde72018ea41d535d4cfea0e",
"vad/tests/data/test.opus": "8c009ea434e0323f453dc311f03d980929406af6c44c34897503f0b01e84265e",
"vad/tests/data/test.wav": "89f17d9c94c4b31eb320f424628bcbc920abaddbee6e2760fd868bfb1d9a2e47",
"vad/tests/test_audio_backends.py": "ec981db4dd93bc816ed3b4c69e0cb4c6079d7ea630b7a8a26bd9de30313dd403",
"vad/tests/test_basic.py": "9211653f21693c77cec9bfc48b7061814bda9de85f0c4e33311a30ace2e33c26",
"vad/tests/test_optional_deps.py": "cfe2bdd068dfc1209666656546883ba246f8095cfd75dd9844e6bd590a329121",
"vad/tests/test_sequence_parity.py": "cecd9ff0904c6ecde4c36012a8c209ecc7d8f2a54cba368805528355ea0406f5",
"vad/tests/test_vad_iterator.py": "e24cca107756fa2caad439de3d933160dc92326485c2c0f13837067e144ef132",
"vad/tuning/README.md": "c727ad309a9da5230b997963a2753096073267bd9f7a4e8c97dd2fdbf89ed96d",
"vad/tuning/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"vad/tuning/config.yml": "06443def6341c8ae6439325a0652dfbb6e01b022d9b31065d84261d0c4f358f0",
"vad/tuning/example_dataframe.feather": "d03db5681596414f284ba53c2da52028c0738ae3584cb0865246ff8ef792ce2f",
"vad/tuning/search_thresholds.py": "4b2670739897fc9ed577f52d594b2761a3e96e241ed3fa32841a951efdf908c0",
"vad/tuning/tune.py": "b4c2bb3724fa3fc1ae3818c3e0938e24707aa4f9104058546a989faf3fd87aef",
"vad/tuning/utils.py": "e1da62037c2171b424e705291fe6eadc3218a3c0514e5773b6ba6d707432f1a6"
},
"schema": 1
}
@@ -0,0 +1,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,713 @@
{
"date": "2026-10-15",
"upstream_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
"expected_candidate_profile": {
"provider": "local_s2s",
"model": "openai/gpt-4.1-mini",
"voice": "Kore",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"evidence_policy_revision": "same-session-evidence-retained-v5",
"development_only": true,
"interruption_policy": "close_until_phase3",
"local_s2s": {
"engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
"patch_revision": "rag-local-s2s-phase2-v3",
"contract_revision": "rag-local-s2s-phase2-v1",
"components": {
"stt": {
"backend": "openai",
"model": "openai/whisper-large-v3",
"language": "fa",
"response_format": "json",
"final_only": true
},
"llm": {
"backend": "chat-completions",
"model": "openai/gpt-4.1-mini",
"max_output_tokens": 256
},
"tts": {
"backend": "openai",
"model": "google/gemini-3.8-flash-lite-tts",
"voice": "Kore",
"response_format": "pcm",
"sample_rate": 24000
},
"request_timeout_seconds": 30.0
},
"effective_config_sha256": "049a34b0d42ddb000d34dd52ab49844e3af958ab96eac4614c8a463236aa72a5"
}
},
"observed_engine_profile": null,
"engine_image": null,
"base_image_digest": "sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce",
"dependency_lock": null,
"vad_bundle": {
"host_root": "D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master",
"combined_nltk_vad_manifest": "docs/evaluation/local-s2s/phase-02-local-assets.json",
"manifest_sha256": "8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8",
"linux_jit_validation": false
},
"engine_built": false,
"engine_live_validated": false,
"browser_demo": false,
"paid_requests": 0,
"files": {
".env.example": "c49816b66f435c246ac7c9de53229324dae4b1ac667e6294f79e368f400247b4",
".gitattributes": "b8726d6a05524d792be8f39d874d031168d72eb546a2258970cab23f9add6fc1",
".gitignore": "0b11c3566199edb6b1888b0d7318fc9a3c542074862f426ddef36280ead8f8d1",
"app/api/v1/live.py": "510ac4b9c5bbe8c90c90ef28981b0a7fec2aa857d178daaad96814eb3bc0d50c",
"app/infrastructure/gemini_live.py": "eaa6e9e1fbe02edd11df00b7ad311fbb04bb9a8af76307c09f0d4cbc33fabe7e",
"app/infrastructure/local_s2s.py": "2847552df0407949007c55ac1bc6a4558fae6b20a2b875af882a55bc2491f218",
"app/infrastructure/realtime.py": "34f423769222c1f76bd33c2109123cad0cc2dca8180c47dd24722eb2512233d0",
"app/infrastructure/voice_provider.py": "f017536fc4e06305f5c9a6ebf1fe891c746dd1f448bb743cbd268889772766f4",
"app/local_s2s_smoke.py": "fc5cf5783bf5af9b8711d1e6beef644ee748ee46d9b0652cea32b153fb85875c",
"app/main.py": "67c9cd5f886199ad7af70e329676ea5b9cc9ab6d069e99d2d722f16aed8f3a3c",
"app/modules/voice/configuration.py": "b3b8be699748c7bef094dc189282370e2146fee9e63385ac66143ec624f44c7e",
"app/modules/voice/local_s2s.py": "44f841b627e211ca41f373016a0c113daaa704f48add79f055266030d9acc78e",
"app/modules/voice/provider.py": "e9a47e0b13c2e9f4f8c0ab140548148a245999c787d2719b56b1c4e391cdf024",
"app/modules/voice/runtime.py": "81bece5d52ef086a9a7caa961643199dfc54e2528a40a5ee20fa2b142fa03b7d",
"app/modules/voice/settings.py": "c022bcc4bd0e77f20f999893ece573b964349fbc49319c03e814a31834102415",
"docker-compose.local-s2s-test.yml": "1b7748d2d4992b869749f5a27d674573637c4ab2f5406af13d2be70e44594de3",
"docs/agent-reference-map.md": "946f020edc9f309272e387819254add99080b36a686a325fef3692e6973153a6",
"docs/evaluation/local-s2s/acceptance-postgres.py": "6b3384950a75e2d18f1ada16fb8452623c195ac467d68ee8feba2a043f8c1eb9",
"docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml": "300af7997e90c18e2fdfc6c21fbc0d4be43fea8b66d3e51a9869779cc012a668",
"docs/evaluation/local-s2s/phase-01.md": "299c6e137d894e7e8177825df317251569ef40d05e2145e5ccee37acf36244a8",
"docs/evaluation/local-s2s/phase-02-acceptance-checklist.md": "769b25e3dd3c85782b9776ec9a097ac43feb1595480e08b41fa55aabada18b7a",
"docs/evaluation/local-s2s/phase-02-browser.override.yml": "faac069f111e3e98022c09bb9ac0ed9b6350394640091f66cc6ef6d2841c7fb2",
"docs/evaluation/local-s2s/phase-02-browser.proxy.json": "0c57f025cfa2b47476a11b0c723800ca76923e65e4fa42f2a6ac9ccc002328f7",
"docs/evaluation/local-s2s/phase-02-local-assets.json": "cdafcecf029073fb08d7028f90cf09e53955056c9d173cf84c804ac37ef12962",
"docs/evaluation/local-s2s/phase-02-remaining-repairs.patch": "325f3abaa7b70a1d1448beae5f4021351de524bb39d8fa79c0398089f9ca9066",
"docs/evaluation/local-s2s/phase-02.md": "de78b6e93f6f3738de63e840f6c9fdf279362bc88e243d92df86dce3966c5cdb",
"docs/evaluation/local-s2s/upstream-pin.json": "73e3d50f7bbdff88893e921d19800c3941ff6d7604aba62b4faf63b13d72326a",
"docs/plans/local-s2s-adapter-plan.md": "e6c1cad582652312409e2c0b91f5279a95b13ae33b351a10ca91e687283a3dcc",
"docs/plans/local-s2s-adapter-progress.md": "1174d13aef2b101b57b6eb55a54a6e1e22429d43b4c3c3e2ce95be16e4498205",
"docs/specifications/RAG-Phase1-API-Catalog.md": "eff254d8dfa270d80e9866623aff550a2157b6331004e8f4b2ba5b610e17dbea",
"docs/specifications/RAG-Phase1-Database-Design.md": "48665ce9bdfbb419c4645cc4fc7ddeca737721a3b5e5a39a6f0cceb9b629422b",
"docs/specifications/RAG-Phase1-Implementation-Guide.md": "f567475b0fa539061c396756f7d2d6f6ef549be2efc06bbc45500aec6e42c448",
"services/local_s2s/Dockerfile": "dec0cc9310321d20fce89397930724770e6dd8053703ecf1d42526df3ae3d508",
"services/local_s2s/Dockerfile.dockerignore": "dc79074c16cca7f80050d4d269dd7b99e04d98a4b156e3a7e8ed2ddd82f51da3",
"services/local_s2s/README.md": "3b8335d70d7ed2b54489176b5db6dd7e5f8a0c1d0c5b557fb24529be0b7301e0",
"services/local_s2s/assets.py": "a16ae47b5fe196883662333cc849d0d4c301a9339b480926a721a436cb60b8cb",
"services/local_s2s/components.py": "b2f153e0ca9c230a62363dce4bdee10ca5da4e7b6367e3c525ca3cceeb623cea",
"services/local_s2s/engine.py": "497d034b3fd974c8d01db3bbc8af0df7295faa770c70d3294307d7af5a485f79",
"services/local_s2s/extension.py": "30f1435241284e2c5233cc6f45c703e10873454c77295f8bc97ee0b76ae83430",
"services/local_s2s/lifecycle.py": "5e59a4194d13fc4399464734403ee6355b9d8558ef0663f5cf0b66a48b3a2225",
"services/local_s2s/pipeline.yaml": "50c3fa906b0096db01dfdc8380cef72d6136eda10c699cb3cee317899ab25947",
"services/local_s2s/prepare_build.py": "11e2bde8ff448f0f909db2a42227f5f33d23c4a3af6f606132e90ea28892627e",
"services/local_s2s/request_policy.py": "0d4d322cf596e2b690699f77a1ab509c82688c9e44795ce42e0bdd5b3e21ba9f",
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
"tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
"tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
"tests/integration/test_local_s2s_phase2.py": "268346f00e5211063898319539a8f41161c5cc437cda8d0f968f26eafcae034b",
"tests/support/local_s2s_pinned.py": "db5bbb39ec364b1d5d67d5865e5ee82ee0fc84dfe60cc0d19555bd2fa8a7f048",
"tests/unit/test_local_s2s_boundary.py": "a7744bfb5fcc21be3f794d9d764f2ca4d91130182127896281005f65ae798345",
"tests/unit/test_local_s2s_engine.py": "fc8c84e8384f09640443a00411d81c6c520db33fbef3f7f8d70ca2ded468b4a9",
"tests/unit/test_local_s2s_phase2.py": "1d1f0199c92cbb47c671a2e19b8fe26bbbafef168bc7ac98f770b75706b4093e",
"tests/unit/test_local_s2s_repairs.py": "c076c2d51542ef4008cc358b0b15b74658f5685afbaa9a4359c82ab4fdf582da"
},
"checks": {
"repair_regressions": {
"passed": 74,
"seconds": 7.68,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
},
"final_combined": {
"passed": 107,
"seconds": 16.67,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
},
"preservation": {
"passed": 242,
"seconds": 33.73,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
},
"git_diff_check": "passed",
"compose_config_quiet": "passed",
"python_source_parse": 9,
"postgres": "executed fresh through guarded disposable runner; local passed, expanded non-green; historical results retained",
"paid_requests": 0,
"acceptance_local_postgres": {
"command": ".venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite local",
"pytest_arguments": [
"tests/integration/test_local_s2s_phase2.py",
"-m",
"postgres",
"--require-postgres",
"-q",
"--tb=short",
"-p",
"no:cacheprovider"
],
"passed": 2,
"failed": 0,
"skipped": 0,
"seconds": 5.18,
"exit_code": 0
},
"acceptance_expanded_postgres": {
"command": ".venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite expanded",
"pytest_arguments": [
"tests/integration/test_local_s2s_phase2.py",
"tests/integration/test_phase2_postgres.py",
"-m",
"postgres",
"--require-postgres",
"-q",
"--tb=short",
"-p",
"no:cacheprovider"
],
"passed": 57,
"failed": 6,
"skipped": 0,
"seconds": 236.5,
"exit_code": 1,
"failure_cases": [
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[ok-gemini]",
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[ok-openai]",
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[no_evidence-gemini]",
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[no_evidence-openai]",
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[error-gemini]",
"test_actual_asgi_tool_dispatch_persistence_and_public_sources[error-openai]"
],
"diagnostic": "RESPONSE_ACK_DEADLINE",
"baseline_comparison": "same cases/diagnostic as previously reproduced immutable HEAD run; comparison not rerun in this checkpoint"
},
"acceptance_compose_configurations": {
"base": "passed",
"browser_override": "passed",
"phase1_plus_browser_overrides": "passed",
"phase1_private_boundary_assertions": "passed",
"launched": false
},
"asset_manifest_validation": {
"passed": true,
"files": 201,
"nltk_actual_load_passed": true,
"linux_engine_validated": false
}
},
"test_container_final_state": "stopped-retained",
"previous_checkpoint": {
"expected_candidate_profile": {
"provider": "local_s2s",
"model": "openai/gpt-4.1-mini",
"voice": "Kore",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"evidence_policy_revision": "same-session-evidence-retained-v5",
"development_only": true,
"interruption_policy": "close_until_phase3",
"local_s2s": {
"engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
"patch_revision": "rag-local-s2s-phase2-v1",
"contract_revision": "rag-local-s2s-phase2-v1",
"components": {
"stt": {
"backend": "openai",
"model": "openai/whisper-large-v3",
"language": "fa",
"response_format": "json",
"final_only": true
},
"llm": {
"backend": "chat-completions",
"model": "openai/gpt-4.1-mini",
"max_output_tokens": 256
},
"tts": {
"backend": "openai",
"model": "google/gemini-3.8-flash-lite-tts",
"voice": "Kore",
"response_format": "pcm",
"sample_rate": 24000
},
"request_timeout_seconds": 30.0
},
"effective_config_sha256": "049a34b0d42ddb000d34dd52ab49844e3af958ab96eac4614c8a463236aa72a5"
}
},
"files": {
"app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
"app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
"app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
"app/modules/voice/local_s2s.py": "dced0769bebb599aaa6af1e7dd8de3f89fa3a847a608d94f9f185f8064e49732",
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
"docker-compose.local-s2s-test.yml": "a3bb148f38b01915721f658bbe3cc6d56245fb6eb426955eb1cf6f11e4b90243",
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
"services/local_s2s/README.md": "99d079cbb0d2aee69254d866565f2b9c4101854823eacf842ae22de0df73a242",
"services/local_s2s/components.py": "d1cc832bb753248879429e93c134dbd4ea8e017a7dae804773ef9fbf12841f28",
"services/local_s2s/engine.py": "4e34793afd6c9fbe63d3542066a8a1388ad47fe49cdb5b589e280bdf464aea41",
"services/local_s2s/extension.py": "ae3834849d3e1534bbed609c3c9291719d3c7d8ba15551a75a2f4c312a4fc14c",
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
"services/local_s2s/prepare_build.py": "03ed65a5dd3da2f5f80a857b99d7e986c6302658ebc1ff1c0ed2e55a13653a02",
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
"tests/unit/test_local_s2s_engine.py": "8a89d6723434c9d5b4682abd01fd59972b151c5889b85466f27fcec32871b6c6",
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf"
},
"checks": {
"final_combined_passed": 107,
"new_postgres_passed": 2,
"expanded_postgres_passed": 57,
"expanded_postgres_failed": 6,
"expanded_failures_reproduced_on_head": 6,
"paid_requests": 0
},
"test_container_final_state": "stopped-retained"
},
"patch_revision": "rag-local-s2s-phase2-v3",
"contract_revision": "rag-local-s2s-phase2-v1",
"acceptance_verdict": "offline_repairs_verified_live_acceptance_pending",
"phase_status": "in_progress",
"repair_checkpoint": {
"upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
"conformance": "hash-checked original pinned methods with isolated SDK/history/ML dependencies; real HTTPX and downstream/upstream TCP loopback transport checks; full SDK/engine unexecuted",
"full_sdk_ml_engine_conformance": false,
"signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
"paid_requests": 0,
"dependency_downloads": 0,
"model_downloads": 0,
"image_builds": 0,
"operational_changes": 0,
"postgres_acceptance": "not run; no disposable TEST_DATABASE_URL verified/used in this checkpoint",
"reservations_rewritten": false,
"required_local_assets": {
"manifest_schema": 1,
"manifest_sha256": "8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8",
"nltk_root": "/assets/nltk",
"vad_root": "/vad/silero-vad",
"manifest_path": "/assets/assets.json",
"provisioned": true,
"provisioning_scope": "existing host resources only; Linux engine validation pending"
},
"remaining_gates": [
"Phase 1 real OpenAI interaction/listening",
"reviewed dependency hash lock and immutable base image digest",
"provisioned fingerprinted NLTK and VAD assets",
"real pinned engine and complete SDK conformance",
"authorized component STT/LLM/TTS audio checks",
"isolated Persian browser greeting/transcripts/normal close"
],
"disconnect_cleanup_window_seconds": 1.0,
"disconnect_test_request_deadline_seconds": 5,
"disconnect_test_scheduling_tolerance_seconds": 0.6,
"half_close_policy": {
"ordinary_eof": "explicit cancellation, not inferred inability to receive",
"receive_only_header": "X-Local-S2S-Half-Close: receive-response",
"declared_fin": "complete bounded response; a subsequent graceful full close is indistinguishable",
"reset": "cancellation"
},
"warmup_constant": {
"name": "WARMUP_MAX_RETRIES",
"value": 6,
"fixture": "tests/fixtures/local_s2s_upstream/base.py.source",
"line": 66,
"extraction": "literal AST from hash-checked pinned source",
"prior_harness_override": 10,
"correction": "prior v2 descriptions incorrectly called the isolated value 10 upstream; historical execution results retained"
},
"identifier_validator": "LocalS2SSettings.local_component_identifier; VoiceSettings.identifier unchanged",
"scoped_diff": "docs/evaluation/local-s2s/phase-02-remaining-repairs.patch"
},
"checkpoint_history": [
{
"patch_revision": "rag-local-s2s-phase2-v2",
"expected_candidate_profile": {
"provider": "local_s2s",
"model": "openai/gpt-4.1-mini",
"voice": "Kore",
"input_sample_rate": 24000,
"output_sample_rate": 24000,
"evidence_policy_revision": "same-session-evidence-retained-v5",
"development_only": true,
"interruption_policy": "close_until_phase3",
"local_s2s": {
"engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
"patch_revision": "rag-local-s2s-phase2-v2",
"contract_revision": "rag-local-s2s-phase2-v1",
"components": {
"stt": {
"backend": "openai",
"model": "openai/whisper-large-v3",
"language": "fa",
"response_format": "json",
"final_only": true
},
"llm": {
"backend": "chat-completions",
"model": "openai/gpt-4.1-mini",
"max_output_tokens": 256
},
"tts": {
"backend": "openai",
"model": "google/gemini-3.8-flash-lite-tts",
"voice": "Kore",
"response_format": "pcm",
"sample_rate": 24000
},
"request_timeout_seconds": 30.0
},
"effective_config_sha256": "049a34b0d42ddb000d34dd52ab49844e3af958ab96eac4614c8a463236aa72a5"
}
},
"files": {
".env.example": "c3b849f91611809200b832017a699d57c14fee3d7694c8227015fac78f85caa0",
"app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
"app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
"app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
"app/modules/voice/local_s2s.py": "65d86f2483ad2b3150aea5983f7690007ff043d1e2bc3c877bdbfa74ad3f36e2",
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
"docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
"docs/agent-reference-map.md": "1deba7eb98f045f49326e27ae6c20586f31989f5856d497a0c82904bc2dc6f92",
"docs/evaluation/local-s2s/phase-02.md": "885ad1c3e7f2f81e74677d9eed29fc4b36898677133b916df84fbafbdc07003e",
"docs/plans/local-s2s-adapter-progress.md": "8b42970f412ca14117daf5b2db7e393e355620fa3358ff9246f4333a4ef88629",
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
"services/local_s2s/README.md": "241d6e9942ee55794f79a5055622585358d6fd3a8906eb260fae6048f5a7f3f4",
"services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
"services/local_s2s/components.py": "caa60d0001e8c637c85aae2deb387291ca469e244665f64219cfaf01e6442290",
"services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
"services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
"services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
"services/local_s2s/prepare_build.py": "a2718307a85128c053aff82612c54ab2f6f170f921e05e9aca42b3cf18b9b4b3",
"services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
"tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
"tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
"tests/support/local_s2s_pinned.py": "25003276c7c6b557bb9861147702a81ab446219e527a4951897785837c1a09bb",
"tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
"tests/unit/test_local_s2s_repairs.py": "a57a8a09a3f213cead8437e0835fae41f5cac349c0c4f60e8871512ac4e8186d"
},
"checks": {
"repair_regressions": {
"passed": 31,
"seconds": 6.82,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
},
"final_combined": {
"passed": 107,
"seconds": 18.66,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
},
"preservation": {
"passed": 242,
"seconds": 34.11,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
},
"git_diff_check": "passed",
"compose_config_quiet": "passed",
"python_source_parse": 9,
"postgres": "not run in repair checkpoint; prior results retained under previous_checkpoint",
"paid_requests": 0
},
"repair_checkpoint": {
"upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
"conformance": "hash-checked original upstream setup/process/request/warmup/stop methods with isolated SDK I/O and ML/history stand-ins; actual HTTPX payload and loopback transport assertions",
"full_sdk_ml_engine_conformance": false,
"signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
"paid_requests": 0,
"dependency_downloads": 0,
"model_downloads": 0,
"image_builds": 0,
"operational_changes": 0,
"postgres_acceptance": "not run; no disposable TEST_DATABASE_URL verified/used in this checkpoint",
"reservations_rewritten": false,
"required_local_assets": {
"manifest_schema": 1,
"manifest_sha256": null,
"nltk_root": "/assets/nltk",
"vad_root": "/vad/silero-vad",
"manifest_path": "/assets/assets.json",
"provisioned": false
},
"remaining_gates": [
"Phase 1 real OpenAI interaction/listening",
"reviewed dependency hash lock and immutable base image digest",
"provisioned fingerprinted NLTK and VAD assets",
"real pinned engine and complete SDK conformance",
"authorized component STT/LLM/TTS audio checks",
"isolated Persian browser greeting/transcripts/normal close"
]
}
},
{
"label": "v3 reviewed offline checkpoint before acceptance preparation",
"patch_revision": "rag-local-s2s-phase2-v3",
"files": {
".env.example": "c3b849f91611809200b832017a699d57c14fee3d7694c8227015fac78f85caa0",
"app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
"app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
"app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
"app/modules/voice/local_s2s.py": "10b27361116ef2284ac1a2fff9e1df29bec8017278b1139fe4c34e9f26c67a34",
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
"docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
"docs/agent-reference-map.md": "1deba7eb98f045f49326e27ae6c20586f31989f5856d497a0c82904bc2dc6f92",
"docs/evaluation/local-s2s/phase-02.md": "12f0d26dcf347586e8c610eb27f15a93efc3088bd429c128fb5ba134ee71fb70",
"docs/plans/local-s2s-adapter-progress.md": "d99a465c0bc3f16d0a2a614412ed2df131d1d50d1270a0bd6139b1ce4d9d5e9d",
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
"services/local_s2s/README.md": "d7a411f7dfd8410ceb58b229dcf9603f031dc83acfa78bf4ec0d16404b81e10e",
"services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
"services/local_s2s/components.py": "fe6f5bd4121b1c68bc3d4747fde82c540cf37d3f459d4a3f6aed0d859124e317",
"services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
"services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
"services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
"services/local_s2s/prepare_build.py": "89885abcd198a9efdedad403b9e34cc88b81935586c17e6221406204b7313b4e",
"services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
"tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
"tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
"tests/support/local_s2s_pinned.py": "9b82e843f1598eae104c04e27e700bb1b10c391d49f194cbf7de3eb1d6ab286e",
"tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
"tests/unit/test_local_s2s_repairs.py": "9cd2298ca3d19cdb34ab3548017ecda8efb02c5b1ed5bddb0b5c727f6985a47e"
},
"checks": {
"repair_regressions": {
"passed": 74,
"seconds": 7.68,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
},
"final_combined": {
"passed": 107,
"seconds": 16.67,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
},
"preservation": {
"passed": 242,
"seconds": 33.73,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
},
"git_diff_check": "passed",
"compose_config_quiet": "passed",
"python_source_parse": 9,
"postgres": "not run in repair checkpoint; prior results retained under previous_checkpoint",
"paid_requests": 0
},
"repair_checkpoint": {
"upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
"conformance": "hash-checked original pinned methods with isolated SDK/history/ML dependencies; real HTTPX and downstream/upstream TCP loopback transport checks; full SDK/engine unexecuted",
"full_sdk_ml_engine_conformance": false,
"signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
"paid_requests": 0,
"dependency_downloads": 0,
"model_downloads": 0,
"image_builds": 0,
"operational_changes": 0,
"postgres_acceptance": "not run; no disposable TEST_DATABASE_URL verified/used in this checkpoint",
"reservations_rewritten": false,
"required_local_assets": {
"manifest_schema": 1,
"manifest_sha256": null,
"nltk_root": "/assets/nltk",
"vad_root": "/vad/silero-vad",
"manifest_path": "/assets/assets.json",
"provisioned": false
},
"remaining_gates": [
"Phase 1 real OpenAI interaction/listening",
"reviewed dependency hash lock and immutable base image digest",
"provisioned fingerprinted NLTK and VAD assets",
"real pinned engine and complete SDK conformance",
"authorized component STT/LLM/TTS audio checks",
"isolated Persian browser greeting/transcripts/normal close"
],
"disconnect_cleanup_window_seconds": 1.0,
"disconnect_test_request_deadline_seconds": 5,
"disconnect_test_scheduling_tolerance_seconds": 0.6,
"half_close_policy": {
"ordinary_eof": "explicit cancellation, not inferred inability to receive",
"receive_only_header": "X-Local-S2S-Half-Close: receive-response",
"declared_fin": "complete bounded response; a subsequent graceful full close is indistinguishable",
"reset": "cancellation"
},
"warmup_constant": {
"name": "WARMUP_MAX_RETRIES",
"value": 6,
"fixture": "tests/fixtures/local_s2s_upstream/base.py.source",
"line": 66,
"extraction": "literal AST from hash-checked pinned source",
"prior_harness_override": 10,
"correction": "prior v2 descriptions incorrectly called the isolated value 10 upstream; historical execution results retained"
},
"identifier_validator": "LocalS2SSettings.local_component_identifier; VoiceSettings.identifier unchanged",
"scoped_diff": "docs/evaluation/local-s2s/phase-02-remaining-repairs.patch"
}
},
{
"label": "acceptance preparation execution-byte fingerprints before Git packaging",
"files": {
".env.example": "c3b849f91611809200b832017a699d57c14fee3d7694c8227015fac78f85caa0",
"app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
"app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
"app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
"app/modules/voice/local_s2s.py": "10b27361116ef2284ac1a2fff9e1df29bec8017278b1139fe4c34e9f26c67a34",
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
"docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
"docs/agent-reference-map.md": "84c2bc8f977614cd3a1f582902f3a5c6ee148b5c8a98835f9ff8a2bca706c64f",
"docs/evaluation/local-s2s/acceptance-postgres.py": "cb58c6a7eba04588235d4227b76e4bf43e3ecf6a48c33258a5b035d4c9376957",
"docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml": "bb689597ac719b98ca2bd2510c9e42a673bf3963c2c655a4a77a1ea913d7468b",
"docs/evaluation/local-s2s/phase-01.md": "f1599ba3a8dd4ac10546d65b23bdb5e7bd282929dfeffbfc106d28b307d633ec",
"docs/evaluation/local-s2s/phase-02-acceptance-checklist.md": "cff45f4c3a5992ab4f1ea426d8c30c75eacee5e770cc4021820ab4af47d30d7b",
"docs/evaluation/local-s2s/phase-02-browser.override.yml": "c03dfacde7b1fddc4945681d067bb33f79017df8876038c7ce36c48c145ed6a7",
"docs/evaluation/local-s2s/phase-02-browser.proxy.json": "6ede500f81c5402fd7bfa1f97e8156130205b2ad85c642447af8bc894d4e0dce",
"docs/evaluation/local-s2s/phase-02-local-assets.json": "8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8",
"docs/evaluation/local-s2s/phase-02-remaining-repairs.patch": "325f3abaa7b70a1d1448beae5f4021351de524bb39d8fa79c0398089f9ca9066",
"docs/evaluation/local-s2s/phase-02.md": "18cc1b4281ef2f5d70733a3b3525d6a8379f7449e818fbdfb94fffbf3397d0b8",
"docs/plans/local-s2s-adapter-progress.md": "66b9ba930091ca8f8f50466c4d6eb9e0ad5140119e9b0f000646199d615499a8",
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
"services/local_s2s/README.md": "3bec6dd97b5cda2b70b97946a8ab077598bfe37f74360447820f1d973a45f389",
"services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
"services/local_s2s/components.py": "fe6f5bd4121b1c68bc3d4747fde82c540cf37d3f459d4a3f6aed0d859124e317",
"services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
"services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
"services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
"services/local_s2s/prepare_build.py": "89885abcd198a9efdedad403b9e34cc88b81935586c17e6221406204b7313b4e",
"services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
"tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
"tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
"tests/support/local_s2s_pinned.py": "9b82e843f1598eae104c04e27e700bb1b10c391d49f194cbf7de3eb1d6ab286e",
"tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
"tests/unit/test_local_s2s_repairs.py": "9cd2298ca3d19cdb34ab3548017ecda8efb02c5b1ed5bddb0b5c727f6985a47e"
}
}
],
"base_image_reference": "python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce",
"base_image_metadata": {
"os": "linux",
"architecture": "amd64",
"cached": true,
"candidate_built": false
},
"acceptance_preparation": {
"date": "2026-10-15",
"runtime_code_changed": false,
"reviewed_baseline": {
"repair": 74,
"combined": 107,
"preservation": 242,
"rerun": false,
"reason": "no material runtime changes; reviewed fingerprints verified unchanged"
},
"checklist": "docs/evaluation/local-s2s/phase-02-acceptance-checklist.md",
"authorization": {
"offline_preparation_and_isolated_database": "current user request",
"source_or_dependency_downloads": false,
"model_downloads": false,
"image_builds": false,
"paid_openai": false,
"paid_openrouter": false,
"consented_speech_supplied": false,
"prior_proposal_was_approved": false
},
"credentials_presence_only": {
"server_openai_configured": true,
"host_process_or_root_env_openrouter_configured": false,
"values_printed": false
},
"source": {
"required_engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
"sibling_head": "30af00916da85efb053b539a040fd71cf392e7e2",
"sibling_dirty": true,
"pin_object_present": false,
"clean_pinned_checkout_prepared": false
},
"assets": {
"manifest": "docs/evaluation/local-s2s/phase-02-local-assets.json",
"manifest_sha256": "8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8",
"file_count": 201,
"nltk_host_root": "C:/Users/A.mazaheri/AppData/Roaming/nltk_data",
"nltk_version": "3.10.3",
"actual_sentence_pos_validation": "passed with download entry points blocked in existing Windows sibling virtualenv",
"linux_engine_validation": false,
"source_assets_changed": false
},
"phase1": {
"accepted": false,
"changed_source_live_observation": null,
"listening": null,
"prepared_override": "docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml",
"configuration_parse": "passed",
"isolation_assertions": "passed",
"candidate_launched": false
},
"frontend": {
"checkout": "D:/raymand/projects/faq_chatbot_frontend",
"head": "815191588c59fc43434cc2454cab3a8b2f8c1648",
"preexisting_package_json_change_preserved": true,
"origin": "http://127.0.0.2:4201",
"candidate_proxy": "docs/evaluation/local-s2s/phase-02-browser.proxy.json",
"launched": false,
"source_changed": false
},
"complete_engine_sdk_runner": "not yet executable; requires full pinned source and locked Linux environment; AST fixtures do not meet this gate",
"actual_posix_termination": false,
"paid_requests": 0,
"downloads": 0,
"image_builds": 0,
"operational_writes": 0,
"postgres": {
"container_id": "e5da8c342ed59fc48a49856bfd76010feda45e4a221f640d34aa330a5cd8a7da",
"image": "sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a",
"host": "127.0.0.1",
"port": 55439,
"database": "rag_local_s2s_test",
"user": "local_s2s_test",
"volume": "9f19da047744737e9bc010ba69c2f22e347f898939d1d42f7bbbb97c4591a3b6",
"identity_and_no_operational_volume_overlap_verified": true,
"server_identity_verified": true,
"require_postgres": true,
"final_state": "exited",
"runner": "docs/evaluation/local-s2s/acceptance-postgres.py"
},
"remaining_gates": [
"bounded Phase 1 OpenAI consent and changed-source human listening",
"clean complete pinned source transfer/offline supply",
"reviewed Linux CPU dependency hash lock and explicit build/download authorization",
"Linux asset validation and complete pinned engine/SDK controlled-I/O runner",
"actual POSIX SIGINT/SIGTERM in-flight observations",
"OpenRouter key, bounded paid authorization and consented speech fixture",
"real component format/rate/audio observations",
"isolated Persian browser greeting/answer/user-assistant transcripts/normal close",
"expanded database suite remains non-green with documented baseline failures"
]
},
"files_hash_basis": "SHA-256 of staged Git blob bytes at commit packaging; execution working-tree byte fingerprints are preserved in checkpoint_history. This avoids platform newline ambiguity and excludes unrelated working-tree hunks."
}
@@ -0,0 +1,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,863 @@
--- a/services/local_s2s/components.py
+++ b/services/local_s2s/components.py
@@ -3,8 +3,11 @@
from collections import Counter
import socket
from threading import Event, Thread
-import time
import httpx
+
+# One shared wall-clock window for cancellation, transport closure and slot release.
+CLEANUP_WINDOW_SECONDS = 1.0
+HALF_CLOSE_HEADER = 'x-local-s2s-half-close'
LIMITS = {'/v1/audio/transcriptions': (1100000, 65536),
'/v1/chat/completions': (1048576, 1048576),
@@ -79,8 +82,73 @@
async def _error(self, writer, status):
await self._write(writer, f'HTTP/1.1 {status} Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'.encode())
+ async def _watch_downstream(self, reader, writer, receive_only):
+ # FIN cannot distinguish full close from SHUT_WR. By contract it cancels
+ # ordinary requests; explicit receive-only clients may still read a reply.
+ try:
+ extra = await reader.read(1)
+ if not extra and receive_only:
+ await writer.wait_closed() # still observe a reset/transport loss
+ except (OSError, ValueError):
+ pass
+
+ async def _forward(self, client, writer, path, fields, body, response):
+ request = client.build_request('POST', 'https://openrouter.ai/api' + path,
+ headers={'Authorization': 'Bearer ' + self.key,
+ 'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'},
+ content=bytes(body))
+ # The owner closes the response independently, even if cancellation or a
+ # stalled stream prevents this operation from reaching normal completion.
+ result = await client.send(request, stream=True)
+ response.append(result)
+ if result.status_code != 200:
+ await self._error(writer, 502)
+ return
+ media = result.headers.get('content-type', '').split(';')[0]
+ expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream')
+ if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity':
+ await self._error(writer, 502)
+ return
+ await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media +
+ '\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii'))
+ total = 0
+ # No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
+ async for raw in result.aiter_bytes():
+ total += len(raw)
+ if total > LIMITS[path][1]:
+ raise ValueError('Response capacity')
+ for offset in range(0, len(raw), 8192):
+ part = raw[offset:offset + 8192]
+ await self._write(writer, f'{len(part):x}\r\n'.encode() + part + b'\r\n')
+ if not total:
+ raise ValueError('Empty component response')
+ await self._write(writer, b'0\r\n\r\n')
+
+ async def _close_owned(self, writer, tasks, client, response):
+ writer.close()
+ for task in tasks:
+ task.cancel()
+ # Close all transports independently; one stalled close must not defer
+ # another. asyncio.wait bounds the entire cleanup, including task joins.
+ closing = [asyncio.create_task(writer.wait_closed())]
+ if client is not None:
+ closing.append(asyncio.create_task(client.aclose()))
+ closing.extend(asyncio.create_task(result.aclose()) for result in response)
+ done, pending = await asyncio.wait(set(tasks) | set(closing), timeout=CLEANUP_WINDOW_SECONDS)
+ for task in done:
+ if not task.cancelled():
+ error = task.exception()
+ if task in closing and error is not None:
+ self.counts['close_errors'] += 1
+ if pending:
+ self.counts['close_errors'] += len(pending)
+ writer.transport.abort()
+ for task in pending:
+ task.cancel()
+ task.add_done_callback(lambda t: None if t.cancelled() else t.exception())
+
async def _serve(self, reader, writer, deadline):
- client = None
+ client, tasks, response = None, [], []
try:
async with asyncio.timeout_at(deadline):
# Header acquisition has its own short bound, including partial headers.
@@ -97,7 +165,7 @@
if method != 'POST' or path not in LIMITS or version not in ('HTTP/1.0', 'HTTP/1.1'):
await self._error(writer, 403)
return
- request_limit, response_limit = LIMITS[path]
+ request_limit, _ = LIMITS[path]
size = int(fields.get('content-length', '-1'))
if 'transfer-encoding' in fields or not 0 < size <= request_limit:
await self._error(writer, 413)
@@ -111,34 +179,21 @@
if fields.get('authorization') != 'Bearer local-components':
await self._error(writer, 403)
return
+ half_close = fields.get(HALF_CLOSE_HEADER)
+ if half_close not in (None, 'receive-response'):
+ await self._error(writer, 400)
+ return
self.counts[path] += 1 # one admitted provider attempt, including failed probes
client = httpx.AsyncClient(transport=self.transport, timeout=httpx.Timeout(self.inactivity, connect=self.inactivity),
follow_redirects=False, trust_env=False)
- async with client.stream('POST', 'https://openrouter.ai/api' + path,
- headers={'Authorization': 'Bearer ' + self.key,
- 'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'}, content=bytes(body)) as result:
- if result.status_code != 200:
- await self._error(writer, 502)
- return
- media = result.headers.get('content-type', '').split(';')[0]
- expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream')
- if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity':
- await self._error(writer, 502)
- return
- await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media +
- '\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii'))
- total = 0
- # No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
- async for raw in result.aiter_bytes():
- total += len(raw)
- if total > response_limit:
- raise ValueError('Response capacity')
- for offset in range(0, len(raw), 8192):
- part = raw[offset:offset + 8192]
- await self._write(writer, f'{len(part):x}\r\n'.encode() + part + b'\r\n')
- if not total:
- raise ValueError('Empty component response')
- await self._write(writer, b'0\r\n\r\n')
+ forwarding = asyncio.create_task(self._forward(client, writer, path, fields, body, response))
+ watching = asyncio.create_task(self._watch_downstream(reader, writer, half_close == 'receive-response'))
+ tasks.extend((forwarding, watching))
+ done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
+ if forwarding in done:
+ forwarding.result()
+ else:
+ self.counts['disconnected'] += 1
except TimeoutError:
self.counts['expired'] += 1
except asyncio.CancelledError:
@@ -148,17 +203,8 @@
asyncio.LimitOverrunError, httpx.HTTPError):
self.counts['failures'] += 1
finally:
- # Independent transport closure: failure never writes a successful final chunk.
- writer.close()
- if client is not None:
- try:
- await asyncio.wait_for(client.aclose(), .5)
- except (Exception, asyncio.CancelledError):
- self.counts['close_errors'] += 1
- try:
- await asyncio.wait_for(writer.wait_closed(), .5)
- except (Exception, asyncio.CancelledError):
- self.counts['close_errors'] += 1
+ # No successful terminal chunk is fabricated on any failure path.
+ await self._close_owned(writer, tasks, client, response)
def shutdown(self):
if self.loop is not None and self.loop.is_running():
--- a/app/modules/voice/local_s2s.py
+++ b/app/modules/voice/local_s2s.py
@@ -7,7 +7,7 @@
UPSTREAM_REVISION = '619e3fe4f71d1c6f35c15870d588a3638de34722'
CONTRACT_REVISION = 'rag-local-s2s-phase2-v1'
-PATCH_REVISION = 'rag-local-s2s-phase2-v2'
+PATCH_REVISION = 'rag-local-s2s-phase2-v3'
class LocalS2SSettings(BaseModel):
@@ -38,7 +38,7 @@
@field_validator('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
@classmethod
- def identifier(cls, value):
+ def local_component_identifier(cls, value):
if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value):
raise ValueError('Invalid local component identifier')
return value
--- a/services/local_s2s/prepare_build.py
+++ b/services/local_s2s/prepare_build.py
@@ -47,7 +47,7 @@
(target / 'requirements.in').write_text('\n'.join(sorted(set(dependencies))) + '\n', encoding='utf-8')
(target / 'build-manifest.json').write_text(json.dumps(dict(upstream=PIN, base_image=args.base_image,
upstream_pyproject_sha256=hashlib.sha256((source / 'pyproject.toml').read_bytes()).hexdigest(),
- patch_revision='rag-local-s2s-phase2-v2', built=False), indent=2) + '\n', encoding='utf-8')
+ patch_revision='rag-local-s2s-phase2-v3', built=False), indent=2) + '\n', encoding='utf-8')
print('Prepared source and dependency inputs. Resolve a Linux hash lock before building; no downloads performed.')
--- a/tests/support/local_s2s_pinned.py
+++ b/tests/support/local_s2s_pinned.py
@@ -26,3 +26,10 @@
module = ast.Module(body=[ast.ImportFrom(module='__future__', names=[ast.alias(name='annotations')], level=0)] + definitions, type_ignores=[])
exec(compile(ast.fix_missing_locations(module), str(ROOT / name), 'exec'), namespace)
return namespace
+
+
+def constant(name, identifier):
+ """Read a literal from the hash-checked source, never a fixture override."""
+ node = next(n for n in tree(name).body if isinstance(n, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == identifier for t in n.targets))
+ return ast.literal_eval(node.value)
--- a/tests/unit/test_local_s2s_repairs.py
+++ b/tests/unit/test_local_s2s_repairs.py
@@ -7,6 +7,7 @@
from pathlib import Path
import signal
import socket
+import socketserver
from threading import Event, Lock, Thread, Timer, current_thread, BoundedSemaphore
import time
from types import SimpleNamespace
@@ -14,10 +15,10 @@
import httpx
import pytest
from services.local_s2s.request_policy import LimitedChatClient, install_client_policy
-from services.local_s2s.components import ComponentServer
+from services.local_s2s.components import ComponentServer, CLEANUP_WINDOW_SECONDS
from services.local_s2s.assets import REQUIRED_NLTK, REQUIRED_VAD, AssetError, validate_assets, configure_nltk, patch_pipeline_source
from services.local_s2s.lifecycle import cleanup, run_owned
-from tests.support.local_s2s_pinned import functions, tree, ROOT
+from tests.support.local_s2s_pinned import functions, tree, constant, ROOT
from tests.unit.test_local_s2s_phase2 import local_config
@@ -46,7 +47,7 @@
def upstream_handler(client):
- ns = dict(time=time, logger=logging.getLogger('pinned-fixture'), WARMUP_MAX_RETRIES=10,
+ ns = dict(time=time, logger=logging.getLogger('pinned-fixture'), WARMUP_MAX_RETRIES=constant('base.py.source', 'WARMUP_MAX_RETRIES'),
_build_chat_optional_kwargs=lambda *_: {})
functions('chat.py.source', [(None, '_request_chat_completions'),
('ChatCompletionsApiModelHandler', '_request'), ('ChatCompletionsApiModelHandler', 'warmup'),
@@ -155,8 +156,8 @@
@contextmanager
-def gateway(handler=None, *, timeout=.2, inactivity=.1):
- server = ComponentServer('fixture-key', port=0, transport=httpx.MockTransport(handler or (lambda r: httpx.Response(503))),
+def gateway(handler=None, *, timeout=.2, inactivity=.1, transport=None):
+ server = ComponentServer('fixture-key', port=0, transport=transport or httpx.MockTransport(handler or (lambda r: httpx.Response(503))),
timeout=timeout, inactivity=inactivity)
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
@@ -421,3 +422,169 @@
monkeypatch.setattr(engine, 'build_runtime', lambda *a: calls.append('provider'))
assert engine.main() == 1 and calls == []
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
+
+
+@contextmanager
+def loopback_upstream(*, headers=False, hang_close=False):
+ """Real local TCP upstream: cancellation must close its actual HTTP socket."""
+ entered, closed, transport_closed = Event(), Event(), Event()
+ class Handler(socketserver.BaseRequestHandler):
+ def handle(self):
+ self.request.settimeout(6)
+ try:
+ data = b''
+ while b'\r\n\r\n' not in data:
+ data += self.request.recv(4096)
+ head, body = data.split(b'\r\n\r\n', 1)
+ size = int(next(line.split(b':', 1)[1] for line in head.split(b'\r\n') if line.lower().startswith(b'content-length:')))
+ while len(body) < size:
+ body += self.request.recv(size - len(body))
+ if headers:
+ self.request.sendall(b'HTTP/1.1 200 OK\r\nContent-Type: audio/pcm\r\nTransfer-Encoding: chunked\r\n\r\n')
+ entered.set()
+ # No data is produced. Only owned cancellation closes this socket.
+ assert self.request.recv(1) == b''
+ except ConnectionResetError:
+ pass
+ finally:
+ closed.set()
+ class Server(socketserver.ThreadingTCPServer):
+ daemon_threads = True
+ remote = Server(('127.0.0.1', 0), Handler)
+ thread = Thread(target=remote.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
+ thread.start()
+ class Transport(httpx.AsyncHTTPTransport):
+ async def handle_async_request(self, request):
+ request.url = httpx.URL(f'http://127.0.0.1:{remote.server_address[1]}' + request.url.path)
+ return await super().handle_async_request(request)
+ async def aclose(self):
+ await super().aclose()
+ transport_closed.set()
+ if hang_close:
+ await asyncio.Event().wait()
+ try:
+ yield Transport(retries=0), entered, closed, transport_closed
+ finally:
+ remote.shutdown(); remote.server_close(); thread.join(1)
+
+
+def speech_request(extra=b''):
+ return (b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 2\r\n'
+ b'Authorization: Bearer local-components\r\n' + extra + b'\r\n{}')
+
+
+@pytest.mark.parametrize('headers', [False, True], ids=['before-upstream-headers', 'stalled-after-headers'])
+def test_disconnect_cancels_silent_real_upstream_and_releases_slot(headers):
+ with loopback_upstream(headers=headers) as (transport, entered, closed, transport_closed):
+ with gateway(transport=transport, timeout=5, inactivity=4) as server:
+ peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
+ try:
+ peer.sendall(speech_request())
+ assert entered.wait(1)
+ if headers:
+ received = b''
+ while b'\r\n\r\n' not in received:
+ received += peer.recv(4096)
+ assert received.startswith(b'HTTP/1.1 200')
+ assert not received.endswith(b'0\r\n\r\n')
+ began = time.monotonic()
+ finally:
+ peer.close()
+ assert closed.wait(CLEANUP_WINDOW_SECONDS + .4)
+ assert transport_closed.wait(.4)
+ wait_released(server)
+ assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
+ assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
+ assert server.counts['accepted'] == server.counts['released'] == 1
+
+
+@pytest.mark.parametrize('half_close', [False, True], ids=['normal', 'declared-receive-only-half-close'])
+def test_success_and_declared_half_close_receive_complete_response(half_close):
+ entered = Event()
+ async def remote(request):
+ entered.set()
+ await asyncio.sleep(.08) # receive-side EOF precedes upstream headers
+ return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=b'xx')
+ with gateway(remote, timeout=2, inactivity=1) as server:
+ with socket.create_connection(('127.0.0.1', server.server_port), timeout=1) as peer:
+ peer.sendall(speech_request(b'X-Local-S2S-Half-Close: receive-response\r\n' if half_close else b''))
+ if half_close:
+ peer.shutdown(socket.SHUT_WR)
+ received = b''
+ while part := peer.recv(4096):
+ received += part
+ assert entered.is_set()
+ assert received.startswith(b'HTTP/1.1 200')
+ assert received.endswith(b'2\r\nxx\r\n0\r\n\r\n')
+ wait_released(server)
+ assert server.counts['disconnected'] == server.counts['expired'] == 0
+
+
+def test_undeclared_half_close_is_explicit_cancellation_even_if_peer_can_receive():
+ with loopback_upstream() as (transport, entered, closed, transport_closed):
+ with gateway(transport=transport, timeout=5, inactivity=4) as server:
+ with socket.create_connection(('127.0.0.1', server.server_port), timeout=2) as peer:
+ peer.sendall(speech_request())
+ assert entered.wait(1)
+ peer.shutdown(socket.SHUT_WR)
+ assert peer.recv(4096) == b'' # policy cancellation, not inferred inability to receive
+ assert closed.wait(1) and transport_closed.wait(1)
+ wait_released(server)
+ assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
+
+
+def test_disconnect_cleanup_has_shared_bound_even_if_transport_close_stalls():
+ with loopback_upstream(hang_close=True) as (transport, entered, closed, transport_closed):
+ with gateway(transport=transport, timeout=5, inactivity=4) as server:
+ peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
+ peer.sendall(speech_request())
+ assert entered.wait(1)
+ began = time.monotonic()
+ peer.close()
+ assert closed.wait(1) and transport_closed.wait(1)
+ wait_released(server)
+ assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
+ assert server.counts['close_errors'] >= 1
+
+
+LOCAL_IDENTIFIERS = ('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
+
+
+@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
+@pytest.mark.parametrize('value', ['bad id', 'bad\tvalue', 'bad\nvalue', 'bad\x00value', 'bad\x7fvalue', 'bad\u00e9value'])
+def test_voice_settings_inherits_local_identifier_validation(field, value):
+ from pydantic import ValidationError
+ with pytest.raises(ValidationError, match='Invalid local component identifier'):
+ local_config(**{field: value}) # constructs the real VoiceSettings, not the base class
+
+
+@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
+def test_voice_settings_preserves_valid_local_identifiers(field):
+ value = 'vendor/Valid-Model_1.2'
+ assert getattr(local_config(**{field: value}), field) == value
+
+
+@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
+def test_invalid_local_identifiers_fail_before_assets_gateway_or_provider(monkeypatch, field, capsys):
+ from services.local_s2s import engine, assets, lifecycle
+ import sys
+ monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
+ monkeypatch.setenv('LOCAL_S2S_ALLOW_PAID_STARTUP', 'true')
+ monkeypatch.setenv(field.upper(), 'bad id')
+ calls = []
+ monkeypatch.setattr(assets, 'validate_assets', lambda *a: calls.append('assets'))
+ monkeypatch.setattr(lifecycle, 'run_owned', lambda *a: calls.append('provider'))
+ assert engine.main() == 1 and calls == []
+ assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
+
+
+def test_warmup_retry_constant_is_read_from_hash_checked_upstream_source():
+ assert constant('base.py.source', 'WARMUP_MAX_RETRIES') == 6
+
+
+@pytest.mark.parametrize('field', ['gemini_model', 'gemini_voice', 'openai_realtime_model', 'openai_realtime_voice'])
+def test_existing_provider_identifier_validators_remain_active(field):
+ from pydantic import ValidationError
+ with pytest.raises(ValidationError, match='Invalid voice profile identifier'):
+ local_config(**{field: 'bad id'})
+ assert getattr(local_config(**{field: 'Valid-1.2'}), field) == 'Valid-1.2'
--- a/services/local_s2s/README.md
+++ b/services/local_s2s/README.md
@@ -134,7 +134,8 @@
The request client policy is installed **before handler construction**. It puts
`max_tokens=LOCAL_S2S_MAX_OUTPUT_TOKENS` on every Chat Completions request, including
normal STT-derived text turns and the constructor's warmup, and forces zero retries
-even when pinned warmup asks `with_options(max_retries=10)`. The configured request
+even when pinned warmup asks `with_options(max_retries=6)` (see the provenance
+correction below; the earlier isolated harness supplied 10). The configured request
deadline also enters the actual base setup before warmup; attestation reads the
active client policy, not `gen_kwargs` (unused by that upstream text path).
@@ -202,3 +203,64 @@
Windows signal tests dispatch the installed handlers; they do not claim OS-level
POSIX signal delivery. Real engine, component audio and isolated Persian browser
greeting/transcripts/normal close evidence are still required for live acceptance.
+
+
+## Phase 2 remaining repairs: extension v3
+
+Current behavior is `rag-local-s2s-phase2-v3`, with the v1 private contract shape.
+Fresh profiles and prepared build manifests use v3; v1/v2 reservations remain
+frozen and fail revision mismatch instead of being rewritten. Preserve earlier
+build inputs and prepare a fresh workspace for v3. The five v2 repairs remain.
+No browser events, PCM24k, retrieval authority or interruption capability changed.
+
+After the complete request body, an owned downstream watcher runs concurrently
+with upstream header acquisition and streaming. It does not need response data
+or a failed write to notice closure. Ordinary downstream EOF/reset cancels the
+upstream operation. Response/client closure and task joining share a **one-second
+cleanup window**, followed by slot release; stalled close operations are cancelled
+and the downstream transport is aborted when that window expires. Existing total
+and inactivity limits remain. Failed partial responses never gain a successful
+terminal HTTP chunk. Cancellation does not prove remote inference/billing stopped.
+
+TCP FIN alone cannot reveal whether a peer fully closed or only called SHUT_WR.
+The private component gateway therefore defines the following explicit policy:
+
+- Ordinary clients keep their send side open until completion. EOF is cancellation
+ by contract, even when that peer could still receive. SDK requests follow this path.
+- A client intentionally stopping its send side while retaining its receive side
+ must send `X-Local-S2S-Half-Close: receive-response` before the body. After a complete
+ body, FIN then allows the bounded response to finish. A reset/transport error still
+ cancels. A subsequent graceful full close is indistinguishable from the declared
+ half-close and remains bounded by the original request deadlines.
+- Other header values fail before provider admission; extra request bytes/pipelining
+ are unsupported. The half-close header is private, is not forwarded upstream and
+ does not change the browser protocol. The gateway closes its send side at completion.
+
+Real loopback tests exercise both downstream and upstream TCP sockets for disconnect
+before headers and after headers with no further upstream output. They assert local
+upstream socket closure, HTTP transport closure and slot release within the cleanup
+window plus scheduling tolerance, before the five-second test request deadline.
+Separate tests cover normal success, declared half-close success, undeclared FIN
+cancellation and a stalled transport close. They require no external services.
+
+The local identifier validator now has a distinct method name so VoiceSettings
+inherits it alongside its existing OpenAI/Gemini validator. All four local model/
+voice fields reject whitespace, controls and non-ASCII before assets, construction
+or probes. Valid identifiers and existing provider validation are retained.
+
+Provenance correction: the hash-checked pinned `base.py.source` defines
+`WARMUP_MAX_RETRIES = 6` at line 66; Chat Completions imports that constant. The v2
+harness injected 10 as an isolated override and incorrectly described it as the
+pinned value. Its historical 31/107/242 execution results remain unchanged, but
+that description was wrong. Current warmup tests read 6 from the verified source
+AST and test both retryable HTTP and connection failures with exactly one attempt.
+The full OpenAI SDK/ML engine still has not been executed.
+
+Final offline checks for v3: **74 repair, 107 combined and 242 preservation tests
+passed**, using `-p no:cacheprovider`. Compose configuration validation and
+`git diff --check` passed. Exact commands/timings and the scoped patch are in the
+[Phase 2 report](../../docs/evaluation/local-s2s/phase-02.md#remaining-defect-repair-checkpoint-extension-v3).
+No paid calls, downloads, image builds, operational changes or PostgreSQL acceptance
+were performed here. Phase 2 remains in_progress/live acceptance pending until
+real-engine, component-audio and isolated Persian browser greeting/transcripts/
+normal-close evidence exists, alongside the existing Phase 1 prerequisite.
--- a/docs/evaluation/local-s2s/phase-02.md
+++ b/docs/evaluation/local-s2s/phase-02.md
@@ -164,7 +164,7 @@
| Confirmed upstream behavior / defect | Scoped repair and evidence |
| --- | --- |
| Base `process()` handles STT text through Chat Completions `_request_chat_completions`; that path ignores the prior `gen_kwargs` cap. Constructor setup invokes warmup. | Install the client policy and configured setup timeout before construction. Every actual Chat Completions create receives `max_tokens`; pinned normal text, warmup and setup tests inspect JSON with nondefault limits 17/83 and 19/71. Active attestation reads the installed policy. |
-| Pinned `warmup()` explicitly clones the client with `WARMUP_MAX_RETRIES=10`. | Policy clones force zero retries; retryable HTTP 503 and connection failures each produce exactly one attempt. Counters count admitted failed probes. Owner construction/probe deadline is 90 seconds; per-exchange default is 30 seconds. |
+| Pinned `warmup()` explicitly clones the client with `WARMUP_MAX_RETRIES=6` (the earlier harness override was 10; correction below). | Policy clones force zero retries; retryable HTTP 503 and connection failures each produce exactly one attempt. Counters count admitted failed probes. Owner construction/probe deadline is 90 seconds; per-exchange default is 30 seconds. |
| Pipeline import catches missing punkt/tagger resources and calls `nltk.download`. | Build preparation replaces those blocks with local validation. Required NLTK files and local VAD bundle have a reviewed SHA-256 manifest and expected manifest digest. Preflight checks every asset and loads original sentence/POS functions before provider construction. Missing/corrupt/malformed assets or tokenizers attempting blocked downloads produce a fixed safe category with zero provider calls. No tokenizer substitution. |
| Prior gateway timing began after header acquisition and buffered streams in 8192-byte pieces. | Owned asynchronous connection lifecycle bounds silent/partial headers, body reads, upstream headers/reads and downstream drains. Total and inactivity deadlines are independent. Small SSE/PCM chunks flow immediately; expiration/disconnect cancels upstream, closes transports and releases slots. Failed partial chunked responses omit the terminal chunk. Tests exercise actual loopback sockets, cancellation and stalled writes. |
| Upstream `ConfiguredRuntime.stop()` can raise before clearing resources; `wait()` invokes stop. The launcher bypassed upstream command signal management. | Independent bounded runtime stop, gateway shutdown, socket close and thread join always produce numeric cleanup/request counters. Owned SIGINT/SIGTERM handlers signal the stop event and restore predecessors. Tests exercise the pinned failing stop method, a hung stop/construction and termination during an in-flight mock request. Windows tests dispatch installed handlers; OS-level POSIX signal delivery remains unverified. |
@@ -238,3 +238,92 @@
not an interpreter import failure. Scoped untracked repair files were also
checked for trailing whitespace. Compose validation parsed configuration only;
it did not create/start any service or print credentials.
+
+
+## Remaining-defect repair checkpoint: extension v3
+
+**Verdict: offline regressions passed; Phase 2 remains in_progress and live
+acceptance pending.** The five prior repairs remain; Phase 3 and operational
+services were untouched. The [scoped patch](phase-02-remaining-repairs.patch) is
+relative to this checkpoint's in-session pre-edit snapshots, so unrelated existing
+working-tree changes are excluded. Files: `services/local_s2s/components.py`,
+`app/modules/voice/local_s2s.py`, `services/local_s2s/prepare_build.py`, the pinned
+source harness and repair tests, operator guide, this report, provenance and ledger.
+No existing OpenAI/Gemini assertion was removed or relaxed.
+
+1. **Disconnect ownership.** A concurrent downstream watcher starts after the body
+ and cancels the owned forwarding task on ordinary EOF/reset, including before
+ upstream headers and while response streaming produces nothing. Response/client
+ transport closure and task joining share a one-second cleanup window; expiry
+ aborts the downstream transport, cancels remaining cleanup and releases the slot.
+ Total/inactivity deadlines and incomplete chunked failure remain intact.
+ Real upstream and downstream TCP loopback tests assert upstream socket closure,
+ transport closure and slot release before a five-second request deadline, with
+ a 0.6-second scheduling allowance beyond the cleanup window. A stalled close
+ test verifies the cleanup bound itself. The old continuous-output disconnect
+ test remains; the earlier v2 disconnect description alone did not establish
+ these stalled-upstream cases.
+2. **Half-close policy.** FIN cannot distinguish full close from SHUT_WR. For
+ ordinary requests, EOF is explicitly cancellation, even if the peer can receive.
+ Intentional receive-only half-close is supported with the private header
+ `X-Local-S2S-Half-Close: receive-response`; FIN after the complete body then keeps
+ response delivery alive, while reset/transport errors still cancel. A graceful
+ full close after that declaration is inherently indistinguishable and remains
+ bounded by request deadlines. This header is not forwarded upstream and is not
+ a browser event/API change. Loopback tests prove normal and declared half-close
+ success, plus undeclared half-close cancellation. Extra bytes/pipelining are
+ unsupported and unknown header values fail before provider admission.
+3. **Inherited validation.** Renamed only `LocalS2SSettings.identifier` to
+ `local_component_identifier`, avoiding Pydantic's inherited validator override
+ by `VoiceSettings.identifier`. Through the real VoiceSettings, all four local
+ STT/LLM/TTS model and TTS voice fields now reject whitespace, control and non-ASCII
+ values. Tests preserve valid identifiers, check unchanged OpenAI/Gemini validators
+ and verify invalid environment configuration fails before assets/gateway/provider
+ construction or probes.
+4. **Source provenance correction.** `WARMUP_MAX_RETRIES` is **6**, defined at
+ line 66 of hash-checked `base.py.source`, imported by `chat.py.source`. The v2
+ test harness supplied literal 10, an isolated override, and the report/guide
+ incorrectly identified it as upstream's value. Those descriptions are corrected;
+ historical execution counts/timings remain unchanged. The harness now extracts
+ the literal from the verified source AST, with an explicit value assertion.
+ Pinned warmup HTTP 503/connection-failure tests run using 6 and still assert one
+ attempt. Complete SDK retry/ML engine execution is not claimed.
+
+Intentional behavior changes use `rag-local-s2s-phase2-v3` in fresh identities and
+build manifests; the private shape revision remains v1. No old reservation or
+frozen profile was rewritten. Native fingerprints, browser PCM24k/events,
+authorization/replay/epoch checks and fail-safe unsupported interruption remain.
+Persistent provider credentials stay server-side. No terminal/history receipt
+was fabricated. The pinned source fixture bytes and hashes were not changed.
+
+Final commands and outcomes:
+
+```powershell
+.venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider
+# 74 passed in 7.68s (31 prior repairs retained; 43 added regressions)
+.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
+# 107 passed in 16.67s
+.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider
+# 242 passed in 33.73s
+docker compose -f docker-compose.local-s2s-test.yml config --quiet
+# Passed: parse only; no service started or rendered secrets printed
+git diff --check
+# Passed
+```
+
+The initial targeted run before the final existing-provider validation cases was
+70 passed in 7.35s. All requested final suites passed; no baseline failure was
+hidden or assertion weakened. Historical broader ordinary/DB failures above and
+in the Phase 1 report remain separate and unresolved. PostgreSQL was not run in
+this checkpoint: no verified disposable TEST_DATABASE_URL was used. Any later DB
+acceptance requires that verification and `--require-postgres`.
+
+Evidence boundaries and remaining gates: original upstream methods run with an
+isolated SDK/history/ML harness; HTTPX and the new loopback transport tests use real
+local sockets. These are offline fixture results, not complete engine/OpenAI SDK,
+provider-audio or browser acceptance. No paid calls, downloads, image builds,
+operational actions or Phase 3 work occurred. Still required: Phase 1 real OpenAI
+interaction/listening, reviewed Linux dependency hash lock and immutable base image
+digest, provisioned/fingerprinted NLTK and VAD assets, real pinned-engine/SDK
+conformance, authorized component audio, and isolated Persian browser greeting,
+transcripts and normal close. See the [v3 operator guide](../../../services/local_s2s/README.md#phase-2-remaining-repairs-extension-v3).
--- a/docs/evaluation/local-s2s/phase-02-provenance.json
+++ b/docs/evaluation/local-s2s/phase-02-provenance.json
@@ -12,7 +12,7 @@
"interruption_policy": "close_until_phase3",
"local_s2s": {
"engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
- "patch_revision": "rag-local-s2s-phase2-v2",
+ "patch_revision": "rag-local-s2s-phase2-v3",
"contract_revision": "rag-local-s2s-phase2-v1",
"components": {
"stt": {
@@ -56,22 +56,22 @@
"app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
"app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
"app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
- "app/modules/voice/local_s2s.py": "65d86f2483ad2b3150aea5983f7690007ff043d1e2bc3c877bdbfa74ad3f36e2",
+ "app/modules/voice/local_s2s.py": "10b27361116ef2284ac1a2fff9e1df29bec8017278b1139fe4c34e9f26c67a34",
"app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
"docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
"docs/agent-reference-map.md": "1deba7eb98f045f49326e27ae6c20586f31989f5856d497a0c82904bc2dc6f92",
- "docs/evaluation/local-s2s/phase-02.md": "885ad1c3e7f2f81e74677d9eed29fc4b36898677133b916df84fbafbdc07003e",
- "docs/plans/local-s2s-adapter-progress.md": "8b42970f412ca14117daf5b2db7e393e355620fa3358ff9246f4333a4ef88629",
+ "docs/evaluation/local-s2s/phase-02.md": "12f0d26dcf347586e8c610eb27f15a93efc3088bd429c128fb5ba134ee71fb70",
+ "docs/plans/local-s2s-adapter-progress.md": "d99a465c0bc3f16d0a2a614412ed2df131d1d50d1270a0bd6139b1ce4d9d5e9d",
"services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
"services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
- "services/local_s2s/README.md": "241d6e9942ee55794f79a5055622585358d6fd3a8906eb260fae6048f5a7f3f4",
+ "services/local_s2s/README.md": "d7a411f7dfd8410ceb58b229dcf9603f031dc83acfa78bf4ec0d16404b81e10e",
"services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
- "services/local_s2s/components.py": "caa60d0001e8c637c85aae2deb387291ca469e244665f64219cfaf01e6442290",
+ "services/local_s2s/components.py": "fe6f5bd4121b1c68bc3d4747fde82c540cf37d3f459d4a3f6aed0d859124e317",
"services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
"services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
"services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
"services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
- "services/local_s2s/prepare_build.py": "a2718307a85128c053aff82612c54ab2f6f170f921e05e9aca42b3cf18b9b4b3",
+ "services/local_s2s/prepare_build.py": "89885abcd198a9efdedad403b9e34cc88b81935586c17e6221406204b7313b4e",
"services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
"tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
"tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
@@ -80,25 +80,25 @@
"tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
"tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
"tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
- "tests/support/local_s2s_pinned.py": "25003276c7c6b557bb9861147702a81ab446219e527a4951897785837c1a09bb",
+ "tests/support/local_s2s_pinned.py": "9b82e843f1598eae104c04e27e700bb1b10c391d49f194cbf7de3eb1d6ab286e",
"tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
"tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
- "tests/unit/test_local_s2s_repairs.py": "a57a8a09a3f213cead8437e0835fae41f5cac349c0c4f60e8871512ac4e8186d"
+ "tests/unit/test_local_s2s_repairs.py": "9cd2298ca3d19cdb34ab3548017ecda8efb02c5b1ed5bddb0b5c727f6985a47e"
},
"checks": {
"repair_regressions": {
- "passed": 31,
- "seconds": 6.82,
+ "passed": 74,
+ "seconds": 7.68,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
},
"final_combined": {
"passed": 107,
- "seconds": 18.66,
+ "seconds": 16.67,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
},
"preservation": {
"passed": 242,
- "seconds": 34.11,
+ "seconds": 33.73,
"command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
},
"git_diff_check": "passed",
@@ -179,13 +179,13 @@
},
"test_container_final_state": "stopped-retained"
},
- "patch_revision": "rag-local-s2s-phase2-v2",
+ "patch_revision": "rag-local-s2s-phase2-v3",
"contract_revision": "rag-local-s2s-phase2-v1",
"acceptance_verdict": "offline_repairs_verified_live_acceptance_pending",
"phase_status": "in_progress",
"repair_checkpoint": {
"upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
- "conformance": "hash-checked original upstream setup/process/request/warmup/stop methods with isolated SDK I/O and ML/history stand-ins; actual HTTPX payload and loopback transport assertions",
+ "conformance": "hash-checked original pinned methods with isolated SDK/history/ML dependencies; real HTTPX and downstream/upstream TCP loopback transport checks; full SDK/engine unexecuted",
"full_sdk_ml_engine_conformance": false,
"signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
"paid_requests": 0,
@@ -210,6 +210,157 @@
"real pinned engine and complete SDK conformance",
"authorized component STT/LLM/TTS audio checks",
"isolated Persian browser greeting/transcripts/normal close"
- ]
- }
+ ],
+ "disconnect_cleanup_window_seconds": 1.0,
+ "disconnect_test_request_deadline_seconds": 5,
+ "disconnect_test_scheduling_tolerance_seconds": 0.6,
+ "half_close_policy": {
+ "ordinary_eof": "explicit cancellation, not inferred inability to receive",
+ "receive_only_header": "X-Local-S2S-Half-Close: receive-response",
+ "declared_fin": "complete bounded response; a subsequent graceful full close is indistinguishable",
+ "reset": "cancellation"
+ },
+ "warmup_constant": {
+ "name": "WARMUP_MAX_RETRIES",
+ "value": 6,
+ "fixture": "tests/fixtures/local_s2s_upstream/base.py.source",
+ "line": 66,
+ "extraction": "literal AST from hash-checked pinned source",
+ "prior_harness_override": 10,
+ "correction": "prior v2 descriptions incorrectly called the isolated value 10 upstream; historical execution results retained"
+ },
+ "identifier_validator": "LocalS2SSettings.local_component_identifier; VoiceSettings.identifier unchanged",
+ "scoped_diff": "docs/evaluation/local-s2s/phase-02-remaining-repairs.patch"
+ },
+ "checkpoint_history": [
+ {
+ "patch_revision": "rag-local-s2s-phase2-v2",
+ "expected_candidate_profile": {
+ "provider": "local_s2s",
+ "model": "openai/gpt-4.1-mini",
+ "voice": "Kore",
+ "input_sample_rate": 24000,
+ "output_sample_rate": 24000,
+ "evidence_policy_revision": "same-session-evidence-retained-v5",
+ "development_only": true,
+ "interruption_policy": "close_until_phase3",
+ "local_s2s": {
+ "engine_revision": "619e3fe4f71d1c6f35c15870d588a3638de34722",
+ "patch_revision": "rag-local-s2s-phase2-v2",
+ "contract_revision": "rag-local-s2s-phase2-v1",
+ "components": {
+ "stt": {
+ "backend": "openai",
+ "model": "openai/whisper-large-v3",
+ "language": "fa",
+ "response_format": "json",
+ "final_only": true
+ },
+ "llm": {
+ "backend": "chat-completions",
+ "model": "openai/gpt-4.1-mini",
+ "max_output_tokens": 256
+ },
+ "tts": {
+ "backend": "openai",
+ "model": "google/gemini-3.8-flash-lite-tts",
+ "voice": "Kore",
+ "response_format": "pcm",
+ "sample_rate": 24000
+ },
+ "request_timeout_seconds": 30.0
+ },
+ "effective_config_sha256": "049a34b0d42ddb000d34dd52ab49844e3af958ab96eac4614c8a463236aa72a5"
+ }
+ },
+ "files": {
+ ".env.example": "c3b849f91611809200b832017a699d57c14fee3d7694c8227015fac78f85caa0",
+ "app/api/v1/live.py": "298e2b94d2bff2213128e19cfca174be0090a9635b764e91641c12eda8981631",
+ "app/infrastructure/local_s2s.py": "548d47d03eb9e4b26b9bfe8d04019968a251c4e3448eedc2b3f5fe60addeef5f",
+ "app/infrastructure/voice_provider.py": "03ebab36669e4b480d6c9f069f6cb046738109f2957df9900c1b80df87e30ef1",
+ "app/local_s2s_smoke.py": "2836e07c57256da9d3208442fae1dfbaf788c8af4f08b2c965d6582eebc27fe3",
+ "app/main.py": "3e02856b29c185f04bc7e95c07865c0ab29c2ac099582bae2bc1c4de0b4e5280",
+ "app/modules/voice/configuration.py": "ec1c6190f53275bf1e94935d133971d022d40579a6e8feff20a0e69a0872d1d1",
+ "app/modules/voice/local_s2s.py": "65d86f2483ad2b3150aea5983f7690007ff043d1e2bc3c877bdbfa74ad3f36e2",
+ "app/modules/voice/settings.py": "436dcaeb2f823a256400c4d703d8d4c6c4f0035e3659f4e7ad90b07940c17fd6",
+ "docker-compose.local-s2s-test.yml": "67482fb5a81011e37279eae260722f2d7c70c1c8e1105378429ec05607473cda",
+ "docs/agent-reference-map.md": "1deba7eb98f045f49326e27ae6c20586f31989f5856d497a0c82904bc2dc6f92",
+ "docs/evaluation/local-s2s/phase-02.md": "885ad1c3e7f2f81e74677d9eed29fc4b36898677133b916df84fbafbdc07003e",
+ "docs/plans/local-s2s-adapter-progress.md": "8b42970f412ca14117daf5b2db7e393e355620fa3358ff9246f4333a4ef88629",
+ "services/local_s2s/Dockerfile": "c907618421765d167993351b1f1d749156f6754fb91623b8f8d045b2b8de575b",
+ "services/local_s2s/Dockerfile.dockerignore": "a5e2c99be83b703c6e4a0a79028b266301e0ed886e7703ecb0e52cd72818f20b",
+ "services/local_s2s/README.md": "241d6e9942ee55794f79a5055622585358d6fd3a8906eb260fae6048f5a7f3f4",
+ "services/local_s2s/assets.py": "dd643068dee301470b66d4646ee0e61c91d753f61cf0114ed224435986c98fa2",
+ "services/local_s2s/components.py": "caa60d0001e8c637c85aae2deb387291ca469e244665f64219cfaf01e6442290",
+ "services/local_s2s/engine.py": "b5de737fe4793b8b766f142f6ffa35d5e4a67627effa7ce93181810107733f0e",
+ "services/local_s2s/extension.py": "1749b22aa92b40469e4d350ea18950f1414216bbb57460ea594be42ee14fbeed",
+ "services/local_s2s/lifecycle.py": "8b8f603eea6b79d22c73c22940be2ef5bb5e4b5875a38ae036e47fce8eb48a5f",
+ "services/local_s2s/pipeline.yaml": "a455d4f1c853ca70c38b03e0881d323c4abcb33dd68b66cb7d3409e34d761b75",
+ "services/local_s2s/prepare_build.py": "a2718307a85128c053aff82612c54ab2f6f170f921e05e9aca42b3cf18b9b4b3",
+ "services/local_s2s/request_policy.py": "8f489e166f0783222b244639ba0ee6513d2bff04c20f3efcd2145b987e6ff312",
+ "tests/fixtures/local_s2s_upstream/LICENSE": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46",
+ "tests/fixtures/local_s2s_upstream/base.py.source": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609",
+ "tests/fixtures/local_s2s_upstream/chat.py.source": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015",
+ "tests/fixtures/local_s2s_upstream/lifecycle.py.source": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6",
+ "tests/fixtures/local_s2s_upstream/manifest.json": "16e791623fd4a79ce36fb466da0905446a5d8d44f46e7aaac0988251e3d42027",
+ "tests/fixtures/local_s2s_upstream/pipeline.py.source": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7",
+ "tests/integration/test_local_s2s_phase2.py": "5ce4bd7c06f67b55f1bca607365f789a1203a8a03eaf3d0f81fe21268680253f",
+ "tests/support/local_s2s_pinned.py": "25003276c7c6b557bb9861147702a81ab446219e527a4951897785837c1a09bb",
+ "tests/unit/test_local_s2s_engine.py": "dbc61671c94a10777e80bfbf179b8e1bb89348de49a9512a921433e0e70074d0",
+ "tests/unit/test_local_s2s_phase2.py": "24ed8633e75dadcf15a305215fc725df351e14d480c5bf76119edc3d70aa20bf",
+ "tests/unit/test_local_s2s_repairs.py": "a57a8a09a3f213cead8437e0835fae41f5cac349c0c4f60e8871512ac4e8186d"
+ },
+ "checks": {
+ "repair_regressions": {
+ "passed": 31,
+ "seconds": 6.82,
+ "command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider"
+ },
+ "final_combined": {
+ "passed": 107,
+ "seconds": 18.66,
+ "command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider"
+ },
+ "preservation": {
+ "passed": 242,
+ "seconds": 34.11,
+ "command": ".venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider"
+ },
+ "git_diff_check": "passed",
+ "compose_config_quiet": "passed",
+ "python_source_parse": 9,
+ "postgres": "not run in repair checkpoint; prior results retained under previous_checkpoint",
+ "paid_requests": 0
+ },
+ "repair_checkpoint": {
+ "upstream_source_fixture_manifest": "tests/fixtures/local_s2s_upstream/manifest.json",
+ "conformance": "hash-checked original upstream setup/process/request/warmup/stop methods with isolated SDK I/O and ML/history stand-ins; actual HTTPX payload and loopback transport assertions",
+ "full_sdk_ml_engine_conformance": false,
+ "signal_evidence": "installed SIGINT/SIGTERM handlers dispatched in Windows tests; POSIX OS delivery unverified",
+ "paid_requests": 0,
+ "dependency_downloads": 0,
+ "model_downloads": 0,
+ "image_builds": 0,
+ "operational_changes": 0,
+ "postgres_acceptance": "not run; no disposable TEST_DATABASE_URL verified/used in this checkpoint",
+ "reservations_rewritten": false,
+ "required_local_assets": {
+ "manifest_schema": 1,
+ "manifest_sha256": null,
+ "nltk_root": "/assets/nltk",
+ "vad_root": "/vad/silero-vad",
+ "manifest_path": "/assets/assets.json",
+ "provisioned": false
+ },
+ "remaining_gates": [
+ "Phase 1 real OpenAI interaction/listening",
+ "reviewed dependency hash lock and immutable base image digest",
+ "provisioned fingerprinted NLTK and VAD assets",
+ "real pinned engine and complete SDK conformance",
+ "authorized component STT/LLM/TTS audio checks",
+ "isolated Persian browser greeting/transcripts/normal close"
+ ]
+ }
+ }
+ ]
}
--- a/docs/plans/local-s2s-adapter-progress.md
+++ b/docs/plans/local-s2s-adapter-progress.md
@@ -11,7 +11,7 @@
| Phase | Status | Evidence | Visible demo | Blockers |
| --- | --- | --- | --- | --- |
| 1 - Preserve OpenAI and introduce the provider boundary | offline_complete_live_pending | [Phase 1 report](../evaluation/local-s2s/phase-01.md); baseline 215 passed, final focused 242 passed; full suite has 5 existing failures (details in report) | Before/after controlled-clock replay; command in report | Changed-source real OpenAI interaction/listening pending; build lock/image digest required before Phase 2 build |
-| 2 - Add an isolated local stack and browser voice session | in_progress | [Phase 2 report](../evaluation/local-s2s/phase-02.md); v2 repair checkpoint: 31 new regression, 107 final combined and 242 preservation checks passed; earlier 2 new PostgreSQL checks passed, expanded DB regressions have 6 failures reproduced on HEAD; DB not rerun for repairs | Playable offline test-tone WAV and simulated native audio/transcripts; real browser demo unrun | Phase 1 acceptance; dependency lock/base digest/fingerprinted NLTK and VAD assets; actual engine build/SDK conformance and authorized real Persian/browser checks |
+| 2 - Add an isolated local stack and browser voice session | in_progress | [Phase 2 report](../evaluation/local-s2s/phase-02.md); v3 repair checkpoint: 74 repair regressions (including 31 prior), 107 final combined and 242 preservation checks passed; pinned warmup constant corrected to 6; earlier 2 new PostgreSQL checks passed, expanded DB regressions have 6 failures reproduced on HEAD; DB not rerun for repairs | Playable offline test-tone WAV and simulated native audio/transcripts; real browser demo unrun | Phase 1 acceptance; dependency lock/base digest/fingerprinted NLTK and VAD assets; actual engine build/SDK conformance and authorized real Persian/browser checks |
| 3 - Complete interruption, shared RAG and used sources | not_started | Not run | Not demonstrated | Resolve prerequisites |
| 4 - Validate quality/cost and prove controlled switch/rollback | not_started | Not run | Not demonstrated | Resolve prerequisites |
@@ -0,0 +1,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."
}
+482
View File
@@ -0,0 +1,482 @@
# 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**.
Phase 2 is **not accepted**. Phase 1 live acceptance remains open. No operational
provider switch, paid request, dependency/model download or engine build was performed.
## Delivered
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
off by default and requires explicit development/transport-test opt-in.
- Immutable profile containing upstream/extension/contract revisions, component
models/voice, final-only Persian STT, fixed PCM24k and an effective configuration
digest. Secrets and secret-derived hashes are excluded.
- Versioned engine launcher/extension reading initialized component identities
and applied native session state. A session echo alone fails readiness.
Missing model/voice/rate/credential configuration fails safely; native input,
response/tool/transcript identities and replay fingerprints are preserved.
- Bounded local HTTP gateway, no retries, bounded pipeline queues, request
deadlines, final-only STT and startup request counters. Truncated streams omit
the final HTTP chunk so consumers observe failure. Counters are not cost proof.
- Unsupported interruption/history repair closes safely until Phase 3. No
acknowledgement, transcript alignment or successful terminal is invented.
- Standalone isolated Compose, pinned-source build preparation, Docker recipe,
local-only preprovisioned VAD loading, environment examples and operator guide.
The engine receives no database credentials. Application startup checks the
candidate database/storage before lifecycle reconciliation, and rechecks the
actual database connection at reservation/stream admission.
- Stub/opt-in live smoke with multipart or JSON STT and playable WAV output.
The saved stub WAV is explicitly a synthetic 440 Hz test tone.
Main files: `app/modules/voice/local_s2s.py`, `configuration.py`, `settings.py`,
`app/infrastructure/local_s2s.py`, `voice_provider.py`, `app/main.py`,
`app/api/v1/live.py`, `app/local_s2s_smoke.py`, `services/local_s2s/`, `docker-compose.local-s2s-test.yml`,
`.env.example`, and the three new Phase 2 test files. Phase 1 and unrelated
working-tree changes were retained. No schema migration or old-profile rewrite.
## Actual checks
Commands ran from the repository root with the existing Windows virtualenv;
`-p no:cacheprovider` avoids pytest cache writes.
| Check | Result |
| --- | --- |
| Focused OpenAI/Gemini/runtime plus new local adapter/engine tests | **277 passed in 143.65 s** |
| Final Phase 2 tests after adding transcript and rejected-body coverage | **35 passed in 3.94 s** |
| Existing auth/startup/lifecycle/HTTP regression tests | **72 passed in 16.32 s** |
| Final combined local + HTTP/startup suite after actual-connection isolation guard | **107 passed in 13.90 s** |
| New PostgreSQL profile replay/revocation tests with `--require-postgres` | **2 passed in 4.66 s** |
| Expanded PostgreSQL lifecycle/transport regressions | **57 passed, 6 failed in 292.92 s**; details below |
| `docker compose -f docker-compose.local-s2s-test.yml config --quiet` | Passed; no candidate started |
| `git diff --check` | Passed (Git reports the existing CRLF policy for `.env.example`) |
| Stub smoke and independent WAV header inspection | Passed; 3 mocked stages, **0 paid requests**, mono PCM16, 24,000 Hz, 9,600 samples (0.4 s) |
| Operational image/container inspection and `/health/ready` | Original IDs/images unchanged; **ready / available** |
Focused command:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_engine.py tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q --tb=short -p no:cacheprovider
```
Final local command:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py -q --tb=short -p no:cacheprovider
```
Final combined command:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
```
Existing HTTP/startup command:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
```
PostgreSQL tests used a **new cached-image container** `rag-local-s2s-postgres-test`,
ID `e5da8c342ed59fc48a49856bfd76010feda45e4a221f640d34aa330a5cd8a7da`,
image `sha256:7b822b0aac60967beb1ea5e576b8602c94c300a157d187f385ae3e0da199b90a`,
at `127.0.0.1:55439`, database `rag_local_s2s_test`. No operational database was used.
The test harness created/dropped disposable schemas. Commands, with
`TEST_DATABASE_URL` set privately to this isolated database:
```powershell
.venv/Scripts/python -m pytest tests/integration/test_local_s2s_phase2.py -m postgres --require-postgres -q --tb=short -p no:cacheprovider
.venv/Scripts/python -m pytest tests/integration/test_local_s2s_phase2.py tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q --tb=short -p no:cacheprovider
```
The six expanded-suite failures are all
`test_actual_asgi_tool_dispatch_persistence_and_public_sources`, combinations of
`ok|no_evidence|error` and `gemini|openai`. They wait for public source events before
feeding subsequent provider responses and hit `RESPONSE_ACK_DEADLINE`. The new
local tests are green. Baseline comparison loaded immutable `HEAD` versions of settings, configuration,
Realtime, Gemini, factory, runtime and main **in memory**, using `git show HEAD:<path>`,
then ran the same six cases via `pytest.main` with `-k test_actual_asgi_tool_dispatch_persistence_and_public_sources -m postgres --require-postgres -q --tb=no -p no:cacheprovider`: **the same 6 failures, 55 deselected in 113.06 s**. No working files were reverted; no existing
assertions or timeout thresholds were weakened to hide failures. The full ordinary
suite was not rerun; its prior failures remain documented in the Phase 1 report.
## See the result now
Open [the generated WAV](../../../temp/local-s2s-phase2-stub.wav) in an audio player.
It is a **test tone, not actual Persian speech**. To generate another artifact:
```powershell
.venv/Scripts/python -m app.local_s2s_smoke --output temp/local-s2s-another-stub.wav
```
The command refuses to overwrite an existing file. Run the final local test command
above to see native setup, audio/transcript delivery, safe failure and close checks.
These are simulated provider events/HTTP responses, not a real engine/browser demo.
## Remaining gates and acceptance verdict
1. Phase 1 changed-source real OpenAI interaction/listening is still pending.
2. The real pinned engine was **not built or initialized**. Resolve/review the
Linux dependency hash lock and base-image digest, supply a preprovisioned VAD
source/asset bundle, then run actual upstream/configuration conformance.
The launcher is statically audited and fixture-tested; real dependency/API
incompatibilities remain possible. No reproducible image is claimed yet.
3. No paid-call approval was obtained: the user's clarification was not consent.
No OpenRouter key was accessed. Real STT/LLM/TTS requests, PCM-rate verification,
Persian listening and the isolated browser greeting/normal close remain open.
4. Model discovery was a free catalogue read: STT `openai/whisper-large-v3` and
LLM `openai/gpt-4.1-mini` were listed; the TTS candidate is
`google/gemini-3.8-flash-lite-tts` / `Kore`. This is not speech acceptance.
OpenAI TTS IDs were absent from the observed speech catalogue; no fallback was added.
5. The Angular source is absent from this repository. Repoint the existing client
in its own checkout, using a separate browser profile and candidate-only Origin.
This Compose profile intentionally uses a disabled embedding endpoint for a
greeting/transport demonstration; it does not certify RAG or interruption quality.
[Operator guide: build, isolated bootstrap, browser and consented live WAV steps](../../../services/local_s2s/README.md).
The application/browser PCM and public event contracts remain unchanged.
Operational identities remain those in [Phase 1](phase-01.md): running
`rag-api-mini` image `sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3`;
stopped original `rag-api` image
`sha256:6f9b1bc3e0eeb76e0143fb33e2773f3fe3e639fbc3c4b2c11139aaabb58ea028`.
No restart or rollback was attempted. Phase 3 must not start until Phase 2 acceptance.
The temporary acceptance database container was stopped after verification (retained, not removed).
[Phase 2 source fingerprints and expected candidate profile](phase-02-provenance.json)
record unbuilt/unverified state explicitly; they contain no provider credentials.
## Five-defect repair checkpoint (2026-10-15, extension v2)
This checkpoint supersedes the earlier candidate's offline safety claims for the
five repaired paths; earlier execution records above remain historical evidence.
**Verdict: offline repairs verified; Phase 2 remains in_progress, live acceptance
pending.** Phase 3 was not implemented and the operational deployment was not switched.
Verification used the actual source at upstream commit
`619e3fe4f71d1c6f35c15870d588a3638de34722`. Hash-checked source fixtures and the
upstream Apache license are in `tests/fixtures/local_s2s_upstream/`; their manifest
records original paths and SHA-256 values. Only source text/license was fetched.
The isolated harness compiles original upstream methods from those sources; it
isolates SDK I/O, history and ML imports. It inspects outgoing HTTPX JSON and actual
loopback HTTP framing/closure, rather than accepting fake handler attributes as
request conformance. Full SDK/ML/image execution remains a separate gate.
| Confirmed upstream behavior / defect | Scoped repair and evidence |
| --- | --- |
| Base `process()` handles STT text through Chat Completions `_request_chat_completions`; that path ignores the prior `gen_kwargs` cap. Constructor setup invokes warmup. | Install the client policy and configured setup timeout before construction. Every actual Chat Completions create receives `max_tokens`; pinned normal text, warmup and setup tests inspect JSON with nondefault limits 17/83 and 19/71. Active attestation reads the installed policy. |
| Pinned `warmup()` explicitly clones the client with `WARMUP_MAX_RETRIES=6` (the earlier harness override was 10; correction below). | Policy clones force zero retries; retryable HTTP 503 and connection failures each produce exactly one attempt. Counters count admitted failed probes. Owner construction/probe deadline is 90 seconds; per-exchange default is 30 seconds. |
| Pipeline import catches missing punkt/tagger resources and calls `nltk.download`. | Build preparation replaces those blocks with local validation. Required NLTK files and local VAD bundle have a reviewed SHA-256 manifest and expected manifest digest. Preflight checks every asset and loads original sentence/POS functions before provider construction. Missing/corrupt/malformed assets or tokenizers attempting blocked downloads produce a fixed safe category with zero provider calls. No tokenizer substitution. |
| Prior gateway timing began after header acquisition and buffered streams in 8192-byte pieces. | Owned asynchronous connection lifecycle bounds silent/partial headers, body reads, upstream headers/reads and downstream drains. Total and inactivity deadlines are independent. Small SSE/PCM chunks flow immediately; expiration/disconnect cancels upstream, closes transports and releases slots. Failed partial chunked responses omit the terminal chunk. Tests exercise actual loopback sockets, cancellation and stalled writes. |
| Upstream `ConfiguredRuntime.stop()` can raise before clearing resources; `wait()` invokes stop. The launcher bypassed upstream command signal management. | Independent bounded runtime stop, gateway shutdown, socket close and thread join always produce numeric cleanup/request counters. Owned SIGINT/SIGTERM handlers signal the stop event and restore predecessors. Tests exercise the pinned failing stop method, a hung stop/construction and termination during an in-flight mock request. Windows tests dispatch installed handlers; OS-level POSIX signal delivery remains unverified. |
Original source locations: `LLM/base_openai_compatible_language_model.py`
(`setup`, `process`), `LLM/chat_completions_language_model.py`
(`_request_chat_completions`, `warmup`), `s2s_pipeline.py` (NLTK import block),
and `configured_runtime.py` (`ConfiguredRuntime.stop`, `wait`). All paths are
under upstream `src/speech_to_speech/` at the pinned SHA.
The behavior revision is now `rag-local-s2s-phase2-v2`; private contract shape
remains `rag-local-s2s-phase2-v1`. New profiles pin v2. Existing reservations,
frozen profiles and historical v1 evidence are not rewritten. Raw event
fingerprints, authorization/replay/epoch checks, browser PCM24k/events and
fail-safe unsupported interruption remain covered by the preservation suites.
No existing OpenAI/Gemini assertions were weakened. Only the engine test client
fixture gained the effective policy fields required by v2 attestation.
Final repair regression command (31 passed in 6.82 s):
```powershell
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider
```
Required final combined command (107 passed in 18.66 s):
```powershell
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
```
Required preservation command (242 passed in 34.11 s):
```powershell
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider
```
These are offline tests, with zero paid calls, model/dependency downloads, image
builds or operational changes. PostgreSQL acceptance was **not run in this repair
checkpoint**: no disposable `TEST_DATABASE_URL` was verified/used. The earlier
2-pass and 57-pass/6-baseline-failure DB records above are not a fresh acceptance
claim; existing full-suite and database baseline failures remain open.
Reviewable repair files: `services/local_s2s/{request_policy,assets,lifecycle,
components,engine,extension,prepare_build}.py`, local behavior revision,
engine-only Compose asset mounts and example settings, pinned fixtures/harness,
`test_local_s2s_repairs.py`, engine fixture and these operator/evaluation records.
Unrelated working-tree changes were preserved. No terminal events, repair receipts
or live observations were fabricated; persistent provider credentials stay server-side.
To see the repaired behavior, run the three commands above. For actual speech,
follow the [updated operator guide](../../../services/local_s2s/README.md#phase-2-repair-checkpoint-extension-v2)
after separate authorization: provision/fingerprint local NLTK and VAD assets,
review Linux dependency lock and immutable base digest, build an isolated candidate,
then verify complete real-engine/SDK conformance, component audio and isolated
Persian browser greeting, transcripts and normal close. The Phase 1 real OpenAI
interaction/listening gate also remains open. No live acceptance is claimed until
those observations exist. The prior WAV remains a simulated test tone.
Additional offline checks:
```powershell
git diff --check
docker compose -f docker-compose.local-s2s-test.yml config --quiet
.venv/Scripts/python -c "import ast, tokenize; from pathlib import Path; paths=list(Path('services/local_s2s').glob('*.py'))+[Path('tests/unit/test_local_s2s_repairs.py'),Path('tests/support/local_s2s_pinned.py')]; [ast.parse(tokenize.open(p).read(),filename=str(p)) for p in paths]; print(str(len(paths))+' Python files parsed using Python source encodings')"
```
All passed; 9 Python source files parsed. An initial inspection using
`read_text(encoding='utf-8')` failed on the engine file's UTF-8 BOM; rerunning with
Python's source encoding detection passed. This was an inspection-command issue,
not an interpreter import failure. Scoped untracked repair files were also
checked for trailing whitespace. Compose validation parsed configuration only;
it did not create/start any service or print credentials.
## Remaining-defect repair checkpoint: extension v3
**Verdict: offline regressions passed; Phase 2 remains in_progress and live
acceptance pending.** The five prior repairs remain; Phase 3 and operational
services were untouched. The [scoped patch](phase-02-remaining-repairs.patch) is
relative to this checkpoint's in-session pre-edit snapshots, so unrelated existing
working-tree changes are excluded. Files: `services/local_s2s/components.py`,
`app/modules/voice/local_s2s.py`, `services/local_s2s/prepare_build.py`, the pinned
source harness and repair tests, operator guide, this report, provenance and ledger.
No existing OpenAI/Gemini assertion was removed or relaxed.
1. **Disconnect ownership.** A concurrent downstream watcher starts after the body
and cancels the owned forwarding task on ordinary EOF/reset, including before
upstream headers and while response streaming produces nothing. Response/client
transport closure and task joining share a one-second cleanup window; expiry
aborts the downstream transport, cancels remaining cleanup and releases the slot.
Total/inactivity deadlines and incomplete chunked failure remain intact.
Real upstream and downstream TCP loopback tests assert upstream socket closure,
transport closure and slot release before a five-second request deadline, with
a 0.6-second scheduling allowance beyond the cleanup window. A stalled close
test verifies the cleanup bound itself. The old continuous-output disconnect
test remains; the earlier v2 disconnect description alone did not establish
these stalled-upstream cases.
2. **Half-close policy.** FIN cannot distinguish full close from SHUT_WR. For
ordinary requests, EOF is explicitly cancellation, even if the peer can receive.
Intentional receive-only half-close is supported with the private header
`X-Local-S2S-Half-Close: receive-response`; FIN after the complete body then keeps
response delivery alive, while reset/transport errors still cancel. A graceful
full close after that declaration is inherently indistinguishable and remains
bounded by request deadlines. This header is not forwarded upstream and is not
a browser event/API change. Loopback tests prove normal and declared half-close
success, plus undeclared half-close cancellation. Extra bytes/pipelining are
unsupported and unknown header values fail before provider admission.
3. **Inherited validation.** Renamed only `LocalS2SSettings.identifier` to
`local_component_identifier`, avoiding Pydantic's inherited validator override
by `VoiceSettings.identifier`. Through the real VoiceSettings, all four local
STT/LLM/TTS model and TTS voice fields now reject whitespace, control and non-ASCII
values. Tests preserve valid identifiers, check unchanged OpenAI/Gemini validators
and verify invalid environment configuration fails before assets/gateway/provider
construction or probes.
4. **Source provenance correction.** `WARMUP_MAX_RETRIES` is **6**, defined at
line 66 of hash-checked `base.py.source`, imported by `chat.py.source`. The v2
test harness supplied literal 10, an isolated override, and the report/guide
incorrectly identified it as upstream's value. Those descriptions are corrected;
historical execution counts/timings remain unchanged. The harness now extracts
the literal from the verified source AST, with an explicit value assertion.
Pinned warmup HTTP 503/connection-failure tests run using 6 and still assert one
attempt. Complete SDK retry/ML engine execution is not claimed.
Intentional behavior changes use `rag-local-s2s-phase2-v3` in fresh identities and
build manifests; the private shape revision remains v1. No old reservation or
frozen profile was rewritten. Native fingerprints, browser PCM24k/events,
authorization/replay/epoch checks and fail-safe unsupported interruption remain.
Persistent provider credentials stay server-side. No terminal/history receipt
was fabricated. The pinned source fixture bytes and hashes were not changed.
Final commands and outcomes:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider
# 74 passed in 7.68s (31 prior repairs retained; 43 added regressions)
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_lifecycle.py tests/unit/test_phase3_acceptance_repairs.py -q --tb=short -p no:cacheprovider
# 107 passed in 16.67s
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py tests/unit/test_gemini_live.py -q -p no:cacheprovider
# 242 passed in 33.73s
docker compose -f docker-compose.local-s2s-test.yml config --quiet
# Passed: parse only; no service started or rendered secrets printed
git diff --check
# Passed
```
The initial targeted run before the final existing-provider validation cases was
70 passed in 7.35s. All requested final suites passed; no baseline failure was
hidden or assertion weakened. Historical broader ordinary/DB failures above and
in the Phase 1 report remain separate and unresolved. PostgreSQL was not run in
this checkpoint: no verified disposable TEST_DATABASE_URL was used. Any later DB
acceptance requires that verification and `--require-postgres`.
Evidence boundaries and remaining gates: original upstream methods run with an
isolated SDK/history/ML harness; HTTPX and the new loopback transport tests use real
local sockets. These are offline fixture results, not complete engine/OpenAI SDK,
provider-audio or browser acceptance. No paid calls, downloads, image builds,
operational actions or Phase 3 work occurred. Still required: Phase 1 real OpenAI
interaction/listening, reviewed Linux dependency hash lock and immutable base image
digest, provisioned/fingerprinted NLTK and VAD assets, real pinned-engine/SDK
conformance, authorized component audio, and isolated Persian browser greeting,
transcripts and normal close. See the [v3 operator guide](../../../services/local_s2s/README.md#phase-2-remaining-repairs-extension-v3).
## Acceptance preparation checkpoint (2026-10-15; v3 unchanged)
**Phase 2 remains in_progress / NOT ACCEPTED.** No runtime repair or refactor was
needed. The reviewed implementation/test fingerprints were checked unchanged
before documentation updates; the 74/107/242 baseline was not repeated. No paid
call, source/dependency/model download, image build, operational write, reservation
rewrite or Phase 3 implementation occurred. New files are acceptance preparation,
asset fingerprints and a guarded disposable-DB runner.
The [concrete acceptance checklist](phase-02-acceptance-checklist.md) records exact
commands, isolation, request ceilings proposed for approval, expected observations,
stop conditions and remaining gates. Candidate-only Phase 1 source-mount and
browser/proxy overrides were prepared and parsed; they were NOT launched. The
Phase 1 recipe uses the existing immutable API image as a dependency runtime,
mounts changed source read-only, masks inherited /app/data and uses separate test
DB/storage. It changes neither the operational container nor image. Source/runtime
compatibility still needs an actual consenting OpenAI interaction and listening.
Phase 1 stays open: server-side OpenAI key presence was verified without printing
its value; no bounded live approval or consented fixture is recorded. OpenRouter
key presence was false in both the checked host process and root server .env.
No key was copied to browser/profile/provenance.
Actual independent progress:
- Existing assets were found and fingerprinted: **201 files**, combined NLTK/Silero
manifest [phase-02-local-assets.json](phase-02-local-assets.json), SHA-256
`8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8`.
The existing sibling Windows environment loaded NLTK **3.10.3** sentence/POS
resources with downloader entry points blocked. No original asset changed.
Linux VAD/JIT and complete engine validation remain unrun.
- The cached immutable base was identified as
`python:3.11-slim@sha256:0dd364ba7e10242f07755449e3a3d0e35f9efd987952737b90def6709ab0c5ce`,
Linux/amd64. No dependency lock or candidate image exists. The sibling engine
checkout is dirty at `30af00916da85efb053b539a040fd71cf392e7e2` and does NOT contain
the required pin object; `git cat-file -t <pin>` failed. Its changes were preserved.
Building/reviewing a full pinned source graph requires an authorized clean
transfer/offline source tree, followed by reviewed Linux dependency resolution.
- PostgreSQL was actually run with `--require-postgres` on the retained verified
disposable container/database at 127.0.0.1:55439, never operational port 5432.
The runner validates fixed container/image/volume and host port, non-overlap with
operational storage, and `current_database()/current_user` before tests. Secrets
stay inside the subprocess environment. Fixtures create/drop random owned schemas.
- Local DB acceptance: **2 passed in 5.18 s**, zero skips. Expanded: **57 passed,
6 failed in 236.50 s**, zero skips. All six are the same
`test_actual_asgi_tool_dispatch_persistence_and_public_sources`
`ok|no_evidence|error` x `gemini|openai` cases, with RESPONSE_ACK_DEADLINE. They
match the earlier immutable-HEAD baseline comparison recorded above; that
comparison was not rerun here. No application/test assertion changed and broad
database acceptance remains non-green. The test container returned to exited
after each run; no volumes or operational data were removed.
- Frontend source was found outside this repository at
`D:/raymand/projects/faq_chatbot_frontend`, HEAD
`815191588c59fc43434cc2454cab3a8b2f8c1648`, with a pre-existing package.json edit.
Its proxy and files were not modified. An external candidate-only proxy and
trusted Origin 127.0.0.2:4201 were prepared; no browser/microphone run occurred.
Executed acceptance commands:
```powershell
.venv/Scripts/python -m services.local_s2s.assets --nltk-root "$env:APPDATA/nltk_data" --vad-root D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master --output docs/evaluation/local-s2s/phase-02-local-assets.json
D:/raymand/projects/speech-to-speech-test/.venv/Scripts/python.exe -c "import json,os,nltk; from pathlib import Path; from services.local_s2s.assets import validate_assets,configure_nltk; root=Path(os.environ['APPDATA'])/'nltk_data'; vad=Path('D:/raymand/projects/speech-to-speech-test/.cache/torch/hub/snakers4_silero-vad_master'); digest=validate_assets(root,vad,'docs/evaluation/local-s2s/phase-02-local-assets.json'); configure_nltk(nltk,root); print(json.dumps({'manifest_sha256':digest,'nltk_version':nltk.__version__,'sentence_and_pos_load':'passed','runtime_downloads':'blocked','environment':'existing Windows sibling virtualenv; not Linux engine'}))"
.venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite local
.venv/Scripts/python docs/evaluation/local-s2s/acceptance-postgres.py --suite expanded
docker compose -f docker-compose.local-s2s-test.yml config --quiet
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml config --quiet
docker compose -f docker-compose.local-s2s-test.yml -f docs/evaluation/local-s2s/phase-01-openai-acceptance.override.yml -f docs/evaluation/local-s2s/phase-02-browser.override.yml config --quiet
git diff --check
```
Asset commands passed; all three Compose parses passed. Rendered Phase 1 config
was inspected privately: read-only current app mount, masked inherited data,
non-operational DB/volumes, selected OpenAI provider, no OpenRouter key in API,
loopback binding and candidate Origin passed assertions. No rendered secret was
printed. Final git diff/metadata checks are recorded in provenance. The guarded
runner invokes the exact earlier local/expanded pytest commands with
`-m postgres --require-postgres -q --tb=short -p no:cacheprovider` and a verified
TEST_DATABASE_URL set privately. Its expanded exit code was 1; this is not hidden.
Remaining prerequisites are exact: Phase 1 bounded OpenAI consent and actual
changed-source listening; a clean complete pinned source tree; reviewed immutable
Linux dependency lock and build authorization; Linux asset compatibility; an
executable complete-engine controlled-I/O harness with actual SDK and POSIX signal
evidence; OpenRouter key and bounded paid consent plus consented Persian speech;
then real components and an isolated browser greeting/answer/transcripts/normal
close. The AST harness, NLTK load, DB passes and Compose parses do not replace any
of those observations. Proposed live limits in the checklist are NOT permission.
No automatic approval rejection blocked this checkpoint; dependent work remains
unrun because prerequisites/authorizations are absent.
@@ -0,0 +1,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"
]
}

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