Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(realtime): meter scrub-gate audio release by vetted text, not delta arrival (BUG-069)

Ruben Lütke90282b06c4ee
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 5e464fddc1..45f1d8f359 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -4960,3 +4960,95 @@ and "input incomplete" are different states, and only the second may block.
And every provider-edge policy must be checked per adapter vocabulary: a
guard keyed to an event type one adapter never emits is a guard that does
not exist for that adapter.
+
+## BUG-069: Realtime speech chopped mid-word — the scrub gate's one-release-per-transcript-delta credit starves audio (HIGH, FIXED 2026-07-17)
+
+**Symptom (maintainer report + live session 2026-07-17 08:30, gemini-live).**
+Spoken replies sound chopped: a word is cut mid-syllable ("Win … ter"), the
+voice goes silent for seconds mid-sentence, then the rest of the answer
+plays; occasionally an answer aborts entirely into the generic failure
+phrase. Worst near the start of a reply. This is the general form of
+BUG-068's "Bug 2" (the ~1 s audible hole), whose instrumentation was built
+exactly for this recurrence.
+
+**Evidence.** The `_note_audio_flow` probe (added for BUG-068) attributed
+both stalls of the 08:30 session on its first real occurrence:
+`mid-reply audio stalled 5264 ms … (scrub-gate hold 5250 ms)` and
+`stalled 7046 ms … (hold 6953 ms)` — "the transcript needed to clear this
+audio arrived late". Not a silent provider, not a playback underrun: OUR
+scrub gate held decoded audio while waiting for provider transcription.
+A direct Gemini Live probe (scratch script, one text turn, timestamped
+events) then showed the provider-side cadence: the ENTIRE 514-char reply
+transcript arrived as ONE `output_transcription` delta alongside the first
+audio chunk, followed by a pure audio stream. Live sessions have also shown
+the opposite skew (output transcription >5 s BEHIND the audio, incident
+2026-07-16 11:24). Conclusion: no realtime provider paces its transcript
+deltas against its audio deltas — any gate release policy keyed to delta
+ARRIVAL COUNT instead of vetted text QUANTITY starves.
+
+**Root cause (jarvis/realtime/scrub_gate.py).** The ADR-0010 audio-hold
+gate released audio per-delta: a clean transcript delta set a one-shot
+`_cleared` flag which released everything buffered plus exactly ONE
+subsequent chunk, then closed again. With Gemini's en-bloc up-front
+transcript that meant: first chunk plays, every later chunk buffers until
+the next transcript delta — which never comes until turn end (or comes
+seconds late). The audible result is precisely the reported word-splitting
+(release boundary falls mid-word) and the multi-second holes. The
+secondary abort: `_MAX_UNSCRUBBED_AUDIO_MS = 5_000` sat BELOW Gemini's
+routine transcription lag, so a healthy answer whose transcript ran >5 s
+behind was dropped wholesale and replaced by the failure phrase
+("manchmal bricht es einfach ab"). <!-- i18n-allow: quoted German maintainer report -->
+
+**Fixes.**
+1. *Coverage budget (scrub_gate.py).* Release accounting now counts vetted
+ text QUANTITY: every transcript char that passed `scrub_for_voice` funds
+ `_COVERAGE_MS_PER_CHAR = 55.0` ms of audio; a chunk flows immediately
+ while cumulative `released_ms + chunk_ms` stays inside that budget. The
+ rate is deliberately FASTER than any real voice (~18 chars/s vs a
+ measured ~14), so the budget UNDERESTIMATES the spoken duration of the
+ vetted text — released audio cannot outrun the span the scrubber
+ already cleared. The legacy behavior is preserved verbatim as the floor:
+ a clean delta still clears everything buffered before it plus one
+ subsequent chunk; residue-only aggregates still fund nothing
+ (`_coverage_active`); hard leaks still drop everything; audio with no
+ transcript at all still fails closed. Cross-platform pure integer math,
+ no LLM (AP-11), no I/O.
+2. *Stall abort threshold (session.py).* `_MAX_UNSCRUBBED_AUDIO_MS`
+ 5 000 → 15 000: covers the observed 5-7 s lag with 2x margin; memory
+ cost is trivial (~1 MB PCM). Deliberately not larger — this bound is
+ also the ceiling on how much never-transcribed PCM `finalize()` could
+ flush at a turn boundary whose transcription died mid-turn, and
+ `finalize()` now logs any tail released far beyond the coverage
+ estimate so that scenario names itself in the log.
+3. *Trusted-reply fallback at turn completion (session.py).* With the 5 s
+ trip no longer firing first, a delegate readback whose transcription
+ never arrives now reaches the turn-complete fail-closed path — which
+ used to speak the generic failure phrase over OUR OWN already-delivered
+ brain reply. That path now hands the trusted reply text to the surface
+ TTS (same contract as the pending-buffer trip: `surface_fallback_spoken`
+ dedupe + withheld late provider rendering). Review hardening: all three
+ direct-to-surface fallback sites now pass the raw Brain reply through
+ `scrub_for_voice` before it reaches TTS (ADR-0010 — the normal path
+ only ever speaks it via the provider re-render through the gate), and
+ the delivered-flags are set only when the cancel will actually speak
+ (a second cancel in one turn is a logged no-op, not a silent reply
+ loss).
+
+**Guards.** `tests/unit/realtime/test_scrub_gate.py`
+(`test_en_bloc_upfront_transcript_keeps_audio_flowing`,
+`test_budget_exhaustion_buffers_audio_beyond_vetted_text`,
+`test_clean_delta_credit_still_releases_one_chunk_beyond_budget`,
+`test_residue_only_transcript_never_activates_the_budget`, plus the
+updated later-segment-leak and response-boundary tests);
+`tests/unit/realtime/test_session.py`
+(`test_later_segment_leak_audio_not_emitted`,
+`test_scrub_trip_during_delegate_readback_speaks_trusted_reply`).
+
+**Lesson.** A gate between two streams that the producer does not pace
+against each other must meter by QUANTITY (how much content has been
+vetted), never by event ARRIVAL (how many vetting messages have been
+seen). Arrival-keyed credits encode an interleaving assumption no provider
+guarantees — and every violation of that assumption is audible. Second
+lesson, again: safety bounds sized to "normal" provider behavior
+(5 s of pending audio) become answer-killers the day the provider is
+routinely slower; bound on resource cost, not on optimism.
diff --git a/jarvis/realtime/scrub_gate.py b/jarvis/realtime/scrub_gate.py
index 6b8472be27..4791a8c0df 100644
--- a/jarvis/realtime/scrub_gate.py
+++ b/jarvis/realtime/scrub_gate.py
@@ -6,15 +6,33 @@ decoded audio delta and release it only once its transcript region has passed
``scrub_for_voice``. A hard leak (stacktrace / raw repr / shell command) drops
the buffered audio and signals the session to cancel + speak the fallback.
Regex-only, no LLM (AP-11).
+
+Release accounting is a COVERAGE BUDGET, not a per-delta credit. Providers do
+not pace their output transcription against their audio: a Gemini Live probe
+(2026-07-17) delivered the ENTIRE reply transcript as one delta alongside the
+first audio chunk, and live sessions have shown the opposite — transcription
+falling 5-7 s behind the audio. The previous design released exactly one
+audio push per transcript delta, so an up-front en-bloc transcript starved
+every later chunk until turn end: the audible word-splitting stutter and
+multi-second mid-reply holes of BUG-069. Now each clean transcript char funds
+``_COVERAGE_MS_PER_CHAR`` of audio, cumulatively per response. The rate is
+deliberately FASTER than any real speaking voice (~18 chars/s vs a real
+12-17), so the budget systematically underestimates the true spoken duration
+of the vetted text — released audio therefore always stays inside the span
+the scrubber has already cleared. Audio beyond that span still buffers,
+fail-closed, exactly as before.
"""
from __future__ import annotations
+import logging
import time
from jarvis.brain.output_filter import FALLBACK_PHRASES, ScrubResult, scrub_for_voice
from jarvis.core.protocols import AudioChunk
+log = logging.getLogger(__name__)
+
_HARD_LEAK_ACTIONS = frozenset(
{
"removed_tool_json",
@@ -43,6 +61,14 @@ _KNOWN_SCRUB_ACTIONS = (
_HARD_LEAK_ACTIONS | _NON_BLOCKING_SCRUB_ACTIONS | {_RESIDUE_ACTION}
)
_TRANSCRIPT_TAIL_MAX_CHARS = 4_096
+# How much audio one vetted transcript char funds. 55 ms/char is ~18 chars/s
+# — faster than any real TTS voice speaks (measured Gemini Live German:
+# ~14 chars/s, i.e. ~70 ms/char) — so the budget UNDERESTIMATES the spoken
+# duration of already-scrubbed text and released audio cannot outrun it.
+_COVERAGE_MS_PER_CHAR = 55.0
+# A finalize() tail this far beyond the coverage estimate cannot be explained
+# by the deliberate underestimation alone; log it as a transcription stall.
+_FINALIZE_EXCESS_LOG_MS = 5_000.0
class ScrubHoldGate:
@@ -61,6 +87,14 @@ class ScrubHoldGate:
self._transcript_seen = False
self._transcript_tail = ""
self._hard_leak_actions: tuple[str, ...] = ()
+ # Coverage budget (BUG-069): audio released so far vs. the estimated
+ # spoken duration of every transcript char the scrubber has vetted.
+ # ``_coverage_active`` stays False until the AGGREGATE transcript has
+ # been clean at least once — a turn that opens with residue (a lone
+ # dash, a filler opener) must not fund any release.
+ self._released_ms = 0.0
+ self._covered_chars = 0
+ self._coverage_active = False
# Hold-time telemetry: how long the batch released last waited for its
# clearing transcript. Lets the session attribute an audible mid-reply
# hole to a late transcript delta instead of a silent provider
@@ -129,9 +163,15 @@ class ScrubHoldGate:
# protected compound as its own transcript delta. The complete
# utterance is not available yet, so this benign residue neither
# authorizes buffered audio nor aborts the response. The next
- # meaningful delta decides.
+ # meaningful delta decides. Its chars still count toward coverage
+ # (they are part of the spoken text and keep being re-checked via
+ # the aggregate), but the budget stays dormant until the aggregate
+ # has been clean once.
+ self._covered_chars += len(text)
self._cleared = False
return text
+ self._covered_chars += len(text)
+ self._coverage_active = True
self._cleared = True
if _is_stream_safe_residue(result):
# Preserve the provider's boundary verbatim. Replacing this one
@@ -149,7 +189,19 @@ class ScrubHoldGate:
return _restore_edge_whitespace(text, result.cleaned)
async def push_audio(self, chunk: AudioChunk) -> list[AudioChunk]:
- """Buffer or release an audio delta. Returns chunks safe to play now."""
+ """Buffer or release an audio delta. Returns chunks safe to play now.
+
+ Release order of precedence:
+ 1. A clean transcript delta clears everything buffered before it plus
+ this chunk (audio received before the delta belongs to text up to
+ that delta on a co-timed stream) — the pre-budget behavior,
+ unchanged.
+ 2. The coverage budget: this chunk flows immediately while cumulative
+ released audio stays inside the estimated spoken duration of all
+ vetted transcript chars. This is what keeps playback continuous
+ when a provider sends its transcript up-front en bloc (BUG-069).
+ Anything else buffers, fail-closed.
+ """
if self._hard_leak:
return []
if self._cleared:
@@ -157,13 +209,29 @@ class ScrubHoldGate:
self._pending = []
self._pending_audio_ms = 0.0
self._cleared = False
+ self._released_ms += _duration_ms(out)
self._consume_hold_clock()
return out
+ chunk_ms = _duration_ms((chunk,))
+ if self._coverage_active:
+ # Evaluate the WHOLE backlog plus this chunk so a budget that
+ # grew since the backlog formed can un-stick it (FIFO preserved:
+ # either everything flows or everything keeps buffering).
+ total_ms = self._pending_audio_ms + chunk_ms
+ if (
+ self._released_ms + total_ms
+ <= self._covered_chars * _COVERAGE_MS_PER_CHAR
+ ):
+ out = self._pending + [chunk]
+ self._pending = []
+ self._pending_audio_ms = 0.0
+ self._released_ms += total_ms
+ self._consume_hold_clock()
+ return out
if not self._pending and self._pending_since is None:
self._pending_since = time.monotonic()
self._pending.append(chunk)
- sample_rate = max(1, int(chunk.sample_rate or 0))
- self._pending_audio_ms += (len(chunk.pcm) / 2) * 1_000 / sample_rate
+ self._pending_audio_ms += chunk_ms
return []
def release_available(self) -> list[AudioChunk]:
@@ -179,6 +247,7 @@ class ScrubHoldGate:
self._pending = []
self._pending_audio_ms = 0.0
self._cleared = False
+ self._released_ms += _duration_ms(out)
self._consume_hold_clock()
return out
@@ -211,13 +280,37 @@ class ScrubHoldGate:
return True
def finalize(self) -> list[AudioChunk]:
- """Release the clean transcript-covered tail at the response boundary."""
+ """Release the clean transcript-covered tail at the response boundary.
+
+ Trust basis: at a genuine response boundary every transcript delta of
+ the turn has arrived and passed the aggregate scrub, so the buffered
+ tail is covered by vetted text. The coverage estimate deliberately
+ UNDERESTIMATES spoken duration, so a legitimate tail routinely sits
+ somewhat above the budget — never drop it for that. But a tail far
+ beyond the estimate means transcription lagged or died mid-turn;
+ log it so the next incident names this producer (BUG-069 review).
+ """
if self.fail_closed() or self._hard_leak:
return []
out = self._pending
self._pending = []
self._pending_audio_ms = 0.0
self._cleared = False
+ tail_ms = _duration_ms(out)
+ excess_ms = (
+ self._released_ms
+ + tail_ms
+ - self._covered_chars * _COVERAGE_MS_PER_CHAR
+ )
+ if out and excess_ms > _FINALIZE_EXCESS_LOG_MS:
+ log.info(
+ "scrub gate released a %d ms tail at the response boundary, "
+ "%d ms beyond the vetted-text coverage estimate — the "
+ "provider transcription lagged or stopped mid-turn",
+ int(tail_ms),
+ int(excess_ms),
+ )
+ self._released_ms += tail_ms
self._consume_hold_clock()
return out
@@ -232,6 +325,18 @@ class ScrubHoldGate:
self._hard_leak_actions = ()
self._pending_since = None
self.last_hold_ms = 0.0
+ self._released_ms = 0.0
+ self._covered_chars = 0
+ self._coverage_active = False
+
+
+def _duration_ms(chunks: tuple[AudioChunk, ...] | list[AudioChunk]) -> float:
+ """Total playback duration of 16-bit mono PCM chunks in milliseconds."""
+ total = 0.0
+ for chunk in chunks:
+ sample_rate = max(1, int(chunk.sample_rate or 0))
+ total += (len(chunk.pcm) / 2) * 1_000.0 / sample_rate
+ return total
def _restore_edge_whitespace(original: str, cleaned: str) -> str:
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index d154e9251a..c07359aa64 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -40,7 +40,14 @@ from jarvis.speech.hangup import HANGUP_RE
log = logging.getLogger(__name__)
-_MAX_UNSCRUBBED_AUDIO_MS = 5_000
+# Give up on a response only when transcription is truly dead. The old 5 s
+# bound sat below Gemini's routine 5-7 s output-transcription lag and aborted
+# REAL answers mid-sentence with the generic failure phrase (live forensic
+# 2026-07-17 08:30, BUG-069). 15 s covers the observed lag with 2x margin;
+# it is deliberately not larger because this bound is also the ceiling on how
+# much never-transcribed PCM finalize() could flush at a turn boundary whose
+# transcription died mid-turn. Memory cost is trivial either way.
+_MAX_UNSCRUBBED_AUDIO_MS = 15_000
_PROVIDER_HANDSHAKE_TOTAL_TIMEOUT_S = 12.0
_AUDIO_SEND_TIMEOUT_S = 2.0
_TOOL_TRANSCRIPT_WAIT_S = 3.0
@@ -1329,10 +1336,14 @@ class RealtimeVoiceSession:
if (
delegate_state is not None
and delegate_state.delivery_started
+ # A cancel this turn already spoke; marking the
+ # reply as delivered before a no-op cancel would
+ # silently lose it (BUG-069 review).
+ and not self._scrub_cancelled_for_turn
):
- trusted_reply = str(
- delegate_state.last_reply or ""
- ).strip()
+ trusted_reply = self._scrubbed_trusted_reply(
+ delegate_state
+ )
if trusted_reply:
delegate_state.surface_fallback_spoken = True
await self._cancel_unsafe_output(
@@ -1516,7 +1527,8 @@ class RealtimeVoiceSession:
# TTS path; never rerun the user request or its tools.
fallback_text = (
"".join(self._output_transcript).strip()
- or delegate_state.last_reply
+ or self._scrubbed_trusted_reply(delegate_state)
+ or self._gate.fallback_phrase()
)
if not self._output_transcript:
self._output_transcript.append(fallback_text)
@@ -1542,9 +1554,36 @@ class RealtimeVoiceSession:
)
final_chunks = self._gate.finalize()
if self._gate.hard_leak_pending():
+ # Same rendering-failure contract as the pending-buffer
+ # trip above: a delegate readback whose transcription
+ # never arrived is OUR already-delivered brain reply,
+ # not a leak. Speak the trusted text instead of the
+ # generic failure phrase (live incident 2026-07-16
+ # 11:24 reached this path once the unscrubbed-audio
+ # bound stopped tripping first, BUG-069).
+ trusted_reply = ""
+ if (
+ delegate_state is not None
+ and delegate_state.delivery_started
+ and not delegate_state.surface_fallback_spoken
+ # A cancel this turn already spoke; marking the
+ # reply as delivered before a no-op cancel would
+ # silently lose it (BUG-069 review).
+ and not self._scrub_cancelled_for_turn
+ and self._output_samples_sent == 0
+ ):
+ trusted_reply = self._scrubbed_trusted_reply(
+ delegate_state
+ )
+ if trusted_reply:
+ delegate_state.surface_fallback_spoken = True
+ self._drop_provider_output_until_user_turn = (
+ True
+ )
await self._cancel_unsafe_output(
reason="output transcript missing at turn completion",
interrupt_provider=False,
+ fallback_text=trusted_reply or None,
)
for chunk in final_chunks:
await self._emit_audio(chunk)
@@ -1651,6 +1690,20 @@ class RealtimeVoiceSession:
except Exception: # noqa: BLE001, S110
pass
+ def _scrubbed_trusted_reply(self, delegate_state: Any) -> str:
+ """Scrub-clean the delegate's trusted reply for direct surface speech.
+
+ The stored ``last_reply`` is raw Brain output; the normal path only
+ speaks it after the provider re-renders it through the scrub gate.
+ Every direct-to-surface fallback must apply the same regex scrub
+ (ADR-0010, AP-11) before the text reaches TTS — the sibling
+ ``_direct_tool_fallback_text`` already follows this contract.
+ """
+ raw = str(getattr(delegate_state, "last_reply", "") or "").strip()
+ if not raw:
+ return ""
+ return scrub_for_voice(raw, language=self._language).cleaned.strip()
+
async def _cancel_unsafe_output(
self,
*,
@@ -1660,6 +1713,17 @@ class RealtimeVoiceSession:
) -> None:
"""Cancel one unsafe provider response and emit one honest fallback."""
if self._scrub_cancelled_for_turn:
+ # A second cancel in the same turn is a silent no-op by design
+ # (one fallback per turn) — but it must be diagnosable, or a
+ # caller that staged a trusted reply here loses it without a
+ # trace (BUG-069 review; BUG-056 pattern).
+ log.debug(
+ "realtime[%s] suppressed a second scrub cancel this turn "
+ "(reason: %s, staged fallback dropped: %s)",
+ self.session_id,
+ reason,
+ bool(fallback_text),
+ )
return
self._scrub_cancelled_for_turn = True
self._drop_provider_output_until_new_response = True
diff --git a/tests/unit/realtime/test_scrub_gate.py b/tests/unit/realtime/test_scrub_gate.py
index ff0fc1873a..625454517b 100644
--- a/tests/unit/realtime/test_scrub_gate.py
+++ b/tests/unit/realtime/test_scrub_gate.py
@@ -67,9 +67,13 @@ async def test_leading_streaming_dash_waits_for_meaningful_transcript():
@pytest.mark.asyncio
async def test_split_filler_opener_can_complete_a_substantive_reply():
- """A temporary ``Let me think`` prefix must not abort streamed output."""
+ """A temporary ``Let me think`` prefix must not abort streamed output.
+
+ The 2000 ms chunk exceeds what the few prefix chars fund, so it must
+ buffer until the substantive continuation arrives — never abort.
+ """
gate = ScrubHoldGate(language="en")
- buffered = _chunk(8)
+ buffered = _chunk(48_000)
display = [await gate.feed_transcript("Let me")]
display.append(await gate.feed_transcript(" think"))
@@ -247,13 +251,14 @@ async def test_scrub_is_regex_only_no_llm(monkeypatch):
@pytest.mark.asyncio
async def test_later_segment_leak_is_caught_after_a_clean_first_segment():
- """_cleared must be one-shot: a later segment's audio still gets held.
-
- Regression for the sticky-_cleared defect: after the first clean
- transcript in a turn released `_cleared = True` and never reset it, so
- every later push_audio() released immediately without buffering — audio
- for a later segment (which may contain a hard leak) could reach the
- speaker before its own transcript was scrubbed.
+ """Audio beyond the vetted coverage budget still gets held.
+
+ Regression for the sticky-_cleared defect, updated for the BUG-069
+ coverage budget: a short clean first segment funds only its own
+ estimated spoken duration, so a later segment's audio that outruns that
+ budget (and whose own transcript may be a hard leak) must buffer until
+ its transcript is scrubbed — and must be dropped when that transcript
+ turns out to be a stacktrace.
"""
gate = ScrubHoldGate(language="en")
@@ -264,9 +269,9 @@ async def test_later_segment_leak_is_caught_after_a_clean_first_segment():
out1 = await gate.push_audio(_chunk(4))
assert out1 # segment 1 audio released
- # Segment 2: audio arrives before ITS transcript. If _cleared were still
- # sticky from segment 1, this would release immediately (the bug).
- out2 = await gate.push_audio(_chunk(4))
+ # Segment 2: 2000 ms of audio arrives before ITS transcript — far more
+ # than the 24-char first segment can fund. It must buffer, not release.
+ out2 = await gate.push_audio(_chunk(48_000))
assert out2 == [] # must be buffered, not released
# Segment 2's transcript turns out to be a hard leak (a real stacktrace).
@@ -310,7 +315,9 @@ async def test_missing_transcript_fails_closed_instead_of_releasing_audio():
async def test_clean_transcript_covers_buffered_tail_at_response_boundary():
gate = ScrubHoldGate(language="en")
first = _chunk(4)
- tail = _chunk(8)
+ # 2000 ms — beyond what the 25-char transcript's coverage budget funds,
+ # so it must wait for the response boundary.
+ tail = _chunk(48_000)
await gate.feed_transcript("A complete safe response.")
assert await gate.push_audio(first) == [first]
@@ -330,6 +337,80 @@ async def test_untranscribed_audio_buffer_is_bounded_by_audio_duration():
assert gate.hard_leak_pending() is True
assert gate.finalize() == []
+async def test_en_bloc_upfront_transcript_keeps_audio_flowing():
+ """BUG-069 core fix: an up-front whole-reply transcript funds ALL audio.
+
+ A Gemini Live probe (2026-07-17) delivered the entire reply transcript as
+ ONE delta alongside the first audio chunk, then streamed audio only. The
+ pre-budget gate released exactly one chunk per transcript delta, so every
+ later chunk starved until turn end — the audible word-splitting stutter
+ and 5-7 s mid-reply holes. With the coverage budget, each chunk must flow
+ the moment it arrives.
+ """
+ gate = ScrubHoldGate(language="en")
+ transcript = (
+ "A perfectly ordinary answer about the weather today, spoken in "
+ "several unhurried sentences that together run far longer than the "
+ "audio pushed below, arriving complete before nearly all its audio."
+ )
+
+ await gate.feed_transcript(transcript)
+ assert gate.release_available() == [] # nothing buffered yet
+
+ for _ in range(10):
+ chunk = _chunk(9_600) # 400 ms at 24 kHz — a realistic Gemini chunk
+ assert await gate.push_audio(chunk) == [chunk]
+ assert gate.pending_audio_ms == 0.0
+
+
+async def test_budget_exhaustion_buffers_audio_beyond_vetted_text():
+ """Fail-closed core: audio outrunning the vetted text still buffers."""
+ gate = ScrubHoldGate(language="en")
+
+ await gate.feed_transcript("Okay.") # funds ~275 ms
+ first = _chunk(9_600) # 400 ms
+ assert await gate.push_audio(first) == [first] # clean-delta release
+
+ second = _chunk(9_600)
+ assert await gate.push_audio(second) == [] # budget spent: buffer
+
+ await gate.feed_transcript(" The rest of the sentence arrives late.")
+ assert gate.release_available() == [second]
+
+
+async def test_clean_delta_credit_still_releases_one_chunk_beyond_budget():
+ """The budget redesign must never be stricter than the old gate.
+
+ When a clean delta arrives with nothing buffered, the pre-budget gate
+ preserved its credit and released exactly one later chunk regardless of
+ size. That parity must survive: the first chunk after such a delta flows
+ even though the tiny transcript cannot fund its duration — and only one.
+ """
+ gate = ScrubHoldGate(language="en")
+
+ await gate.feed_transcript("Hi.") # funds only ~165 ms
+ assert gate.release_available() == [] # nothing buffered: credit survives
+
+ first = _chunk(9_600) # 400 ms — larger than the funded estimate
+ assert await gate.push_audio(first) == [first] # legacy credit release
+ assert await gate.push_audio(_chunk(9_600)) == [] # credit is one-shot
+
+
+async def test_residue_only_transcript_never_activates_the_budget():
+ """A turn whose aggregate transcript is still residue funds nothing."""
+ gate = ScrubHoldGate(language="en")
+
+ await gate.feed_transcript("Great question.") # residue: filler opener
+ assert await gate.push_audio(_chunk(9_600)) == []
+
+ await gate.feed_transcript(" Bones need calcium and daily movement.")
+ assert gate.release_available() # aggregate turned clean: audio flows
+
+
@pytest.mark.asyncio
async def test_hard_leak_exposes_detector_actions_for_diagnosis():
"""BUG-056: the 15:13 abort was undiagnosable — only the generic reason
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index acc6965cb2..95861d10f6 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -957,8 +957,11 @@ async def test_later_segment_leak_audio_not_emitted():
# could ride along before its own transcript is scrubbed. The session
# must flush release_available() right after sending a clean transcript
# so the gate's _cleared flag never spans into the next segment's audio.
+ # The leak segment carries 1500 ms of PCM — beyond what the 23-char clean
+ # first sentence funds under the BUG-069 coverage budget, so it must stay
+ # buffered until its own (leaking) transcript arrives and drops it.
a1 = b"\x11\x22" * 8
- a2 = b"\x33\x44" * 8
+ a2 = b"\x33\x44" * 36_000
events = [
RealtimeEvent(
type="audio_delta", audio=AudioChunk(pcm=a1, sample_rate=24000, timestamp_ns=0)
@@ -2004,15 +2007,16 @@ async def test_scrub_trip_during_delegate_readback_speaks_trusted_reply():
"""A tripped transcript hold re-speaks the delivered reply, not an error.
Gemini renders an injected trusted result faster than real time while its
- output transcription lags; once >5 s of PCM sat unclaimed the scrub gate
- cancelled the readback and the user heard a generic error AFTER waiting
- through the whole delegated action (live incident 2026-07-16 11:24). The
- reply text is our own already-delivered brain output, so the surface TTS
- must speak it instead.
+ output transcription lags entirely (live incident 2026-07-16 11:24). With
+ no transcript delta the whole turn, the gate fails closed at
+ turn_complete (BUG-069: the mid-turn buffer cap no longer trips first) —
+ and that path used to speak a generic error AFTER the user waited through
+ the whole delegated action. The reply text is our own already-delivered
+ brain output, so the surface TTS must speak it instead.
"""
reply = "The delegated answer the user must still hear."
- # 3 s of 24 kHz 16-bit PCM per chunk; the second chunk pushes the
- # unclaimed buffer past the 5 s scrub cap without any transcript delta.
+ # 3 s of 24 kHz 16-bit PCM per chunk — audio arrives, its transcript
+ # never does, and the turn ends normally.
three_seconds = AudioChunk(
pcm=b"\x01\x02" * 72_000, sample_rate=24_000, timestamp_ns=0
)