Skip to content

fix(backend): skip missing ids in batch_update_action_items to avoid NotFound 500 - #8307

Closed
ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/action-items-batch-update-missing-id
Closed

ZachL111 wants to merge 3 commits into
BasedHardware:mainfrom
ZachL111:fix/action-items-batch-update-missing-id

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

PATCH /v1/action-items/batch forwards the client-supplied list of reorder entries straight into batch_update_action_items in backend/database/action_items.py, which calls batch.update() for every id with no existence check. In Firestore, batch.update() on a document that does not exist raises google.api_core.exceptions.NotFound when the batch commits, so a single stale or deleted id in the request returns HTTP 500 and drops every other valid reorder in the same batch. This pre-filters the requested ids to the ones that actually exist and skips the rest, so one stale id no longer takes down the whole batch. This is a proactive hardening change; there is no filed GitHub issue for it.

Root cause

In backend/database/action_items.py, batch_update_action_items builds the batch in a bare loop with no guard:

for item in items:
    update_data = {'updated_at': now}
    if item.sort_order is not None:
        update_data['sort_order'] = item.sort_order
    if item.indent_level is not None:
        update_data['indent_level'] = item.indent_level

    if len(update_data) > 1:  # More than just updated_at
        doc_ref = action_items_ref.document(item.id)
        batch.update(doc_ref, update_data)
        count += 1

The ids come from the request body, so the caller can send an id for an item that was already deleted or never existed. batch.update() requires the target document to exist. The write is queued without complaint, but at batch.commit() Firestore raises google.api_core.exceptions.NotFound for the missing target, and because a batch is atomic the whole commit fails. FastAPI surfaces that as a 500, and none of the other reorders in the batch land.

Fix

Resolve which requested ids exist up front with a single db.get_all call, then skip any id that is not in that set before queuing its update:

# Pre-filter to existing docs: batch.update() on a missing doc raises
# google NotFound, which would 500 the whole batch on one stale id.
requested_ids = [item.id for item in items]
existing_ids = {
    doc.id
    for doc in db.get_all([action_items_ref.document(i) for i in requested_ids])
    if doc is not None and doc.exists
}

for item in items:
    if item.id not in existing_ids:
        continue
    update_data = {'updated_at': now}
    ...

This is the same existence-batch pattern folders.bulk_move_conversations_to_folder already uses. When every id exists the behavior is unchanged: the same documents get the same updates and the batch commits as before.

Testing

Added backend/tests/unit/test_action_items_batch_update_missing_id.py, registered in backend/test.sh. database.action_items imports the Firestore SDK and the client singleton at module top, so the test stubs those and loads the real module from source, then swaps in a fake db whose get_all reports only the seeded ids as existing and whose fake batch raises a NotFound stand-in at commit if any update targeted a missing doc, matching real commit-time behavior. The cases: a mix of one existing and one stale id updates only the existing one and never raises; an all-missing request is a clean no-op with nothing committed; and the happy path where all ids exist still updates each one. 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 filter added here does not appear anywhere in the history of backend/database/action_items.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.

2 issues found across 3 files

Confidence score: 3/5

  • In backend/database/action_items.py, the batch update path can return an inflated updated_count when requested IDs are missing, so clients may treat partial updates as fully successful and make incorrect follow-up decisions — compute updated_count from actually updated records (or return skipped IDs) before merging.
  • In backend/database/action_items.py, pre-filter reads still include no-op entries, which adds avoidable Firestore reads and latency under load — filter to items with sort_order/indent_level changes before get_all to de-risk performance regressions.

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

Fix all with cubic | Re-trigger cubic

Comment thread backend/database/action_items.py Resolved
Comment thread backend/database/action_items.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 3 files (changes from recent commits).

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/action_items.py">

<violation number="1" location="backend/database/action_items.py:453">
P2: Duplicate ids are not deduplicated, so one action item can be updated multiple times and `updated_count` can over-report unique items updated.</violation>
</file>

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

Fix all with cubic | Re-trigger cubic

# Only items that carry a sort_order/indent_level change can produce a write;
# entries with neither are no-ops, so skip them before the existence read to
# avoid wasted Firestore get_all reads.
actionable_items = [item for item in items if item.sort_order is not None or item.indent_level is not None]

@cubic-dev-ai cubic-dev-ai Bot Jun 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Duplicate ids are not deduplicated, so one action item can be updated multiple times and updated_count can over-report unique items updated.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/action_items.py, line 453:

<comment>Duplicate ids are not deduplicated, so one action item can be updated multiple times and `updated_count` can over-report unique items updated.</comment>

<file context>
@@ -428,34 +428,46 @@ def update_action_item(uid: str, action_item_id: str, update_data: dict) -> bool
+    # Only items that carry a sort_order/indent_level change can produce a write;
+    # entries with neither are no-ops, so skip them before the existence read to
+    # avoid wasted Firestore get_all reads.
+    actionable_items = [item for item in items if item.sort_order is not None or item.indent_level is not None]
+    if not actionable_items:
+        return 0
</file context>
Suggested change
actionable_items = [item for item in items if item.sort_order is not None or item.indent_level is not None]
actionable_by_id = {}
for item in items:
if item.sort_order is None and item.indent_level is None:
continue
actionable_by_id[item.id] = item
actionable_items = list(actionable_by_id.values())
Fix with 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