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.
864 lines
55 KiB
Diff
864 lines
55 KiB
Diff
--- 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 |
|
|
|