Skip to content

fix(backend): derive calendar meeting doc id from natural key to prevent duplicate TOCTOU - #8294

Closed
ZachL111 wants to merge 4 commits into
BasedHardware:mainfrom
ZachL111:fix/calendar-meeting-duplicate-toctou
Closed

ZachL111 wants to merge 4 commits into
BasedHardware:mainfrom
ZachL111:fix/calendar-meeting-duplicate-toctou

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

POST /v1/calendar/meetings stores a meeting with a check-then-create pattern: the router calls get_meeting_id_by_calendar_event and only calls create_meeting when nothing was found. create_meeting writes to a fresh random Firestore document id every time, so two concurrent posts for the same calendar event both miss the existence check and each create a separate document. The result is duplicate meeting docs for one real calendar event, and later updates land on whichever copy the query happens to return. This change derives the document id deterministically from the natural key (uid, calendar_source, calendar_event_id) so concurrent creates converge on a single document instead of producing duplicates. This is a proactive hardening change; there is no filed GitHub issue for it.

Root cause

In backend/database/calendar_meetings.py, create_meeting always allocates a new auto-id document:

def create_meeting(uid: str, meeting_data: Dict) -> str:
    # Add timestamps (always in UTC for consistent querying)
    from datetime import timezone

    now = datetime.now(timezone.utc)
    meeting_data['created_at'] = now
    meeting_data['synced_at'] = now

    # Create document
    doc_ref = _get_meetings_collection(uid).document()
    doc_ref.set(meeting_data)

    return doc_ref.id

_get_meetings_collection(uid).document() with no id returns a random Firestore id, so each call writes a brand new document regardless of whether one already exists for that calendar event. The caller in backend/routers/calendar_meetings.py, store_calendar_meeting, guards this with a read first:

existing_meeting_id = calendar_db.get_meeting_id_by_calendar_event(
    uid, request.calendar_event_id, request.calendar_source
)

if existing_meeting_id:
    # Update existing meeting
    calendar_db.update_meeting(uid, existing_meeting_id, meeting_dict)
    meeting_id = existing_meeting_id
else:
    # Create new meeting
    meeting_id = calendar_db.create_meeting(uid, meeting_dict)

That read and the create are not atomic, so it is a time-of-check to time-of-use race. When the same event is posted twice close together (a client retry, or the macOS and mobile clients syncing the same event), both requests run get_meeting_id_by_calendar_event before either write commits, both see None, and both fall into the create branch. Two random-id documents are written for one event. From then on get_meeting_id_by_calendar_event uses .limit(1) and returns just one of them, so subsequent updates silently touch one copy while the duplicate stays stale.

Fix

When the meeting carries a natural key (calendar_event_id and calendar_source), derive the document id from it with document_id_from_seed and write with merge=True, so concurrent creates for the same event collide on one document instead of producing duplicates. created_at is only stamped when the document does not already exist, so a racing write does not reset it. Meetings without a natural key keep the old random-id path.

event_id = meeting_data.get('calendar_event_id')
source = meeting_data.get('calendar_source')
if event_id and source:
    doc_id = document_id_from_seed(f'{uid}:{source}:{event_id}')
    doc_ref = _get_meetings_collection(uid).document(doc_id)
    snapshot = doc_ref.get()
    if not snapshot.exists:
        meeting_data['created_at'] = now
    doc_ref.set(meeting_data, merge=True)
    return doc_ref.id

# Fallback: no natural key -> preserve old random-id behavior.
meeting_data['created_at'] = now
doc_ref = _get_meetings_collection(uid).document()
doc_ref.set(meeting_data)

document_id_from_seed already exists in backend/database/_client.py and is the same helper other domains use to make ids deterministic. A single first-time create behaves the same as before for the caller: it returns the document id and the stored fields are unchanged.

Testing

Added backend/tests/unit/test_calendar_meeting_duplicate_toctou.py, registered in backend/test.sh. database/calendar_meetings.py imports google.cloud.firestore and database._client at module top, so the test imports the real module from source under a meta-path stub finder that stubs only those heavy dependencies, then injects a real deterministic document_id_from_seed and a fake meetings collection. The fake collection returns the same document object for a given id and a fresh random-id object for document() with no id, mirroring Firestore semantics, so the duplicate behavior is observable.

Cases covered: two creates with identical calendar_event_id and calendar_source converge on one document (same returned id, exactly one materialized doc, no random-id docs created); the returned id matches the uid:source:calendar_event_id seed; and the second racing create does not overwrite created_at and merges into the existing doc. The patch uses create=True so it also applies against the pre-fix module, which means the red comes from the actual duplicate-doc behavior (two random ids) rather than a missing attribute. 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-id write 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.

1 issue found across 3 files

Confidence score: 3/5

  • In backend/database/calendar_meetings.py, the get() then conditional set() flow for created_at is still a TOCTOU race, so concurrent creates can overwrite the original timestamp and corrupt record chronology/audit semantics in production — switch this to an atomic write path (e.g., SETNX/single-statement upsert/transactional guard) before merging.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/database/calendar_meetings.py">

<violation number="1" location="backend/database/calendar_meetings.py:37">
P2: `created_at` protection is still racy: the new `get()` + conditional `set()` is a TOCTOU check and can overwrite `created_at` under concurrent creates.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

Comment thread backend/database/calendar_meetings.py Resolved

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

1 issue found across 2 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

Comment thread backend/database/calendar_meetings.py Resolved
@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