Repository navigation
fix(backend): prevent Firestore batch boundary overflow and document contention ( bounty proposal) - #20724
fix(backend): prevent Firestore batch boundary overflow and document contention ( bounty proposal)#20724Aj2280 wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
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 itsto_dictlambda returns the lastreffor 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
| 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}') |
There was a problem hiding this comment.
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>
| 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: |
There was a problem hiding this comment.
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>
| 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]) |
There was a problem hiding this comment.
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>
| 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): |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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>
| 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
left a comment
There was a problem hiding this comment.
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 ofdb.get_allinget_action_items_by_idsfixes the unbounded RPC. Returningunique_idsfromdelete_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 thetry/exceptaroundindex.deleteare 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 sharedutils.observability.fallback.record_fallbackhelper rather than only a warning log, so the degradation is measurable.backend/routers/action_items.py— sanitizingrequest.idsbefore the locked-item preflight is correct and removes the double-normalization risk between preflight and delete; the empty-after-sanitize short-circuit and foldingrecord_product_eventinto the sameif deleted_idsblock 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.
|
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! |
|
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:
Before your next PR, please skim:
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! |
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, andbackend/routers/action_items.py.Problem & Failure Modes
delete_action_items_batchandbatch_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.get_action_items_by_idspreviously passed unbounded lists of document references into a singledb.get_all()call without chunking, failing when batches exceeded Firestore's RPC limits.backend/database/vector_db.py:delete_action_item_vectors_batch,index.deletehad no exception handling. Transient network timeouts or Pinecone degradation raised uncaught exceptions after Firestore had already committed deletions, returning HTTP 500s.backend/routers/action_items.py:batch_delete_action_itemspassed raw ID lists into locked-item preflight checks and the database deletion layer without prior deduplication or whitespace sanitization.Changes
delete_action_items_batch,batch_set_sync_requested,get_action_items_by_ids, and thebatch_delete_action_itemsrouter preflight.get_action_items_by_idsinto 499-op batches fordb.get_all().try...exceptindelete_action_item_vectors_batchso downstream vector transients do not abort transactional deletions.uidparameters.backend/tests/unit/test_action_items_batch_boundary_and_contention.pycovering deduplication, >499 chunking, Pinecone transient error isolation, and empty/whitespace input safety.Invariants Affected
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