feat(voice): support evidence reuse, 120s output capacity, and input ASR coalescing

- Add internal reuse_last_evidence tool for continuing existing topic without repeated retrieval
- Expand OpenAI output capacity to 120s / 5,760,000 bytes and add delivery fairness
- Coalesce adjacent user ASR transcript deltas to prevent client control queue overflow
- Add server-side OPENAI_REALTIME_SPEED configuration and update style to v4
- Add extensive unit and integration regressions for evidence reuse, capacity, and fairness
This commit is contained in:
11linear11
2026-10-12 17:57:27 -04:00
parent 9e6864ae2a
commit 111710c47c
33 changed files with 1189 additions and 55 deletions
+28
View File
@@ -0,0 +1,28 @@
{
"corpus": "live_repair_benchmark.md",
"synthetic": true,
"candidate_token_budgets": [512, 1024, 2048, 4096],
"repetitions_per_candidate": 3,
"questions": [
{"id": "Q01", "category": "fact", "question": "طبق داده آزمایشی، هزینه بررسی پذیرش چقدر است؟", "essential_facts": ["20 million rials", "review fee"]},
{"id": "Q02", "category": "multi_part", "question": "برای پرونده کامل پذیرش چه مدارکی لازم است؟", "essential_facts": ["signed form", "activity permit copy", "technical plan"]},
{"id": "Q03", "category": "conditions", "question": "بررسی پذیرش چه مدت طول می‌کشد و در صورت نقص چه می‌شود؟", "essential_facts": ["at most 10 working days for a complete file", "defects notified within 5 working days", "clock pauses during correction", "correction duration unspecified"]},
{"id": "Q04", "category": "numbers", "question": "تضمین و هزینه بررسی را جداگانه بگویید؛ آیا یکی جای دیگری را می‌گیرد؟", "essential_facts": ["30 million rial refundable deposit", "20 million rial review fee", "deposit does not replace fee"]},
{"id": "Q05", "category": "exceptions", "question": "تخفیف پژوهشی به چه پروژه‌ای تعلق می‌گیرد و چه هزینه‌هایی را کم می‌کند؟", "essential_facts": ["noncommercial research", "valid research center certificate", "50 percent of review fee", "10 million rial resulting review fee", "no infrastructure or deposit discount"]},
{"id": "Q06", "category": "exceptions", "question": "اگر پروژه تجاری باشد ولی گواهی پژوهشی داشته باشد، تخفیف می‌گیرد؟", "essential_facts": ["commercial projects excluded", "certificate alone is insufficient"]},
{"id": "Q07", "category": "exclusions", "question": "فعالیت گروه X با گواهی پژوهشی قابل پذیرش است؟", "essential_facts": ["hazardous group X prohibited", "research certificate does not override prohibition"]},
{"id": "Q08", "category": "dates", "question": "آیین‌نامه آزمایشی چه شناسه و تاریخ اجرایی دارد؟", "essential_facts": ["R-17", "January 1 2026"]},
{"id": "Q09", "category": "conditions", "question": "اعتبار مجوز چند ماه است و از چه تاریخی حساب می‌شود؟", "essential_facts": ["12 months", "from issue date"]},
{"id": "Q10", "category": "conditions", "question": "برای تمدید مجوز چه مهلت و شرایطی وجود دارد؟", "essential_facts": ["at least 30 days before expiry", "safety review", "no established debt"]},
{"id": "Q11", "category": "exceptions", "question": "مجوز منقضی خودکار تمدید می‌شود؟", "essential_facts": ["no automatic renewal", "new application required"]},
{"id": "Q12", "category": "multi_part", "question": "پروژه پژوهشی واجد شرایط چه هزینه بررسی و تضمینی می‌دهد؟ زیرساخت چه می‌شود؟", "essential_facts": ["10 million rial review fee", "30 million rial deposit", "infrastructure separate and undiscounted", "infrastructure amount unspecified"]},
{"id": "Q13", "category": "exceptions", "question": "اگر پذیرش رد شود، کدام مبالغ برمی‌گردد؟", "essential_facts": ["30 million rial deposit refunded", "review fee not refunded"]},
{"id": "Q14", "category": "insufficient_evidence", "question": "اگر قبل از بررسی انصراف دهم، هزینه بررسی هم برمی‌گردد؟", "essential_facts": ["deposit fully refunded", "review fee treatment on withdrawal unspecified", "no invented refund rule"]},
{"id": "Q15", "category": "insufficient_evidence", "question": "الان چند قطعه زمین در پارک آزمایشی موجود است؟", "essential_facts": ["current land availability absent", "cannot verify current availability"]},
{"id": "Q16", "category": "insufficient_evidence", "question": "تعرفه جاری زیرساخت چقدر است؟", "essential_facts": ["infrastructure amount absent", "no invented current tariff"]},
{"id": "Q17", "category": "ambiguity", "question": "هزینه چقدر است؟", "essential_facts": ["clarify review versus infrastructure or deposit", "no unsupported single total"]},
{"id": "Q18", "category": "follow_up", "preceding_question": "Q05", "question": "ادامه بده و استثناها را توضیح بده.", "essential_facts": ["remain on research discount topic", "commercial projects excluded", "infrastructure and deposit excluded", "group X still prohibited"], "expected_retrieval_delta": 0},
{"id": "Q19", "category": "topic_change", "preceding_question": "Q05", "question": "حالا موضوع تمدید مجوز را توضیح بده.", "essential_facts": ["30 days before expiry", "safety review", "no established debt", "expired permit requires new application"], "expected_fresh_search": true},
{"id": "Q20", "category": "insufficient_evidence", "question": "برای پذیرش با چه شماره‌ای تماس بگیرم و می‌توانی تماس را منتقل کنی؟", "essential_facts": ["experimental admissions unit", "telephone unspecified", "no claim of automatic transfer"]}
]
}
+36
View File
@@ -0,0 +1,36 @@
# داده ساختگی برای آزمون گفتگوی صوتی
این سند یک مجموعه داده ساختگی برای آزمون است و مقررات واقعی شرکت شهرک‌های
صنعتی اصفهان را بیان نمی‌کند. موضوع آن «پارک آزمایشی الف» است.
## پذیرش آزمایشی
آیین‌نامه آزمایشی R-17 از ۱ ژانویه ۲۰۲۶ اجرا می‌شود. درخواست پذیرش به فرم
امضاشده، تصویر مجوز فعالیت و طرح فنی نیاز دارد. هزینه بررسی ۲۰ میلیون ریال
است؛ هزینه زیرساخت جداگانه محاسبه می‌شود و مبلغ آن در این سند مشخص نشده است.
تضمین قابل بازگشت ۳۰ میلیون ریال است و جایگزین هزینه بررسی نیست.
بررسی پرونده کامل حداکثر ۱۰ روز کاری طول می‌کشد. نقص مدارک باید ظرف ۵ روز
کاری اعلام شود. مهلت بررسی در مدت رفع نقص متوقف می‌شود و زمان رفع نقص در
این سند تعیین نشده است.
پروژه پژوهشی غیرتجاری با گواهی معتبر از مرکز پژوهشی، ۵۰ درصد تخفیف هزینه
بررسی دارد؛ بنابراین هزینه بررسی آن ۱۰ میلیون ریال است. تخفیف به هزینه
زیرساخت یا تضمین تعلق نمی‌گیرد. پروژه تجاری مشمول این تخفیف نیست.
فعالیت خطرناک گروه X پذیرفته نمی‌شود؛ داشتن گواهی پژوهشی این ممنوعیت را
رفع نمی‌کند. مرجع پرسش درباره پذیرش «واحد پذیرش آزمایشی» است؛ شماره تلفن
و امکان انتقال خودکار تماس در این سند ذکر نشده است.
## مجوز آزمایشی
مدت اعتبار مجوز ۱۲ ماه از تاریخ صدور است. درخواست تمدید باید دست‌کم ۳۰ روز
پیش از انقضا ارائه شود. تمدید نیازمند بازبینی ایمنی و نداشتن بدهی قطعی است.
مجوز منقضی خودکار تمدید نمی‌شود و درخواست جدید لازم دارد.
در صورت رد پذیرش، تضمین ۳۰ میلیون ریالی بازگردانده می‌شود؛ هزینه بررسی
بازگردانده نمی‌شود. انصراف پیش از شروع بررسی نیز باعث بازگشت کامل تضمین
می‌شود؛ این سند درباره بازگشت هزینه بررسی در حالت انصراف حکمی ندارد.
این سند درباره موجودی فعلی زمین، تعرفه جاری زیرساخت، بدهی شخصی متقاضی،
وضعیت پرونده واقعی یا شماره تلفن واحد پذیرش اطلاعاتی ندارد.
@@ -0,0 +1,86 @@
"""Reuse revalidation on isolated PostgreSQL; no embedding/provider calls."""
import asyncio
from uuid import UUID, uuid4
import pytest
from sqlalchemy import text
from app.modules.knowledge.evidence import SearchExecution
from app.modules.knowledge.service import selection_replace
from app.modules.voice.durable_tools import DurableTools
from tests.integration.test_phase2_postgres import seeded_env, reserve
from tests.support.search import publish, QUERY
pytestmark = pytest.mark.postgres
def saved_evidence(e):
_, sid = reserve(e)
execution = SearchExecution(e.actor)
record = e.lifecycle.admit_tool(e.user, sid, 'real-retrieval', str(uuid4()), {'query': QUERY}, execution)
with e.engine.connect() as conn:
chunk = conn.execute(text('SELECT id,text,location FROM document_chunks WHERE document_id=:id'), {'id': e.doc}).mappings().first()
result = dict(status='ok', knowledge_revision=record['knowledge_revision'], warnings=[], sources=[dict(
document_id=str(e.doc), chunk_id=str(chunk['id']), source_ref='S1', title='Fixture',
text=chunk['text'], location=chunk['location'])])
assert e.lifecycle.complete_tool(e.user, sid, record['id'], result, execution)
return sid, dict(durable_id=record['id'], ref=str(record['public_ref']), result=result)
def test_reuse_preserves_retrieval_record_and_real_sources(seeded_env):
e = seeded_env
sid, original = saved_evidence(e)
store = DurableTools(e.lifecycle, e.user, sid)
execution = SearchExecution(e.actor)
result = asyncio.run(store.reuse(original, execution))
assert result == original['result']
asyncio.run(store.delivery(dict(original, reused_result=result), execution))
with e.engine.connect() as conn:
assert conn.execute(text('SELECT count(*) FROM tool_calls WHERE live_session_id=:sid'), {'sid': sid}).scalar_one() == 1
assert conn.execute(text('SELECT public_ref FROM tool_calls WHERE id=:id'), {'id': original['durable_id']}).scalar_one() == UUID(original['ref'])
@pytest.mark.parametrize('change', ['selection_add', 'selection_remove', 'deactivate', 'delete', 'logout', 'disable', 'epoch', 'close', 'cancelled_result'])
def test_reuse_rejects_changed_authority_revision_or_document(seeded_env, tmp_path, change):
e = seeded_env
sid, original = saved_evidence(e)
if change == 'selection_add':
new_document = publish(e.engine, e.settings, tmp_path / 'additional', e.actor)
with e.engine.connect() as conn:
before = conn.execute(text('SELECT knowledge_revision,access_epoch FROM organization_settings WHERE organization_id=:org'), {'org': e.org}).one()
selection = selection_replace(e.engine, e.actor, before.knowledge_revision, [e.doc, new_document])
assert selection['access_epoch'] == before.access_epoch
assert selection['revision'] == before.knowledge_revision + 1
elif change == 'selection_remove':
selection_replace(e.engine, e.actor, original['result']['knowledge_revision'], [])
elif change == 'logout':
e.auth.logout(e.token)
elif change == 'close':
e.lifecycle.finish_session(e.user, sid)
else:
with e.engine.begin() as conn:
if change == 'deactivate':
conn.execute(text('UPDATE documents SET is_active=false WHERE id=:id'), {'id': e.doc})
elif change == 'delete':
conn.execute(text('UPDATE documents SET deleted_at=now(),is_active=false WHERE id=:id'), {'id': e.doc})
elif change == 'disable':
conn.execute(text('UPDATE users SET is_enabled=false WHERE id=:id'), {'id': e.actor})
elif change == 'epoch':
conn.execute(text('UPDATE organization_settings SET access_epoch=access_epoch+1 WHERE organization_id=:org'), {'org': e.org})
else:
conn.execute(text("UPDATE tool_calls SET status='failed',error_code='TOOL_CANCELLED' WHERE id=:id"), {'id': original['durable_id']})
store = DurableTools(e.lifecycle, e.user, sid)
with pytest.raises(ValueError):
asyncio.run(store.reuse(original, SearchExecution(e.actor)))
def test_reuse_rechecks_revision_at_delivery_boundary(seeded_env):
e = seeded_env
sid, original = saved_evidence(e)
execution = SearchExecution(e.actor)
store = DurableTools(e.lifecycle, e.user, sid)
result = asyncio.run(store.reuse(original, execution))
with e.engine.begin() as conn:
conn.execute(text('UPDATE organization_settings SET knowledge_revision=knowledge_revision+1 WHERE organization_id=:org'), {'org': e.org})
with pytest.raises(ValueError, match='CONTEXT_REVOKED'):
asyncio.run(store.delivery(dict(original, reused_result=result), execution))
@@ -0,0 +1,51 @@
"""Both outbound authority fences use real, current PostgreSQL authority."""
import pytest
from sqlalchemy import text
from app.modules.knowledge.evidence import SearchExecution
from tests.integration.test_phase2_postgres import seeded_env, reserve
pytestmark = pytest.mark.postgres
@pytest.mark.parametrize('stale', ['session', 'turn'])
def test_joint_stream_check_rejects_either_stale_capture(seeded_env, stale):
e = seeded_env
_, sid = reserve(e)
session, turn = SearchExecution(e.actor), SearchExecution(e.actor)
e.lifecycle.validate_stream(e.user, sid, turn, session_execution=session)
# Change actual actor authority without notifying the in-memory registry.
with e.engine.begin() as conn:
conn.execute(text("UPDATE users SET role='user' WHERE id=:id"), {'id': e.actor})
fresh = SearchExecution(e.actor)
e.lifecycle.validate_stream(e.user, sid, fresh)
if stale == 'session':
turn = fresh
else:
session = fresh
with pytest.raises(ValueError, match='CONTEXT_REVOKED'):
e.lifecycle.validate_stream(e.user, sid, turn, session_execution=session)
@pytest.mark.parametrize('change,code', [
('logout', 'SESSION_REVOKED'), ('disable', 'ACCOUNT_DISABLED'),
('epoch', 'CONVERSATION_STALE'), ('close', 'LIVE_SESSION_UNUSABLE'),
])
def test_joint_stream_check_preserves_current_authority_gates(seeded_env, change, code):
e = seeded_env
_, sid = reserve(e)
session, turn = SearchExecution(e.actor), SearchExecution(e.actor)
e.lifecycle.validate_stream(e.user, sid, turn, session_execution=session)
with e.engine.begin() as conn:
if change == 'logout':
conn.execute(text('UPDATE auth_sessions SET revoked_at=now() WHERE id=:id'),
{'id': e.user.auth_session_id})
elif change == 'disable':
conn.execute(text('UPDATE users SET is_enabled=false WHERE id=:id'), {'id': e.actor})
elif change == 'epoch':
conn.execute(text('UPDATE organization_settings SET access_epoch=access_epoch+1 WHERE organization_id=:id'),
{'id': e.org})
if change == 'close':
e.lifecycle.finish_session(e.user, sid)
with pytest.raises(ValueError, match=code):
e.lifecycle.validate_stream(e.user, sid, turn, session_execution=session)
+71
View File
@@ -0,0 +1,71 @@
// Run the actual frontend worklet against a fixed numeric arrival trace.
// Usage: node tests/support/live_playback_trace.mjs /absolute/frontend/path
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
const frontend = process.argv[2];
assert(frontend, 'Provide the frontend repository path');
const source = readFileSync(resolve(frontend, 'public/assets/worklets/pcm-playback.worklet.js'), 'utf8');
const results = [];
for (const rate of [24000, 44100, 48000]) {
for (const prebufferMs of [80, 120, 160, 240]) {
for (const scenario of ['jitter', 'provider_pause']) {
let Processor;
const context = vm.createContext({
sampleRate: rate,
AudioWorkletProcessor: class {
constructor() {
this.messages = [];
this.port = { postMessage: m => this.messages.push(m) };
}
},
registerProcessor: (_, cls) => { Processor = cls; },
});
vm.runInContext(source, context);
const proc = new Processor();
proc.prebuffer = Math.floor(rate * prebufferMs / 1000);
// 250 20-ms frames. Three arrive together every 60 ms with bounded jitter.
const arrivals = [];
for (let i = 0; i < 250; i++) {
const batch = Math.floor(i / 3);
const at = batch * 60 + (batch % 5 === 0 ? 30 : 0) +
(scenario === 'provider_pause' && i >= 100 ? 2000 : 0);
arrivals.push({ at, samples: 480 });
}
arrivals.sort((a, b) => a.at - b.at);
let index = 0, firstConsumedMs = null, underruns = 0, openIdleMs = 0;
let wasDry = false, sealed = false, peakQueuedSource = 0;
const quantumMs = 128000 / rate;
for (let now = 0; now < 12000; now += quantumMs) {
while (index < arrivals.length && arrivals[index].at <= now) {
const pcm = new Int16Array(arrivals[index].samples).fill(1000);
proc.port.onmessage({ data: { type: 'push', pcm: pcm.buffer, sampleRate: 24000, audioRef: 'fixed-trace' } });
index++;
}
if (index === arrivals.length && !sealed) {
proc.port.onmessage({ data: { type: 'flush', audioRef: 'fixed-trace' } });
sealed = true;
}
peakQueuedSource = Math.max(peakQueuedSource, proc.queuedSource);
const before = proc.refPlayedOut.get('fixed-trace') ?? 0;
proc.process([[]], [[new Float32Array(128)]]);
const consumed = (proc.refPlayedOut.get('fixed-trace') ?? 0) > before;
if (consumed && firstConsumedMs === null) firstConsumedMs = now;
const dry = !consumed && firstConsumedMs !== null && !sealed;
if (dry) openIdleMs += quantumMs;
if (dry && !wasDry) underruns++;
wasDry = dry;
if (sealed && proc.count === 0) break;
}
const consumedSamples = proc.refPlayedOut.get('fixed-trace');
assert.equal(consumedSamples, rate * 5, 'Every admitted sample must drain');
assert(!proc.messages.some(m => m.type === 'overflow'), 'Two-second source queue must remain bounded');
assert(peakQueuedSource <= 48000);
results.push({ scenario, rate, prebufferMs, firstConsumedMs: Math.round(firstConsumedMs),
underruns, openIdleMs: Math.round(openIdleMs), peakQueuedSource: Math.ceil(peakQueuedSource), consumedSamples });
}
}
}
console.log(JSON.stringify(results, null, 2));
+62
View File
@@ -55,6 +55,68 @@ async def cleanup(runtime, receive):
await asyncio.gather(receive,return_exceptions=True)
await runtime.close()
def test_close_attempts_transport_when_pump_resists_cancellation():
async def scenario():
wire = FakeGoogleTransport()
aborted = []
wire.transport = SimpleNamespace(abort=lambda: aborted.append(True))
adapter = GeminiLiveAdapter(wire, settings=RuntimeSettings(_env_file=None, send_timeout_seconds=.02))
started, release = asyncio.Event(), asyncio.Event()
async def pump():
started.set()
try:
await release.wait()
except asyncio.CancelledError:
await release.wait()
adapter._pump_task = asyncio.create_task(pump())
await started.wait()
try:
waiter = asyncio.create_task(adapter.close())
await asyncio.sleep(0)
waiter.cancel()
await asyncio.gather(waiter, return_exceptions=True)
for _ in range(2):
with pytest.raises(TimeoutError, match='pump termination'):
await asyncio.wait_for(adapter.close(), .5)
assert wire.closed == 1 and aborted == [True]
assert adapter._inbound_events.empty()
finally:
release.set()
await adapter._pump_task
asyncio.run(scenario())
def test_close_transport_deadline_does_not_wait_for_cancellation_acknowledgement():
async def scenario():
wire = FakeGoogleTransport()
started, release, cancelled = asyncio.Event(), asyncio.Event(), asyncio.Event()
aborted = []
async def close():
wire.closed += 1
started.set()
try:
await release.wait()
except asyncio.CancelledError:
cancelled.set()
await release.wait()
wire.close = close
wire.transport = SimpleNamespace(abort=lambda: aborted.append(True))
adapter = GeminiLiveAdapter(wire, settings=RuntimeSettings(_env_file=None, send_timeout_seconds=.02))
try:
with pytest.raises(TimeoutError, match='transport close'):
await asyncio.wait_for(adapter.close(), .5)
await started.wait()
await cancelled.wait()
assert wire.closed == 1 and aborted == [True]
with pytest.raises(TimeoutError, match='transport close'):
await adapter.close()
assert wire.closed == 1
finally:
release.set()
await asyncio.sleep(0)
asyncio.run(scenario())
@pytest.mark.parametrize('rows,status', [([row()],'ok'),([],'no_evidence')])
def test_native_tool_correlation_canonical_result_and_once_only_continuation(settings,monkeypatch,runner,persisted,rows,status):
service = canonical_service(settings,monkeypatch,rows)
+62 -1
View File
@@ -1,5 +1,6 @@
"""Controlled-clock synchronization races and private branch attribution."""
import asyncio
import logging
from types import SimpleNamespace
import pytest
@@ -10,6 +11,66 @@ from tests.unit.test_realtime_phase1 import (
from tests.unit.test_realtime_repairs import Clock, without_ticker
def test_numeric_timeline_is_disabled_by_default(runner, persisted, caplog):
caplog.set_level(logging.INFO, logger="app.modules.voice.diagnostics")
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(delta(48000))
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
assert "Voice trace" not in caplog.text
finally:
await runtime.close()
asyncio.run(scenario())
def test_cancellation_timeline_distinguishes_receipt_from_locked_processing(runner, persisted, caplog):
caplog.set_level(logging.INFO, logger="app.modules.voice.diagnostics")
async def scenario():
clock = Clock()
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
runtime.settings = runtime.settings.model_copy(update={"diagnostic_trace_enabled": 1})
await without_ticker(runtime)
try:
await input_turn(runtime)
await response(runtime, transport)
await runtime.handle(delta(48000))
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
await input_turn(runtime, "u2", 10)
await until(lambda: "stage=cancel_sent" in caplog.text)
deadline = runtime.responses["r1"].cancel_deadline
clock.now = deadline - .1
async with runtime.lock:
terminal_task = asyncio.create_task(done(runtime, status="cancelled"))
await until(lambda: "stage=terminal_received" in caplog.text)
assert "stage=terminal_processed" not in caplog.text
clock.advance(.05)
await terminal_task
assert runtime.usable and runtime.responses["r1"].terminal
assert runtime.responses["r1"].cancel_deadline == deadline
stages = [r.message.split("stage=")[1].split()[0] for r in caplog.records if "Voice trace" in r.message]
expected = ["cancel_enqueued", "cancel_dispatched", "cancel_sent", "terminal_received", "terminal_processed"]
assert [s for s in stages if s in expected] == expected
assert "lock_wait_ms=" in caplog.text
assert "turn=live-turn-1" in caplog.text
assert "generated_bytes=48000" in caplog.text and "sent_bytes=48000" in caplog.text
finally:
await runtime.close()
asyncio.run(scenario())
def test_trace_rejects_content_and_untrusted_references(caplog):
from app.modules.voice.diagnostics import trace
caplog.set_level(logging.INFO, logger="app.modules.voice.diagnostics")
trace("SECRET_SESSION", "audio_received", turn_ref="SECRET_TURN", audio_ref="SECRET_AUDIO",
chunk_bytes=9600, text="SECRET_DOCUMENT", generated_bytes=2**63, played_ms=True)
assert "SECRET" not in caplog.text
assert "generated_bytes=2147483647" in caplog.text and "chunk_bytes=9600" in caplog.text
assert "played_ms=" not in caplog.text
@pytest.mark.parametrize("terminal_first", [False, True])
@pytest.mark.parametrize("verified", [False, True])
def test_cancel_error_requires_verified_classification_and_terminal(
@@ -298,4 +359,4 @@ def test_no_active_classifier_is_profile_and_signature_bounded(model, voice, acc
adapter = RealtimeAdapter(object(), model=model, voice=voice)
assert adapter.is_no_active(CAPTURED_NO_ACTIVE) is accepted
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, code="other"))
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, param="response_id"))
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, param="response_id"))
+3 -2
View File
@@ -37,7 +37,7 @@ def test_voice_only_comparison_keeps_all_other_setup_fields_fixed():
assert setups[0] == setups[1] == setups[2]
def test_gemini_effective_policy_and_profile_are_unchanged():
def test_gemini_effective_policy_and_evidence_revision_are_pinned():
async def scenario():
wire = Transport()
adapter = GeminiLiveAdapter(wire)
@@ -48,7 +48,8 @@ def test_gemini_effective_policy_and_profile_are_unchanged():
await adapter.close()
asyncio.run(scenario())
profile = VoiceSettings(_env_file=None, provider='gemini').profile()
assert set(profile) == {'provider','model','voice','input_sample_rate','output_sample_rate'}
assert set(profile) == {'provider','model','voice','input_sample_rate','output_sample_rate','evidence_policy_revision'}
assert profile['evidence_policy_revision'] == 'same-session-evidence-v1'
@pytest.mark.parametrize('voice', ['marin', 'cedar'])
+29 -1
View File
@@ -35,6 +35,10 @@ def test_defaults_and_candidate_profile():
assert candidate.profile()['audio_input']['transcription']['languages']==['fa','en']
@pytest.mark.parametrize('values', [
dict(openai_realtime_speed=0.24),
dict(openai_realtime_speed=1.51),
dict(openai_realtime_speed=float('nan')),
dict(openai_realtime_speed=float('inf')),
dict(openai_realtime_asr_model='gpt-live-transcribe'),
dict(openai_realtime_asr_model='gpt-transcribe'),
dict(openai_realtime_asr_languages=('fa','en')),
@@ -56,15 +60,39 @@ def test_invalid_configuration(values):
with pytest.raises(ValueError): VoiceSettings(_env_file=None,**values)
def test_environment_candidate(monkeypatch):
monkeypatch.setenv('OPENAI_REALTIME_SPEED','1.15')
monkeypatch.setenv('OPENAI_REALTIME_ASR_MODEL','gpt-transcribe')
monkeypatch.setenv('OPENAI_REALTIME_ASR_LANGUAGE','null')
monkeypatch.setenv('OPENAI_REALTIME_ASR_LANGUAGES','["fa","en"]')
monkeypatch.setenv('OPENAI_REALTIME_ASR_KEYWORDS','["PCM16LE","API"]')
monkeypatch.setenv('OPENAI_REALTIME_VAD_SILENCE_DURATION_MS','800')
config=VoiceSettings(_env_file=None,provider='openai')
assert config.profile()['audio_output_speed']==1.15
assert config.audio_input()['transcription']['languages']==['fa','en']
assert config.audio_input()['turn_detection']['silence_duration_ms']==800
@pytest.mark.parametrize('speed', [0.25, 1.0, 1.15, 1.5])
def test_speech_speed_is_pinned_and_provider_mismatch_is_rejected(speed):
config=VoiceSettings(_env_file=None,provider='openai',openai_realtime_speed=speed)
adapter=RealtimeAdapter(Transport(),input_settings=config)
ack=deepcopy(adapter.setup()['session'])
assert ack['audio']['output']['speed']==config.profile()['audio_output_speed']==speed
assert ack['audio']['output']['format']==dict(type='audio/pcm',rate=24000)
assert adapter.acknowledged(ack)
ack['audio']['output']['speed']=1.1 if speed!=1.1 else 1.0
assert not adapter.acknowledged(ack)
del ack['audio']['output']['speed']
assert not adapter.acknowledged(ack)
def test_factory_rejects_invalid_speed_before_remote_open(monkeypatch):
async def connect(*args):
pytest.fail('Invalid speed must not open a provider transport')
monkeypatch.setattr(voice_provider,'connect_openai',connect)
config=VoiceSettings(_env_file=None,provider='openai',openai_realtime_api_key='fake-only')
bad=config.model_copy(update={'openai_realtime_speed':float('nan')})
with pytest.raises(ValueError):
asyncio.run(voice_provider.create_adapter(bad,RuntimeSettings()))
@pytest.mark.parametrize('field,value',[
('transcription',dict(model='whisper-1',language='fa')),
('noise_reduction',None),
@@ -97,7 +125,7 @@ def test_factory_validation_precedes_remote_open_and_gemini_isolation(monkeypatc
gemini=VoiceSettings(_env_file=None,provider='gemini',gemini_api_key='fake-only')
changed=gemini.model_copy(update={'openai_realtime_vad_silence_duration_ms':800})
assert changed.profile()==gemini.profile()
assert set(gemini.profile())=={'provider','model','voice','input_sample_rate','output_sample_rate'}
assert set(gemini.profile())=={'provider','model','voice','input_sample_rate','output_sample_rate','evidence_policy_revision'}
a=await voice_provider.create_adapter(gemini,RuntimeSettings())
b=await voice_provider.create_adapter(changed,RuntimeSettings())
assert a.setup()==b.setup()
+3 -2
View File
@@ -1055,8 +1055,9 @@ def test_asr_repeated_partial_text_is_incremental_not_semantically_deduplicated(
await received(runtime, transport, json.dumps(dict(complete, event_id="asr-again")))
await until(lambda: runtime.control_count == 0)
transcripts = [e for e in out if e.get("role") == "user"]
assert [(e["text"], e["status"]) for e in transcripts] == [
(text, "partial"), (text, "partial"), (text + text, "completed")]
assert ''.join(e['text'] for e in transcripts if e['status'] == 'partial') == text + text
assert [(e['text'], e['status']) for e in transcripts if e['status'] != 'partial'] == [
(text + text, 'completed')]
assert all(e["turn_ref"] == turn.ref for e in transcripts)
assert not commands(transport, "response.create") and not runtime.calls
finally:
+3 -3
View File
@@ -287,10 +287,10 @@ def test_detected_forwarded_speech_overflow_without_commit(runner, persisted):
try:
await runtime.handle(dict(type="input_audio_buffer.speech_started",
item_id="bounded", audio_start_ms=0))
for _ in range(50):
for _ in range(320):
await runtime.input_audio(bytes(9600))
await until(lambda: runtime.input_transport_count == 0)
assert runtime.forwarded_buffer_bytes == 480000
assert runtime.forwarded_buffer_bytes == 3072000
await runtime.input_audio(bytes(2))
assert runtime.failure == "LIVE_BUFFER_OVERFLOW"
assert runtime.input_transport_bytes == runtime.input_buffer_bytes == 0
@@ -485,7 +485,7 @@ def test_smoke_never_succeeds_from_early_transcript(runner, persisted, monkeypat
await emit(event)
return original_runtime(adapter, service, shared_runner, actor, gated, **kwargs)
monkeypatch.setattr(voice_smoke, "VoiceRuntime", runtime_factory)
config = SimpleNamespace(openai_api_key=SecretStr("not-a-key"),
config = SimpleNamespace(provider='openai', openai_api_key=SecretStr("not-a-key"),
openai_realtime_model="gpt-realtime-mini", openai_proxy=None)
service = SimpleNamespace(engine=None, search=lambda *_: dict(status="no_evidence", sources=[]))
task = asyncio.create_task(voice_smoke.run(service, runner, uuid4(), config, "q", 3, 4))
+113
View File
@@ -0,0 +1,113 @@
"""Caption bursts cannot starve PCM; every frame keeps its authority fence."""
import asyncio
from types import SimpleNamespace
import pytest
from tests.unit.test_realtime_phase1 import runner, persisted, make, input_turn, response, delta, until, done
def test_long_input_transcript_burst_preserves_text_and_control_order(runner, persisted):
async def scenario():
runtime, _, _ = await make(SimpleNamespace(engine=None), runner, persisted)
entered, release = asyncio.Event(), asyncio.Event()
output = []
async def sink(event):
if isinstance(event, dict) and event.get('type') == 'transcript' and not entered.is_set():
entered.set()
await release.wait()
output.append(event)
async def asr(text, completed=False):
event = dict(type='conversation.item.input_audio_transcription.' +
('completed' if completed else 'delta'), item_id='u1', content_index=0)
event['transcript' if completed else 'delta'] = text
await runtime.handle(event)
try:
turn = await input_turn(runtime)
await until(lambda: not runtime.controls and runtime.active_control is None)
runtime.emit = sink
await asr('اول ')
await entered.wait()
parts = [f'بخش {i}، ' for i in range(200)]
for part in parts[:100]:
await asr(part)
runtime.control(dict(type='error', turn_ref=turn.ref, error=dict(
code='LIVE_TRANSCRIPTION_FAILED', message='test', retryable=False)))
for part in parts[100:]:
await asr(part)
text = 'اول ' + ''.join(parts)
await asr(text, completed=True)
assert runtime.usable
assert runtime.control_count <= 5
release.set()
await until(lambda: any(isinstance(e, dict) and e.get('status') == 'completed'
for e in output))
transcripts = [e for e in output if isinstance(e, dict) and e.get('type') == 'transcript']
assert ''.join(e['text'] for e in transcripts if e['status'] == 'partial') == text
assert transcripts[-1]['text'] == text
relevant = [e for e in output if isinstance(e, dict) and e.get('type') in ('transcript', 'error')]
assert [e['type'] for e in relevant] == ['transcript', 'transcript', 'error', 'transcript', 'transcript']
assert all(e['turn_ref'] == turn.ref for e in relevant)
await until(lambda: runtime.control_count == 0)
assert runtime.control_bytes == 0
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize('revoked', [False, True])
def test_caption_burst_interleaves_audio_and_preserves_revocation(runner, persisted, revoked):
async def scenario():
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted)
output = []
entered, release = asyncio.Event(), asyncio.Event()
async def sink(event):
if isinstance(event, dict) and event.get('type') == 'transcript' and not entered.is_set():
entered.set()
await release.wait()
output.append(event)
try:
await input_turn(runtime)
reply = await response(runtime, transport)
await until(lambda: not runtime.controls and runtime.active_control is None)
runtime.emit = sink
def caption(text, completed=False):
runtime.assistant_transcript(reply, dict(type='transcript', turn_ref=reply.turn.ref,
role='assistant', text=text), completed=completed)
caption('first ')
await entered.wait()
parts = [f'{i} ' for i in range(40)]
async with runtime.lock:
for part in parts:
caption(part)
assert len(runtime.controls) == 1
assert runtime.controls[0].event['text'] == ''.join(parts)
await runtime.handle(delta(19200))
if revoked:
persisted['enabled'] = False
release.set()
if revoked:
await until(lambda: not runtime.usable)
assert runtime.failure == 'CONTEXT_REVOKED'
assert not any(isinstance(e, bytes) for e in output)
else:
await until(lambda: sum(len(e) for e in output if isinstance(e, bytes)) == 19200)
first_audio = next(i for i,e in enumerate(output) if isinstance(e, bytes))
queued_caption = next(i for i,e in enumerate(output) if isinstance(e, dict)
and e.get('type') == 'transcript' and e['text'] == ''.join(parts))
started = next(i for i,e in enumerate(output) if isinstance(e, dict) and e['type'] == 'audio_started')
assert started < first_audio < queued_caption
text = 'first ' + ''.join(parts)
caption(text, completed=True)
await done(runtime)
await until(lambda: any(isinstance(e,dict) and e['type']=='transcript'
and e['status']=='completed' for e in output))
transcripts = [e for e in output if isinstance(e,dict) and e['type']=='transcript']
assert ''.join(e['text'] for e in transcripts if e['status']=='partial') == text
assert transcripts[-1]['text'] == text
assert runtime.usable
finally:
release.set()
await runtime.close()
asyncio.run(scenario())
+105
View File
@@ -0,0 +1,105 @@
"""Same-connection tool ordering; persisted eligibility is tested on PostgreSQL."""
import asyncio
from copy import deepcopy
from types import SimpleNamespace
from uuid import uuid4
import pytest
from tests.unit.test_realtime_phase1 import runner, persisted, make, input_turn, response, call, done, until, commands
@pytest.mark.parametrize('existing_source', [False, True])
def test_same_topic_reuses_original_retrieval_and_new_topic_searches(runner, persisted, existing_source):
searches, reuses = [], []
result = dict(status='ok', knowledge_revision=1, warnings=[], sources=[dict(
source_ref='S1', document_id=str(uuid4()), chunk_id=str(uuid4()), title='Fixture',
text='Verified fixture facts', location=dict(page=1, section=None))])
def search(execution, query, context):
searches.append(query)
return deepcopy(result)
class Store:
async def execute(self, external_id, record, ctx, args, invoke):
record['durable_id'] = uuid4()
return await invoke()
async def delivery(self, record, execution):
pass
async def reuse(self, original, execution):
reuses.append(original['durable_id'])
return deepcopy(original['result'])
async def scenario():
runtime, wire, out = await make(SimpleNamespace(engine=None, search=search), runner, persisted)
runtime.tool_store = Store()
try:
await input_turn(runtime)
await response(runtime, wire)
await runtime.handle(call(query='first topic'))
await done(runtime)
await until(lambda: runtime.last_evidence is not None)
original = runtime.calls['c1'][1]
await response(runtime, wire, 'r2')
await done(runtime, 'r2')
await input_turn(runtime, 'u2', 210)
await response(runtime, wire, 'r3')
if existing_source:
runtime.current.execution.sources([dict(result['sources'][0],
document_id=uuid4(), chunk_id=uuid4())])
reuse = call('r3', 'c2', name='reuse_last_evidence', raw='{}')
await runtime.handle(reuse)
await runtime.handle(dict(reuse, event_id='duplicate-reuse'))
await done(runtime, 'r3')
await until(lambda: runtime.calls['c2'][1]['sent'])
assert searches == ['first topic'] and reuses == [original['durable_id']]
reused = runtime.calls['c2'][1]
assert reused['ref'] == original['ref'] and reused['durable_id'] == original['durable_id']
expected = dict(original['result']['sources'][0], source_ref='S2' if existing_source else 'S1')
assert reused['result']['sources'] == [expected]
await until(lambda: any(isinstance(e, dict) and e.get('type') == 'sources' and e.get('turn_ref') == 'live-turn-2' for e in out))
event = next(e for e in out if isinstance(e, dict) and e.get('type') == 'sources' and e.get('turn_ref') == 'live-turn-2')
assert event['tool_call_id'] == original['ref']
await response(runtime, wire, 'r4')
await done(runtime, 'r4')
await input_turn(runtime, 'u3', 420)
await response(runtime, wire, 'r5')
await runtime.handle(call('r5', 'c3', query='new topic'))
await done(runtime, 'r5')
await until(lambda: runtime.calls['c3'][1]['sent'])
assert searches == ['first topic', 'new topic'] and len(reuses) == 1
finally:
await runtime.close()
assert runtime.last_evidence is None
asyncio.run(scenario())
@pytest.mark.parametrize('raw', ['{}', '{"user_id":"forged"}', '{"query":"q"}', 'null', '[]'])
def test_reuse_without_valid_bundle_never_searches_or_accepts_scope(runner, persisted, raw):
async def scenario():
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
await response(runtime, wire)
await runtime.handle(call(name='reuse_last_evidence', raw=raw))
await done(runtime)
await until(lambda: runtime.calls['c1'][1]['result'] is not None)
result = runtime.calls['c1'][1]['result']
if raw == '{}':
assert result['status'] == 'no_evidence' and result['warnings'] == ['fresh_search_required']
else:
assert result['error']['code'] == 'INVALID_TOOL_ARGUMENTS'
finally:
await runtime.close()
asyncio.run(scenario())
def test_interrupted_turn_clears_evidence_before_continuation(runner, persisted):
async def scenario():
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
try:
await input_turn(runtime)
origin = await response(runtime, wire)
runtime.last_evidence = (origin, dict(durable_id=uuid4(), result=dict(status='ok', sources=[])))
await input_turn(runtime, 'u2', 210)
assert runtime.last_evidence is None and origin.interrupted and origin.turn.cancelled.is_set()
finally:
await runtime.close()
asyncio.run(scenario())
+148
View File
@@ -0,0 +1,148 @@
"""Finite OpenAI reservoir, aggregate accounting and independent playback credit."""
import asyncio
from types import SimpleNamespace
import tracemalloc
import pytest
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.settings import RuntimeSettings
from tests.unit.test_realtime_phase1 import (
runner, persisted, make, input_turn, response, delta, done, until, commands,
)
from tests.unit.test_realtime_repairs import Clock
def test_provider_capacity_defaults_and_operator_override(monkeypatch):
assert RuntimeSettings(_env_file=None).max_output_backlog_bytes == 1440000
assert RuntimeSettings.for_provider('gemini').max_output_backlog_bytes == 1440000
limits = RuntimeSettings.for_provider('openai')
assert limits.max_output_backlog_bytes == 5760000
assert limits.output_slab_limit == 664
assert limits.output_credit_window_bytes == 72000
assert limits.max_queued_audio_bytes == 96000
assert limits.max_binary_message_bytes == 9600
profile = VoiceSettings(_env_file=None, provider='openai').profile()
assert profile['output_backlog_bytes'] == 5760000
assert profile['output_slab_limit'] == 664
assert 'output_backlog_bytes' not in VoiceSettings(_env_file=None, provider='gemini').profile()
monkeypatch.setenv('LIVE_MAX_OUTPUT_BACKLOG_BYTES', '1440000')
assert RuntimeSettings.for_provider('openai').max_output_backlog_bytes == 1440000
@pytest.mark.parametrize('values', [
dict(max_output_backlog_bytes=1440048),
dict(output_capacity_profile='openai-repair', max_output_backlog_bytes=5760048),
dict(output_capacity_profile='openai-repair', max_output_backlog_bytes=5760001),
])
def test_capacity_configuration_remains_finite_and_aligned(values):
with pytest.raises(ValueError):
RuntimeSettings(_env_file=None, **values)
def test_gemini_rejects_openai_capacity_before_provider_open(monkeypatch):
from app.infrastructure import voice_provider
async def forbidden(*args):
pytest.fail('Gemini must reject the OpenAI capacity profile before opening')
monkeypatch.setattr(voice_provider, 'connect_gemini', forbidden)
config = VoiceSettings(_env_file=None, provider='gemini', gemini_api_key='fake-only')
with pytest.raises(ValueError, match='OpenAI output capacity'):
asyncio.run(voice_provider.create_adapter(config, RuntimeSettings.for_provider('openai')))
async def burst(runtime, seconds, item='a1', position=0):
for _ in range(seconds // 2):
event = delta(96000, item_id=item)
event['output_index'] = position
await runtime.handle(event)
def test_eighty_second_burst_across_refs_drains_without_increasing_credit(runner, persisted):
async def scenario():
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
runtime.settings = RuntimeSettings(_env_file=None, output_capacity_profile='openai-repair',
diagnostic_trace_enabled=1)
runtime.adapter.settings = runtime.settings
try:
await input_turn(runtime)
await response(runtime, wire)
for item, pos in [('a1', 0), ('a2', 1)]:
await burst(runtime, 40, item, pos)
await runtime.handle(dict(type='response.output_audio.done', response_id='r1',
item_id=item, output_index=pos, content_index=0))
await done(runtime)
assert runtime.usable
assert runtime.peak_backlog_bytes == 3840000
async with asyncio.timeout(10):
while any(a.state != 'retired' for a in runtime.audio.values()):
for audio in list(runtime.audio.values()):
assert audio.credit + audio.reserved <= 72000
if audio.started and audio.state != 'retired':
await runtime.playback_progress(audio.ref, audio.sent // 48)
await asyncio.sleep(.001)
assert runtime.usable
assert sum(len(e) for e in out if isinstance(e, bytes)) == 3840000
assert sum(a.played for a in runtime.audio.values()) == 80000
assert all(a.sent == a.generated and a.credit == 0 for a in runtime.audio.values())
finally:
await runtime.close()
asyncio.run(scenario())
def test_new_bound_rejects_before_decode_and_allocation(runner, persisted, monkeypatch):
async def scenario():
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
runtime.settings = RuntimeSettings(_env_file=None, output_capacity_profile='openai-repair',
diagnostic_trace_enabled=1)
runtime.adapter.settings = runtime.settings
try:
await input_turn(runtime)
await response(runtime, wire)
tracemalloc.start()
try:
await burst(runtime, 120)
_, peak = tracemalloc.get_traced_memory()
print(f'120-second synthetic reservoir allocation peak: {peak} bytes')
assert peak < 16 * 1024 * 1024
finally:
tracemalloc.stop()
assert runtime.usable and runtime.peak_backlog_bytes == 5760000
audio = next(iter(runtime.audio.values()))
generated = audio.generated
def forbidden(*args, **kwargs):
pytest.fail('Overflow must reject before decoding another delta')
monkeypatch.setattr('app.modules.voice.runtime.base64.b64decode', forbidden)
await runtime.handle(delta(48))
assert runtime.failure == 'LIVE_BUFFER_OVERFLOW'
assert audio.generated == generated
finally:
await runtime.close()
asyncio.run(scenario())
@pytest.mark.parametrize('interrupt', [False, True])
def test_large_backlog_preserves_stall_and_cancellation_processing(runner, persisted, interrupt):
async def scenario():
clock = Clock()
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
runtime.settings = RuntimeSettings(_env_file=None, output_capacity_profile='openai-repair')
runtime.adapter.settings = runtime.settings
try:
await input_turn(runtime)
await response(runtime, wire)
await burst(runtime, 80)
await until(lambda: next(iter(runtime.audio.values())).sent > 0)
if interrupt:
await runtime.handle(dict(type='input_audio_buffer.speech_started',
item_id='u2', audio_start_ms=10))
await until(lambda: bool(commands(wire, 'response.cancel')))
await done(runtime, status='cancelled')
assert runtime.responses['r1'].terminal and runtime.usable
assert all(not a.data for a in runtime.audio.values())
else:
clock.advance(5.01)
runtime.check_deadlines()
assert runtime.failure == 'LIVE_BUFFER_OVERFLOW'
finally:
await runtime.close()
asyncio.run(scenario())
+9 -2
View File
@@ -132,10 +132,12 @@ def test_search_failure_policy(runner, persisted, supersede, exc, code):
@pytest.mark.parametrize("known", [False, True])
def test_unverified_profile_cancellation_diagnostics(runner, persisted, caplog, known):
@pytest.mark.parametrize("voice", ["shimmer", "coral"])
def test_profile_cancellation_diagnostics(runner, persisted, caplog, known, voice):
async def scenario():
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
runtime.adapter.model = "gpt-realtime-2.1"
runtime.adapter.voice = voice
try:
await input_turn(runtime)
await response(runtime, transport)
@@ -146,8 +148,13 @@ def test_unverified_profile_cancellation_diagnostics(runner, persisted, caplog,
type="invalid_request_error" if known else "PRIVATE_TYPE",
code="response_cancel_not_active" if known else "PRIVATE_CODE",
param=None if known else "PRIVATE_PARAM", message="PRIVATE_MESSAGE")))
if known and voice == "shimmer":
assert runtime.usable and runtime.failure is None
assert not runtime.responses["r1"].terminal
assert len(commands(transport, "response.create")) == 1
return
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
assert "cancellation_profile_2_1_shimmer=1" in caplog.text
assert f"cancellation_profile_2_1_shimmer={int(voice == 'shimmer')}" in caplog.text
for field in ("type", "code", "param"):
assert f"cancellation_{field}_match={int(known)}" in caplog.text
assert "PRIVATE" not in caplog.text