Skip to content

fix(backend): make remove_person_speech_sample transactional - #8316

Closed
ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/remove-speech-sample-transactional
Closed

ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/remove-speech-sample-transactional

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

remove_person_speech_sample in backend/database/users.py deletes a speech sample path and its aligned transcript from two parallel arrays (speech_samples and speech_sample_transcripts) on a person document. It does a plain read, mutates the lists in memory, then writes both back. Because the read and the write are separate Firestore calls with nothing tying them together, two removes (or a remove racing an add) running at the same time both read the same starting state and the second write clobbers the first, so one deletion is silently lost and the two arrays can drift out of alignment. This change wraps the read-modify-write in a Firestore transaction so the whole operation is atomic, matching add_person_speech_sample, which is already transactional.

Root cause

In backend/database/users.py, remove_person_speech_sample reads with a bare get() and writes with a bare update():

person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()

if not person_doc.exists:
    return False

person_data = person_doc.to_dict()
samples = person_data.get('speech_samples', [])
transcripts = person_data.get('speech_sample_transcripts', [])

# Find index of sample to remove
try:
    idx = samples.index(sample_path)
except ValueError:
    return False  # Sample not found

# Remove from both arrays by index
samples.pop(idx)
if idx < len(transcripts):
    transcripts.pop(idx)

person_ref.update(
    {
        'speech_samples': samples,
        'speech_sample_transcripts': transcripts,
        'updated_at': datetime.now(timezone.utc),
    }
)
return True

The get() and the update() are independent operations. There is no transaction and no optimistic check on the document version, so this is a classic read-modify-write race. If two requests remove different samples at the same time, both read the original list, each pops one entry, and each writes the whole list back. The last write wins and the other removal is dropped. The same window lets the speech_samples and speech_sample_transcripts arrays go out of sync, which then corrupts the by-index pairing the function depends on. add_person_speech_sample right above it already guards against exactly this by running its read-modify-write inside db.transaction(), so the remove path was the inconsistent one.

Fix

Move the read-modify-write into a @transactional helper and have the public function drive it with a real db.transaction(). The read now uses get(transaction=transaction) and the write uses transaction.update(...), so Firestore retries the whole block on a conflicting concurrent write instead of letting one update overwrite another.

@transactional
def _remove_sample_transaction(transaction, person_ref, sample_path):
    """Transaction to atomically remove a sample and its aligned transcript."""
    snapshot = person_ref.get(transaction=transaction)
    if not snapshot.exists:
        return False

    person_data = snapshot.to_dict()
    samples = person_data.get('speech_samples', [])
    transcripts = person_data.get('speech_sample_transcripts', [])

    try:
        idx = samples.index(sample_path)
    except ValueError:
        return False  # Sample not found

    samples.pop(idx)
    if idx < len(transcripts):
        transcripts.pop(idx)

    transaction.update(
        person_ref,
        {
            'speech_samples': samples,
            'speech_sample_transcripts': transcripts,
            'updated_at': datetime.now(timezone.utc),
        },
    )
    return True


def remove_person_speech_sample(uid: str, person_id: str, sample_path: str) -> bool:
    person_ref = db.collection('users').document(uid).collection('people').document(person_id)
    return _remove_sample_transaction(db.transaction(), person_ref, sample_path)

The return values and the by-index removal logic are unchanged. A single, uncontended remove behaves exactly as before and still returns True on success, False when the person or the sample is not found.

Testing

Added backend/tests/unit/test_users_remove_sample_transaction.py, registered in backend/test.sh. database.users pulls in firebase_admin, stripe, and the Firestore client, so the test stubs those modules first (including a pass-through transactional that runs the decorated helper inline) and then imports database.users from source. The cases use a fake person ref and fake transaction that record how reads and writes are routed:

  • The remove reads with get(transaction=...) and writes with transaction.update(...), never a bare person_ref.update(...), proving the read-modify-write is atomic.
  • The matching index is popped from both speech_samples and speech_sample_transcripts, and updated_at is set.
  • The public remove_person_speech_sample hands the helper a transaction obtained from db.transaction().
  • A missing sample and a missing person each return False and write nothing.

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 transactional remove added here does not appear anywhere in the history of backend/database/users.py, 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: 4/5

  • In backend/tests/unit/test_users_remove_sample_transaction.py, the not-found error-path tests don’t assert person_ref.get_transactions, so they could pass even if the implementation regresses to person_ref.get() without a transaction; merging as-is leaves a gap that may miss transaction-consistency regressions in production error handling — add assertions that the read path uses get_transactions in both not-found tests before merging.

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

Fix all with cubic | 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