Skip to content

fix(ble): retry failed codec reads and prevent defaulting to PCM8 (#20779) - #21524

Merged
kodjima33 merged 6 commits into
BasedHardware:mainfrom
hardik4love-lang:fix/codec-read-failure-handling-20779
Oct 16, 2026
Merged

kodjima33 merged 6 commits into
BasedHardware:mainfrom
hardik4love-lang:fix/codec-read-failure-handling-20779

Conversation

@hardik4love-lang

@hardik4love-lang hardik4love-lang commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

Fixes #20779 by introducing retry logic for audio codec reads in OmiDeviceConnection.performGetAudioCodec(), preventing silent fallback to BleAudioCodec.pcm8 on empty data or transient GATT errors, guarding call sites in capture_controller.dart and sdcard_wal_sync.dart, and adding hermetic unit test coverage.

Line-Count-Exception: app/lib/services/capture/capture_controller.dart | 4475 -> 4487 | guard and rollback background mode on audio codec read failure

Product invariants affected

  • INV-CAP-1

How it was verified

Verified via hermetic Dart unit tests covering retry with exponential backoff on transient errors, decoding of codec IDs (PCM8 and OpusFS320), and StateError throwing on persistent failure/empty payload.

Tests

app/test/unit/omi_connection_audio_codec_test.dart

UI evidence

UI-Evidence: none -- Non-UI BLE protocol and codec retry logic verified via hermetic unit tests.

Failure class (fixes)

Failure-Class: none

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @hardik4love-lang — this targets a real, well-reproduced defect (#20779) and the core direction is right: an empty or failed codec read must not silently become PCM8, and retrying a transient GATT failure before giving up is the correct shape.

What I verified in app/lib/services/devices/connectors/omi_connection.dart:

  • The retry loop (3 attempts, 100ms x attempt backoff) and the removal of the codecId = 1 initialization fix exactly the failure mode the issue describes; pcm8 is now only returned when the characteristic explicitly yields 1.
  • The new throw StateError(...) changes the contract of performGetAudioCodec() from never-throws to throws-after-retries. I traced every caller: most are safe — the capture coordinator's stage runner (capture_coordinator.dart _pump / fail-closed path) absorbs the error and fails closed, and storage_sync.dart / ring_storage_sync.dart wrap their getAudioCodec() calls in try/catch.

Two call paths are not prepared for the new throw and I'd like them addressed before merge:

  1. sdcard_wal_sync.dart — _getMissingWals() (~line 178) calls _getAudioCodec(deviceId) with no try/catch, and it is reached from setDevice() (declared void setDevice(...) async, i.e. async-void) and from start(). A StateError there becomes an unhandled async exception on device connect and leaves _wals unpopulated. Please catch it and degrade the same way storage_sync/ring_storage_sync do (skip listing rather than throw).

  2. capture_controller.dart — setBackgroundModeEnabled() awaits _getAudioCodec(device.id) (~line 2509) unguarded, and it is called directly from the settings UI (settings_groups.dart _setBackgroundMode). It also sets _preferences.backgroundModeEnabled = true before that await, so a throw leaves the in-memory flag enabled while _saveNativeBleStreamConfig never runs. Please guard the read and handle/roll back the failure consistently.

Minor, non-blocking: for an unknown codec id the default: branch still returns pcm8, while the issue's expected behavior says PCM8 should only come from an actual 1. Keeping it is a defensible forward-compat choice, but consider BleAudioCodec.unknown or a more visible log so field reports are traceable.

A small unit test would also be welcome — e.g. a fake transport whose read throws twice then returns 20 (asserts opus), and one that always fails (asserts the StateError and that pcm8 is never returned). test/unit/omi_connection_serial_number_test.dart shows the harness pattern.

Fixing the two unguarded call sites is required; the rest are suggestions. Happy to re-review.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added needs-tests PR introduces logic that should be covered by tests flutter flutter work labels Oct 14, 2026
@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Hi @Git-on-my-level,

Thank you for the detailed code review and tracing of all call sites!

I have addressed all items:

  1. sdcard_wal_sync.dart (_getMissingWals): Wrapped _getAudioCodec(deviceId) in a try/catch guard. If reading the codec fails or throws, it now logs the debug trace and returns [] (skipping listing rather than throwing), preventing unhandled async exceptions in setDevice() and start().
  2. capture_controller.dart (setBackgroundModeEnabled): Guarded �wait _getAudioCodec(device.id) with try/catch. On failure, it cleanly rolls back _preferences.backgroundModeEnabled = false, clears
    ativeBleStreamingEnabled,
    ativeBleForegroundReady, and
    ativeBleStreamConfig, notifies listeners, and returns alse without leaving partial in-memory state.
  3. Hermetic Unit Test Suite (omi_connection_audio_codec_test.dart): Added 5 unit tests utilizing the mock transport pattern:
    • Verifies transient read failures (2 consecutive errors) retry and succeed with BleAudioCodec.opus on attempt 3.
    • Verifies explicit byte 1 returns BleAudioCodec.pcm8.
    • Verifies explicit byte 21 returns BleAudioCodec.opusFS320.
    • Verifies persistent GATT exceptions exhaust 3 retries and throw StateError without defaulting to PCM8.
    • Verifies persistent empty byte arrays exhaust 3 retries and throw StateError without defaulting to PCM8.

Ready for re-review! Thank you.

@Git-on-my-level
Git-on-my-level dismissed their stale review October 15, 2026 20:16

Dismissed: both blocking concerns from this review (unguarded _getAudioCodec in sdcard_wal_sync.dart _getMissingWals and in capture_controller.dart setBackgroundModeEnabled) and the requested unit tests are resolved on head 70aaa53.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution and removed needs-tests PR introduces logic that should be covered by tests labels Oct 15, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @hardik4love-lang — everything from my earlier review is addressed on this head. Verified per file:

  • app/lib/services/capture/capture_controller.dart: setBackgroundModeEnabled now guards the _getAudioCodec read and fully rolls back on failure (backgroundModeEnabled = false, streaming prefs persisted false, nativeBleStreamConfig removed, notifyListeners(), returns false) — and backgroundModeEnabled = true was moved after the guarded read, so the half-enabled state I flagged can no longer occur.
  • app/lib/services/wals/sdcard_wal_sync.dart: _getMissingWals() catches the codec-read failure and skips listing (return []), matching the degrade pattern in storage_sync / ring_storage_sync and avoiding the unhandled async exception from setDevice() / start().
  • app/lib/services/devices/connectors/omi_connection.dart: the retry/throw contract is unchanged from the earlier review and still correct — pcm8 only on an explicit 1, StateError after 3 attempts.
  • app/test/unit/omi_connection_audio_codec_test.dart: the new suite covers exactly the requested cases — throw-twice-then-20 → opus with exactly 3 read attempts asserted, explicit 1 → pcm8, 21 → opusFS320, and persistent failure / persistent empty reads → StateError (pcm8 never defaulted). One tiny non-blocking nit: await expectLater(connection.performGetAudioCodec(), throwsA(isA<StateError>())) would be cleaner than the un-awaited expect(() => ...) wrapper.

I've dismissed the earlier changes-requested review since both blocking call sites are fixed. One thing remains before merge: no CI checks have run on this head yet, so the new unit suite hasn't executed in CI — the merge decision should wait for a green run. Leaving this for maintainer merge review.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Hi @Git-on-my-level,

The PR metadata preflight check is now PASS green (Run 38855454758) with the updated body declarations (- INV-CAP-1 and line-count exception for capture_controller.dart).

The branch and test suite are ready for maintainer merge click! Thank you.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

hardik4love-lang (unflagged on this PR) adds retry+explicit failure for BLE codec reads, fixes real issue #20779 (filed by Itaxh1 but third-party pickup, not self-bounty). Scoped, test added, CI in-progress (acceptable). 4/5.

@kodjima33
kodjima33 merged commit 0764942 into BasedHardware:main Oct 16, 2026
37 checks passed
@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Thank you @kodjima33 and @Git-on-my-level for reviewing and merging! Glad to have this critical P1 audio codec stability defect resolved for all pendant users.

Bounty Claim Details

@kodjima33 @josancamon19

@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Hi @kodjima33, @josancamon19,

Following up on bounty settlement for merged PR #21524 (Issue #20779):

Whenever the batch disbursement runs, please confirm. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

flutter flutter work positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A failed codec read makes an Opus pendant stream as PCM8 (garbled transcript, no local backup)

3 participants