Skip to content

fix(recaps): validate reads and preserve recovery responses - #21347

Merged
aryanorastar merged 6 commits into
BasedHardware:mainfrom
kaleidoscopeAI:fix/daily-summaries-validation-resilience
Oct 27, 2026
Merged

aryanorastar merged 6 commits into
BasedHardware:mainfrom
kaleidoscopeAI:fix/daily-summaries-validation-resilience

Conversation

@kaleidoscopeAI

@kaleidoscopeAI kaleidoscopeAI commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Malformed Daily Recap records can crash reads, and invalid generated content must not be saved as the completed recap that later retries reuse. This completes the existing validation PR at the read and generation/persistence boundaries.

  • Keep the shared read/JSON-validation guard, valid-row pagination and search limits, bounded scans, content-free validation logs, and the public-sharing allowlist. Corrupt-only owner reads return 503 rather than a false empty account; missing/private public records remain 404.
  • Validate generated candidates before persistence in both legacy and V4 producers, including scheduled and on-demand work. Their existing failure handling releases the day lock and retains retryable failure state. The manual notification-preview route also validates before saving or delivering; regeneration still validates before overwrite.
  • Creation returns only completed existing records. V4 pending/failed/not-generated state rows re-enter the real producer, so a failed attempt can generate on retry; a live competing day lock returns 409. Existing malformed completed records remain preserved, without automatic paid regeneration or source-conversation changes.

Original validation approach and baseline tests by @kaleidoscopeAI; contributor commits remain intact. Maintainer fixes extend this same PR rather than duplicate it.

Verification

  • Review at 1a6bed0 found a genuine P2: the saving helper persisted an invalid record before the route returned 502, and retry returned 503 without generation. The old retry test replaced that helper and could not detect the write. New tests failed in both producer modes on unchanged code; that test has been replaced.
  • 138 affected unit tests passed through backend/test.sh. All 24 real-main.app integration cases passed, with actual producer selection, source eligibility/deserialization, day locks, Firestore create/update, state markers, response serialization and idempotency. Only paid-compute/model/provider boundaries and the hermetic datastore adapters are substituted; the generation/persistence helper is not replaced.
  • Failure/retry cases cover invalid schema, non-JSON content and invalid root payloads in both legacy and V4 modes; invalid refresh preserves previous content/ID/sharing, and a healthy retry replaces it in place. Existing content and source conversations remain intact; a third creation returns the stored recap without another model call.
  • Local uvicorn/curl independently returned 502 -> 200 -> 200 in both modes: no invalid generated record after failure, only a V4 failed state where applicable, one completed recap after retry and exactly two model calls. No production/customer data or provider transaction was used.
  • Current-head CI is green at 7e8af1b47faa65610f5b99667ef41346b2a797fd with ci:full: six backend unit shards and guardrails, hermetic backend E2E (165 passed, three skipped, two expected failures), both stack gauntlets, API/emulator/runtime/source contracts, formatting/hygiene, and the full Flutter analyzer/test check. The normal push gate also passed all 38 preflight checks and reported zero backend type errors. Prior 626 unit/query results at 1a6bed0 are historical evidence, not proof for this follow-up. The final diff was reviewed; fix(recaps): validate reads and preserve recovery responses #21347 remains draft for re-review as requested.

Rollout: after review/merge, deploy the API backend serving recap routes and the notifications job using the changed shared producers. No new mobile build, credential or index is required. Existing malformed historical data and these customers' actual missing recaps/recording sync require separate Support investigation; these fixtures do not establish their cause or recovery.

Closes #21360 (technical work; the separate Support case stays open). Existing references: #8264, #1551.

Failure-Class: FC-malformed-doc-read
Line-Count-Exception: backend/routers/users.py | 2724 -> 2773 | Validate recap candidates at the owning producer before persistence while preserving explicit failure and retry behavior.
Line-Count-Exception: backend/routers/developer.py | 2828 -> 2834 | Validate recap candidates at the owning producer before persistence while preserving explicit failure and retry behavior.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-27T17:11:45.455607Z 7e8af1b Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@kaleidoscopeAI
kaleidoscopeAI force-pushed the fix/daily-summaries-validation-resilience branch 2 times, most recently from 848ce9a to baa6f31 Compare October 13, 2026 01:16
…ResponseValidationError crashes

Failure-Class: none
@kaleidoscopeAI
kaleidoscopeAI force-pushed the fix/daily-summaries-validation-resilience branch from baa6f31 to 69c38cc Compare October 13, 2026 01:24
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @kaleidoscopeAI — clean, well-scoped hardening fix, and the 404-instead-of-500 semantics for corrupt documents is the right call. Reviewed all three files:

  • backend/routers/developer.py — get_developer_daily_summaries (lines ~1293-1307) and get_developer_daily_summary (lines ~1336-1348): per-record validation with warnings and skip/404 correctly prevents one malformed Firestore doc from 500ing a whole page. I verified this genuinely mirrors the existing action-item hardening further up in the same file (lines ~820-840), so it's consistent with the established pattern, including the audit finally-block receiving the correct returned_count and status in the 404 paths.
  • backend/routers/users.py — get_daily_summaries (~1922-1931), search_daily_summaries (~2014-2023), get_daily_summary (~2032-2038): same validate-and-skip loop applied consistently. Good detail that search validates after filter_daily_summaries so corrupt-but-matching records can't crash the search either.
  • backend/tests/unit/test_daily_summary_validation_resilience.py — hermetic tests with mocked daily_summaries_db covering both list endpoints, both get-by-id 404 paths, and search. The non-dict record ("non-dict-record") and missing-date cases are nice adversarial fixtures.

Two non-blocking nits for consideration:

  1. In developer.py the sibling action-item code catches pydantic's ValidationError specifically; the new blocks catch bare Exception. Practically equivalent for pydantic v2 model_validate, but tightening to ValidationError would match the file's own convention.
  2. In the users.py list endpoints a corrupt record is skipped silently from the client's perspective (no count/flag) — consistent with the developer-API pattern, so fine, just noting the product tradeoff.

Checks are green and the change is read-only with no auth/scope changes. Leaving for human maintainer review before merge; nothing blocking from my side.


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

…nvention

The new validate-and-skip blocks in developer.py caught bare `Exception`;
the sibling action-item/conversation hardening in the same file catches
pydantic's `ValidationError` specifically. Tighten the two new blocks to
match, addressing review nit 1.
@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed all three changed files against the head commit — this is a solid, well-scoped hardening and the approach matches the pattern already established for action items in developer.py. Thank you!

backend/routers/developer.py — get_developer_daily_summaries now validates each record via DailySummaryResponse.model_validate and logs+skips malformed/legacy docs instead of letting one bad document 500 the whole page, and returned_count now correctly reflects the filtered list. get_developer_daily_summary maps corrupt documents to a clean 404 inside the existing try/finally audit block, so audit status stays accurate. The narrow except ValidationError matches the file's existing idiom.

backend/routers/users.py — the list, search, and single-get endpoints get the same per-record treatment. I checked utils/daily_summary_search.filter_daily_summaries: it is already defensive with isinstance checks, so filtering itself never crashed; the fix correctly addresses the response-serialization failure that came after it. The single-get 404 fallback is right.

backend/tests/unit/test_daily_summary_validation_resilience.py — good hermetic coverage: corrupt nested memories_learned entries, non-dict records, missing docs, and a search case, across all five endpoints, with DB calls patched out. Backend unit suite and the hermetic merge gate are green on this head.

Two minor, non-blocking notes for a follow-up if you feel like it:

  1. users.py uses except Exception around model_validate while developer.py uses except ValidationError — the broad catch is safe here given the 404 fallback, but the narrower one documents intent better (it just needs a ValidationError import).
  2. The regenerate and shared-summary endpoints still return stored docs unvalidated, so a corrupt doc could still 500 those paths — pre-existing behavior, happy to see it in a follow-up.

Leaving this ready for a maintainer merge decision.


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

aryanorastar added a commit that referenced this pull request Oct 16, 2026
…ciliation (#21362)

## 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](https://raw.githubusercontent.com/BasedHardware/omi/04dda1ae63f6cca9181534b01de1bfac73300b47/.agent-artifacts/ui-evidence/daily-recap-recovery-completeness/001-mobile-ios-recovery-dark.png)
![Legacy sync needs
attention](https://raw.githubusercontent.com/BasedHardware/omi/04dda1ae63f6cca9181534b01de1bfac73300b47/.agent-artifacts/ui-evidence/daily-recap-recovery-completeness/003-mobile-ios-sync-needs-attention.png)
![Confirmed
processing](https://raw.githubusercontent.com/BasedHardware/omi/04dda1ae63f6cca9181534b01de1bfac73300b47/.agent-artifacts/ui-evidence/daily-recap-recovery-completeness/004-mobile-ios-sync-processed.png)

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

Copy link
Copy Markdown
Contributor Author

Gentle ping for maintainer review — all 7/7 hermetic unit tests are green, and the per-record validation approach matches the pattern established in developer.py. Ready to merge whenever convenient!

@aryanorastar
aryanorastar marked this pull request as draft October 27, 2026 14:02
@aryanorastar aryanorastar changed the title fix(daily-summaries): validate recap records individually to prevent ResponseValidationError crashes fix(recaps): validate reads and preserve recovery responses Oct 27, 2026
@aryanorastar aryanorastar added the ci:full Maintainer-granted: run full CI on this fork PR label Oct 27, 2026 — with ChatGPT Codex Connector
@aryanorastar
aryanorastar marked this pull request as ready for review October 27, 2026 17:11
@aryanorastar
aryanorastar merged commit 5ffeb08 into BasedHardware:main Oct 27, 2026
53 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) ci:full Maintainer-granted: run full CI on this fork PR positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Follow up: Daily Recap gaps and unverified recording sync after the October outage

3 participants