Skip to content

fix(android): make BLE reconnect and CV1/Limitless backlog recovery transactional - #10571

Closed
axAilotl wants to merge 8 commits into
BasedHardware:mainfrom
axAilotl:codex/android-ble-backlog-reliability
Closed

axAilotl wants to merge 8 commits into
BasedHardware:mainfrom
axAilotl:codex/android-ble-backlog-reliability

Conversation

@axAilotl

@axAilotl axAilotl commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • serialize Android BLE GATT operations, bind callbacks to the active connection session, retry transient busy states, and use bounded reconnect backoff
  • preserve contiguous Limitless flash acknowledgments so a missing page is never acknowledged past
  • make Limitless page appends retry-idempotent with durable per-device/session watermarks and interrupted-append rollback
  • advance the Limitless destructive pendant ACK watermark only after the BLE write callback succeeds
  • validate CV1 notification continuity and complete ring ranges before advancing the pendant
  • make WAL creation, upload, reconciliation, restart recovery, and retry ownership transactional and memory-bounded
  • when Android Background Mode and automatic upload are both explicitly enabled, allow only a native deviceConnected wake to resume backlog recovery in the background

Why

The old Android path mixed concurrent GATT operations, accepted stale callbacks after reconnect, treated notification arrival as implicit continuity, and allowed multiple sync observers to race. A partial or failed drain could therefore look successful, while a busy or screen-off phone could leave a large pendant backlog retrying inefficiently.

Limitless flash recovery also advanced its local deletion watermark immediately after starting an asynchronous BLE ACK. If the audio fsync succeeded but the ACK failed or the connection became ambiguous, the pendant retained the page and the next drain appended the same durable audio again. The writer now records an append checkpoint before writing, fsyncs audio, and atomically replaces that checkpoint with a device/session page watermark. A restart truncates an interrupted append, while a completed page is skipped on redrain. Pendant deletion advances only from a successful GATT completion callback.

Behavior and rollout

  • failed or partial CV1 ranges remain on the pendant and retry from the same durable sequence
  • locally written WALs are flushed and registered before the cumulative ADVANCE
  • uploaded WALs reconcile before they can be offered again
  • Limitless ACK failure/disconnect leaves the pendant watermark unchanged and redrain does not duplicate durable audio
  • Limitless interrupted writer transactions roll back to their recorded file offset before retry
  • background recovery remains opt-in and Android-only; connectivity, cooldown, and user-retry wakes still wait for foreground
  • failures during a background pass schedule no background timer and remain retryable on the next foreground wake

Candidate testing on the Galaxy reached 98.7 KiB/s during CV1 backlog transfer. The shared durable-sync layer is intentionally included here because it owns the app-side acknowledgment contract used by both mobile platforms.

Validation

  • make preflight: deterministic manifest, hygiene, architecture, and invariant checks passed; local worktree PR-metadata discovery is unavailable because the task branch differs from the existing fork PR branch
  • focused Limitless ACK/idempotency JVM regressions added for failed ACK + redrain, successful ACK completion, interrupted append rollback, and in-flight ACK coverage
  • GitHub Mobile App Checks: generated files, analyzer + Flutter tests, and Android dev-debug APK compile smoke passed at b76f2415eaa811ad5bd703faa078664df7005e47
  • prior branch validation remains: bash app/test.sh, Android BLE/Limitless unit tests, analyzer ratchet, focused continuity/ring/WAL/background-policy tests, integrated Galaxy/CV1 testing, and preflight

Failure-Class: none

@Git-on-my-level

Copy link
Copy Markdown
Member

Strong work on the data-safety invariants here — this is clearly the right direction for backlog reliability. The advance gate is defensively correct: RingProtocol.canAdvance requires reachedDone && doneOk && !flushError && !isCancelled && receivedCompleteRange && !protocolError && crcVerified, the WAL manifest now rewrites atomically via temp-file + rename with a serialized save barrier, source-aware WAL identity makes retries idempotent, and the ContiguousFlashPageLedger correctly refuses to advance the cumulative ACK watermark across a page hole. The unit-test coverage across BLE backoff, GATT queue, notification coalescing, flash ledger, ring sync, and WAL recovery is thorough.

A few things I'd want a human maintainer to confirm before this leaves draft:

  1. Draft → ready. Marking as non-blocking review since the PR is still draft; the design is sound but merge-readiness is your call.

  2. CRC gate effectiveness. crcVerified defaults to true (ring_storage_sync.dart) and only flips when the optional DONE CRC32 extension is present. That's a reasonable back-compat default, but worth confirming the firmware versions this targets actually emit the trailing CRC32 — otherwise the CRC check is effectively a no-op for those devices and the gate rests entirely on receivedCompleteRange.

  3. Scope. This bundles BLE reconnect (Kotlin), GATT serialization (Kotlin), Limitless flash drain (Kotlin), CV1 ring sync + transactional WAL layer (Dart), and a new Android background-recovery wake policy. It's defensible as one "backlog reliability" outcome, and I'm not asking for a split for size alone — but it's a broad architectural change across user-audio durability surfaces, so it warrants maintainer product/architecture sign-off rather than auto-approval.

  4. Background recovery opt-in. Gating the background pass to deviceConnected only (Android + Background Mode + auto-upload), with connectivity/cooldown/user-retry wakes still waiting for foreground, is conservative and well-tested. Just confirming that matches product intent for background audio backlog recovery.

Leaving as a positive signal — not a formal approval, since this is a draft touching data-durability and background recovery.


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-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests labels Jul 25, 2026
@axAilotl
axAilotl force-pushed the codex/android-ble-backlog-reliability branch from 9981ef2 to 9e8da57 Compare July 25, 2026 21:56
Alex Vega added 7 commits July 25, 2026 17:58
Buffer out-of-order flash pages and advance the pendant's cumulative delete watermark only across a contiguous, fsynced prefix.

Failure-Class: none
Validate the full announced record range, flush and register local WALs, and send ADVANCE only after a successful DONE. A partial notification stream or process-visible file write is no longer enough to discard pendant records.

Failure-Class: none
Use O(1) queue drains and one typed output buffer while preserving the exact little-endian WAL format and durable ADVANCE ordering.

Verified: bash app/test.sh (983 tests); app/scripts/analyze_ratchet.sh; physical 3,996,000-byte CV1 ring read with matching CRC.
Allow exactly the native device-connected wake to resume durable backlog recovery while Android Background Mode and automatic upload are both opted in. Keep all other background wakes suppressed and retain failed work for the next foreground retry without a background timer.

Failure-Class: none
@axAilotl
axAilotl force-pushed the codex/android-ble-backlog-reliability branch from 9e8da57 to 9ed4a58 Compare July 25, 2026 21:59
@Git-on-my-level

Copy link
Copy Markdown
Member

This is a strong, well-scoped reliability pass — the transactional data-safety model is the right design for both the CV1 ring and the Limitless pendant. Thanks for the careful work and the accompanying unit coverage.

What I verified and liked:

  • GattOperationQueue + isActiveGatt(gatt) correctly binds every GATT callback to the operation and session that started it, closing the stale-callback / wrong-command-released hazard the old ConcurrentLinkedQueue had.
  • RingProtocol.canAdvance requiring READ_BEGIN + byte-count + DONE (+ optional CRC) agreement before CMD_RING_ADVANCE, and durable WAL registration (sourceId = ring_start_end) happening only before the advance, is exactly the cumulative-ACK safety invariant this path needed. Out-of-order ranges correctly stay on the pendant.
  • ContiguousFlashPageLedger guaranteeing the ACK watermark can't jump a gap, and the fsync barrier (ackWritten) blocking later ACKs after a failed flush, both correctly prevent pendant data loss on a partial drain.
  • Reconnect backoff not resetting on mere physical connect (only on a stable session) is the right call — flapping transport setup failures now back off instead of hot-looping.

Two things worth a human maintainer's eye before this leaves draft:

  1. On a CRC mismatch the current range is left un-advanced and retried, which is safe, but if the firmware re-sends the identical corrupt bytes the drain will loop on that range until inactivity/stall fires. Confirming the pendant can recover (or documenting that a manual clear is expected) would be useful.
  2. recoverRejectedGatt on a descriptor-write failure forces a full reconnect — correct for safety, but worth a quick sanity check that a transient CCCD rejection under radio contention doesn't regress perceived reliability versus the old silent completeCommand().

No security, dependency, CI/workflow, or agent-instruction surfaces are touched. The shared durable-sync layer's inclusion is justified by the PR's own note that it owns the app-side acknowledgment contract for both platforms. Keeping the existing needs-maintainer-review / needs-tests labels; leaving this as a positive signal rather than a formal approval since it's still draft and materially changes data-safety behavior on two recovery paths.


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 force-pushed the codex/android-ble-backlog-reliability branch from b874787 to de6ffc6 Compare July 28, 2026 23:35
Persist device/session page identity only after durable audio, recover an interrupted append by truncating to its recorded offset, and advance cumulative pendant deletion only after the BLE write callback succeeds.\n\nFailure-Class: none

Co-authored-by: multica-agent <[email protected]>
@Git-on-my-level
Git-on-my-level force-pushed the codex/android-ble-backlog-reliability branch from de6ffc6 to b76f241 Compare July 28, 2026 23:47
@Git-on-my-level

Copy link
Copy Markdown
Member

The latest commit (b76f241 — "make Limitless drain ACK idempotent") directly addresses the ambiguous-ACK → duplicate-append hazard called out earlier: the pendant-deletion watermark now advances only from a successful BLE write callback, and page appends are retry-idempotent via per-device/session watermarks.

What checks out in the new idempotency layer:

  • Checkpoint/rollback WAL pattern. LimitlessBatchAudioWriter.append() records the pending-append path+offset in SharedPreferences before writing frames, fsyncs the audio, then atomically replaces that checkpoint with the page watermark. An interrupted append is truncated to the recorded offset on restart (recoverPendingAppendLocked), so a crash between fsync and watermark-commit leaves no partial page.

  • LimitlessPageDeduplicator.appendOnce checks the durable watermark first (idempotent return), appends + fsyncs, then commits the watermark. If the watermark write fails, it rolls back the audio bytes — no double-append is possible even across process restarts.

  • LimitlessAckCommitGate transmits the cumulative ACK only after the sync() fsync barrier succeeds, and advances lastAckedPageIndex only inside the BLE completion callback. A failed callback sets blocked, which is sticky for the rest of the drain cycle. That's deliberately conservative: the drain ends via the existing stall/inactivity timeout with pages safely retained on the pendant, and the next cycle starts with a fresh gate.

One thing worth a quick maintainer sanity check: the sticky blocked flag means a single transient ACK failure (e.g. radio contention) stops all further ACKs in that drain, even for pages that were already durably appended. The drain won't lose data — it just won't reclaim pendant space until the next cycle. Confirming that's the intended tradeoff (safety over throughput) seems worthwhile, though it matches the conservative direction of the rest of the PR.

The Limitless idempotency JVM tests (failed-ACK + redrain, interrupted-append rollback, in-flight ACK) cover the key fault paths. Still leaving this as a positive signal rather than formal approval — draft status, the broad scope across Kotlin/Dart data-durability surfaces, and the existing needs-maintainer-review / needs-tests labels all warrant human sign-off before merge.


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

@undivisible undivisible added human Human-authored pull request app flutter flutter work mobile security-review Touches auth, provider routing, secrets, or security-sensitive surfaces privacy-review Touches user-data persistence, permissions, or privacy-sensitive surfaces labels Aug 10, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for this thorough rework — the transactional recovery model is well-structured and the test coverage is strong. Observations from the diff:

GattOperationQueue / OmiBleManager.kt — The serialized one-operation-at-a-time queue with identity-keyed callback completion (GattOperationKey) is the right fix for stale-callback-after-reconnect. The isActiveGatt(gatt) guard on every callback path correctly rejects callbacks from retired GATT objects. Worth verifying on hardware: requestMtu now completes via the queue rather than the old listener-swap in requestMtuThenNotifyReady — onMtuChanged was removed from BleConnectionListener, so confirm no other consumer depends on it.

LimitlessAckCommitGate / LimitlessFlashDrainEngine.kt — Advancing the pendant-deletion watermark only from the successful BLE write callback (not after write() returns) is the correct fix for duplicate-append-after-ambiguous-ACK. The BLOCKED state on fsync failure is appropriately conservative. The pendingFinishReason deferral so the drain doesn't complete before an in-flight ACK settles is a good detail.

ContiguousFlashPageLedger — Correctly prevents ACKing past a gap. The 64-page BUFFER_LIMIT_REACHED guard bounds memory during a persistent gap.

LimitlessBatchAudioWriter.kt — The checkpoint/rollback pattern (checkpointLocked then write then rollbackLocked on failure) with synchronous SharedPreferences.commit() for the per-device/session watermark is sound. recoverPendingAppendLocked() truncation on restart handles interrupted appends.

ring_storage_sync.dart — Bounded-range transactions (each range independently durable before CMD_RING_ADVANCE) is a significant improvement over the single cumulative ADVANCE. RingProtocol.canAdvance() combining reachedDone, doneOk, receivedCompleteRange, protocolError, and crcVerified is thorough. The immutable sourceId (ring_{start}_{end}) with file-collision check is a good idempotency boundary.

wal_file_manager.dart — Temp-file-then-rename atomic write with serialized _saveBarrier correctly prevents torn writes and ordering violations under concurrent saves. Backup fallback on corruption is a good resilience improvement.

ble_packet_continuity.dart — Modular-arity duplicate/gap detection with exact-adjacent-duplicate suppression is well-reasoned. Forwarding reused-ID packets with different payloads (reset disposition) is the safe default.

Background recovery — The backgroundDeviceRecoveryEnabled gate (Android + Background Mode + auto-upload, only for WakeTrigger.deviceConnected) is appropriately restrictive; tests confirm other wakes remain foreground-only.

The needs-tests label appears stale given the extensive JVM and Dart test additions across all new components. Leaving for human maintainer to clear along with security/privacy review of the pendant-deletion and WAL persistence semantics.


Review by glm-5.2 (automated). Leaving for human maintainer review — the data-loss-sensitive pendant-deletion and WAL-persistence transactional model needs maintainer sign-off on the acknowledgment contract before merge.


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

@axAilotl

Copy link
Copy Markdown
Contributor Author

Closing this experimental CV1/storage-first branch. The only firmware reliability change being carried forward is #11578; this PR is not part of that release candidate.

@axAilotl axAilotl closed this Aug 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hey @axAilotl 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

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

Labels

app flutter flutter work human Human-authored pull request mobile needs-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests privacy-review Touches user-data persistence, permissions, or privacy-sensitive surfaces security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants