Skip to content

fix(recaps,sync): complete historical recovery and stuck-upload reconciliation - #21362

Merged
aryanorastar merged 4 commits into
mainfrom
fix/daily-recap-recovery-completeness
Oct 16, 2026
Merged

aryanorastar merged 4 commits into
mainfrom
fix/daily-recap-recovery-completeness

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Daily Recap recovery was unreachable on mobile/web, and successful recovery could still disappear behind an older read or remain hidden on Home. Offline Sync also left restored uploads without a job handle permanently processing and overstated what successful processing proved. Complete the recovery path and reconcile these remaining sync/reporting gaps. Fixes #11821; remaining customer-account outcomes are tracked by #21360.

  • Add historical-date recovery to mobile Notifications settings/Daily Recaps and web Conversations using the existing idempotent POST /v1/users/daily-summaries authority. No push token or enabled schedule is needed; source recordings and existing recaps are preserved.
  • Publish successful mobile recovery to mounted Home readers, including a previously empty Home section. Fence older reads, preserve existing cards on failures, and offer retry. A malformed list envelope is a read failure, not an empty account.
  • Give web recap snapshots owner-scoped cache keys and one read lease for initial load/refresh/pagination. Re-read after a creation/deletion commits before adopting an older result, retain chronological order and server offsets, reject late data after account switches, and surface recap read failures with a specific retry.
  • Reconcile uploaded WALs with missing/blank job handles: requeue retained audio through the existing deduplicated upload path without consuming retries; preserve unavailable rows when local audio is missing. Persist the outcome and fence asynchronous file checks on account changes.
  • Show Processed rather than inventing a created conversation for an empty/silent completed job. The legacy status card and empty-pending state no longer claim completion while another recording needs attention. Local-copy cleanup copy states the deletion period without promising a cloud audio copy. Retention behavior, storage settings, capacity controls and batching are unchanged.

Product invariants affected

INV-CAP-1 — retained recordings stay intact through orphan-job recovery. Requeueing preserves audio and retry budget; missing-file outcomes remain visible rather than being acknowledged as synced. No deletion or retention policy changes.

How it was verified

  • bash app/test.sh: full hermetic suite passed, 5,368 passed / 21 skipped. Analyzer ratchet passed; existing informational diagnostics remain within baseline.
  • Focused mobile recovery/API/Home/sync tests: 176 passed. WAL suite also passed with CAPTURE_EVIDENCE_V1_DARK_WRITE=true: 146 passed.
  • make mobile-verify ARGS='fast --paths app/lib/pages/home/widgets/home_daily_recaps.dart app/lib/pages/conversations/sync_page.dart app/lib/pages/conversations/auto_sync_page.dart app/lib/services/wals/local_wal_sync.dart': 23 existing relevant journeys passed. These are the seeded journey lane, separate from the new focused recovery tests.
  • bun run check: typecheck, Moonshine smoke, and the full current web suite passed: 127 files / 682 tests. The final recap lifecycle file passed all 8 tests.
  • Actual WAL service lifecycle regression: restored orphaned upload → retained file requeued → upload ACK with job ID → job polling → confirmed processing/conversation result → durable index reload. Audio bytes stay unchanged; uploader/status transport are test seams, not a real-device/backend-capacity measurement.
  • Local HTTP smoke from the first commit exercised the real FastAPI creation/list routes and emulator storage: disabled schedule, no FCM token, missing October 4 recap beyond automatic catch-up, stable ID on retry, one generation, zero pushes, honest 400 for an empty date, and unchanged source conversation/prior recap/schedule. Only the summary provider and quota gate were fixture seams.
  • The recovery widget was exercised through that local API in an iOS simulator and browser preview. The final actual legacy/Auto Sync widgets were rendered with synthetic inventories and the bundled font, asserted, captured, and visually inspected. No physical customer-device or customer-account recovery test is claimed. Impeccable's final changed-target detector returned no findings.

Tests

daily_summary_creation_test.dart and apiDailyRecaps.test.ts: endpoint/date/response identity, malformed/legacy replies and status failures. daily_recap_recovery_action_test.dart and GenerateRecapAction.test.tsx: date selection, cancellation, single flight and honest failures. home_recap_recovery_test.dart: successful recovery from another screen reveals Home, older responses cannot hide it, and failed reads retry.

useRecapsCreation.test.ts: ownership, creation vs initial read, reads both before and during deletion, malformed-response retry, stable identity, chronological pagination and raw server offsets. ConversationSplitView.test.tsx verifies the user-facing read-error retry. local_wal_sync_test.dart covers missing/empty/whitespace handles, durable retry state, preserved bytes, unavailable audio, and the whole retained-file upload/poll lifecycle. sync_completion_truth_test.dart and sync_row_recovery_window_test.dart execute the actual sync screens/rows and prevent false completion, conversation and cloud-copy claims.

Release and customer verification

The October scheduler/gateway/retry fixes (#21020, #21304, #21310) are already on current main. Production notifications deployments for #21304 and #21310 succeeded on October 12. They restore the known generation failures and remain required context for this report.

This PR needs merge, a mobile release containing these changes, and web deployment. It uses existing backend contracts; no new backend deployment is required by this PR. macOS already uses the shared creation endpoint.

The remaining customer-account checks are operational verification, not an assertion that the client PR restored customer data: confirm scheduled recaps resumed, generate/check each missing eligible date from retained server conversations, and confirm every reported recording reached processing completion on the customer's installed release. The feedback lacks a platform/version/exact sync error; do not claim the orphan-job fix is its proven cause.

#21347 remains open for malformed stored recap read validation; #21319 remains open for pendant upload batching, and #21216 tracks capacity/backlog complaints. Their causes are not established for this customer. Do not duplicate those fixes or claim those separate symptoms solved by this PR. Keep #21360/Featurebase open until the account outcome is verified.

Local preflight passed all 27 checks. Architecture and implementation/release checklist: app/docs/recap-recovery.md.

UI evidence

Synthetic inventories; screenshots contain no customer data.

Recovery on iOS
Legacy sync needs attention
Confirmed processing

Failure class (fixes)

Failure-Class: FC-read-in-flight-across-delete-resurrects-row

The existing class covers stale list adoption across a committed mutation. The shared recap read owner fences both deletion and recovery; controllable-future tests cover reads admitted before and during deletion. The orphan-upload and missing-control changes are separate concrete gaps, guarded by their service/UI regression tests.

Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2690 -> 2728 | Keep orphan-job reconciliation, snapshot iteration, post-await row revalidation, persistence and session fencing inside the existing WAL lifecycle owner rather than splitting mutation authority.

@aryanorastar aryanorastar changed the title fix(recaps): make historical recovery reachable on mobile and web fix(recaps,sync): complete historical recovery and stuck-upload reconciliation Oct 13, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @aryanorastar — reviewed this end to end against the current tree. This is a strong, cohesive completion of the recap-recovery path; a few notes below, nothing blocking.

What I verified:

  • Backend authority: the new clients assume POST /v1/users/daily-summaries — confirmed it exists on main (backend/routers/users.py, create_user_daily_summary) with exactly the semantics the UI maps: returns an existing record for the date without spending tokens, 429 cooldown armed only after a real generation, 409 while another writer holds the day, 422 for future dates, 400 for nothing-to-summarize, 402 via quota. The status switches in daily_recap_recovery_action.dart and recapGeneration.ts line up one-for-one.
  • app/lib/backend/http/api/daily_summary_creation.dart: strict envelope validation (non-empty string id, date echo, TypeError → FormatException) and session-snapshot fencing so a late result after an account switch surfaces authTerminal instead of stale data. Good.
  • app/lib/services/wals/local_wal_sync.dart: the new orphan pass in reconcileUploadedWals (uploaded rows with null/blank jobId) correctly splits retained audio → miss (re-enters the deduplicated upload path with retryCount preserved, per the new tests) vs missing audio → corrupted/unavailable, with _isCurrent(generation) checks after every await and a reconcile_revert log event. This closes the permanently-"processing" state cleanly.
  • web/app/src/hooks/useRecaps.ts: the rewrite is the riskiest file here and it holds up — owner-scoped cache keys, one read lease shared across initial/refresh/pagination, mutationRevision forcing in-flight reads to re-read after a create/delete (a stale page can't erase a recovered row or resurrect a deleted one), generation fencing for account churn, and server offsets kept while sorting chronologically. The 196-line useRecapsCreation.test.ts covers the important races; I ran the four new/changed web test files locally and all pass.
  • Truthfulness fixes: "Processed" instead of inventing a created conversation (sync_page.dart, auto_sync_page.dart), the pending empty state no longer claims all-caught-up while recordings need attention, and the auto-remove copy states the deletion period without promising a cloud copy. The removal of the daily-summary-settings/test caller in users.dart leaves no dangling references in app or web source (the generated API client still carries the path type, which is expected since the backend keeps the route for released clients).
  • l10n: every key the new Dart code touches already exists in app_en.arb, so no ARB churn here is correct rather than an oversight.
  • Docs: PRODUCT.md addition is narrow, and app/docs/recap-recovery.md matches the implemented behavior (I spot-checked the endpoint/date-picking claims against the code). Changelog fragment and UI evidence follow existing conventions.

Minor, non-blocking:

  1. syncStatusConversationCreated is now unused in app/lib — worth a follow-up sweep with scripts/l10n.py remove so the ARB set doesn't carry a dead key across locales.
  2. GenerateRecapAction.tsx recomputes today/yesterday/oldest on every render; a memo would keep the selectable window stable across a re-render that crosses midnight (edge case, purely cosmetic).

No security, privacy, workflow, or dependency surfaces touched, and CI is green across the Dart, Android, and web lanes. Leaving for normal maintainer merge review — the cross-client state-consistency reasoning (read leases, WAL reconciliation) is the part worth a human's eyes before merge, and it reads correct to me.


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

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

Solid recap-recovery + WAL-reconciliation work with real test coverage, CI green, CLEAN merge state. Not merging: this bundles multiple feature-shaped additions (new historical-date recovery UI, new web recap caching, WAL reconciliation) across mobile+web in a single 1900+ line change, well above the scoped-diff bar for this area — treating as feature-shaped per policy's default-to-feature-when-unsure rule, so approve-only.

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified this end to end against the current head — a few notes for the record:

  • The shared creation authority checks out: POST /v1/users/daily-summaries (backend/routers/users.py:1925, unchanged by this PR) is idempotent for an existing date, requires no push token, and its status semantics (422 future date, 429 post-generation cooldown, 409 while the cron is mid-generation, 400 nothing-to-summarize) map exactly onto the client error handling in web/app/src/lib/recapGeneration.ts and the Dart ApiFailure paths in daily_summary_creation.dart.
  • reconcileUploadedWals in app/lib/services/wals/local_wal_sync.dart correctly reverts uploaded rows with a null/blank jobId: retained audio re-enters the deduplicated upload path with retryCount preserved, missing audio stays visible as unavailable rather than being silently dropped. The _isCurrent(generation) fence after each async file check handles account switches cleanly.
  • The useRecaps.ts rewrite is the right shape: owner-scoped cache keys, one read lease across initial load/refresh/pagination, and the mutation-revision re-read so a stale in-flight response can't erase a recovered row or resurrect a deleted one. One minor nit, non-blocking: the re-read loop in readPage has no explicit bound when a mutation lands mid-read; it converges after one extra fetch in practice.
  • Removal of the legacy daily-summary-settings/test client paths leaves no orphaned in-tree callers (only the generated OpenAPI clients still reference the route, as expected), and all l10n keys used by the new UI (syncCardNeedsAttention, statusProcessed, autoRemoveSyncedCopiesDays, …) already exist.
  • Ran the changed web test files locally (CI's frontend lint was skipped here): 31/31 pass, including the account-churn and stale-read regression suites.

Thanks for the thorough recovery story — the truthfulness fixes around sync status ("Processed" instead of inventing a conversation) are a nice touch.


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

Copy link
Copy Markdown
Collaborator

@aryanorastar this conflicts with main now. Please rebase and push; it still looks valid.

…ery-completeness

Resolve conflicts with main's duration-based sync progress, consolidated
storage group and shared recap events: keep the PR's needs-attention sync
state and retention subtitle, move recovery onto announceRecapArrived
(dropping the PR's private DailyRecapUpdates notifier), and update the
recap docs and sync/recap tests to match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed a1e0c34: merged current main. It conflicted in three app files, now resolved.

  • Sync card (sync_page.dart): keeps main's audio-seconds progress ("Turning 2h into conversations") and adds this PR's needs-attention state after it. The old job-count line (processingProgress) is gone, since main removed it.
  • Storage settings (auto_sync_page.dart): keeps main's single Storage group. The auto-remove row keeps this PR's day-count subtitle, and main already applies retention immediately.
  • Home recaps (home_daily_recaps.dart): keeps main's arrival/deletion events and generation guard, plus this PR's 15 s timeout, load-failed state and refresh after "see all".
  • One recap event owner: recovery now calls main's shared announceRecapArrived, so this PR's private DailyRecapUpdates notifier is removed. A new Home test checks that a late read can't bring back a recap deleted mid-refresh.
  • Tests and docs: sync tests updated for audio-seconds progress. Added a 127-row backlog regression covering a 429, a transient read, missing job handles, unavailable audio and one job stuck in the queue; retained bytes are kept. The recap-recovery doc now cites the merged fix(sync): stop reconcile polling loop on rate limit and clear uploaded wals on delete pending (#21279) #21387, fix(app): bound sync upload batches by audio seconds, not file count #21319 and fix(sync): never strand backfill pending entries without an owner #21755.
  • Checks: Flutter 275 passed across 13 files. flutter analyze shows no new issues; 7 pre-existing infos in local_wal_sync.dart remain. Web recap tests 31 passed; tsc clean. The diff against main is this PR's files plus the new regression test.

@Git-on-my-level

Copy link
Copy Markdown
Member

Re-verified on the new merged head a1e0c34 (merge of current main + conflict resolution). Everything substantive from my earlier reviews still holds on this tree, and the new bits check out:

  • Merge resolution: the three conflicted app files resolved cleanly. Notably, the intermediate daily_recap_updates.dart notifier from the first commit is gone at this head — recovery now publishes through the pre-existing recap_events.dart announceRecapArrived stream, so there is exactly one recap-event owner and Home/Activity readers refresh from a single channel. home_recap_recovery_test.dart covers the previously-empty-Home case, and daily_recaps_page.dart reloads server pagination after recovery instead of splicing an older row into page one (avoids the pagination-skip bug).
  • WAL reconciliation (local_wal_sync.dart) re-checked on the merged tree: orphaned uploaded rows (null/blank jobId) requeue retained audio via WalStatus.miss with retryCount preserved and lastRetryAt pacing; missing audio goes markCorrupted and stays visible as unavailable. _isCurrent(generation) fences after each awaited _localFileExists, and the reconcile_revert event is persisted for diagnosis.
  • Backend authority unchanged by the merge: POST /v1/users/daily-summaries on current main is still idempotent for an existing date (no LLM spend, no push token), with 422/429/409/400 semantics mapping one-for-one onto the client error paths in daily_summary_creation.dart and recapGeneration.ts.
  • CI on this exact head: Dart Analyze & Tests, Android Emulator Acceptance, Android JVM, CodeQL, and the Backend Hermetic Merge Gate are all green. Frontend Lint was skipped again despite the web changes, so I ran the web verification locally in a worktree: bun install --frozen-lockfile clean, bun run typecheck clean, full vitest suite 133 files / 715 tests passed (including the account-churn and stale-read regression suites).

Note for whoever merges: @kodjima33's approval attaches to 04dda1a, before this merge — the only movement since is the main merge plus the notifier/stream swap described above, which reads as an improvement, but the approval technically predates this head.

No dependency, workflow, or backend surfaces touched. Fine from my side for maintainer merge on this head.


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

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

aryanorastar trusted contributor but 2095-line bundle adds entirely new UI surfaces alongside claimed fix - fails scoped-diff criterion, feature-shaped. Approve only.

The orphan-upload recovery loop iterated _wals.where(...) and awaited
_localFileExists inside the live iteration, so addExternalWal admitting
a recording mid-pass threw ConcurrentModificationError and stalled
recovery. Walk a snapshot instead, and after every await re-read the row:
it must still belong to this sync and still be uploaded under the same
job handle, so a row an upload re-claimed, retention released, or another
path finished is never overwritten.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed 8e53eb6: orphan-upload reconciliation no longer crashes when a recording arrives mid-pass, and it re-reads rows before moving them.

  • Bug: the orphan loop in local_wal_sync.dart iterated _wals.where(...) and awaited _localFileExists inside the live iteration. addExternalWal appends synchronously before its first await, so a recording admitted mid-pass threw ConcurrentModificationError and stalled recovery.
  • Fix: the pass walks a snapshot of candidates. After every await, _stillUploadedUnder re-reads the row: it must still belong to this sync and still be uploaded under the same job handle (blank for orphans). A row an upload re-claimed under a new job, retention released, or another path finished is left as it is. The same check guards the not-found, completed and failed job paths, which also write to rows captured before an await.
  • Tests (sync_poll_storm_test.dart):
    • Through the real reconcileUploadedWals and addExternalWal: the pass completes, orphan audio is recovered and persisted, the incoming recording stays intact and durable, no audio is deleted and no retry budget is spent. The original code fails this with "Concurrent modification during iteration".
    • Rows changed during a file check keep their newer state; job polling still runs for the newly claimed handle.
    • An account change mid-check moves nothing.
  • Checks: 47 WAL/sync suites, 564 passed. flutter analyze shows no new issues; the 7 pre-existing infos remain. Web via Bun: typecheck clean, 31 passed. make preflight: 28 checks passed.
  • PR body: the local_wal_sync.dart line-count exception now reads 2690 -> 2728 (current main plus this fix). The recap-recovery doc and checklist are updated.

@aryanorastar
aryanorastar merged commit a34502c into main Oct 16, 2026
45 checks passed
@aryanorastar
aryanorastar deleted the fix/daily-recap-recovery-completeness branch October 16, 2026 17:19
aryanorastar added a commit that referenced this pull request Oct 16, 2026
…io (#21829)

## What changed and why

Bound a ring-buffer download that becomes silent after READ_BEGIN or
DATA. The
initial five-second timeout was cancelled on BEGIN, leaving only a
30-minute
overall deadline. A connected, stalled read therefore kept the transfer
owner
busy instead of yielding to normal capture/retry orchestration.

- Reset a 15-second idle deadline on the first valid BEGIN and nonempty
DATA,
matching the existing legacy SD idle bound. Repeated BEGIN, empty DATA
and
  control chatter are not progress.
- Observe arrival before queued custody/disk work. On timeout, stop
admitting
notifications, send STOP on the original connection epoch, drain already
received bytes and flush complete records through the existing durable
WAL
owner. Do not acknowledge an unfinished source or advance an unproven
frontier.
- Cancel idle timers on completion/error and put read-command failures
through
the same cleanup. A valid DONE arrival cancels the radio idle deadline
even
while its validation waits behind custody I/O. Healthy DONE and existing
  custody capability gates remain.
- Make the ring custody fixtures wait for read/status admission rather
than
  fixed startup sleeps, keeping the original durable-advance assertions.
- Preserve the saved cause, original stack and phase when a read-command
  failure goes through cleanup; keep catch-and-continue behavior.

Related: #21279 (uploaded jobs queued/429), #21387 (merged polling
backoff),
#21319 (merged short-WAL batching), #21755 (merged backfill
dispatcher-owner
repair), #21823 (merged batch-worker quarantine), and #21362
(retained-upload
recovery). These are separate stages.
This PR does not close the customer case or assert that the reported 1.4
KB/s,
capture interruption, cloud worker state or missing recaps share this
cause.
No firmware version or diagnostic export was supplied for the Discord
0/127
report, and no production repair, storage deletion or deployment is
performed.

Why isn't this a shared primitive instead? The existing ring reader
already
owns read admission, STOP, notification ordering, durable flush and
frontier
validation. Its watchdog belongs inside that owner, not in a parallel
recovery
actor. The injectable timer tests the real owner without waiting 15
seconds.

## Product invariants affected

- INV-CAP-1 — complete received records still use existing durable
file/index
  registration. Timeout leaves the source pending and sends no unproven
advance. Legacy firmware may reclaim on BLE delivery before app
durability;
this does not repair or conceal that existing risk or promise recovery
of
  incomplete records.

## Verification

- Production ring-owner regression: 14 tests passed, including idle
BEGIN,
partial audio, ignored chatter, cancelled deadlines, healthy DONE and
bytes
queued behind a deliberately blocked custody check, with and without
DONE.
- Capture interruption/reconnect journey (`mobile-verify fast --paths
app/lib/services/wals/ring_storage_sync.dart`): 3 checks passed, no
skips.
- Full app analyzer ratchet: passed. `make preflight`: 25 checks passed.
- Broader ring/custody/capture regression suites: all 129 passed on the
final
code, including the diagnostic guard and the 14 ring-owner tests above.
- Diagnostic guard: confirmed red without the transfer failure's saved
error,
then green with its original stack, cause and phase preserved.
Changed-file
  analyzer: no issues found.
- Physical BLE throughput, microphone behavior, customer-account
processing
and released-app retest: not performed; require hardware/account
evidence.

Architecture and implementation/release checklist:
`app/docs/offline-sync-stall-recovery.md`. The listen/pusher pipeline
map is
updated. This needs a mobile release after merge, not a backend
deployment.

## UI evidence

UI-Evidence: none -- transfer lifecycle only; no UI, copy or layout
changes

## Failure class

Failure-Class: FC-sync-failure-records-drop-cause
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Recap backfill endpoint is unreachable from every client; e2e covers: masks the orphaned settings page

4 participants