Skip to content

Server-side VAD gate: skip silence before Deepgram send to reduce streaming cost #4644

Closed

Description

@beastoin

Problem

Deepgram (DG) bills per second of audio sent, including silence. BigQuery analysis (Jan 2026, 162,429 streaming hours, 219K sessions) shows average WPM of 27.3 vs normal speech at ~130 WPM — implying ~79% of streaming time is non-speech being billed.

Speech Density % of Hours Est. Silence Description
0-5 WPM 19.2% (31,166h) ~98% Dead air — wearable on, nobody talking
5-15 WPM 11.8% (19,110h) ~92% Very sparse speech
15-30 WPM 11.0% (17,799h) ~83% Light/intermittent
30-60 WPM 13.4% (21,831h) ~65% Moderate conversation
60-100 WPM 9.7% (15,760h) ~38% Active conversation
100-130 WPM 4.1% (6,721h) ~12% Dense conversation
130+ WPM 30.8% (50,042h) ~0% Very dense speech

41.9% of all hours are below 30 WPM — mostly silence being billed per-second.

Infrastructure: Which Services Use Cloud vs Self-Hosted DG

From Helm charts (backend/charts/):

Service Prod DG Mode Config Billing
backend-listen Cloud (Hosted) DEEPGRAM_SELF_HOSTED_ENABLED: "false" Per-second (billed for silence)
pusher Self-Hosted DEEPGRAM_SELF_HOSTED_ENABLED: "true" at dg.omi.me Fixed license (~fixed monthly)
pre-recorded Cloud only No self-hosted variant Per-second

All real-time streaming from devices goes through backend-listen → Cloud DG → billed per-second. VAD gate savings apply to 100% of real-time streaming traffic.

Self-hosted DG (pusher only): Nova-3 release-251210, engine min 1 / max 10 replicas, 60 streaming requests/pod, GPU nodes. Recently scaled down (PR #4811, merged Feb 15 — min replicas 3→1).

Config files:

  • backend/charts/backend-listen/prod_omi_backend_listen_values.yaml:223-226
  • backend/charts/pusher/prod_omi_pusher_values.yaml:232-235
  • backend/charts/deepgram-self-hosted/nova-3/prod_omi_values.yaml

Proposed Fix

Insert server-side Silero VAD check before sending audio to DG WebSocket. Skip or replace silence chunks so DG bills less.

Current path (backend-listen):

App → WebSocket → backend decodes audio → stt_audio_buffer.extend(data) → dg_socket.send(chunk)

With VAD gate:

App → WebSocket → backend decodes audio → VAD check → send only if speech → dg_socket.send(chunk)

Insertion point — transcribe.py:1873-1875 (before stt_audio_buffer.extend(data)). The flush_stt_buffer() at :1754-1783 routes audio to DG via dg_socket.send(chunk) at :1770.

Existing VAD code — utils/stt/vad.py:14-15: Silero VAD model already loaded globally at module import. However, is_speech_present() (:23-49) resets state every call — not suitable for streaming. Needs new stateful per-session VAD class.

Savings Estimate

Since backend-listen is 100% cloud-hosted, VAD gate applies to all real-time streaming hours:

  • Conservative (50% VAD effectiveness): ~10% of total DG spend
  • Moderate (70% effectiveness): ~15-19% of total DG spend
  • Aggressive (80% effectiveness): ~20%+ of total DG spend

Note: Self-hosted (pusher) has fixed license cost — VAD gate there would save GPU capacity but not billing. Focus is on backend-listen.

Risk Matrix

Risk Severity Detail
Timestamp drift CRITICAL DG timestamps assume continuous audio. Skipping silence compresses the timeline. Code at :1515 and :1524-1529 applies linear offset. Speaker ID ring buffer extraction at :1352-1384 uses abs_start/abs_end from :1612-1615 — would extract wrong audio if timestamps are compressed.
DG connection timeout HIGH keepalive: "true" (streaming.py:286) is TCP-level only. DG hosted connections timeout after ~30s without audio data. Extended silence → connection drop.
Endpointing breakage HIGH endpointing=300 (streaming.py:445) triggers utterance end on 300ms silence. VAD gaps inject artificial boundaries, splitting utterances. Segment merging (:120, gap < 3s) may recover some but not all.
CPU overhead LOW Silero ~5-10ms per 30ms chunk. At ~175 concurrent streams, needs asyncio.to_thread() wrapping or will block event loop.

Note: "Self-hosted routing" is NOT a risk — backend-listen and pusher are separate deployments with separate env vars. No per-session routing needed.

Implementation Plan

Phase 1: Shadow Mode (zero risk)

  • Add VAD check at insertion point but do NOT skip any audio — log only
  • Log: {session_id, chunk_timestamp, vad_result, chunk_bytes}
  • Measure actual silence ratio, VAD latency, boundary accuracy, CPU impact
  • Deliverables: per-session VADGateState class, shadow logging, VAD_SHADOW_MODE=true feature flag

Phase 2: VAD Gate (after shadow data confirms)

  • Pre-roll buffer: 300-500ms before speech detection fires (prevent clipping word starts)
  • Hangover timer: 600-1000ms after speech ends (prevent trailing phoneme loss)
  • Timestamp remapping: Cumulative silence gap tracker per session, remap DG timestamps at :1524
  • DG keepalive during silence: Periodic minimal audio frames to prevent connection timeout
  • Gradual rollout: Feature flag 5% → 25% → 100%, monitor transcription quality

Phase 3: Optimization

  • Threshold tuning from shadow data
  • Diarization quality evaluation with context gaps
  • Evaluate whether pusher could also benefit (GPU capacity savings on self-hosted)

Key Decision: Skip Silence vs Send Comfort Noise

Approach Savings Complexity Risk
Skip chunks entirely Maximum High — requires timestamp remapping at :1515, :1524-1529, :1612-1615, ring buffer Timestamp drift, endpointing breakage
Send comfort noise ~50-70% of skip Low — timestamps stay aligned, no remapping needed Minimal — DG processes low-amplitude frames correctly

Recommendation: Start with comfort noise for Phase 2. Graduate to full skip only if shadow data shows remaining cost justifies timestamp remapping work.

Data Sources

  • DG Usage API, DG Requests API, BigQuery hourly_usage_raw
  • Helm charts: backend/charts/backend-listen/, backend/charts/pusher/, backend/charts/deepgram-self-hosted/
  • Backend code: main @ ce4f2255c
  • Analysis: @mon (data) + @Chen (code deep dive, infra audit)

Activity

  1. added
    capture
    p1
    on Feb 6, 2026
  2. beastoin commented on Feb 6, 2026

    @beastoin
    CollaboratorAuthor

    📝 The proposed solution here is based on data analysis and has not been verified by the CTO. If you have a better approach to address this, feel free to propose it.

  3. beastoin commented on Feb 20, 2026

    @beastoin
    CollaboratorAuthor

    Deep Dive: Server-Side VAD Gate Implementation

    Updated Data (Jan 2026, BigQuery hourly_usage_raw)

    162,429 streaming hours across 219K sessions. Average WPM: 27.3 (normal speech ≈ 130 WPM), implying ~79% of streaming time is non-speech.

    Speech Density % of Hours Est. Silence Description
    0-5 WPM 19.2% (31,166h) ~98% Dead air — wearable on, nobody talking
    5-15 WPM 11.8% (19,110h) ~92% Very sparse speech
    15-30 WPM 11.0% (17,799h) ~83% Light/intermittent
    30-60 WPM 13.4% (21,831h) ~65% Moderate conversation
    60-100 WPM 9.7% (15,760h) ~38% Active conversation
    100-130 WPM 4.1% (6,721h) ~12% Dense conversation
    130+ WPM 30.8% (50,042h) ~0% Very dense speech

    41.9% of all hours are below 30 WPM — mostly silence being billed per-second.

    Hosted vs self-hosted split (from 15K request sample): 55.9% of streaming hours = hosted (billed per-second). VAD savings only apply to the hosted portion. Estimated savings: 13-21% of total DG spend depending on VAD effectiveness.


    Code Deep Dive

    Insertion point — transcribe.py:1873-1875:

    if not use_custom_stt:
        stt_audio_buffer.extend(data)
        await flush_stt_buffer()

    VAD check goes BEFORE stt_audio_buffer.extend(data). The flush_stt_buffer() function at :1754-1783 routes audio to DG via dg_socket.send(chunk) at :1770.

    Existing VAD code — utils/stt/vad.py:14-15: Silero VAD model is already loaded globally at module import. However:

    • is_speech_present() (:23-49) calls vad_iterator.reset_states() on every invocation — not suitable for streaming (needs stateful operation across chunks within a session)
    • Production VAD actually uses a hosted API (HOSTED_VAD_API_URL) at :72, not the local model
    • torch.set_num_threads(1) at :12 — single-threaded, would serialize if called synchronously across concurrent streams

    Risk Matrix

    Risk Severity Detail
    Timestamp drift CRITICAL DG returns timestamps relative to audio received. Skipping silence compresses the timeline. Code at :1515 (first_audio_byte_timestamp + segments[0]["start"]) and :1524-1529 (linear offset) assumes continuous audio. Speaker ID ring buffer extraction at :1352-1384 uses abs_start/abs_end computed at :1612-1615 — would extract wrong audio if timestamps are compressed.
    DG connection timeout HIGH keepalive: "true" at streaming.py:286 is TCP-level keepalive only. DG hosted connections timeout after ~30s without audio data. Extended silence → connection drop → session restart.
    Endpointing breakage HIGH DG endpointing=300 at streaming.py:445 triggers utterance end on 300ms silence. VAD gaps inject artificial silence boundaries, splitting single utterances into multiple segments. Segment merging (:120, b.start - a.end < 3) may recover some but not all.
    Self-hosted routing MODERATE is_dg_self_hosted at streaming.py:285 is a global env var, not per-session. Can't selectively enable VAD for hosted-only sessions without code changes.
    CPU overhead LOW Silero VAD: ~5-10ms per 30ms chunk. At ~175 concurrent streams in async event loop, needs asyncio.to_thread() wrapping or will block.

    Implementation Plan

    Phase 1: Shadow Mode (zero risk, 1-2 weeks)

    Add VAD check at the insertion point but do NOT skip any audio — log results only.

    # At transcribe.py:1873, before stt_audio_buffer.extend(data)
    if vad_shadow_enabled:
        is_speech = session_vad.check(data)  # Stateful per-session VAD
        vad_logger.log(session_id, chunk_ts, is_speech, len(data))

    What we measure:

    • Actual silence ratio per session (validate against BQ WPM estimates)
    • VAD latency per chunk (confirm <10ms)
    • Speech boundary accuracy (compare VAD speech/silence transitions against DG transcript timing)
    • CPU impact at scale (monitor event loop lag)

    Deliverables:

    • Per-session VADGateState class with stateful Silero iterator (no reset_states() per call)
    • Shadow logging to structured logs (session_id, timestamp, vad_result, chunk_bytes)
    • Feature flag: VAD_SHADOW_MODE=true env var
    • Dashboard/query to analyze shadow data

    Phase 2: VAD Gate (after shadow data confirms estimates)

    • Pre-roll buffer: 300-500ms of audio buffered before speech detection fires, sent with first speech chunk (prevents clipping word starts)
    • Hangover timer: 600-1000ms of continued sending after speech ends (prevents trailing phoneme loss)
    • Timestamp remapping layer: Maintain cumulative silence gap tracker per session. When DG returns timestamps, add back the accumulated silence gaps before time_offset calculation at :1524
    • DG keepalive during silence: Send periodic empty/minimal audio frames (not billed if below threshold) to prevent connection timeout
    • Gradual rollout: Feature flag with percentage (5% → 25% → 100%), monitoring WER proxy (words per session before/after)

    Phase 3: Optimization

    • Selective hosted-only gating (requires per-session routing refactor)
    • Tune thresholds based on shadow data
    • Evaluate whether diarization quality degrades with context gaps

    Key Decision: Skip Silence vs Send Silence

    Two approaches to VAD gating:

    1. Skip chunks entirely — Maximum cost savings, but requires timestamp remapping everywhere (:1515, :1524-1529, :1612-1615, ring buffer extraction). High implementation complexity.

    2. Send comfort noise / minimal audio — Send low-amplitude frames during silence. DG still processes them (some cost) but timestamps stay aligned. Lower savings (~50-70% of approach 1) but dramatically simpler and safer.

    Recommendation: Start with approach 2 for Phase 2 (send minimal audio during detected silence). Graduate to approach 1 only if shadow data shows the remaining cost is significant enough to justify the timestamp remapping work.


    Analysis: @mon (BQ data, DG billing research) + @Chen (code deep dive, risk assessment)
    Data sources: DG Usage API, DG Requests API, BigQuery hourly_usage_raw, backend code (main @ ce4f225)

  4. changed the title [-]Auto-pause Deepgram streaming on silent connections to reduce transcription waste[/-] [+]Server-side VAD gate: skip silence before Deepgram send to reduce streaming cost[/+] on Feb 20, 2026
  5. beastoin commented on Feb 22, 2026

    @beastoin
    CollaboratorAuthor

    Deep Analysis: Verified Implementation Plan

    Traced the full audio path, ran empirical DG WebSocket tests with real speech audio, and verified billing via the DG Usage API. Key findings below.

    Verified Audio Path

    WebSocket → codec decode (opus/aac/lc3/pcm) → ring buffer (wall-clock timestamps)
      → stt_audio_buffer.extend() → flush_stt_buffer() → dg_socket.send(chunk)
    

    Insertion point: Between ring buffer write (transcribe.py:1871) and STT buffer extend (transcribe.py:1874). Ring buffer always gets all audio (speaker ID needs it). VAD gate only controls what reaches DG.

    Key Discovery: DG KeepAlive Protocol

    DG has an official KeepAlive feature designed for this use case:

    Feature Detail
    Message format {"type": "KeepAlive"} (text WebSocket frame)
    Timeout 10 seconds without audio or KeepAlive (not 30s as originally assumed)
    Billing Not billed (verified via DG Usage API — see test results below)
    Timestamps Continue from where audio paused, not from KeepAlive time
    SDK support Already enabled in codebase (keepalive: "true" at streaming.py:286), auto-sends every 5s
    Finalize {"type": "Finalize"} flushes DG transcript buffer on demand

    Empirical Test Results (4 tests, real speech audio via gTTS)

    Test: Timestamp Compression — CONFIRMED

    • Sent speech, then 10s KeepAlive (no audio), then more speech
    • DG timestamps compressed by ~8.6s — second speech started at DG_time ~7.3s instead of ~17s
    • Remapping is required: real_time = dg_time + cumulative_skipped_silence

    Test: Endpointing During KeepAlive — DOES NOT FIRE

    • 0 UtteranceEnd events during 5s KeepAlive pause
    • DG's endpointing=300 relies on audio silence detection; KeepAlive messages are invisible to it
    • {"type": "Finalize"} is required on speech→silence transition to flush pending transcript

    Test: Finalize — WORKS (0.2s flush)

    • Sending Finalize immediately after speech → remaining transcript delivered in ~0.2s

    Test: Billing Comparison — VERIFIED via DG Usage API

    Silence as audio (current) KeepAlive (proposed) Reduction
    Audio sent 23.3s 13.3s -43%
    DG billed duration 23.27s 13.27s -43%
    Wall clock ~23.7s ~23.7s same

    The ~10s of KeepAlive was completely invisible to billing. DG billed exactly the audio data received.

    Issue Corrections

    Original Claim Verified Reality
    DG timeout is 30s+ 10 seconds (DG docs)
    Comfort noise saves 50-70% $0 savings — DG bills per audio-second regardless of amplitude
    Need manual KeepAlive sends SDK already auto-sends every 5s (keepalive: "true" enabled)
    Segment merging 3s gap threshold 30 seconds gap threshold in conversations.py
    Endpointing works during gaps Does NOT fire during KeepAlive (0 events)

    Architecture: Dual-Timeline (Codex-verified)

    • Ring buffer: Untouched — stores ALL audio with real wall-clock timestamps (for speaker ID)
    • DG stream: Receives only speech audio (compressed timeline)
    • Timestamp mapper: Append-only checkpoint list with binary search, converts DG compressed time → real time
    # On each silence→speech transition, record checkpoint:
    checkpoints.append((current_dg_time, cumulative_real_seconds_skipped))
    
    # Remap: real_time = dg_time + offset_at(dg_time) via bisect_right
    # Applied at speaker ID abs_start/abs_end calculation (transcribe.py:1612-1615)

    Risk Matrix

    Risk Severity Mitigation
    Timestamp drift → speaker ID fails CRITICAL Breakpoint map remaps DG→real time; ring buffer untouched
    DG connection timeout (10s) HIGH SDK auto-KeepAlive every 5s (already enabled)
    Endpointing doesn't fire during KeepAlive HIGH Send Finalize on speech→silence transition
    Word-start clipping MEDIUM 400ms pre-roll buffer
    Trailing phoneme loss MEDIUM 300ms hangover timer
    CPU overhead (Silero VAD) LOW ~5-10ms per 30ms chunk; asyncio.to_thread() if needed

    Implementation Plan

    Phase 1 — Shadow Mode (~1 week, zero risk):
    Add VADStreamingGate class. Log VAD decisions at insertion point but send ALL audio as before. Measure actual silence ratio, VAD latency, false negative rate. Feature flag: VAD_GATE_MODE=shadow.

    Phase 2 — Active Gate (~2 weeks):
    Gate audio: skip silence → SDK KeepAlive keeps connection → send Finalize on speech→silence → timestamp remapping via checkpoint list. Gradual rollout: 5% → 25% → 100%.

    Phase 3 — Tuning (~1 week):
    Optimize pre-roll (300-500ms) and hangover (250-400ms) from production data. Evaluate diarization quality with gaps.

    Estimated Savings

    With ~79% of streaming time being silence (27.3 avg WPM vs 130 WPM normal speech):

    • Conservative (50% VAD effectiveness): ~26% reduction in cloud streaming spend
    • Moderate (70% effectiveness): ~36% reduction
    • Aggressive (80% effectiveness): ~41% reduction

    Applied to backend-listen hosted streaming only. Self-hosted (pusher) has fixed license cost.


    by AI for @beastoin

  6. beastoin commented on Feb 22, 2026

    @beastoin
    CollaboratorAuthor

    Verification Scripts

    Reproducible scripts used for the empirical testing above. Requires pip install websockets httpx and DEEPGRAM_API_KEY env var.

    Audio setup — generate two short speech WAV files (16kHz mono PCM16):

    pip install gTTS pydub
    python3 -c "
    from gtts import gTTS
    from pydub import AudioSegment
    import io
    
    for text, path in [
        ('The quick brown fox jumps over the lazy dog. This is a test of speech recognition.', '/tmp/speech_before.wav'),
        ('After a long pause, the speaker returns with new information about the topic.', '/tmp/speech_after.wav'),
    ]:
        mp3_buf = io.BytesIO()
        gTTS(text=text, lang='en').write_to_fp(mp3_buf)
        mp3_buf.seek(0)
        AudioSegment.from_mp3(mp3_buf).set_frame_rate(16000).set_channels(1).set_sample_width(2).export(path, format='wav')
        print(f'Generated {path}')
    "

    Script 1: vad-gate-verify-v2.py — Behavior verification (4 tests)

    Tests: timestamp compression, endpointing during KeepAlive, Finalize behavior, silence-vs-KeepAlive comparison.

    # Run all tests
    DEEPGRAM_API_KEY=your_key python3 vad-gate-verify-v2.py all
    
    # Run individual test (2=timestamps, 3=endpointing, 4=finalize, 5=compare)
    DEEPGRAM_API_KEY=your_key python3 vad-gate-verify-v2.py 2
    vad-gate-verify-v2.py (click to expand)
    #!/usr/bin/env python3
    """
    VAD Gate Verification Script v2 — Issue #4644
    Uses REAL speech audio (gTTS) to test DG behavior with KeepAlive gaps.
    """
    
    import asyncio
    import json
    import os
    import sys
    import time
    import wave
    from dataclasses import dataclass, field
    from typing import List, Optional
    
    try:
        import websockets
    except ImportError:
        os.system(f"{sys.executable} -m pip install websockets -q")
        import websockets
    
    DG_API_KEY = os.environ.get("DEEPGRAM_API_KEY")
    SAMPLE_RATE = 16000
    CHUNK_MS = 30
    BYTES_PER_CHUNK = int(SAMPLE_RATE * 2 * CHUNK_MS / 1000)  # 960 bytes
    
    
    def load_wav(path: str) -> bytes:
        with wave.open(path, 'rb') as wf:
            assert wf.getframerate() == SAMPLE_RATE, f"Expected {SAMPLE_RATE}Hz, got {wf.getframerate()}"
            assert wf.getnchannels() == 1, f"Expected mono, got {wf.getnchannels()}"
            return wf.readframes(wf.getnframes())
    
    
    @dataclass
    class Event:
        wall_time: float
        event_type: str
        text: str = ""
        dg_start: Optional[float] = None
        dg_end: Optional[float] = None
        words: List[dict] = field(default_factory=list)
        raw: dict = field(default_factory=dict)
    
    
    class DGClient:
        def __init__(self):
            self.events: List[Event] = []
            self.ws = None
            self.t0 = 0.0
            self.audio_sent_s = 0.0
            self._recv_task = None
    
        async def connect(self, endpointing=300):
            params = (f"encoding=linear16&sample_rate={SAMPLE_RATE}&channels=1"
                      f"&punctuate=true&endpointing={endpointing}&diarize=true"
                      f"&smart_format=true&no_delay=true&interim_results=false")
            url = f"wss://api.deepgram.com/v1/listen?{params}"
            self.ws = await websockets.connect(url, additional_headers={"Authorization": f"Token {DG_API_KEY}"})
            self.t0 = time.time()
            self._recv_task = asyncio.create_task(self._recv())
            self._log("CONNECT", "connected")
    
        async def _recv(self):
            try:
                async for msg in self.ws:
                    if not isinstance(msg, str):
                        continue
                    data = json.loads(msg)
                    t = data.get("type", "?")
                    wall = time.time() - self.t0
    
                    if t == "Results":
                        alt = data.get("channel", {}).get("alternatives", [{}])[0]
                        text = alt.get("transcript", "")
                        words = alt.get("words", [])
                        is_final = data.get("is_final", False)
                        if text.strip():
                            dg_start = words[0]["start"] if words else None
                            dg_end = words[-1]["end"] if words else None
                            evt = Event(wall, "transcript", text, dg_start, dg_end, words, data)
                            self.events.append(evt)
                            self._log("TRANSCRIPT",
                                      f"DG={dg_start:.3f}-{dg_end:.3f}s final={is_final} \"{text}\"")
                        elif is_final:
                            self.events.append(Event(wall, "empty_final"))
    
                    elif t == "UtteranceEnd":
                        self.events.append(Event(wall, "utterance_end"))
                        self._log("UTTERANCE_END", "")
    
                    elif t == "SpeechStarted":
                        self.events.append(Event(wall, "speech_started"))
                        self._log("SPEECH_STARTED", "")
    
                    elif t == "Metadata":
                        self._log("METADATA", f"req_id={data.get('request_id','?')[:12]}")
    
                    elif "error" in str(data).lower():
                        self._log("ERROR", str(data)[:200])
    
            except websockets.exceptions.ConnectionClosed as e:
                self._log("CLOSED", f"code={e.code}")
    
        def _log(self, tag: str, msg: str):
            wall = time.time() - self.t0 if self.t0 else 0
            print(f"  [{tag:>15}] t={wall:7.3f}s | {msg}")
    
        async def send_audio(self, pcm: bytes, label: str = "audio"):
            """Send audio in real-time chunks."""
            offset = 0
            n = 0
            while offset < len(pcm):
                chunk = pcm[offset:offset + BYTES_PER_CHUNK]
                await self.ws.send(chunk)
                offset += BYTES_PER_CHUNK
                n += 1
                self.audio_sent_s += CHUNK_MS / 1000
                await asyncio.sleep(CHUNK_MS / 1000)
            self._log("SEND", f"{label}: {n} chunks ({self.audio_sent_s:.2f}s total audio)")
    
        async def keepalive(self, duration_s: float, interval_s: float = 3.0):
            """Send KeepAlive messages (no audio) for duration."""
            self._log("KA_START", f"pausing audio for {duration_s}s")
            start = time.time()
            count = 0
            while (time.time() - start) < duration_s:
                await self.ws.send(json.dumps({"type": "KeepAlive"}))
                count += 1
                remaining = duration_s - (time.time() - start)
                if remaining > 0:
                    await asyncio.sleep(min(interval_s, remaining))
            self._log("KA_END", f"sent {count} KeepAlive over {time.time()-start:.1f}s")
    
        async def finalize(self):
            self._log("FINALIZE", "sending Finalize")
            await self.ws.send(json.dumps({"type": "Finalize"}))
    
        async def close(self):
            try:
                await self.ws.send(json.dumps({"type": "CloseStream"}))
            except:
                pass
            await asyncio.sleep(1.5)
            if self._recv_task:
                self._recv_task.cancel()
                try:
                    await self._recv_task
                except asyncio.CancelledError:
                    pass
    
    
    def analyze(client: DGClient, test_name: str):
        print(f"\n{'='*70}")
        print(f"ANALYSIS: {test_name}")
        print(f"{'='*70}")
        print(f"  Audio sent to DG: {client.audio_sent_s:.2f}s")
        print(f"  Real wall time:   {time.time() - client.t0:.2f}s")
    
        transcripts = [e for e in client.events if e.event_type == "transcript"]
        utt_ends = [e for e in client.events if e.event_type == "utterance_end"]
        speech_starts = [e for e in client.events if e.event_type == "speech_started"]
    
        print(f"  Transcripts:      {len(transcripts)}")
        print(f"  UtteranceEnds:    {len(utt_ends)}")
        print(f"  SpeechStarted:    {len(speech_starts)}")
    
        for i, t in enumerate(transcripts):
            print(f"  [{i}] DG={t.dg_start:.3f}-{t.dg_end:.3f}s wall={t.wall_time:.3f}s "
                  f"\"{t.text[:70]}\"")
    
        if len(transcripts) >= 2:
            first, last = transcripts[0], transcripts[-1]
            dg_span = last.dg_end - first.dg_start
            wall_span = last.wall_time - first.wall_time
            print(f"\n  DG timestamp span:  {dg_span:.3f}s")
            print(f"  Wall clock span:    {wall_span:.3f}s")
            print(f"  Gap (wall - DG):    {wall_span - dg_span:.3f}s")
            if wall_span - dg_span > 2.0:
                print(f"  >>> TIMESTAMPS COMPRESSED: DG skipped {wall_span-dg_span:.1f}s of KeepAlive time")
            else:
                print(f"  >>> TIMESTAMPS ALIGNED with wall clock")
    
    
    async def test_2_keepalive_timestamp():
        """KEY TEST: Do timestamps compress during KeepAlive?"""
        print(f"\n{'='*70}")
        print("TEST 2: KEEPALIVE GAP — Speech -> KeepAlive 10s -> Speech")
        print("QUESTION: Does DG timestamp compress or stay aligned?")
        print(f"{'='*70}")
    
        speech1 = load_wav("/tmp/speech_before.wav")
        speech2 = load_wav("/tmp/speech_after.wav")
    
        c = DGClient()
        await c.connect()
        await c.send_audio(speech1, "speech_before_gap")
        await c.keepalive(10, interval_s=3)
        await c.send_audio(speech2, "speech_after_gap")
        await asyncio.sleep(3)
        await c.close()
        analyze(c, "KeepAlive Timestamp Test")
    
    
    async def test_3_endpointing():
        """Does endpointing trigger during KeepAlive?"""
        print(f"\n{'='*70}")
        print("TEST 3: ENDPOINTING — Does UtteranceEnd fire during KeepAlive?")
        print(f"{'='*70}")
    
        speech = load_wav("/tmp/speech_before.wav")
    
        c = DGClient()
        await c.connect(endpointing=300)
        await c.send_audio(speech, "speech")
        await c.keepalive(5, interval_s=2)
        await asyncio.sleep(2)
        await c.close()
    
        utt_ends = [e for e in c.events if e.event_type == "utterance_end"]
        print(f"\n  RESULT: {len(utt_ends)} UtteranceEnd events")
        if utt_ends:
            print("  >>> ENDPOINTING WORKS during KeepAlive")
        else:
            print("  >>> ENDPOINTING DOES NOT fire during KeepAlive")
        analyze(c, "Endpointing Test")
    
    
    async def test_4_finalize():
        """Does Finalize flush the transcript?"""
        print(f"\n{'='*70}")
        print("TEST 4: FINALIZE — Send speech, Finalize, then more speech")
        print(f"{'='*70}")
    
        speech1 = load_wav("/tmp/speech_before.wav")
        speech2 = load_wav("/tmp/speech_after.wav")
    
        c = DGClient()
        await c.connect()
        await c.send_audio(speech1, "speech_1")
        await c.finalize()
        await asyncio.sleep(2)
        await c.send_audio(speech2, "speech_2")
        await asyncio.sleep(3)
        await c.close()
        analyze(c, "Finalize Test")
    
    
    async def test_5_compare():
        """Compare: silence audio (billed) vs KeepAlive (free)."""
        print(f"\n{'='*70}")
        print("TEST 5: COMPARE — Silence audio vs KeepAlive (side by side)")
        print(f"{'='*70}")
    
        speech1 = load_wav("/tmp/speech_before.wav")
        speech2 = load_wav("/tmp/speech_after.wav")
        silence_5s = b'\x00\x00' * (SAMPLE_RATE * 5)
    
        print("\n  --- 5A: Sending actual silence audio (BILLED) ---")
        ca = DGClient()
        await ca.connect()
        await ca.send_audio(speech1, "speech_1")
        await ca.send_audio(silence_5s, "silence_5s")
        await ca.send_audio(speech2, "speech_2")
        await asyncio.sleep(3)
        await ca.close()
        analyze(ca, "5A: Silence Audio (billed)")
    
        await asyncio.sleep(2)
    
        print("\n  --- 5B: Sending KeepAlive instead (FREE) ---")
        cb = DGClient()
        await cb.connect()
        await cb.send_audio(speech1, "speech_1")
        await cb.keepalive(5, interval_s=2)
        await cb.send_audio(speech2, "speech_2")
        await asyncio.sleep(3)
        await cb.close()
        analyze(cb, "5B: KeepAlive (free)")
    
        print(f"\n{'='*70}")
        print("BILLING COMPARISON:")
        print(f"  5A (silence audio): {ca.audio_sent_s:.2f}s billed")
        print(f"  5B (KeepAlive):     {cb.audio_sent_s:.2f}s billed")
        saving = ca.audio_sent_s - cb.audio_sent_s
        pct = (saving / ca.audio_sent_s * 100) if ca.audio_sent_s > 0 else 0
        print(f"  Savings:            {saving:.2f}s ({pct:.0f}%)")
    
    
    async def main():
        print("VAD GATE VERIFICATION v2 — Real Speech Audio")
        assert DG_API_KEY, "Set DEEPGRAM_API_KEY env var"
    
        tests = {"2": test_2_keepalive_timestamp, "3": test_3_endpointing,
                 "4": test_4_finalize, "5": test_5_compare}
    
        which = sys.argv[1] if len(sys.argv) > 1 else "all"
        if which == "all":
            for k in sorted(tests):
                try:
                    await tests[k]()
                except Exception as e:
                    print(f"\nTEST {k} FAILED: {e}")
                    import traceback; traceback.print_exc()
                await asyncio.sleep(2)
        elif which in tests:
            await tests[which]()
        else:
            print(f"Usage: {sys.argv[0]} [2|3|4|5|all]")
    
    if __name__ == "__main__":
        asyncio.run(main())

    Script 2: vad-billing-verify.py — Billing verification via Usage API

    Runs two DG sessions (silence audio vs KeepAlive), then queries DG Usage API to compare billed duration.

    # Requires a DG key with usage:read scope
    DEEPGRAM_API_KEY=your_key python3 vad-billing-verify.py
    vad-billing-verify.py (click to expand)
    #!/usr/bin/env python3
    """
    VAD Gate BILLING Verification — Issue #4644
    
    Runs two DG requests:
      A) Speech + silence audio (continuous stream, fully billed)
      B) Speech + KeepAlive (no silence audio sent)
    
    Then queries DG Usage API to compare reported duration per request.
    If KeepAlive is truly free, request B should report less duration than A.
    """
    
    import asyncio
    import json
    import os
    import sys
    import time
    import wave
    
    try:
        import websockets
    except ImportError:
        os.system(f"{sys.executable} -m pip install websockets -q")
        import websockets
    
    try:
        import httpx
    except ImportError:
        os.system(f"{sys.executable} -m pip install httpx -q")
        import httpx
    
    DG_API_KEY = os.environ.get("DEEPGRAM_API_KEY")
    SAMPLE_RATE = 16000
    CHUNK_MS = 30
    BYTES_PER_CHUNK = int(SAMPLE_RATE * 2 * CHUNK_MS / 1000)
    
    
    def load_wav(path):
        with wave.open(path, 'rb') as wf:
            return wf.readframes(wf.getnframes())
    
    
    async def run_dg_session(label: str, speech_before: bytes, gap_mode: str,
                              gap_duration_s: float, speech_after: bytes) -> dict:
        """Run a DG session and return request_id + audio stats."""
        params = (f"encoding=linear16&sample_rate={SAMPLE_RATE}&channels=1"
                  f"&punctuate=true&endpointing=300&diarize=false"
                  f"&smart_format=true&no_delay=true&interim_results=false")
        url = f"wss://api.deepgram.com/v1/listen?{params}"
        headers = {"Authorization": f"Token {DG_API_KEY}"}
    
        request_id = None
        audio_sent_s = 0.0
    
        async with websockets.connect(url, additional_headers=headers) as ws:
            async def recv():
                nonlocal request_id
                async for msg in ws:
                    if isinstance(msg, str):
                        data = json.loads(msg)
                        if data.get("type") == "Metadata":
                            request_id = data.get("request_id")
                            print(f"  [{label}] Got request_id: {request_id}")
    
            recv_task = asyncio.create_task(recv())
    
            offset = 0
            while offset < len(speech_before):
                chunk = speech_before[offset:offset + BYTES_PER_CHUNK]
                await ws.send(chunk)
                offset += BYTES_PER_CHUNK
                audio_sent_s += CHUNK_MS / 1000
                await asyncio.sleep(CHUNK_MS / 1000)
            print(f"  [{label}] Sent speech_before: {audio_sent_s:.2f}s audio")
    
            if gap_mode == "silence_audio":
                silence = b'\x00\x00' * int(SAMPLE_RATE * gap_duration_s)
                offset = 0
                while offset < len(silence):
                    chunk = silence[offset:offset + BYTES_PER_CHUNK]
                    await ws.send(chunk)
                    offset += BYTES_PER_CHUNK
                    audio_sent_s += CHUNK_MS / 1000
                    await asyncio.sleep(CHUNK_MS / 1000)
                print(f"  [{label}] Sent silence audio: {gap_duration_s}s ({audio_sent_s:.2f}s total)")
            elif gap_mode == "keepalive":
                start = time.time()
                ka_count = 0
                while (time.time() - start) < gap_duration_s:
                    await ws.send(json.dumps({"type": "KeepAlive"}))
                    ka_count += 1
                    remaining = gap_duration_s - (time.time() - start)
                    if remaining > 0:
                        await asyncio.sleep(min(3.0, remaining))
                print(f"  [{label}] Sent {ka_count} KeepAlive over {gap_duration_s}s ({audio_sent_s:.2f}s total audio)")
    
            offset = 0
            before_after = audio_sent_s
            while offset < len(speech_after):
                chunk = speech_after[offset:offset + BYTES_PER_CHUNK]
                await ws.send(chunk)
                offset += BYTES_PER_CHUNK
                audio_sent_s += CHUNK_MS / 1000
                await asyncio.sleep(CHUNK_MS / 1000)
            print(f"  [{label}] Sent speech_after: {audio_sent_s - before_after:.2f}s ({audio_sent_s:.2f}s total)")
    
            await ws.send(json.dumps({"type": "CloseStream"}))
            await asyncio.sleep(2)
            recv_task.cancel()
            try:
                await recv_task
            except asyncio.CancelledError:
                pass
    
        return {
            "label": label,
            "request_id": request_id,
            "audio_sent_s": audio_sent_s,
            "gap_mode": gap_mode,
            "gap_duration_s": gap_duration_s,
        }
    
    
    async def query_dg_usage(request_id: str) -> dict:
        """Query DG Usage API for a specific request."""
        url = f"https://api.deepgram.com/v1/usage/requests/{request_id}"
        headers = {"Authorization": f"Token {DG_API_KEY}"}
    
        async with httpx.AsyncClient() as client:
            resp = await client.get(url, headers=headers, timeout=30)
            if resp.status_code == 200:
                return resp.json()
            else:
                return {"error": resp.status_code, "body": resp.text[:500]}
    
    
    async def main():
        print("=" * 70)
        print("VAD GATE BILLING VERIFICATION — Issue #4644")
        print("=" * 70)
        assert DG_API_KEY, "Set DEEPGRAM_API_KEY env var (needs usage:read scope)"
    
        speech1 = load_wav("/tmp/speech_before.wav")
        speech2 = load_wav("/tmp/speech_after.wav")
        gap_s = 10
    
        print(f"\n--- Test A: Speech + {gap_s}s SILENCE AUDIO + Speech ---")
        result_a = await run_dg_session("A-silence", speech1, "silence_audio", gap_s, speech2)
    
        await asyncio.sleep(2)
    
        print(f"\n--- Test B: Speech + {gap_s}s KEEPALIVE + Speech ---")
        result_b = await run_dg_session("B-keepalive", speech1, "keepalive", gap_s, speech2)
    
        print(f"\n{'='*70}")
        print("AUDIO SENT COMPARISON:")
        print(f"  Test A (silence audio): {result_a['audio_sent_s']:.2f}s audio data sent")
        print(f"  Test B (KeepAlive):     {result_b['audio_sent_s']:.2f}s audio data sent")
        print(f"  Difference:             {result_a['audio_sent_s'] - result_b['audio_sent_s']:.2f}s")
    
        print(f"\n{'='*70}")
        print("QUERYING DG USAGE API...")
        print("(Note: DG may take up to 1 hour to update usage. Trying immediately.)")
    
        for delay in [5, 30, 60]:
            print(f"\n  Waiting {delay}s before querying...")
            await asyncio.sleep(delay)
    
            usage_a = await query_dg_usage(result_a["request_id"]) if result_a["request_id"] else {"error": "no request_id"}
            usage_b = await query_dg_usage(result_b["request_id"]) if result_b["request_id"] else {"error": "no request_id"}
    
            print(f"\n  Test A ({result_a['request_id'][:12] if result_a['request_id'] else '?'}):")
            if "error" not in usage_a:
                duration_a = usage_a.get("duration", usage_a.get("response", {}).get("duration", "?"))
                print(f"    DG reported duration: {duration_a}")
                print(f"    Full response: {json.dumps(usage_a)[:500]}")
            else:
                print(f"    Error: {usage_a}")
    
            print(f"\n  Test B ({result_b['request_id'][:12] if result_b['request_id'] else '?'}):")
            if "error" not in usage_b:
                duration_b = usage_b.get("duration", usage_b.get("response", {}).get("duration", "?"))
                print(f"    DG reported duration: {duration_b}")
                print(f"    Full response: {json.dumps(usage_b)[:500]}")
            else:
                print(f"    Error: {usage_b}")
    
            if "error" not in usage_a and "error" not in usage_b:
                print(f"\n{'='*70}")
                print("BILLING VERDICT:")
                try:
                    dur_a = float(usage_a.get("duration", 0))
                    dur_b = float(usage_b.get("duration", 0))
                    if dur_a > 0 and dur_b > 0:
                        diff = dur_a - dur_b
                        print(f"  Test A duration: {dur_a:.2f}s")
                        print(f"  Test B duration: {dur_b:.2f}s")
                        print(f"  Difference:      {diff:.2f}s")
                        if diff > 2.0:
                            print(f"  >>> KEEPALIVE IS FREE: {diff:.1f}s less billed in Test B")
                        elif abs(diff) < 1.0:
                            print(f"  >>> KEEPALIVE IS BILLED SAME: No significant difference")
                        else:
                            print(f"  >>> INCONCLUSIVE: {diff:.1f}s difference")
                except (TypeError, ValueError):
                    print("  Could not parse durations for comparison")
                break
    
        results = {
            "test_a": result_a,
            "test_b": result_b,
            "usage_a_raw": usage_a if 'usage_a' in dir() else None,
            "usage_b_raw": usage_b if 'usage_b' in dir() else None,
        }
        with open("/tmp/vad-billing-results.json", "w") as f:
            json.dump(results, f, indent=2, default=str)
        print(f"\nRaw results saved to /tmp/vad-billing-results.json")
    
    
    if __name__ == "__main__":
        asyncio.run(main())

    by AI for @beastoin

  7. beastoin commented on Feb 22, 2026

    @beastoin
    CollaboratorAuthor

    Implementation Limitations Found (PR #4931)

    Post-implementation analysis found 8 limitations that affect quality and cost savings. Addressing before active-mode rollout.

    CRITICAL

    1. KeepAlive NOT implemented — Code docs say "silence skipped, KeepAlive sent instead" but keep_alive() is never called. When silence is skipped, nothing is sent to DG. DG's 30-second idle timeout will drop the connection mid-conversation if user is genuinely silent for 30s+. Transcripts are lost, conversation must reconnect.

    HIGH

    1. Speech threshold hardcoded to 0.5 — Silero VAD returns 0.0–1.0 probability; anything below 0.5 is classified as silence. Soft speakers, whispers, and accented speech at 0.45–0.49 get clipped. No VAD_GATE_SPEECH_THRESHOLD env var to tune per-deployment.

    2. Pre-roll depth varies with chunk size — Code assumes 30ms chunks for pre-roll buffer sizing. If actual chunks differ (20ms or 40ms), pre-roll depth is unpredictable (220ms–440ms instead of target 300ms).

    3. Speech profile disables gate for 80% of users — Gate is disabled entirely when preseconds > 0 (speech profile active). ~80% of users have speech profiles, so the gate never activates for most sessions. Cost savings drastically lower than projected. Need to activate gate AFTER profile phase completes.

    MEDIUM

    1. Checkpoint compaction loses early timestamps — Capped at 500 checkpoints. Long sessions (4+ hours) drop old checkpoints; late DG transcripts referencing early segments get inaccurate timestamp remapping. No auxiliary time-based checkpoints.

    2. Finalize exceptions swallowed silently — except Exception: pass on finalize means failed flushes lose transcript chunks with zero visibility. No metric, no log.

    3. VAD buffer truncation — If incoming audio doesn't align to 512-sample VAD windows, buffer truncates to last 512 samples. Up to 32ms of audio context lost, degrading VAD accuracy on speech onset.

    4. No cost/quality production metrics — Gate tracks local silence ratio but nothing correlates with actual DG billing. No dg_audio_bytes_skipped counter, no WER tracking. PR claims ~43% reduction but no prod telemetry to confirm.

    Working on fixes for all items. Priority: #4 (preseconds bypass), #1 (keepalive), #2 (threshold tunability).


    by AI for @beastoin

  8. self-assigned this
    on Feb 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

capturep1

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions