Skip to content

fix(collections): Use correct file batch ID#1073

Open
vprashrex wants to merge 3 commits into
mainfrom
fix/openai-vector-store-batch-id
Open

fix(collections): Use correct file batch ID#1073
vprashrex wants to merge 3 commits into
mainfrom
fix/openai-vector-store-batch-id

Conversation

@vprashrex

@vprashrex vprashrex commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator

Issue

Closes #1076

Summary

  • Before: The previous implementation did not use the file batch ID from the create() function when listing failed files.
  • Now: The new implementation utilizes the correct file batch ID for better accuracy in listing failed files.
  • Adjustments were made to the function responsible for listing failed files.
  • Integration of the file batch ID into the previous code structure.

Checklist

Before submitting a pull request, please ensure that you mark these task.

  • Ran fastapi run --reload app/main.py or docker compose up in the repository root and test.
  • If you've fixed a bug or added code that is tested and has test cases.

Notes

Please add here if any other information is required for the reviewer.

Original PR description

Issue

Closes #PLEASE_TYPE_ISSUE_NUMBER

Summary

Explain the motivation for making this change. What existing problem does the pull request solve?

Checklist

Before submitting a pull request, please ensure that you mark these task.

  • Ran fastapi run --reload app/main.py or docker compose up in the repository root and test.
  • If you've fixed a bug or added code that is tested and has test cases.

Summary by CodeRabbit

  • New Features

    • Added support for uploading .xls and .xlsx spreadsheets.
    • Added pre-upload validation for PDF, Word, Excel, CSV, and JSON files, including detection of empty, corrupted, encrypted, or mismatched files.
    • Improved upload validation to provide clearer client-facing error messages.
  • Bug Fixes

    • Improved vector-store indexing reliability and failure reporting.
    • Failed indexing now avoids leaving partially indexed document collections.
  • Documentation

    • Added guidance on vector-store batch behavior and indexing limitations.

@coderabbitai

coderabbitai Bot commented Jul 23, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

OpenAIVectorStoreCrud.update now separates file-batch creation from polling and preserves the creation batch ID for failed-file lookup. Uploads also gain content validation and XLS/XLSX format mappings.

Changes

Vector batch ingestion

Layer / File(s) Summary
Separate batch creation and polling
backend/app/crud/rag/open_ai.py
The ingestion flow captures the ID from create(), passes it to poll(), and uses it for failed-file retrieval and logging.
Batch flow and error-path tests
backend/app/tests/crud/rag/test_open_ai.py, backend/app/tests/services/collections/providers/test_openai_provider.py
Tests distinguish creation and polling IDs, verify batch wiring and file arguments, and raise OpenAI exceptions from create().
Shared mocks and ingestion notes
backend/app/tests/utils/llm_provider.py, backend/app/tests/utils/openai.py, docs/wiki/modules/knowledge-base.md
Shared mocks use separate create() and poll() operations, and documentation records the batch-ID behavior and rollback semantics.

Document upload validation

Layer / File(s) Summary
Content validation engine
backend/app/services/documents/helpers.py
Adds format sniffing and content checks for text, PDF, OOXML, CSV, and JSON uploads, with client-safe HTTP validation errors.
Upload route and spreadsheet format wiring
backend/app/api/routes/documents.py, backend/app/services/doctransform/registry.py
The upload route invokes validate_upload, and format mappings now include .xls and .xlsx.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

Suggested labels: bug

Suggested reviewers: prajna1999, nishika26

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes several unrelated document-validation, route, registry, and docs changes beyond the batch-ID fix. Split the document validation, route, registry, and docs updates into a separate PR and keep this one focused on batch-ID handling.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: fixing file batch ID handling in collections.
Linked Issues check ✅ Passed The create() batch ID is preserved and used for failed-file listing, satisfying the linked issue.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/openai-vector-store-batch-id

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot changed the title fix(collections): Use file batch ID from create() when listing failed files fix(collections): Use correct file batch ID Jul 23, 2026
@github-actions

github-actions Bot commented Jul 23, 2026

Copy link
Copy Markdown

OpenAPI changes   ⚪ No API surface changes

Note

This PR does not modify the API contract.

mainec45aacc · generated by oasdiff

@codecov

codecov Bot commented Jul 23, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 70.10870% with 55 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
backend/app/services/documents/helpers.py 60.76% 51 Missing ⚠️
backend/app/tests/utils/openai.py 0.00% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (2)
backend/app/tests/crud/rag/test_open_ai.py (2)

72-72: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the self-evident comment.

assert_not_called() already expresses this expectation; retain comments only when they explain rationale. As per coding guidelines, “Write comments and docstrings to explain why something is done, not what the code already shows.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/tests/crud/rag/test_open_ai.py` at line 72, Remove the
self-evident “list_files should not have been called on the happy path” comment
near the assert_not_called() expectation in the test, leaving the assertion
unchanged.

Source: Coding guidelines


44-44: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add required type annotations to changed test signatures.

Annotate non-self fixture parameters and return values consistently.

  • backend/app/tests/crud/rag/test_open_ai.py#L44-L44: annotate mock_client: MagicMock.
  • backend/app/tests/crud/rag/test_open_ai.py#L75-L75: annotate injected fixtures and add -> None.
  • backend/app/tests/crud/rag/test_open_ai.py#L106-L108: annotate injected fixtures and add -> None.
  • backend/app/tests/crud/rag/test_open_ai.py#L122-L124: annotate injected fixtures and add -> None.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/tests/crud/rag/test_open_ai.py` at line 44, Add the requested
annotations in backend/app/tests/crud/rag/test_open_ai.py: type _wire_batch’s
mock_client parameter as MagicMock, and annotate all non-self injected fixture
parameters plus return values with -> None in the test functions at lines 75,
106-108, and 122-124. Apply the annotations consistently across all four
affected sites.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@backend/app/tests/crud/rag/test_open_ai.py`:
- Line 72: Remove the self-evident “list_files should not have been called on
the happy path” comment near the assert_not_called() expectation in the test,
leaving the assertion unchanged.
- Line 44: Add the requested annotations in
backend/app/tests/crud/rag/test_open_ai.py: type _wire_batch’s mock_client
parameter as MagicMock, and annotate all non-self injected fixture parameters
plus return values with -> None in the test functions at lines 75, 106-108, and
122-124. Apply the annotations consistently across all four affected sites.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 79f5c90e-9ea2-43f6-8dc9-ff715cb54c65

📥 Commits

Reviewing files that changed from the base of the PR and between 49fd4ad and 6ca053f.

📒 Files selected for processing (6)
  • backend/app/crud/rag/open_ai.py
  • backend/app/tests/crud/rag/test_open_ai.py
  • backend/app/tests/services/collections/providers/test_openai_provider.py
  • backend/app/tests/utils/llm_provider.py
  • backend/app/tests/utils/openai.py
  • docs/wiki/modules/knowledge-base.md

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (2)
backend/app/services/documents/helpers.py (2)

1-6: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Modernize deprecated typing imports.

Callable/Iterable should come from collections.abc, and Tuple is deprecated in favor of builtin tuple (PEP 585). Ruff flags both (UP035).

♻️ Proposed fix
-from typing import Callable, Optional, Tuple, Iterable, Union
+from collections.abc import Callable, Iterable
+from typing import Optional, Union

Note: other Tuple[...] usages later in the file (e.g. _read_edges, validate_document_content... wait, that one already uses lowercase Tuple return) should be updated to tuple[...] for consistency once the import changes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/services/documents/helpers.py` around lines 1 - 6, Update the
imports in this module so Callable and Iterable come from collections.abc,
remove Tuple from typing, and replace every Tuple[...] annotation in the file
with the builtin tuple[...] syntax; preserve Optional and Union unless
independently required.

Source: Linters/SAST tools


53-57: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Duplicated magic byte signatures between MISLABELLED_BINARY_SIGNATURES and FORMAT_SPECS; "doc" has no FormatSpec.

b"PK\x03\x04" and b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" are inlined in both structures. Extracting them (and the zip-signature triple used for both docx and xlsx) into named constants would remove the duplication.

Separately, "doc" is absent from FORMAT_SPECS even though it shares the OLE2 signature documented for "xls" (comment at line 246 explicitly calls out ".doc"), and registry.py maps .doc"doc". As written, .doc uploads get zero content sniffing while .xls uploads (same binary container format) do.

♻️ Proposed fix
+OLE2_SIGNATURE = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
+ZIP_SIGNATURES = (b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")
+
 MISLABELLED_BINARY_SIGNATURES: dict[bytes, str] = {
-    b"PK\x03\x04": "an Office/zip file (xlsx, docx)",
-    b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1": "a legacy Office file (xls, doc)",
+    ZIP_SIGNATURES[0]: "an Office/zip file (xlsx, docx)",
+    OLE2_SIGNATURE: "a legacy Office file (xls, doc)",
     b"%PDF-": "a PDF",
 }
...
     "docx": FormatSpec(
-        signatures=(b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"), checker=_check_docx
+        signatures=ZIP_SIGNATURES, checker=_check_docx
     ),
     "xlsx": FormatSpec(
-        signatures=(b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"), checker=_check_xlsx
+        signatures=ZIP_SIGNATURES, checker=_check_xlsx
     ),
-    "xls": FormatSpec(signatures=(b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1",)),
+    "xls": FormatSpec(signatures=(OLE2_SIGNATURE,)),
+    "doc": FormatSpec(signatures=(OLE2_SIGNATURE,)),

Also applies to: 237-250

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/services/documents/helpers.py` around lines 53 - 57, Extract the
shared PK/zip and OLE2 byte signatures into named constants, then reuse them in
MISLABELLED_BINARY_SIGNATURES and the relevant FORMAT_SPECS entries, including
the existing zip-signature triple for docx and xlsx. Add a “doc” FORMAT_SPECS
entry matching the “xls” OLE2 signature and appropriate shared sniffing behavior
so .doc uploads are handled like .xls.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@backend/app/services/documents/helpers.py`:
- Around line 1-6: Update the imports in this module so Callable and Iterable
come from collections.abc, remove Tuple from typing, and replace every
Tuple[...] annotation in the file with the builtin tuple[...] syntax; preserve
Optional and Union unless independently required.
- Around line 53-57: Extract the shared PK/zip and OLE2 byte signatures into
named constants, then reuse them in MISLABELLED_BINARY_SIGNATURES and the
relevant FORMAT_SPECS entries, including the existing zip-signature triple for
docx and xlsx. Add a “doc” FORMAT_SPECS entry matching the “xls” OLE2 signature
and appropriate shared sniffing behavior so .doc uploads are handled like .xls.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6e6e3f5f-23a5-4f47-96b3-cfc57b2d0caa

📥 Commits

Reviewing files that changed from the base of the PR and between 6ca053f and 8c02d57.

📒 Files selected for processing (3)
  • backend/app/api/routes/documents.py
  • backend/app/services/doctransform/registry.py
  • backend/app/services/documents/helpers.py

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Collection: Correct batch ID usage

1 participant