Skip to content

fix(desktop): never strand local-segments conversations after five failed uploads - #19613

Merged
kodjima33 merged 5 commits into
mainfrom
claude/amazing-einstein-dm6k1g
Sep 29, 2026
Merged

kodjima33 merged 5 commits into
mainfrom
claude/amazing-einstein-dm6k1g

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

On Apple Silicon, desktop capture is on-device (Parakeet), and those sessions finalize via POST /v1/conversations/from-segments (finalizationStrategy: .localSegments). Every failure went through markRetryableFailure and incremented retryCount, offline failures included. getSessionsNeedingFinalization then required retryCount < 5, and the only post-exhaustion query, getExhaustedCloudSessionsWithLocalSegments, covers cloudReconcile only. About 30 minutes offline after a conversation, or a backend brownout (from-segments failed 74% of the time for two days in late Aug 2026), left the conversation stuck in local SQLite for good. It was never uploaded, summarized or synced, and never listed. The backend dedups on uuid5(uid, client_conversation_id) (backend/routers/developer.py), so retrying indefinitely is safe.

  • No exhausted state for .localSegments. canRetry is always true for that strategy. The backoff is capped at 1 h via the new FinalizationRetryPolicy (1, 2, 4, 8, 16, 32 min, then hourly). Cloud reconciliation keeps its bounded budget and local fallback, now also under the 1 h cap.
  • Offline errors don't spend budget. FinalizationFailureClass.classify treats notConnectedToInternet, networkConnectionLost, cannotFindHost, cannotConnectToHost and dnsLookupFailed as offline. Those failures release the upload claim without incrementing retryCount. recoverPendingFinalizations also skips all attempts while NetworkReachability reports offline, and logs once each time it goes offline or comes back.
  • Permanent 4xx failures are classified separately (any 4xx except 401/408/425/429). They are stored with a permanent_rejection: lastError prefix and reported once through conversationReconciliationFailed (reason=local_segments_rejected). They stay queued and retry hourly, so a backend fix drains them without user action.
  • Wider recovery query. getSessionsNeedingFinalization now includes failed rows whose strategy is local_segments (or NULL with the legacy desktop default) at any retry count. Rows that older builds stranded get picked up after the upgrade.
  • The recovery loop's due check is now isDueForRecovery. Only exhausted cloud sessions skip the backoff, as before; local sessions always respect it.
  • Cloud path: the exhausted local-fallback error was swallowed by try?. It is now logged.
  • Adds a desktop changelog fragment, and lists FinalizationRetryPolicy.swift in e2e/flows/recording-finalization.yaml so the e2e flow-coverage manifest check passes.

"Visible" here means the row stays in the recovery queue and in telemetry. Listing unsynced local sessions in the conversation list (getLocalConversations requires backendSynced) is a UI change and not part of this PR.

Product invariants affected

none

How it was verified

  • make preflight: passed (25 checks), including desktop-test-quality, desktop-swiftlint-baseline and desktop-main-actor-xctest-hooks.
  • python3 desktop/macos/scripts/check_desktop_test_quality.py: OK.
  • scripts/failure-class validate and scripts/pr-preflight --pr-body-file: passed (26 checks).
  • desktop/macos/scripts/check-e2e-flow-coverage.py --base origin/main --strict: passes now. It reported FinalizationRetryPolicy.swift as uncovered before the flow entry was added.
  • Desktop Swift CI on bd77446 (the first compile of this Swift, since I worked in a Linux container with no Swift toolchain): the release compile succeeded and the desktop Swift test step succeeded (TEST_OUTCOME: success). The only red was the e2e flow-coverage manifest check, fixed in 6a58fa4.
  • Not exercised: no named dev bundle was launched, because there is no macOS host here. The behavioral proof is the XCTest suite below.

Tests

desktop/macos/Desktop/Tests/LocalSegmentsFinalizationRetryTests.swift uses a scripted URLProtocol stub, an injected clock and an injected reachability probe. It has no wall-clock sleeps.

  • testLocalSegmentsSessionOutlivesFiveFailuresAndOfflineThenUploads: five 503s (retryCount 1…5), the session still queued, backoff still honored, no attempt while offline, a false-positive reachability window where the URLError does not spend budget, then network recovery. It asserts completed / backendSynced, and checks that all 7 attempts sent the same client_conversation_id. Before this change the session drops out of recovery after the fifth failure.
  • testPermanentRejectionStaysQueuedAndRetriesHourly: a 422 is marked permanent, stays queued, is not retried at 30 min, and uploads after an hour.
  • testRecoveryQueryPicksUpLocalSessionsStrandedByTheOldBudget: rows stranded at retryCount 9 and legacy NULL-strategy rows are recovered; exhausted cloud rows stay excluded.
  • Policy unit tests: failure classification, the backoff schedule and cap, and isDueForRecovery.

Failure class (fixes)

Failure-Class: new

Failure-class transition narrative (only when needed)

Adds .github/failure-classes/FC-retry-budget-strands-sole-local-copy.json.

  • Violated contract: a retry budget may only end work whose data survives somewhere else. From-segments sessions hold the only copy of the transcript, yet they had the cloud path's five-attempt budget, offline errors counted against it, and no recovery query covered them once it ran out.
  • Canonical guard: sole-copy, idempotent uploads have no exhausted state and use a capped backoff. Offline failures don't count, and attempts wait for reachability. Permanent rejections are classified but stay queued. The recovery query covers rows at any retry count.
  • Guard artifact: LocalSegmentsFinalizationRetryTests.swift.
  • Evidence: the late-Aug 2026 from-segments brownout recorded in backend/tests/unit/test_conversation_replacement_backoff.py. evidence_prs is empty because this PR is the first instance.

…iled uploads

On-device (Parakeet) sessions finalize via POST /v1/conversations/from-segments.
Five failures (about 30 minutes offline, or a backend brownout) set
retryCount = 5, which excluded the row from every recovery query: the
conversation was never uploaded and never listed.

- .localSegments sessions have no exhausted state; backoff is capped at 1 h.
  The backend dedups on client_conversation_id, so unbounded retry is safe.
- Offline transport errors do not spend retry budget, and recovery skips
  attempts entirely while the network path monitor reports offline.
- Permanent 4xx rejections are persisted as such, reported once, and kept
  queued at the hourly cadence.
- The recovery query includes failed local-segments rows at any retry
  count, so rows stranded by earlier builds drain on upgrade.
- The exhausted cloud path's local fallback error is logged, not swallowed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017tMpngoYRuCgAYf3w7qfh5
@aryanorastar
aryanorastar marked this pull request as ready for review September 28, 2026 17:35

@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 for this — the diagnosis and the fix direction are right. On-device .localSegments sessions hold the only copy of the transcript, and the shared five-attempt budget meant ~30 minutes offline (or a from-segments brownout) stranded the conversation permanently. I verified the key safety claim: the backend dedups /v1/conversations/from-segments on uuid5(namespace, uid + client_conversation_id) (backend/routers/developer.py:1751), so unbounded retry cannot create duplicate conversations.

Per-file notes:

  • ConversationFinalizationService.swift — the offline gate in recoverPendingFinalizations (log-once via isDeferredForOffline), the static isDueForRecovery refactor, releasing the upload claim without spending budget for .offline failures, the one-time reportPermanentLocalUploadRejection analytics event, and logging (instead of try?-swallowing) the exhausted-cloud local fallback error are all improvements. Exhausted-cloud rows still get their bounded local-fallback attempts on the next tick — good preservation of the #9083 behavior.
  • FinalizationRetryPolicy.swift (new) — classification looks correct: the five URLError codes → .offline, other transport errors → .transient, 4xx except 401/408/425/429 → .permanent (401 as transient for token refresh is right). Backoff 1→2→…→32 min then capped at 1 h, with permanent rejections waiting the full hour.
  • TranscriptionModels.swift — effectiveFinalizationStrategy (persisted value, else backendId → .cloudReconcile, else desktop source → .localSegments) keeps cloud reconciliation under its bounded budget while .localSegments never exhausts via canRetry.
  • TranscriptionStorage.swift — the widened recovery SQL's legacy-row branch (finalizationStrategy IS NULL AND backendId empty AND source = desktop) exactly mirrors the Swift inference, so rows stranded by older builds drain on upgrade. I checked both sides line by line — they match.
  • LocalSegmentsFinalizationRetryTests.swift — real behavioral coverage (URLProtocol stub + GRDB, no network): old-budget survival with offline gating and a stable idempotency key, hourly permanent-rejection cadence, legacy-stranded-row recovery, classification table, backoff cap.
  • FC-retry-budget-strands-sole-local-copy.json / changelog entry — consistent with the failure-class registry convention; changelog is user-facing and accurate.

Blocking item — CI has one root cause, and it's mechanical:

  • Desktop Swift Static & Test Contracts fails the desktop-e2e-flow-coverage manifest check: FinalizationRetryPolicy.swift is the one uncovered changed Swift file (the other three are covered by capture-lifecycle.yaml / recording-finalization.yaml).
  • Desktop Swift Build & Tests then hard-fails on VERIFY_RESULT=failure by design (the release compile and the test target both built clean).

Fix: add FinalizationRetryPolicy.swift to a covers: list in desktop/macos/e2e/flows/ — recording-finalization.yaml already covers its sibling files, and the established pattern for pure-policy files there is the # XCTest is the behavioral proof comment plus the entry. Once that lands, both required checks should go green; no production-code changes are needed.


AI-generated maintainer feedback on behalf of the Omi maintainers. This blocker is mechanical (repo contract), so no special maintainer decision is needed beyond the normal green-CI merge gate.


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

…ation flow

The desktop-e2e-flow-coverage manifest check requires every changed desktop
Swift source to be listed by a flow; the retry policy is a pure helper whose
behavioral proof is LocalSegmentsFinalizationRetryTests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017tMpngoYRuCgAYf3w7qfh5

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level thanks for the review. I've pushed the fix for the blocking item in 6a58fa4: FinalizationRetryPolicy.swift is now in the covers: list of desktop/macos/e2e/flows/recording-finalization.yaml, next to its sibling files, with an "XCTest is the behavioral proof" comment.

To confirm the fix, I ran check-e2e-flow-coverage.py --base origin/main before and after the change. Before, it reported UNCOVERED …/FinalizationRetryPolicy.swift. After, it reports Uncovered: 0 and also passes with --strict. scripts/pr-preflight --pr-body-file passes too (26 checks). The previous CI run's Swift tests had already succeeded (TEST_OUTCOME: success, release compile success), so the manifest check was the only red. No production code changed in this push.


Generated by Claude Code

SwiftLint (force_unwrapping, implicitly_unwrapped_optional) flagged the
setUp copied from the older finalization suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017tMpngoYRuCgAYf3w7qfh5

Copy link
Copy Markdown
Collaborator Author

CI is now green on 4d51812: Desktop Swift Static & Test Contracts, Desktop Swift Build & Tests and the Siri Xcode 27 Advisory all pass.

Once the flow-coverage fix (6a58fa4) was in, the static lane turned up one more issue. SwiftLint flagged two violations in the new test's setUp, String! and .first!, which I had copied from the older finalization suite. 4d51812 removes both; the user id is now a local constant, and the lookup uses try XCTUnwrap(…). No production code changed after your review. @Git-on-my-level, this is ready for another look.


Generated by Claude Code

@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.

Desktop bug fix (owner-override): local-segments conversations (sole copy of transcript) were permanently stranded after 5 failed uploads/offline. CHANGES_REQUESTED review's blocking item (missing e2e flow-coverage entry) is already addressed in this diff and CI is green.

@kodjima33
kodjima33 merged commit 9c0b7d4 into main Sep 29, 2026
49 checks passed
@kodjima33
kodjima33 deleted the claude/amazing-einstein-dm6k1g branch September 29, 2026 14:41
Git-on-my-level added a commit that referenced this pull request Oct 28, 2026
… session ids (#15500) (#23886)

## What changed and why

Fixes #15500 (still-live wave). macOS desktop
recordings were stranded
locally with HTTP 422 on every upload retry: the from-segments wire
model rejected a
blank/whitespace `client_session_id` (under any accepted alias) as a
hard 422, and clients
that persisted a blank id retried identical bytes forever — measured
~16–18k 422s/day on
`/v1/conversations/from-segments` since 2026-10-06 (stable rollout of
desktop v0.12.447
scaled a long-standing ~200/day baseline ~80×; ~670 sessions stuck on
the hourly retry
cadence). The id is optional metadata whose only job is retry dedupe, so
a blank value is
now treated as absent instead of rejecting the only copy of a
transcript. The desktop
client also no longer uploads a blank stored id (the chunked
continuation path requires a
real id), so both sides are closed.

A blank id additionally no longer falls into the unkeyed create path
(Luna review of this
PR): these clients resend byte-identical requests, so if the first
attempt's 200 is lost
while its row lands, a plain create path would fork a duplicate
conversation on retry.
The server now derives a stable retry identity (`derived:<sha256>` over
uid + the
recording's own facts — source, started/finished timestamps, language,
geolocation,
segments) and runs the normal keyed idempotency path with it. Fields a
retry may
legitimately resend differently (folder, calendar context, client
projection,
finalization reason) stay out of the hash, so a retry lands on the first
attempt's
conversation. An id that was never sent keeps the public create-path
contract unchanged;
`null` counts as absent, not blank. The derived id never appears in the
OpenAPI schema.

## Chunked uploads (recovery boundary)

Chunked continuation uploads still require a real session id and keep
their 422 when the
id is blank: each chunk carries different segments, so a per-request
payload hash is not
stable across chunks of one recording, and a metadata-only hash (the
only cross-chunk
input) would key two distinct recordings that share timestamps into one
chunk namespace
(409 content conflict). The chunked blank-id cohort therefore recovers
only after the
desktop release ships the client-side fallback id

(`desktop/macos/Desktop/Sources/ConversationFinalizationService.swift:873`,
derived from
the persistent SQLite row id + `startedAt`, stable across retries and
app restarts); the
local retry queue keeps retrying on capped hourly backoff, so those
sessions drain once
the update is installed. Non-chunked blank-id sessions drain on their
next hourly retry
after the backend deploy alone.

## Product invariants affected

none

## How it was verified

- Production aggregates (read-only, status codes and sizes only, no user
data):
daily 422 counts on the route 2026-09-01→10-28; response-size
fingerprints of the
failing bodies matched locally-generated validation errors for blank
`client_session_id`
values (aliases `client_session_id`/`session_id`/`client_id`, whitespace
lengths 2–8);
failing UAs are desktop builds 12402→12541; failing requests are
3KB–638KB real
  transcript payloads (not truncations).
- Backend: `backend/test.sh` with
`BACKEND_UNIT_TEST_FILE_LIST=tests/unit/test_developer_from_segments_idempotency.py
tests/unit/test_client_segment_continuation.py
tests/unit/test_openapi_contract.py
tests/unit/test_client_processing_acceptance.py` (unit layer), including
the
  replay test below.
- Desktop: focused XCTest
`TranscriptionFinalizationStateMachineTests/testLocalClientConversationIdNeverUploadsABlankStoredId`
via `scripts/dev-feedback.py --once swift` (unit layer).
- Stranded-recovery: after the backend deploy, a stuck non-chunked
session's next hourly
retry sends the identical bytes and now lands (200 →
markSessionCompleted → drained, no
user action). Chunked-cohort sessions drain after the app update ships
the fallback id.
Retry-forever policy (#19613) confirmed on main: `.permanent` failures
stay queued at
hourly cadence and the recovery query includes rows old builds stranded
at
  retryCount ≥ 5.

## Tests

- `test_blank_client_session_id_gets_server_derived_retry_identity`
(parametrized 4
aliases × 4 blank shapes): posts blank ids through the real route and
asserts the
keyed idempotency path runs with a `derived:` session id instead of a
422 — this test
  fails on main.
- `test_byte_identical_blank_id_retry_returns_first_conversation`: the
stuck cohort's
retry shape (first attempt's 200 lost, row landed, identical bytes
resent) returns the
first conversation and never reprocesses — the exact
duplicate-conversation gap from
  the review.
- `test_blank_id_different_recordings_stay_separate`: different
recording facts derive
  different ids and still create two conversations.
- `test_sent_blank_flag_distinguishes_sent_blank_from_absent`: omitted
and `null` ids
  stay on the create path; only a sent blank string derives.
- `test_client_session_id_with_content_still_strips_and_dedupes`: real
ids still strip
  and keep the idempotency path.
- `testLocalClientConversationIdNeverUploadsABlankStoredId`:
nil/empty/whitespace stored
  ids fall back to the derived id; padded ids still strip.

## UI evidence

UI-Evidence: none -- backend validation and upload-id derivation only;
no visible UI changed

Line-Count-Exception: backend/routers/developer.py | 2830 -> 2862 |
derived blank-id retry identity helper sits beside the existing
from-segments idempotency helpers it extends

Failure-Class: new

## Failure-class transition narrative

`FC-optional-client-metadata-fails-closed` (definition added in this
PR).

- Violated contract: ingestion endpoints that receive the only copy of
user data must
degrade broken **optional** client metadata to absent, never 422 — a
retrying client
resends identical bytes, so a hard 422 strands the recording forever.
Evidence:
~16–18k 422s/day on `/v1/conversations/from-segments` since 2026-10-06
from desktop
builds 12402→12541, ~670 sessions stuck on the hourly retry cadence
(#15500), caused
by blank `client_session_id` values hitting the model's `cannot be
empty` raise.
- Canonical guard: blank values normalize to `None` at the wire model,
and a sent-blank
id derives a stable server-side retry identity so the byte-identical
retry is an
idempotency hit, never a duplicate conversation. The parametrized
regression test
posts blank ids under every accepted alias through the real route and
asserts the
keyed path runs with the derived id instead of a 422; the replay test
pins the
  lost-200 retry to one conversation.
- Supporting evidence: the artifact file already carries this guard plus
the
  #19353 finalization-reason guard for the same endpoint. Distinct from
FC-server-bound-excludes-client-design-range (server range excludes
valid client
design values): here the client metadata itself was broken and the
server's job was
  to degrade, not to widen a bound.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/23886?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://cubic.dev/action/auto-fix/pr/BasedHardware/omi/23886?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23886&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants