Skip to content

fix(backend): prevent Firestore batch boundary overflow and document contention ( bounty proposal) - #20724

Closed
Aj2280 wants to merge 2 commits into
BasedHardware:mainfrom
Aj2280:fix/action-items-batch-boundary-and-contention
Closed

Aj2280 wants to merge 2 commits into
BasedHardware:mainfrom
Aj2280:fix/action-items-batch-boundary-and-contention

Conversation

@Aj2280

@Aj2280 Aj2280 commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Failure-Class: FC-batch-fault-domain-head-of-line-poison

Fixes #19449

Summary

Resolves Firestore commit limit overflows (>500 operations) and single-commit document contention in action items batch operations across backend/database/action_items.py, backend/database/vector_db.py, and backend/routers/action_items.py.

Problem & Failure Modes

  1. Firestore Single Commit Contention:
    • In delete_action_items_batch and batch_set_sync_requested, duplicate IDs (from rapid client sync retries or mobile retransmissions) caused multiple operations on the same document reference within a single commit, crashing with:
      InvalidArgument: 400 Multiple operations on document in a single commit.
  2. Missing Batch-Get & Mutation Commit Chunking:
    • get_action_items_by_ids previously passed unbounded lists of document references into a single db.get_all() call without chunking, failing when batches exceeded Firestore's RPC limits.
    • Batch deletion and sync requested writes were vulnerable to oversized inputs.
  3. Pinecone Vector Deletion Failure Cascades:
    • In backend/database/vector_db.py:delete_action_item_vectors_batch, index.delete had no exception handling. Transient network timeouts or Pinecone degradation raised uncaught exceptions after Firestore had already committed deletions, returning HTTP 500s.
  4. Router Preflight Sanitization:
    • backend/routers/action_items.py:batch_delete_action_items passed raw ID lists into locked-item preflight checks and the database deletion layer without prior deduplication or whitespace sanitization.

Changes

  • Deduplication & Sanitization: Stripped whitespace, filtered empty values, and deduplicated IDs preserving input order in delete_action_items_batch, batch_set_sync_requested, get_action_items_by_ids, and the batch_delete_action_items router preflight.
  • Batch Chunking: Chunked get_action_items_by_ids into 499-op batches for db.get_all().
  • Fault-Domain Isolation: Wrapped Pinecone vector batch deletion in try...except in delete_action_item_vectors_batch so downstream vector transients do not abort transactional deletions.
  • Uid Validation: Added safe handling for empty or whitespace-only uid parameters.
  • Hermetic Tests: Added backend/tests/unit/test_action_items_batch_boundary_and_contention.py covering deduplication, >499 chunking, Pinecone transient error isolation, and empty/whitespace input safety.

Invariants Affected

  • INV-MEM-5: Universal memory and task authority.

Verification

  • pytest tests/unit/test_action_items_batch_boundary_and_contention.py tests/unit/test_action_items_batch_chunking.py: 10 passed in 1.14s.
  • scripts/pr-preflight --lane local: Passed all checks including product file line count ratchet and Firestore index guards.

Bounty Proposal

  • Suggested reward: $100 (bounded Firestore reliability fix + comprehensive hermetic regression suite)
  • Payout PayPal email: [email protected]

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.

5 issues found across 4 files

Confidence score: 2/5

  • In vector_db.py, Pinecone failures are treated as successful cleanup, so account deletion can leave action-item vectors behind while removing their Firestore IDs. Preserve the failure signal so the account wipe can handle it.
  • In vector_db.py, one failed 1,000-ID delete stops the loop and leaves all later chunks undeleted. Handle failures per chunk so remaining deletes still run.
  • In action_items.py, the preflight chunk size drops from 500 to 499 and breaks the existing batch-delete regression test. Use 500; the Firestore reads already chunk internally at 499.
  • In test_action_items_batch_boundary_and_contention.py, the sync-requested test never crosses a batch boundary, and its to_dict lambda returns the last ref for every document. Add enough unique IDs to exercise chunking and bind each document’s ID in the lambda.

You’re at about 97% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/tests/unit/test_action_items_batch_boundary_and_contention.py">

<violation number="1" location="backend/tests/unit/test_action_items_batch_boundary_and_contention.py:50">
P3: `to_dict=lambda: {...ref.id...}` inside the list comprehension captures the comprehension-scoped loop variable `ref` by name. After the comprehension finishes, `ref` keeps the last element, so every document's `to_dict()` returns the description of the last ref of the final chunk when `typed_doc()` calls it later. The current assertions don't read `description`, so the test still passes, but any future assertion on per-doc data will silently see corrupted values. Bind the argument at definition time: `lambda ref=ref: ...`.</violation>

<violation number="2" location="backend/tests/unit/test_action_items_batch_boundary_and_contention.py:83">
P3: The chunking fix in `batch_set_sync_requested` has no regression coverage. `test_batch_set_sync_requested_deduplicates_and_avoids_contention` uses only 3 unique IDs, so a single batch executes and `commits == [3]` even if the `count >= 499` chunking branches were deleted entirely — the overflow the PR fixes would not be caught. Add a chunking test mirroring `test_delete_action_items_batch_chunks_over_499` (e.g., 1200 IDs asserting `commits == [499, 998, 1200]`).</violation>
</file>

<file name="backend/routers/action_items.py">

<violation number="1" location="backend/routers/action_items.py:843">
P2: This changes the preflight chunk contract from 500 IDs to 499 IDs, causing the existing batch-delete regression test to fail. Use 500 here; `get_action_items_by_ids` already internally chunks Firestore reads at 499, so the outer preflight does not need to duplicate that boundary.</violation>
</file>

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

<violation number="1" location="backend/database/vector_db.py:1034">
P1: The `try` covers the entire chunk loop, so one failed 1,000-ID delete aborts every later chunk. Catch failures per chunk so transient errors do not leave the remainder of a user's vectors undeleted.</violation>

<violation number="2" location="backend/database/vector_db.py:1038">
P1: This catch makes account deletion report action-item vector cleanup as successful even when Pinecone fails. Preserve a failure signal for this required cleanup so the account wipe does not remove the Firestore IDs while leaving vectors behind.</violation>
</file>

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

Re-trigger cubic

Comment on lines +1034 to +1039
try:
for i in range(0, len(vector_ids), 1000):
index.delete(ids=vector_ids[i : i + 1000], namespace=ACTION_ITEMS_NAMESPACE)
logger.info(f'delete_action_item_vectors_batch count={len(vector_ids)}')
except Exception as e:
logger.warning(f'Failed to delete action item vector batch from Pinecone: {e}')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: The try covers the entire chunk loop, so one failed 1,000-ID delete aborts every later chunk. Catch failures per chunk so transient errors do not leave the remainder of a user's vectors undeleted.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/vector_db.py, line 1034:

<comment>The `try` covers the entire chunk loop, so one failed 1,000-ID delete aborts every later chunk. Catch failures per chunk so transient errors do not leave the remainder of a user's vectors undeleted.</comment>

<file context>
@@ -1026,15 +1026,17 @@ def delete_action_item_vector(uid: str, action_item_id: str) -> None:
-    for i in range(0, len(vector_ids), 1000):
-        index.delete(ids=vector_ids[i : i + 1000], namespace=ACTION_ITEMS_NAMESPACE)
-    logger.info(f'delete_action_item_vectors_batch count={len(vector_ids)}')
+    try:
+        for i in range(0, len(vector_ids), 1000):
+            index.delete(ids=vector_ids[i : i + 1000], namespace=ACTION_ITEMS_NAMESPACE)
</file context>
Suggested change
try:
for i in range(0, len(vector_ids), 1000):
index.delete(ids=vector_ids[i : i + 1000], namespace=ACTION_ITEMS_NAMESPACE)
logger.info(f'delete_action_item_vectors_batch count={len(vector_ids)}')
except Exception as e:
logger.warning(f'Failed to delete action item vector batch from Pinecone: {e}')
for i in range(0, len(vector_ids), 1000):
try:
index.delete(ids=vector_ids[i : i + 1000], namespace=ACTION_ITEMS_NAMESPACE)
except Exception as e:
logger.warning(f'Failed to delete action item vector chunk from Pinecone: {e}')
logger.info(f'delete_action_item_vectors_batch count={len(vector_ids)}')

for i in range(0, len(vector_ids), 1000):
index.delete(ids=vector_ids[i : i + 1000], namespace=ACTION_ITEMS_NAMESPACE)
logger.info(f'delete_action_item_vectors_batch count={len(vector_ids)}')
except Exception as e:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: This catch makes account deletion report action-item vector cleanup as successful even when Pinecone fails. Preserve a failure signal for this required cleanup so the account wipe does not remove the Firestore IDs while leaving vectors behind.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/vector_db.py, line 1038:

<comment>This catch makes account deletion report action-item vector cleanup as successful even when Pinecone fails. Preserve a failure signal for this required cleanup so the account wipe does not remove the Firestore IDs while leaving vectors behind.</comment>

<file context>
@@ -1026,15 +1026,17 @@ def delete_action_item_vector(uid: str, action_item_id: str) -> None:
+        for i in range(0, len(vector_ids), 1000):
+            index.delete(ids=vector_ids[i : i + 1000], namespace=ACTION_ITEMS_NAMESPACE)
+        logger.info(f'delete_action_item_vectors_batch count={len(vector_ids)}')
+    except Exception as e:
+        logger.warning(f'Failed to delete action item vector batch from Pinecone: {e}')
 
</file context>

Comment on lines +843 to +844
for i in range(0, len(sanitized_ids), 499):
existing_items = action_items_db.get_action_items_by_ids(uid, sanitized_ids[i : i + 499])

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: This changes the preflight chunk contract from 500 IDs to 499 IDs, causing the existing batch-delete regression test to fail. Use 500 here; get_action_items_by_ids already internally chunks Firestore reads at 499, so the outer preflight does not need to duplicate that boundary.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/routers/action_items.py, line 843:

<comment>This changes the preflight chunk contract from 500 IDs to 499 IDs, causing the existing batch-delete regression test to fail. Use 500 here; `get_action_items_by_ids` already internally chunks Firestore reads at 499, so the outer preflight does not need to duplicate that boundary.</comment>

<file context>
@@ -833,21 +833,22 @@ def batch_delete_action_items(
+    if not sanitized_ids:
+        return {"status": "Ok", "deleted_count": 0, "deleted_ids": []}
+
+    for i in range(0, len(sanitized_ids), 499):
+        existing_items = action_items_db.get_action_items_by_ids(uid, sanitized_ids[i : i + 499])
         if any(item.get('is_locked', False) for item in existing_items):
</file context>
Suggested change
for i in range(0, len(sanitized_ids), 499):
existing_items = action_items_db.get_action_items_by_ids(uid, sanitized_ids[i : i + 499])
for i in range(0, len(sanitized_ids), 500):
existing_items = action_items_db.get_action_items_by_ids(uid, sanitized_ids[i : i + 500])

assert commits == [499, 998, 1200]


def test_batch_set_sync_requested_deduplicates_and_avoids_contention(monkeypatch):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The chunking fix in batch_set_sync_requested has no regression coverage. test_batch_set_sync_requested_deduplicates_and_avoids_contention uses only 3 unique IDs, so a single batch executes and commits == [3] even if the count >= 499 chunking branches were deleted entirely — the overflow the PR fixes would not be caught. Add a chunking test mirroring test_delete_action_items_batch_chunks_over_499 (e.g., 1200 IDs asserting commits == [499, 998, 1200]).

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_action_items_batch_boundary_and_contention.py, line 83:

<comment>The chunking fix in `batch_set_sync_requested` has no regression coverage. `test_batch_set_sync_requested_deduplicates_and_avoids_contention` uses only 3 unique IDs, so a single batch executes and `commits == [3]` even if the `count >= 499` chunking branches were deleted entirely — the overflow the PR fixes would not be caught. Add a chunking test mirroring `test_delete_action_items_batch_chunks_over_499` (e.g., 1200 IDs asserting `commits == [499, 998, 1200]`).</comment>

<file context>
@@ -0,0 +1,127 @@
+    assert commits == [499, 998, 1200]
+
+
+def test_batch_set_sync_requested_deduplicates_and_avoids_contention(monkeypatch):
+    commits, writes, _ = _install_fake_db(monkeypatch)
+
</file context>

if get_all_returns is not None:
return get_all_returns(refs)
return [
SimpleNamespace(exists=True, id=ref.id, to_dict=lambda: {'description': f'desc-{ref.id}'}) for ref in refs

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: to_dict=lambda: {...ref.id...} inside the list comprehension captures the comprehension-scoped loop variable ref by name. After the comprehension finishes, ref keeps the last element, so every document's to_dict() returns the description of the last ref of the final chunk when typed_doc() calls it later. The current assertions don't read description, so the test still passes, but any future assertion on per-doc data will silently see corrupted values. Bind the argument at definition time: lambda ref=ref: ....

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_action_items_batch_boundary_and_contention.py, line 50:

<comment>`to_dict=lambda: {...ref.id...}` inside the list comprehension captures the comprehension-scoped loop variable `ref` by name. After the comprehension finishes, `ref` keeps the last element, so every document's `to_dict()` returns the description of the last ref of the final chunk when `typed_doc()` calls it later. The current assertions don't read `description`, so the test still passes, but any future assertion on per-doc data will silently see corrupted values. Bind the argument at definition time: `lambda ref=ref: ...`.</comment>

<file context>
@@ -0,0 +1,127 @@
+        if get_all_returns is not None:
+            return get_all_returns(refs)
+        return [
+            SimpleNamespace(exists=True, id=ref.id, to_dict=lambda: {'description': f'desc-{ref.id}'}) for ref in refs
+        ]
+
</file context>
Suggested change
SimpleNamespace(exists=True, id=ref.id, to_dict=lambda: {'description': f'desc-{ref.id}'}) for ref in refs
SimpleNamespace(exists=True, id=ref.id, to_dict=lambda ref=ref: {'description': f'desc-{ref.id}'}) for ref in refs

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @Aj2280 — this is a genuinely useful fix for #19449, and the regression tests are the right shape. I verified the production logic against main and ran the new test file locally at this head (6 passed). One concrete blocker before this can move forward.

Blocking: the Backend unit suite is red on lines added by this PR. All four shards fail at the pyright (1.1.403) step, which runs before pytest, so the new tests never executed in CI. The 5 errors are all reportUnnecessaryIsInstance on the new isinstance(raw, str) / isinstance(aid, str) guards:

  • backend/database/action_items.py:1014 (get_action_items_by_ids)
  • backend/database/action_items.py:1031 (same function's result comprehension)
  • backend/database/action_items.py:1216 (delete_action_items_batch)
  • backend/database/action_items.py:1343 (batch_set_sync_requested)
  • backend/database/vector_db.py:1031 (delete_action_item_vectors_batch)

Since the parameters are typed List[str], pyright treats the guard as provably redundant. Either drop the isinstance checks or restructure the sanitize helper (e.g. a small _clean_ids function) so the check isn't flagged — then CI will actually run the new tests.

Per-file notes on the substance:

  • backend/database/action_items.py — dedup-before-batching genuinely fixes Firestore's "Multiple operations on document in a single commit" on retransmitted/duplicate IDs, and the 499-op chunking of db.get_all in get_action_items_by_ids fixes the unbounded RPC. Returning unique_ids from delete_action_items_batch (instead of the raw input) is also more truthful for the FCM fan-out. Order-preserving repeat semantics in the get path are preserved. All correct.
  • backend/database/vector_db.py — stripping/filters before building Pinecone ids and the try/except around index.delete are the right call so a Pinecone outage after the Firestore commit doesn't 500 the endpoint. Non-blocking suggestion: this is a new fail-open branch, and repo convention (.github/agent-docs/fallback-telemetry.md) is to call the shared utils.observability.fallback.record_fallback helper rather than only a warning log, so the degradation is measurable.
  • backend/routers/action_items.py — sanitizing request.ids before the locked-item preflight is correct and removes the double-normalization risk between preflight and delete; the empty-after-sanitize short-circuit and folding record_product_event into the same if deleted_ids block look right.
  • backend/tests/unit/test_action_items_batch_boundary_and_contention.py — good mock-based coverage of dedup, the 499 boundary, order preservation, empty/whitespace uid, and Pinecone-failure tolerance.

Once the pyright errors are resolved (and the suite actually runs the new tests green), this should be in good shape.


This review is AI-generated feedback on behalf of the maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the backend Backend Task (python) label Oct 5, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for the contribution! Community bounty-style submissions in this area haven't been landing (97% of similar PRs resolved without merge over the last window), so we're closing these as a class. That's not a judgment on this particular work — if you believe it's a genuine exception (a maintainer-filed bounty, or a fix with evidence of a real failure), comment here and it goes straight to a maintainer. Thanks again for contributing!

@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Hey @Aj2280 👋

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 product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Firestore batch boundary overflow and document contention crashes in action_items database

2 participants