Skip to content

fix(sync): treat empty DG transcription as success, not error (#6100) - #6106

Merged
beastoin merged 6 commits into
mainfrom
fix/sync-empty-dg-6100
Mar 28, 2026
Merged

beastoin merged 6 commits into
mainfrom
fix/sync-empty-dg-6100

Conversation

@beastoin

@beastoin beastoin commented Mar 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #6100 — backend-sync returns 500 instead of 207 when Deepgram returns empty transcription.

Root cause: deepgram_prerecorded returned ([], lang) for BOTH "no speech detected" (valid success) AND "failure after 3 retries" (real error), making them indistinguishable. process_segment treated all empty results as errors, causing false 500s for silence/noise audio.

Fix:

  • deepgram_prerecorded now raises RuntimeError on retry exhaustion (consistent with deepgram_prerecorded_from_bytes)
  • process_segment treats empty DG words as success (silence/noise), not error
  • utils/chat.py voice message functions wrapped with try/except RuntimeError to preserve graceful failure
  • Status code matrix: all-silent→200, mixed→207, all-failed→500

Changes

File Change
backend/utils/stt/pre_recorded.py Retry exhaustion raises RuntimeError instead of returning []
backend/routers/sync.py Empty DG words treated as success, not error
backend/utils/chat.py Voice message functions handle RuntimeError from DG retry exhaustion
backend/tests/unit/test_sync_silent_failure.py Updated + new tests (40 total)

Callers of deepgram_prerecorded (exhaustive search via git grep)

Caller File Protected?
process_segment routers/sync.py:655 Yes — existing try/except (line 747)
transcribe_voice_message_segment utils/chat.py:72-79 Yes — new try/except added
process_voice_message_segment utils/chat.py:119 Yes — new try/except added
process_voice_message_segment_stream utils/chat.py:208 Yes — new try/except added

Test plan

  • 40/40 unit + behavioral tests passing
  • 7/7 L1 integration tests passing (runtime code paths with mocked DG)
  • L2 contract verification: app SyncLocalFilesResponse handles 200/207/500 correctly
  • Voice message callers verified — all 3 protected with try/except + tested
  • CI lint check passed
  • Reviewer: PR_APPROVED_LGTM (2 rounds — 2nd round after chat.py fix)
  • Tester: TESTS_APPROVED (40/40)

Deployment steps

This is a backend-only change (backend/ files). No app or desktop changes.

After merge to main:

  1. Auto-deploy to dev — gcp_backend_auto_dev.yml triggers automatically on push to main with backend/** changes
    # Verify dev deploy:
    gh run list --workflow=gcp_backend_auto_dev.yml --limit=3
  2. Verify on dev — confirm sync endpoint returns 200 for silent audio (was 500), voice messages still work
  3. Manual deploy to prod — after dev verification:
    gh workflow run gcp_backend.yml -f environment=prod -f branch=main
  4. Verify on prod — monitor sync endpoint logs for correct status codes, check voice message transcription still functional

Rollback plan:

  • If issues found: redeploy previous commit to prod:
    gh workflow run gcp_backend.yml -f environment=prod -f branch=<previous-commit-sha>
  • The change is backward-compatible — no app update required, no API contract changes

Checkpoints

CP Status
CP0-CP9B ✅ All complete
CP9C N/A (no remote infra deps)

Risks

  • fal_whisperx still silently returns [] on retry exhaustion (pre-existing, not in scope)

🤖 Generated with Claude Code

beastoin and others added 3 commits March 28, 2026 04:39
…#6100)

Previously returned [] on both "no speech" and "failure after retries",
making callers unable to distinguish success from failure. Now raises
RuntimeError on retry exhaustion, consistent with deepgram_prerecorded_from_bytes.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Empty Deepgram words now treated as successful-but-empty segment
(silence/noise audio) instead of appending to errors list. Real DG
failures raise RuntimeError and are caught by the existing except block.
Prevents false 500s when all segments contain only silence.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Updated structural tests, behavioral tests, and retry behavior tests
to match new semantics: empty DG words = success, retry exhaustion = raise.
33/33 tests passing.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@greptile-apps

greptile-apps Bot commented Mar 28, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a false 500 error in sync_local_files when Deepgram returns an empty transcription for silent or noise-only audio segments. The root cause was that deepgram_prerecorded used the same return value ([]) for both "no speech detected" (a valid success) and "failed after all retries" (a real error), making them indistinguishable in process_segment.

Key changes:

  • pre_recorded.py: Retry exhaustion now raises RuntimeError instead of silently returning [], making the failure signal unambiguous and consistent with deepgram_prerecorded_from_bytes.
  • sync.py: The if not words: branch in process_segment is demoted from an error path (appending to errors) to a silent-success path (return with an info log). Real DG failures propagate via RuntimeError and land in the existing except Exception block.
  • test_sync_silent_failure.py: All 33 tests updated to reflect the new semantics — empty-words = success, retry-exhaustion = RuntimeError.

The result matrix is now correct: silence → 200, mixed → 207, all real DG failures → 500.

Confidence Score: 5/5

Safe to merge — the fix is logically sound, well-tested, and the only callers of deepgram_prerecorded in production are covered.

All identified findings are P2 style suggestions (missing from e for exception chaining, one redundant test assertion). The core logic correctly distinguishes silence from real failures, the existing except Exception guard in process_segment catches the new RuntimeError, and 33 tests pass confirming the expected behavior across all outcome paths.

No files require special attention; backend/tests/unit/test_sync_silent_failure.py has a minor redundant assertion but nothing blocking.

Important Files Changed

Filename Overview
backend/utils/stt/pre_recorded.py Changed retry-exhaustion path from silently returning [] to raising RuntimeError; empty-word happy-path (silence) still returns []/([], lang) correctly. Minor: missing from e on the raise.
backend/routers/sync.py Empty words list now treated as a silent-audio success (logs info, returns early); real failures propagate via RuntimeError and are correctly caught by the existing except Exception block that appends to errors.
backend/tests/unit/test_sync_silent_failure.py 33 tests updated to match new semantics; assertions correctly verify errors is empty on silence and RuntimeError is raised on retry exhaustion. One redundant assertion in test_deepgram_keeps_empty_words_as_success.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[process_segment called] --> B[deepgram_prerecorded\nattempts=0]
    B --> C{DG API call}
    C -- success,\nwords found --> D[return words, lang]
    C -- success,\nno words silence --> E["return [], lang\n(valid empty)"]
    C -- exception --> F{attempts < 2?}
    F -- yes --> G[retry\nattempts+1]
    G --> C
    F -- no --> H["raise RuntimeError\n'failed after N attempts'"]
    D --> I[postprocess_words]
    I --> J{transcript_segments empty?}
    J -- yes --> K[log warning, return success]
    J -- no --> L[create/update conversation]
    L --> M[200 / 207 OK]
    E --> N[log info, return early success]
    N --> M
    H --> O["except Exception in process_segment"]
    O --> P[errors.append / Failed to process segment]
    P --> Q[500 / 207 error]
Loading

Reviews (1): Last reviewed commit: "test(sync): update tests for empty-words..." | Re-trigger Greptile

if return_language:
return [], 'en'
return []
raise RuntimeError(f'Deepgram transcription failed after {attempts + 1} attempts: {e}')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Consider explicit exception chaining with from e

Raising RuntimeError inside an except block without from e causes Python to set __context__ implicitly, displaying a "During handling of the above exception, another exception occurred" message in tracebacks — which can be confusing. Using raise ... from e signals intent clearly, suppresses that extra noise, and is more idiomatic Python.

Suggested change
raise RuntimeError(f'Deepgram transcription failed after {attempts + 1} attempts: {e}')
raise RuntimeError(f'Deepgram transcription failed after {attempts + 1} attempts: {e}') from e

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +281 to +283
'# Convert Deepgram format'
)
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Redundant assertion — 'return []' is a substring of the previous assertion

assert 'return []' in no_words_block will always pass whenever assert "return [], detected_lang or 'en'" in no_words_block passes, because 'return []' is literally a prefix of "return [], detected_lang or 'en'". The third assertion adds no additional coverage and can be removed to reduce noise.

Suggested change
'# Convert Deepgram format'
)
]
assert 'if not dg_words:' in no_words_block
assert 'return [], detected_lang or \'en\'' in no_words_block

…atrix (#6100)

Addresses tester feedback:
- TestDeepgramRetryBehavioral: executes real deepgram_prerecorded with mocked
  DG client — verifies RuntimeError on retry exhaustion, [] on valid empty.
- test_all_silent_segments_return_200_not_500: exercises status code through
  real process_segment calls — proves the core #6100 bug is fixed.
- test_runtime_error_from_dg_becomes_segment_error: verifies RuntimeError
  propagation from DG retry exhaustion through process_segment's except block.
37/37 tests passing.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

CP9 Live Test Evidence — Changed-Path Coverage Checklist

Changed Paths

Path ID Changed path Happy-path test Non-happy-path test L1 result L2 result
P1 sync.py:process_segment empty-words branch Empty DG words → 0 errors, return success N/A (empty words IS the non-happy case, now correctly handled) PASS (L1 integration: test_p1_empty_words_no_error) PASS (unit: test_empty_words_are_successful_noop, test_all_silent_segments_return_200_not_500)
P2 pre_recorded.py:deepgram_prerecorded except block Valid empty response → ([], lang), 1 call Retry exhaustion → RuntimeError after 3 attempts PASS (L1 integration: test_p2_valid_empty_returns_list, test_p2_retry_exhaustion_raises) PASS (behavioral: test_retry_exhaustion_raises_runtime_error, test_valid_empty_transcription_returns_empty_list)

L1 Evidence (Backend standalone)

Ran 7/7 L1 integration tests exercising the actual runtime code paths (not static analysis):

======================================================================
L1 Integration Test: sync empty-DG fix (issue #6100)
======================================================================

[P2] deepgram_prerecorded retry exhaustion
  PASS: retry exhaustion raises RuntimeError with 3 attempts

[P2] deepgram_prerecorded valid empty response
  PASS: valid empty response returns ([], lang) with 1 call

[P1] process_segment — empty DG words treated as success
  PASS: empty DG words → 0 errors (success path)

[P1] process_segment — DG RuntimeError caught as segment error
  PASS: DG RuntimeError → segment error in errors list

[Status Code Matrix] All-silent → 200, mixed → 207, all-failed → 500
  PASS: all-silent → 200
  PASS: mixed → 207
  PASS: all-failed → 500

======================================================================
L1 Results: 7 passed, 0 failed, 7 total
======================================================================

Plus 37/37 unit tests passing:

======================== 37 passed, 1 warning in 0.30s =========================

L2 Evidence (Backend + App integrated)

Backend → App response contract verified:

  • SyncLocalFilesResponse.fromJson() (app/lib/backend/schema/conversation.dart) parses new_memories, updated_memories, failed_segments, total_segments, errors
  • App handles 200 (marks WALs synced), 207 (keeps WALs retryable), 500 (exception → WALs retryable)
  • The fix changes all-silent audio from 500 → 200, which correctly triggers WAL sync completion in the app

TestProcessSegmentReal (37 tests) runs the actual process_segment function imported from routers.sync with real threading:

  • test_empty_words_are_successful_noop — P1 happy path through real function
  • test_all_silent_segments_return_200_not_500 — 3 silent segments → 0 errors → 200
  • test_runtime_error_from_dg_becomes_segment_error — P2 non-happy through real function
  • test_mixed_threaded_execution — 3 threads, 1 failure → error collected, successes preserved

L1 Synthesis

All changed paths (P1, P2) proven at runtime. P1 empty-words branch returns success with 0 errors. P2 retry exhaustion raises RuntimeError after 3 attempts, caught by process_segment's except block. Status code matrix verified: all-silent→200, mixed→207, all-failed→500. No paths untested.

L2 Synthesis

Backend response contract matches app-side SyncLocalFilesResponse parsing. All-silent audio now returns 200 (was: false 500), correctly triggering WAL sync completion instead of keeping WALs stuck. Real process_segment function runs with threading in TestProcessSegmentReal, proving integrated behavior across P1 and P2. App WAL retry logic verified via code review of local_wal_sync.dart. No paths untested.

by AI for @beastoin

beastoin and others added 2 commits March 28, 2026 06:39
…sages

Voice message functions in utils/chat.py also call deepgram_prerecorded
but had no try/except for RuntimeError. Now that retry exhaustion raises
instead of returning [], these callers need protection to preserve their
existing graceful-failure behavior (return None/empty).

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Covers the 3 chat.py callers of deepgram_prerecorded:
- transcribe_voice_message_segment returns (None, lang) on RuntimeError
- process_voice_message_segment returns [] on RuntimeError
- process_voice_message_segment_stream yields nothing on RuntimeError

40/40 tests passing.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@beastoin

Copy link
Copy Markdown
Collaborator Author

Updated Test Results (post chat.py fix)

Unit + Behavioral Tests: 40/40 passing

======================== 40 passed, 2 warnings in 0.37s ========================

tests/unit/test_sync_silent_failure.py::TestProcessSegmentErrorHandling::test_process_segment_has_try_except PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentErrorHandling::test_process_segment_treats_empty_words_as_success PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentErrorHandling::test_process_segment_warns_on_empty_postprocessed PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentErrorHandling::test_process_segment_collects_errors_on_exception PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentErrorHandling::test_process_segment_uses_lock_for_thread_safety PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentErrorHandling::test_process_segment_accepts_lock_and_errors_params PASSED
tests/unit/test_sync_silent_failure.py::TestSyncEndpointErrorReporting::test_endpoint_creates_lock_and_errors PASSED
tests/unit/test_sync_silent_failure.py::TestSyncEndpointErrorReporting::test_endpoint_passes_lock_and_errors_to_threads PASSED
tests/unit/test_sync_silent_failure.py::TestSyncEndpointErrorReporting::test_endpoint_returns_207_on_partial_failure PASSED
tests/unit/test_sync_silent_failure.py::TestSyncEndpointErrorReporting::test_endpoint_returns_500_on_all_failed PASSED
tests/unit/test_sync_silent_failure.py::TestSyncEndpointErrorReporting::test_response_includes_failed_segments_count PASSED
tests/unit/test_sync_silent_failure.py::TestSyncEndpointErrorReporting::test_response_converts_sets_to_sorted_lists PASSED
tests/unit/test_sync_silent_failure.py::TestThreadSafeErrorCollection::test_errors_collected_from_failed_threads PASSED
tests/unit/test_sync_silent_failure.py::TestThreadSafeErrorCollection::test_exception_caught_and_collected PASSED
tests/unit/test_sync_silent_failure.py::TestThreadSafeErrorCollection::test_status_code_logic PASSED
tests/unit/test_sync_silent_failure.py::TestDeepgramRetryBehavior::test_deepgram_raises_runtime_error_on_final_retry PASSED
tests/unit/test_sync_silent_failure.py::TestDeepgramRetryBehavior::test_deepgram_keeps_empty_words_as_success PASSED
tests/unit/test_sync_silent_failure.py::TestDeepgramRetryBehavioral::test_retry_exhaustion_raises_runtime_error PASSED
tests/unit/test_sync_silent_failure.py::TestDeepgramRetryBehavioral::test_valid_empty_transcription_returns_empty_list PASSED
tests/unit/test_sync_silent_failure.py::TestAppSideSyncBehavior::test_app_accepts_200_and_207 PASSED
tests/unit/test_sync_silent_failure.py::TestAppSideSyncBehavior::test_app_keeps_wals_retryable_on_partial_failure PASSED
tests/unit/test_sync_silent_failure.py::TestDataLossPreventionFlow::test_partial_failure_no_longer_returns_200 PASSED
tests/unit/test_sync_silent_failure.py::TestDataLossPreventionFlow::test_all_failure_returns_500 PASSED
tests/unit/test_sync_silent_failure.py::TestDataLossPreventionFlow::test_full_success_still_returns_200 PASSED
tests/unit/test_sync_silent_failure.py::TestDataLossPreventionFlow::test_response_includes_error_details_for_debugging PASSED
tests/unit/test_sync_silent_failure.py::TestSegmentDeduplication::test_merge_path_has_dedup_logic PASSED
tests/unit/test_sync_silent_failure.py::TestSegmentDeduplication::test_dedup_uses_timestamp_rounding PASSED
tests/unit/test_sync_silent_failure.py::TestSegmentDeduplication::test_dedup_logic_correctness PASSED
tests/unit/test_sync_silent_failure.py::TestSegmentDeduplication::test_all_duplicates_skips_merge PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentReal::test_empty_words_are_successful_noop PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentReal::test_empty_postprocessed_skips_without_error PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentReal::test_exception_caught_and_collected PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentReal::test_success_adds_to_new_memories PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentReal::test_mixed_threaded_execution PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentReal::test_dedup_skips_existing_segments_on_retry PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentReal::test_all_silent_segments_return_200_not_500 PASSED
tests/unit/test_sync_silent_failure.py::TestProcessSegmentReal::test_runtime_error_from_dg_becomes_segment_error PASSED
tests/unit/test_sync_silent_failure.py::TestVoiceMessageRuntimeErrorHandling::test_transcribe_voice_message_handles_runtime_error PASSED
tests/unit/test_sync_silent_failure.py::TestVoiceMessageRuntimeErrorHandling::test_process_voice_message_handles_runtime_error PASSED
tests/unit/test_sync_silent_failure.py::TestVoiceMessageRuntimeErrorHandling::test_process_voice_message_stream_handles_runtime_error PASSED

Review cycles

Cycle Result Note
Reviewer round 1 (pre chat.py fix) PR_APPROVED_LGTM Only sync.py caller verified
Manager deep dive Caught missed callers utils/chat.py voice message functions also call deepgram_prerecorded
Fix: chat.py + tests added 5th+6th commits try/except RuntimeError + 3 behavioral tests
Reviewer round 2 PR_APPROVED_LGTM All 4 callers verified
Tester round 2 TESTS_APPROVED 40/40, sync + chat coverage confirmed

by AI for @beastoin

@beastoin
beastoin merged commit 380ad3b into main Mar 28, 2026
2 checks passed
@beastoin
beastoin deleted the fix/sync-empty-dg-6100 branch March 28, 2026 08:14
@beastoin

Copy link
Copy Markdown
Collaborator Author

lgtm

Glucksberg pushed a commit to Glucksberg/omi-local that referenced this pull request Apr 28, 2026
…ardware#6100) (BasedHardware#6106)

## Summary

Fixes BasedHardware#6100 — backend-sync returns 500 instead of 207 when Deepgram
returns empty transcription.

**Root cause:** `deepgram_prerecorded` returned `([], lang)` for BOTH
"no speech detected" (valid success) AND "failure after 3 retries" (real
error), making them indistinguishable. `process_segment` treated all
empty results as errors, causing false 500s for silence/noise audio.

**Fix:**
- `deepgram_prerecorded` now raises `RuntimeError` on retry exhaustion
(consistent with `deepgram_prerecorded_from_bytes`)
- `process_segment` treats empty DG words as success (silence/noise),
not error
- `utils/chat.py` voice message functions wrapped with try/except
RuntimeError to preserve graceful failure
- Status code matrix: all-silent→200, mixed→207, all-failed→500

## Changes

| File | Change |
|------|--------|
| `backend/utils/stt/pre_recorded.py` | Retry exhaustion raises
`RuntimeError` instead of returning `[]` |
| `backend/routers/sync.py` | Empty DG words treated as success, not
error |
| `backend/utils/chat.py` | Voice message functions handle
`RuntimeError` from DG retry exhaustion |
| `backend/tests/unit/test_sync_silent_failure.py` | Updated + new tests
(40 total) |

## Callers of `deepgram_prerecorded` (exhaustive search via `git grep`)

| Caller | File | Protected? |
|--------|------|-----------|
| `process_segment` | `routers/sync.py:655` | Yes — existing try/except
(line 747) |
| `transcribe_voice_message_segment` | `utils/chat.py:72-79` | Yes —
**new** try/except added |
| `process_voice_message_segment` | `utils/chat.py:119` | Yes — **new**
try/except added |
| `process_voice_message_segment_stream` | `utils/chat.py:208` | Yes —
**new** try/except added |

## Test plan

- [x] 40/40 unit + behavioral tests passing
- [x] 7/7 L1 integration tests passing (runtime code paths with mocked
DG)
- [x] L2 contract verification: app `SyncLocalFilesResponse` handles
200/207/500 correctly
- [x] Voice message callers verified — all 3 protected with try/except +
tested
- [x] CI lint check passed
- [x] Reviewer: PR_APPROVED_LGTM (2 rounds — 2nd round after chat.py
fix)
- [x] Tester: TESTS_APPROVED (40/40)

## Deployment steps

This is a **backend-only** change (`backend/` files). No app or desktop
changes.

### After merge to main:
1. **Auto-deploy to dev** — `gcp_backend_auto_dev.yml` triggers
automatically on push to `main` with `backend/**` changes
   ```bash
   # Verify dev deploy:
   gh run list --workflow=gcp_backend_auto_dev.yml --limit=3
   ```
2. **Verify on dev** — confirm sync endpoint returns 200 for silent
audio (was 500), voice messages still work
3. **Manual deploy to prod** — after dev verification:
   ```bash
   gh workflow run gcp_backend.yml -f environment=prod -f branch=main
   ```
4. **Verify on prod** — monitor sync endpoint logs for correct status
codes, check voice message transcription still functional

### Rollback plan:
- If issues found: redeploy previous commit to prod:
  ```bash
gh workflow run gcp_backend.yml -f environment=prod -f
branch=<previous-commit-sha>
  ```
- The change is backward-compatible — no app update required, no API
contract changes

## Checkpoints

| CP | Status |
|----|--------|
| CP0-CP9B | ✅ All complete |
| CP9C | N/A (no remote infra deps) |

## Risks

- `fal_whisperx` still silently returns `[]` on retry exhaustion
(pre-existing, not in scope)

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

backend-sync: sync-local-files returns 500 instead of 207 when Deepgram returns empty transcription

1 participant