Skip to content

fix(backend): skip malformed person docs in /v1/users/people list - #8264

Closed
ZachL111 wants to merge 2 commits into
BasedHardware:mainfrom
ZachL111:fix/people-list-name-poison
Closed

ZachL111 wants to merge 2 commits into
BasedHardware:mainfrom
ZachL111:fix/people-list-name-poison

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

GET /v1/users/people returns the user's whole contacts list, declared with response_model=List[Person]. The handler returns raw Firestore dicts and lets FastAPI coerce them against that model. Person.name is a required field with no default, so a single legacy or partial-write person doc that is missing name fails response validation and 500s the entire list, hiding every other valid person from the user. This PR builds each Person inside the handler and skips the malformed docs, so one bad record no longer takes down the whole response. This is a proactive hardening change; there is no filed GitHub issue for it.

Root cause

In backend/routers/users.py, get_all_people ends by returning the raw list:

@router.get('/v1/users/people', tags=['v1'], response_model=List[Person])
def get_all_people(include_speech_samples: bool = True, uid: str = Depends(auth.get_current_user_uid)):
    logger.info(f'get_all_people {include_speech_samples}')
    people = get_people(uid)
    if include_speech_samples:
        # Convert GCS paths to signed URLs for each person
        for i, person in enumerate(people):
            stored_paths = person.get('speech_samples', [])
            people[i]['speech_samples'] = get_speech_sample_signed_urls(stored_paths)
    return people

people is a list of raw Firestore dicts. Because the route sets response_model=List[Person], FastAPI validates each dict against Person when serializing the response. Person requires name (and id) with no default:

class Person(BaseModel):
    id: str
    name: str

So one doc missing name raises pydantic.ValidationError during response serialization, which FastAPI surfaces as a 500 for the whole page. The sibling get_single_person works on one record at a time, so it never hit this, but the list endpoint fails for all records on the first malformed one.

Fix

Validate each doc into a Person in the handler, inside a per-record try/except, and return only the ones that pass:

valid_people = []
for person in people:
    try:
        valid_people.append(Person.model_validate(person))
    except Exception as e:  # noqa: BLE001 - one malformed person must not 500 the whole list
        logger.warning(f"Skipping malformed person doc {person.get('id', 'unknown')}: {e}")
return valid_people

A malformed doc is logged and dropped instead of poisoning the page. For valid input nothing changes: the same people come back in the same order, now as already-validated Person models rather than dicts handed to FastAPI to coerce.

Testing

New backend/tests/unit/test_people_list_name_poison.py (registered in test.sh). routers.users has a heavy import graph, so the test imports it under a stub finder (database, utils, firebase, and other heavy packages are mocked) and calls get_all_people directly. models.* and pydantic are left real so the test exercises actual Person validation. get_people is patched to return a mix of records. Cases: a valid plus a name-less doc returns only the valid one as a Person, and an all-valid list returns every record. Verified red to green: the test fails on current main and passes with this change.

PR status check

No open PR changes this logic. PR #6946 edits routers/users.py for the unified auth and BYOK middleware rewiring, but it only changes the Depends on this handler, not the body that returns the raw list, so it does not address this bug. The guard added here does not appear anywhere in this file's history, so it is not a previously reverted fix being resubmitted. No filed GitHub issue matches.

Review in cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

No issues found across 3 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Re-trigger cubic

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

Backend hardening bug fix with regression test; matches established pattern. (auto-review)

@ZachL111
ZachL111 force-pushed the fix/people-list-name-poison branch from 42cf127 to 439bb72 Compare June 24, 2026 18:41
@Git-on-my-level

Copy link
Copy Markdown
Member

Hi @ZachL111 — thank you for finding and documenting this failure mode. We reviewed it as part of the broader backend reliability triage.

We’re not taking this patch as written because silently skipping malformed persisted records can hide data corruption and make counts/pagination/search results inconsistent. The issue you surfaced is still useful; the safer follow-up is a data-integrity/repair path with explicit invalid counts or failed IDs rather than silently dropping records on read.

I’m closing this PR to keep the review queue focused, not because the report was valueless. Thanks again for surfacing it.

@Git-on-my-level

Copy link
Copy Markdown
Member

Closing after aggregate triage: not taking this as written because it silently hides malformed persisted data. Thanks @ZachL111 for surfacing the issue.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @ZachL111 👋

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 roadmap and vision

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! 💜

aryanorastar added a commit that referenced this pull request Oct 27, 2026
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; #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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants