Skip to content

fix(backend): add batch boundary chunking and deduplication in database action_items - #19450

Open
brandonstensby-dotcom wants to merge 1 commit into
BasedHardware:mainfrom
brandonstensby-dotcom:fix/action-items-batch-boundary-resilience
Open

brandonstensby-dotcom wants to merge 1 commit into
BasedHardware:mainfrom
brandonstensby-dotcom:fix/action-items-batch-boundary-resilience

Conversation

@brandonstensby-dotcom

@brandonstensby-dotcom brandonstensby-dotcom commented Sep 27, 2026 •

Copy link
Copy Markdown

Closes #19449

Summary

Hardens batch operations in backend/database/action_items.py, backend/database/vector_db.py, and backend/routers/action_items.py against Firestore commit size limits and multi-operation document contention under high-volume workloads.

Aligns directly with INV-MEM-5: Universal memory and task authority.
Failure-Class: none.

Root Causes & Structural Remediation

  1. Firestore Single Commit Contention:
    • In delete_action_items_batch and batch_set_sync_requested, passing duplicate IDs causes Firestore write batches to abort with InvalidArgument: 400 Multiple operations on document in a single commit.
    • Fix: Applied order-preserving deduplication and whitespace sanitization via list(dict.fromkeys(...)) before constructing batch mutation operations.
  2. 500-Operation Batch Chunking at L+1 Boundary:
    • delete_action_items_for_conversation, retire_action_items_for_conversation, batch_set_sync_requested, and get_action_items_by_ids previously iterated or batched without chunking, failing when operations exceeded Firestore's hard 500-operation ceiling.
    • Fix: Enforced strict 499-op commit chunking in write batches and 500-doc chunking in get_all, ensuring conversations or batch sync requests with >500 items (tested at 501 items) commit safely across multiple transactions.
  3. Pinecone Vector Deletion Transient Resilience:
    • In backend/database/vector_db.py:delete_action_item_vectors_batch, Pinecone network timeouts previously caused unhandled exceptions after Firestore documents were already deleted.
    • Fix: Wrapped vector index deletion in try...except Exception as exc: logger.warning(...) to guarantee best-effort cleanup without aborting callers.
  4. Router Preflight Sanitization:
    • In backend/routers/action_items.py:batch_delete_action_items, deduplicated incoming request.ids before both the locked-item preflight check and database calls, eliminating redundant Firestore reads and batch write operations.
  5. Strict UID Validation:
    • Added explicit non-empty validation for uid in all modified functions to reject blank or whitespace arguments immediately with descriptive errors.

Testing & Verification

  • Authored 9 hermetic unit tests in backend/tests/unit/test_database_action_items_batch_resilience.py:
    • test_delete_action_items_batch_boundary_chunking_501: Verified 501 items split into 2 commits (499 + 2).
    • test_delete_action_items_batch_deduplicates_and_cleans_ids: Verified duplicate IDs and whitespace are sanitized.
    • test_delete_action_items_for_conversation_boundary_chunking_501: Verified conversation deletion chunks over 500 items.
    • test_retire_action_items_for_conversation_boundary_chunking_501: Verified conversation retirement chunks over 500 items.
    • test_batch_set_sync_requested_chunking_and_deduplication: Verified sync requested chunking and deduplication.
    • test_get_action_items_by_ids_chunking_and_order_preservation: Verified chunked queries at 500 ops while preserving exact input ordering.
    • test_delete_action_item_vectors_batch_handles_pinecone_failure_gracefully: Verified vector store failure degradation.
    • test_router_batch_delete_deduplicates_and_protects_locked: Verified router deduplication before lock preflight and DB execution.
    • test_delete_action_items_batch_invalid_uid_raises: Verified empty UID rejection.
  • All 9 unit tests passed: Ran 9 tests in 0.084s - OK.

Designated Payout Rails

  • Primary: Base USDC: 0xbB9686b9684421A8e326AC0F8B3eCf88Df975120
  • Backup: PayPal: [email protected]

Review in cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @brandonstensby-dotcom — this is a solid, well-scoped fix for the Firestore batch-boundary and duplicate-contention issues you filed in #19449, and the hermetic test coverage is genuinely thorough (the 501-item 499+2 commit boundary assertions are exactly right).

Per-file notes:

  • backend/database/action_items.py: order-preserving dedup via dict.fromkeys before batching in delete_action_items_batch and batch_set_sync_requested correctly prevents 'Multiple operations on document in a single commit'; the new 499-op mid-loop chunking in delete_action_items_for_conversation and retire_action_items_for_conversation fixes real >500-item crashes, and returning total_deleted/total_retired keeps the counts correct across chunks. get_action_items_by_ids chunking db.get_all at 500 with a seen-set preserves the documented input-order contract while deduplicating results.
  • backend/routers/action_items.py: sanitizing request.ids before the locked-item preflight also tightens the 402 paid-plan check (duplicates can no longer inflate the preflight), and the empty-input short-circuit is a nice touch.
  • backend/database/vector_db.py: making Pinecone deletion best-effort after Firestore commits is the right call for this path. One trade-off to be aware of: the broad except means persistent Pinecone failures silently orphan vectors (warning-only, no retry or reconciliation job) — fine for now, but worth a follow-up if orphaned vectors ever become a correctness issue for retrieval.
  • backend/tests/unit/test_database_action_items_batch_resilience.py: hermetic stubbing matches the repo's existing unit-test conventions, and coverage hits every changed code path including the router preflight. Verified the ENCRYPTION_SECRET fixture value matches the pre-existing one in test_firestore_di_seam.py, so no new secret material is introduced.

Two minor observations, neither blocking: (1) the chunk size for db.get_all reads is a defensive choice rather than a documented hard Firestore limit — harmless, and it also caps per-RPC payload size; (2) the new ValueError on empty/whitespace uid is a behavior change for any internal caller passing a blank uid — the router path always supplies an authenticated uid, so this should only surface real bugs.

Because this touches the user-data batch deletion path (Firestore deletes, Pinecone cleanup, and the locked-item paid-plan preflight), leaving for human maintainer review before merge.


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 positive-signal Automation verified a genuine fix/quality contribution backend Backend Task (python) labels Sep 27, 2026

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

On 8c76bf9, backend/database/vector_db.py delete_action_item_vectors_batch catches Exception and only logs, so a failed vector delete is treated as success. Let it raise.

This branch has not been deployed

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

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

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

3 participants