Repository navigation
fix(backend): make system folder ids deterministic to prevent duplicate folders on concurrent init - #8322
fix(backend): make system folder ids deterministic to prevent duplicate folders on concurrent init#8322ZachL111 wants to merge 2 commits into
Conversation
…te folders on concurrent init
… duplicate-folder race
|
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. |
|
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:
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! 💜 |
## 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. -->
- 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]>
Summary
initialize_system_foldersinbackend/database/folders.pyseeds a new user's three system folders on first access. It checks whether the folders collection is empty and, if so, creates each folder under a fresh randomuuid4doc id. Two requests that hit this path at the same time (for example two clients, or a retry firing while the first call is still running) both read an empty collection and both create three folders with different random ids, so the user ends up with six system folders instead of three. This change derives each folder's doc id deterministically from the uid and the folder category, so concurrent initializers write the same three doc ids and the second write overwrites instead of duplicating.Root cause
In
backend/database/folders.py,initialize_system_foldersis a check-then-create with no idempotency on the write:The empty-collection read and the creating writes are not atomic, so the check does not protect against a concurrent caller. Because each doc id comes from
str(uuid.uuid4()), the two callers pick six different ids and eachsetcreates a brand new document. Nothing collides, so nothing is deduplicated, and the user is left with two copies of every system folder. This is a TOCTOU race that produces duplicate documents, not a crash.Fix
Derive each system folder's doc id from a natural key (
uid+ the folder'scategory_mapping) using the existingdocument_id_from_seedhelper indatabase/_client.py, instead of a random uuid:document_id_from_seedis a pure SHA-256 over the seed, so a given uid and category always map to the same id. Concurrent initializers now target the same three documents, and the slower writer overwrites the faster one with identical content. For a single, non-racing caller the behavior is unchanged: three system folders are created with stable ids and the same returned shape.Testing
Added
backend/tests/unit/test_system_folders_deterministic_ids.py, registered inbackend/test.sh.database.foldersis imported under a stub finder that fakes the heavy third-party packages (firebase_admin, google, pinecone, redis, and so on) while runningdatabase._clientanddatabase.foldersfor real, so the actualdocument_id_from_seedderivation executes. The test drivesinitialize_system_folderswith a fresh mocked Firestore (empty collection so it proceeds to create) and records the doc ids passed tofolders_ref.document(...). It covers: two independent first-access runs for the same uid produce the identical set of three doc ids (this is the duplicate-folder race, and it fails with random uuids), the returned docs carry those same ids, the ids match the seededuid + category_mappingderivation, and two different uids never collide on the same ids. 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 deterministic doc id derivation added here does not appear anywhere in the history of
backend/database/folders.py, so it is not a previously reverted fix being resubmitted. No filed GitHub issue matches this duplicate-folder behavior.