Skip to content

fix(backend): skip unknown folder ids in reorder_folders to avoid 500 - #8298

Closed
ZachL111 wants to merge 2 commits into
BasedHardware:mainfrom
ZachL111:fix/folders-reorder-missing-id
Closed

ZachL111 wants to merge 2 commits into
BasedHardware:mainfrom
ZachL111:fix/folders-reorder-missing-id

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

reorder_folders in the folders database layer writes a new order value for every folder id the client sends, with no check that those ids actually belong to the user. If the client sends a stale or foreign id (a folder that was deleted, or one that was never theirs), the Firestore batch tries to update a document that does not exist and the whole reorder request fails with a 500. One bad id in the list takes down the entire reorder, so none of the folders get reordered. This change scopes the writes to ids the user actually owns and skips the rest. This is a proactive hardening change; there is no filed GitHub issue for it.

Root cause

In backend/database/folders.py, reorder_folders loops over the client-supplied ids and calls batch.update on each one directly:

def reorder_folders(uid: str, folder_ids: List[str]) -> bool:
    """Reorder folders by providing an ordered list of folder IDs."""
    user_ref = db.collection('users').document(uid)
    folders_ref = user_ref.collection('folders')

    batch = db.batch()
    for i, folder_id in enumerate(folder_ids):
        folder_ref = folders_ref.document(folder_id)
        batch.update(folder_ref, {'order': i, 'updated_at': datetime.now(timezone.utc)})

    batch.commit()
    return True

batch.update requires the target document to exist. When folder_ids contains an id that has no folder document under users/{uid}/folders, the missing write surfaces as a google.api_core.exceptions.NotFound at batch.commit() time. Firestore batches are all-or-nothing, so that single missing id aborts every write in the batch and the handler returns an unhandled 500. A client holding a stale folder list (deleted on another device, or just out of sync) is enough to trigger it.

Fix

Read the user's real folder ids first via get_folders, then skip any id in the request that is not in that set. Owned ids are written with sequential order values using a separate counter so the gaps left by skipped ids do not leave holes in the ordering:

existing_ids = {f['id'] for f in get_folders(uid)}

batch = db.batch()
order = 0
for folder_id in folder_ids:
    if folder_id not in existing_ids:
        continue
    folder_ref = folders_ref.document(folder_id)
    batch.update(folder_ref, {'order': order, 'updated_at': datetime.now(timezone.utc)})
    order += 1

batch.commit()
return True

For a request where every id is valid the behavior is unchanged: every folder is written, with the same 0..n-1 order values it had before.

Testing

Added backend/tests/unit/test_folders_reorder_missing_id.py, registered in backend/test.sh. reorder_folders pulls in the Google Cloud SDK, the models package, and the Firestore singleton, so the test imports the real database.folders module under a stub finder that auto-mocks only those heavy transitive deps, then calls reorder_folders directly. A fake batch stands in for the Firestore WriteBatch and raises a NotFound stand-in from update() for any ref whose id is not in the valid set, which makes the 500 concrete. The cases covered: a list mixing a ghost id with two real folders skips the ghost, commits once, and writes only the real folders with sequential order values (never touching the ghost id); and an all-valid reorder still writes every folder in the requested order. Verified red to green: the test fails on current main and passes with this change.

PR status check

No open PR changes this logic. The existence check added here does not appear anywhere in the history of backend/database/folders.py, so this 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.

Tip: cubic could auto-approve low-risk PRs like this, if it thinks it's safe to merge. Learn more

Re-trigger cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Hi @ZachL111 — thank you for finding and writing up this reliability issue. We’re consolidating this set of Firestore/data-mutation fixes into a smaller aggregate PR so the long-term shape is easier to maintain and review: #8362.

Your original discovery, reproduction details, and candidate fix are credited in the new PR body and commit metadata. I’m closing this individual PR as superseded by #8362, not because the issue is invalid. Thanks again for surfacing it.

@Git-on-my-level

Copy link
Copy Markdown
Member

Superseded by #8362. Thanks again @ZachL111 — credited there for the original discovery and candidate fix.

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

Git-on-my-level added a commit that referenced this pull request Jun 25, 2026
## Summary

This is an aggregated, systematic replacement for ZachL111's
Firestore/data-mutation hardening PRs. Rather than merging a set of
one-off patches that silently skip missing records, this PR adds
explicit invariants and shared helpers:

- shared deterministic document-id helpers for system folders and
calendar meetings
- idempotent calendar meeting create/upsert that preserves the original
`created_at`
- transactional speech-sample removal so `speech_samples` and
`speech_sample_transcripts` stay aligned
- explicit `BatchMutationResult` reporting for action-item batch
updates/sync (`updated_ids`, `missing_ids`, `noop_ids`)
- downstream vector updates now run only for successfully updated sync
items
- folder delete/reorder validates targets before mutating instead of
silently skipping unknown IDs

Supersedes #8294, #8297, #8298, #8301, #8307, #8316, #8322.

Original issue discovery, reproductions, and candidate fixes by
@ZachL111 — thank you for surfacing these reliability problems. This PR
rewrites them into a smaller shared-contract shape to reduce long-term
maintenance cost.

## Test plan

- [x] `uv run --with pytest --with pydantic python -m pytest
tests/unit/test_firestore_invariant_helpers.py -q`
- [x] `python3 -m py_compile backend/database/document_ids.py
backend/database/_client.py backend/database/folders.py
backend/database/calendar_meetings.py backend/database/users.py
backend/database/action_items.py backend/routers/action_items.py
backend/routers/folders.py backend/models/folder.py
backend/tests/unit/test_firestore_invariant_helpers.py`

## Notes / intentional differences from source PRs

- #8298/#8301/#8307 are redesigned: missing IDs are explicit in the
response instead of being silently skipped or allowed to fail a whole
Firestore batch invisibly.
- #8322 uses a shared `system_folder_doc_id()` helper instead of local
seed-string construction.
- #8294 uses a shared `calendar_meeting_doc_id()` helper. The current
public API only exposes `calendar_source` and `calendar_event_id` as
provider uniqueness dimensions; if provider-account/calendar IDs are
added later, this helper is the single extension point.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/8362?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Git-on-my-level pushed a commit to Git-on-my-level/omi that referenced this pull request Jun 25, 2026
- add shared deterministic document ID helpers for system folders and calendar meetings
- make calendar meeting creates idempotent while preserving created_at
- remove speech samples transactionally to keep samples/transcripts aligned
- report missing action-item IDs explicitly and only update downstream vectors for successful sync writes
- validate folder deletion/reorder targets before mutating

Supersedes BasedHardware#8294, BasedHardware#8297, BasedHardware#8298, BasedHardware#8301, BasedHardware#8307, BasedHardware#8316, BasedHardware#8322.
Original issue discovery, reproductions, and candidate fixes by @ZachL111.

Co-authored-by: Zach <[email protected]>
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.

2 participants