~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(library): distinguish intra-batch duplicates from pre-existing library docs (#5495)
Sba001b008315
diff --git a/changelog.d/5495.bugfix.md b/changelog.d/5495.bugfix.mdnew file mode 100644index 0000000000..bddcdc3681--- /dev/null+++ b/changelog.d/5495.bugfix.md@@ -0,0 +1,10 @@+Collection uploads now correctly report each file's outcome when a single+request batch contains two files with identical bytes: dropped intra-batch+duplicates are listed under a new "Skipped — duplicate of another file+in this upload" bucket using the uploaded filename, instead of being+mis-reported under the first occurrence's filename as "Skipped — already+in collection". In addition, uploads matching existing library documents+now report the newly uploaded filename rather than the stored document's+canonical filename. Multi-file uploads also isolate failures per file+via savepoints instead of rolling back the whole request, ensuring that+a subsequent failing file no longer discards earlier successful uploads.diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex d500b78d7c..7da9df900f 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -1712,6 +1712,48 @@ def update_collection(collection_id):return handle_api_error("updating collection", e)+def _try_pdf_upgrade(+ *,+ db_session,+ document,+ file_content: bytes,+ filename: str,+ pdf_storage: str,+ pdf_storage_manager,+) -> bool:+ """Check PDF upgrade eligibility and attempt upgrading a Document to include PDF bytes.++ Returns True if the document was upgraded, False otherwise. Exceptions+ raised during the upgrade attempt are logged and swallowed; the caller+ sees False and the upload continues as a non-upgraded success.+ """+ if pdf_storage != "database" or pdf_storage_manager is None:+ return False++ # NOTE: Only the PDF magic-byte check is needed here.+ # File count validation is already handled by Flask's MAX_CONTENT_LENGTH.+ # Filename sanitization already happens via sanitize_filename() in upload_to_collection()+ # before this helper is invoked. See PR #3145 review for details.+ if file_content[:4] != b"%PDF":+ logger.debug(+ "Skipping PDF upgrade for {}: not a PDF file",+ filename,+ )+ return False++ try:+ return bool(+ pdf_storage_manager.upgrade_to_pdf(+ document=document,+ pdf_content=file_content,+ session=db_session,+ )+ )+ except Exception:+ logger.exception(f"Failed to upgrade PDF for {filename}")+ return False++@rag_bp.route("/api/collections/<string:collection_id>/upload", methods=["POST"])@@ -1722,7 +1764,6 @@ def upload_to_collection(collection_id):"""Upload files to a collection."""from ...database.session_context import (get_user_db_session,- safe_rollback,)from ...security import sanitize_filename, UnsafeFilenameErrorimport hashlib@@ -1796,6 +1837,19 @@ def upload_to_collection(collection_id):uploaded_files = []errors = []+ # Track hashes processed earlier in THIS request so we can+ # distinguish intra-batch duplicates (two uploaded files with+ # identical content) from duplicates against a pre-existing+ # library doc. Without this, the second occurrence of an+ # intra-batch duplicate was reported as "already_in_collection"+ # under the FIRST occurrence's filename — the warning looked+ # like it was skipping books that were actually being added,+ # and the skipped entry showed the wrong filename (#5495).+ # Maps content hash → Document so a later identical PDF in the+ # same batch can still run the PDF-upgrade path against the+ # document kept from the first occurrence.+ seen_hashes: dict[str, Document] = {}+for file in files:if not file.filename:continue@@ -1811,7 +1865,16 @@ def upload_to_collection(collection_id):)continue+ # Per-file SAVEPOINT: a failure rolls back only this file so+ # earlier successes (and seen_hashes) stay consistent with+ # the outer transaction. Commit the savepoint on every+ # non-exception exit — including soft validation failures —+ # so we never leave nested SAVEPOINTs stacked open across+ # the batch (same pattern as research_sources_service).+ sp = Nonetry:+ sp = db_session.begin_nested()+# Pre-flight size check on Content-Length BEFORE reading# bytes into memory. Cheap rejection for oversized files;# avoids loading 50MB+ into memory just to discard it.@@ -1822,6 +1885,7 @@ def upload_to_collection(collection_id):))if not is_valid:+ sp.commit()errors.append({"filename": filename, "error": error_msg})@@ -1840,6 +1904,7 @@ def upload_to_collection(collection_id):))if not is_valid:+ sp.commit()errors.append({"filename": filename, "error": error_msg})@@ -1848,6 +1913,43 @@ def upload_to_collection(collection_id):# Calculate file hash for deduplicationfile_hash = hashlib.sha256(file_content).hexdigest()+ # Intra-batch duplicate: an earlier file in THIS+ # request had identical bytes. Report it as its own+ # status so the UI doesn't show it under the first+ # occurrence's filename and pretend it was a+ # "skipped - already in collection" hit. The first+ # occurrence already linked the matching Document to+ # this collection (or to the library), so doing the+ # Document hash lookup and link check here would be+ # misleading at best. Still allow PDF upgrade when+ # the kept twin was stored text-only and this copy+ # is a PDF with database storage enabled.+ if file_hash in seen_hashes:+ logger.info(+ "Intra-batch duplicate detected: {} (hash {})",+ filename,+ file_hash,+ )+ target_doc = seen_hashes[file_hash]+ pdf_upgraded = _try_pdf_upgrade(+ db_session=db_session,+ document=target_doc,+ file_content=file_content,+ filename=filename,+ pdf_storage=pdf_storage,+ pdf_storage_manager=pdf_storage_manager,+ )+ sp.commit()+ uploaded_files.append(+ {+ "filename": filename,+ "status": "duplicate_in_batch",+ "id": target_doc.id,+ "pdf_upgraded": pdf_upgraded,+ }+ )+ continue+# Check if document already existsexisting_doc = (db_session.query(Document)@@ -1857,28 +1959,14 @@ def upload_to_collection(collection_id):if existing_doc:# Document exists, check if we can upgrade to include PDF- pdf_upgraded = False- if (- pdf_storage == "database"- and pdf_storage_manager is not None- ):- # NOTE: Only the PDF magic-byte check is needed here.- # File count validation is already handled by Flask's MAX_CONTENT_LENGTH.- # Filename sanitization already happens via sanitize_filename() above.- # See PR #3145 review for details.- if file_content[:4] != b"%PDF":- logger.debug(- "Skipping PDF upgrade for {}: not a PDF file",- filename,- )- else:- pdf_upgraded = (- pdf_storage_manager.upgrade_to_pdf(- document=existing_doc,- pdf_content=file_content,- session=db_session,- )- )+ pdf_upgraded = _try_pdf_upgrade(+ db_session=db_session,+ document=existing_doc,+ file_content=file_content,+ filename=filename,+ pdf_storage=pdf_storage,+ pdf_storage_manager=pdf_storage_manager,+ )# Check if already in collectionexisting_link = (@@ -1897,26 +1985,38 @@ def upload_to_collection(collection_id):status = "added_to_collection"if pdf_upgraded:status = "added_to_collection_pdf_upgraded"+ sp.commit()uploaded_files.append({- "filename": existing_doc.filename,+ # Report the file the user actually+ # uploaded, not the existing doc's+ # filename. Otherwise the user sees+ # one filename repeated under both+ # "added to collection" and+ # "new uploads" (or here under+ # "already in collection") and+ # can't tell which file was which.+ "filename": filename,"status": status,"id": existing_doc.id,"pdf_upgraded": pdf_upgraded,})+ seen_hashes[file_hash] = existing_docelse:status = "already_in_collection"if pdf_upgraded:status = "pdf_upgraded"+ sp.commit()uploaded_files.append({- "filename": existing_doc.filename,+ "filename": filename,"status": status,"id": existing_doc.id,"pdf_upgraded": pdf_upgraded,})+ seen_hashes[file_hash] = existing_docelse:# Create new documentfrom ...document_loaders import (@@ -1928,6 +2028,7 @@ def upload_to_collection(collection_id):# Validate extension is supported before extractionif not is_extension_supported(file_extension):+ sp.commit()errors.append({"filename": filename,@@ -1955,6 +2056,7 @@ def upload_to_collection(collection_id):extracted_text = remove_surrogates(extracted_text)if not extracted_text:+ sp.commit()errors.append({"filename": filename,@@ -2054,6 +2156,11 @@ def upload_to_collection(collection_id):db_session, new_doc.id, collection_id)+ # Release the per-file SAVEPOINT so later failures cannot+ # undo this file's writes (and so soft/success paths do+ # not leave nested SAVEPOINTs stacked open).+ sp.commit()+uploaded_files.append({"filename": filename,@@ -2063,15 +2170,13 @@ def upload_to_collection(collection_id):"pdf_stored": pdf_stored,})+ seen_hashes[file_hash] = new_docexcept Exception:- # A failed flush / save_pdf / ensure_in_collection above- # poisons the shared request session. Without a rollback the- # NEXT file in the loop — and the post-loop commit — cascade- # into PendingRollbackError, failing the whole batch (and- # 500ing files that already succeeded). Recover so one bad- # file doesn't take the rest down.- safe_rollback(db_session, "upload_to_collection")+ # A per-file savepoint rollback isolates the failure of this+ # file so earlier successful uploads in the batch remain intact+ # in the transaction state. Record the error and log the traceback+ # FIRST so a rollback failure cannot suppress them or crash the batch.errors.append({"filename": filename,@@ -2079,6 +2184,13 @@ def upload_to_collection(collection_id):})logger.exception(f"Error uploading file {filename}")+ if sp is not None:+ try:+ sp.rollback()+ except Exception:+ logger.opt(exception=True).warning(+ f"Failed to rollback savepoint for {filename}"+ )db_session.commit()diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex 10680dfab0..596ee0b4b1 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -693,13 +693,17 @@ function showUploadResults(data) {const uploadedFiles = data.uploaded || [];const failedFiles = data.errors || [];- // Categorize by status+ // Categorize by status. duplicate_in_batch is split out so the UI can+ // tell the user "you uploaded two copies of the same file in this batch"+ // separately from "this document was already in the collection from a+ // previous upload" — the data side is identical (the second occurrence+ // was dropped either way), but the actionable advice differs.const newUploads = uploadedFiles.filter(f => f.status === 'uploaded');const addedToCollection = uploadedFiles.filter(f => f.status === 'added_to_collection' || f.status === 'added_to_collection_pdf_upgraded');const alreadyInCollection = uploadedFiles.filter(f => f.status === 'already_in_collection' || f.status === 'pdf_upgraded');+ const duplicateInBatch = uploadedFiles.filter(f => f.status === 'duplicate_in_batch');const actualNewCount = newUploads.length + addedToCollection.length;- const skippedCount = alreadyInCollection.length;let html = '<div style="padding: 1.5rem; background: var(--bg-tertiary); border-radius: 8px;">';@@ -716,13 +720,20 @@ function showUploadResults(data) {</div>`;}- if (skippedCount > 0) {+ if (alreadyInCollection.length > 0) {html += `<div class="ldr-alert ldr-alert-warning" style="padding: 1rem; border-radius: 8px; text-align: center;">- <div style="font-size: 1.5rem; font-weight: 700;">${skippedCount}</div>+ <div style="font-size: 1.5rem; font-weight: 700;">${alreadyInCollection.length}</div><div style="font-size: 0.85rem;">Already Existed</div></div>`;}+ if (duplicateInBatch.length > 0) {+ html += `<div class="ldr-alert ldr-alert-warning" style="padding: 1rem; border-radius: 8px; text-align: center;">+ <div style="font-size: 1.5rem; font-weight: 700;">${duplicateInBatch.length}</div>+ <div style="font-size: 0.85rem;">Batch Duplicates</div>+ </div>`;+ }+if (failedFiles.length > 0) {html += `<div class="ldr-alert ldr-alert-danger" style="padding: 1rem; border-radius: 8px; text-align: center;"><div style="font-size: 1.5rem; font-weight: 700;">${failedFiles.length}</div>@@ -766,6 +777,21 @@ function showUploadResults(data) {</details>`;}+ if (duplicateInBatch.length > 0) {+ // Two (or more) files in the same upload request had identical+ // bytes; only the first was kept. Show each dropped file with+ // its own uploaded filename so the user can match it against+ // what they picked in the file dialog.+ html += `<details style="margin-bottom: 0.5rem;">+ <summary style="cursor: pointer; color: var(--warning-color); font-weight: 500;">+ ⏭️ Skipped - duplicate of another file in this upload (${duplicateInBatch.length})+ </summary>+ <ul style="margin: 0.5rem 0 0 1rem; padding: 0; list-style: none;">+ ${duplicateInBatch.map(f => `<li style="padding: 0.25rem 0;">📄 ${escapeHtml(f.filename)}</li>`).join('')}+ </ul>+ </details>`;+ }+if (failedFiles.length > 0) {html += `<details open style="margin-bottom: 0.5rem;"><summary style="cursor: pointer; color: var(--error-color); font-weight: 500;">@@ -823,3 +849,8 @@ function showError(message) {resultsDiv.innerHTML = html;resultsDiv.style.display = 'block';}++// Export showUploadResults on window for Vitest test suite (tests/js/collection-upload.test.js)+if (typeof window !== 'undefined') {+ window.showUploadResults = showUploadResults;+}diff --git a/tests/js/collection-upload.test.js b/tests/js/collection-upload.test.jsnew file mode 100644index 0000000000..37f314d38b--- /dev/null+++ b/tests/js/collection-upload.test.js@@ -0,0 +1,188 @@+/**+ * Tests for collection_upload.js — showUploadResults breakdown and deduplication UI.+ *+ * Covers:+ * - duplicate_in_batch status bucket rendering+ * - Separate summary cards for Already Existed vs Batch Duplicates+ * - Filename escaping and rendering across all status buckets+ * - PDF-upgrade status variants bucket into the right details sections+ */++let showUploadResults;++beforeAll(async () => {+ // Provide DOM elements expected by collection_upload.js+ document.body.innerHTML = `+ <div id="upload-progress" style="display: block;"></div>+ <div id="upload-results" style="display: none;"></div>+ `;++ // Global variable referenced in HTML template of collection_upload.js+ globalThis.COLLECTION_ID = 'coll-test-123';++ await import('@js/security/xss-protection.js');+ await import('@js/collection_upload.js');+ showUploadResults = window.showUploadResults;+});++beforeEach(() => {+ document.body.innerHTML = `+ <div id="upload-progress" style="display: block;"></div>+ <div id="upload-results" style="display: none;"></div>+ `;+});++describe('showUploadResults', () => {+ it('correctly categorizes duplicate_in_batch into its own bucket and summary card', () => {+ const responseData = {+ success: true,+ uploaded: [+ { filename: 'Book.pdf', status: 'uploaded' },+ { filename: 'Book (1).pdf', status: 'duplicate_in_batch' },+ { filename: 'ExistingDoc.pdf', status: 'already_in_collection' },+ ],+ errors: [],+ };++ showUploadResults(responseData);++ const resultsDiv = document.getElementById('upload-results');+ expect(resultsDiv.style.display).toBe('block');+ const content = resultsDiv.innerHTML;++ // Stat grid should show 1 new file, 1 pre-existing skipped file, and 1 batch duplicate card+ expect(content).toContain('New Files Added');+ expect(content).toContain('Already Existed');+ expect(content).toContain('Batch Duplicates');+ // Counts in the split cards (not a combined skipped pill)+ expect(content).toMatch(/>1<\/div>\s*<div[^>]*>Already Existed/);+ expect(content).toMatch(/>1<\/div>\s*<div[^>]*>Batch Duplicates/);++ // Duplicate bucket summary & details+ expect(content).toContain('Skipped - duplicate of another file in this upload (1)');+ expect(content).toContain('Book (1).pdf');++ // Pre-existing bucket summary & details+ expect(content).toContain('Skipped - already in collection (1)');+ expect(content).toContain('ExistingDoc.pdf');+ });++ it('renders all 5 buckets correctly when present in payload', () => {+ const responseData = {+ success: true,+ uploaded: [+ { filename: 'New1.txt', status: 'uploaded' },+ { filename: 'InLibrary1.txt', status: 'added_to_collection' },+ { filename: 'InColl1.txt', status: 'already_in_collection' },+ { filename: 'Dup1.txt', status: 'duplicate_in_batch' },+ ],+ errors: [{ filename: 'BadFile.txt', error: 'Unsupported format' }],+ };++ showUploadResults(responseData);++ const resultsDiv = document.getElementById('upload-results');+ const content = resultsDiv.innerHTML;++ // New uploads bucket+ expect(content).toContain('New uploads (1)');+ expect(content).toContain('New1.txt');++ // Added to collection bucket+ expect(content).toContain('Added to collection (already in library) (1)');+ expect(content).toContain('InLibrary1.txt');++ // Already in collection bucket+ expect(content).toContain('Skipped - already in collection (1)');+ expect(content).toContain('InColl1.txt');++ // Duplicate in batch bucket+ expect(content).toContain('Skipped - duplicate of another file in this upload (1)');+ expect(content).toContain('Dup1.txt');++ // Failed bucket+ expect(content).toContain('Failed (1)');+ expect(content).toContain('BadFile.txt');+ expect(content).toContain('Unsupported format');++ // Summary card for New Files Added counts uploaded + added_to_collection+ expect(content).toMatch(/>2<\/div>\s*<div[^>]*>New Files Added/);+ });++ it('places pdf_upgraded status variants into the correct buckets', () => {+ const responseData = {+ success: true,+ uploaded: [+ {+ filename: 'LibUpgrade.pdf',+ status: 'added_to_collection_pdf_upgraded',+ },+ { filename: 'CollUpgrade.pdf', status: 'pdf_upgraded' },+ {+ filename: 'BatchUpgrade.pdf',+ status: 'duplicate_in_batch',+ pdf_upgraded: true,+ },+ ],+ errors: [],+ };++ showUploadResults(responseData);++ const content = document.getElementById('upload-results').innerHTML;+ expect(content).toContain('Added to collection (already in library) (1)');+ expect(content).toContain('LibUpgrade.pdf');+ expect(content).toContain('Skipped - already in collection (1)');+ expect(content).toContain('CollUpgrade.pdf');+ expect(content).toContain('Skipped - duplicate of another file in this upload (1)');+ expect(content).toContain('BatchUpgrade.pdf');+ expect(content).toContain('Already Existed');+ expect(content).toContain('Batch Duplicates');+ expect(content).toContain('New Files Added');+ });++ it('escapes html entities in filenames across all buckets', () => {+ const responseData = {+ success: true,+ uploaded: [+ { filename: '<script>alert(1)</script>.pdf', status: 'duplicate_in_batch' },+ ],+ errors: [{ filename: 'bad<script>.txt', error: 'err<script>' }],+ };++ showUploadResults(responseData);++ const resultsDiv = document.getElementById('upload-results');+ const content = resultsDiv.innerHTML;++ expect(content).not.toContain('<script>alert(1)</script>');+ expect(content).toContain('<script>alert(1)</script>');+ expect(content).not.toContain('bad<script>.txt');+ expect(content).toContain('bad<script>.txt');+ expect(content).toContain('err<script>');+ });++ it('does not render Batch Duplicates or Already Existed summary cards or sections when buckets are empty', () => {+ const responseData = {+ success: true,+ summary: { successful: 1, failed: 0 },+ uploaded: [+ { filename: 'FreshDoc.txt', status: 'uploaded' },+ ],+ errors: [],+ };++ showUploadResults(responseData);++ const resultsDiv = document.getElementById('upload-results');+ expect(resultsDiv.style.display).toBe('block');+ const content = resultsDiv.innerHTML;++ expect(content).toContain('New Files Added');+ expect(content).toContain('FreshDoc.txt');+ expect(content).not.toContain('Batch Duplicates');+ expect(content).not.toContain('Already Existed');+ expect(content).not.toContain('Skipped - duplicate of another file in this upload');+ expect(content).not.toContain('Skipped - already in collection');+ });+});diff --git a/tests/research_library/routes/_route_helpers_rag.py b/tests/research_library/routes/_route_helpers_rag.pyindex be858f11d8..3216274547 100644--- a/tests/research_library/routes/_route_helpers_rag.py+++ b/tests/research_library/routes/_route_helpers_rag.py@@ -167,6 +167,23 @@ def _make_db_session():db_session.add = Mock()db_session.flush = Mock()db_session.expire_all = Mock()++ # Per-file SAVEPOINT stubs used by upload_to_collection. Each+ # begin_nested() returns a fresh mock with is_active=True so tests+ # can assert sp.commit() on success paths and sp.rollback() on+ # exception paths (and that is_active is checked before rollback).+ savepoints: list = []++ def _begin_nested():+ sp = Mock()+ sp.is_active = True+ sp.commit = Mock(side_effect=lambda: setattr(sp, "is_active", False))+ sp.rollback = Mock(side_effect=lambda: setattr(sp, "is_active", False))+ savepoints.append(sp)+ return sp++ db_session.begin_nested = Mock(side_effect=_begin_nested)+ db_session._savepoints = savepointsreturn db_sessiondiff --git a/tests/research_library/routes/test_rag_routes_upload_coverage.py b/tests/research_library/routes/test_rag_routes_upload_coverage.pyindex c6f055c4e6..857349d324 100644--- a/tests/research_library/routes/test_rag_routes_upload_coverage.py+++ b/tests/research_library/routes/test_rag_routes_upload_coverage.py@@ -6,7 +6,10 @@ Covers:existing doc already in collection, existing doc added to collection,existing doc pdf upgrade, unsupported extension, no text extracted,new doc success (text-only), new doc success (pdf database storage),- pdf storage failure continues, auto-index triggered, auto-index no password+ pdf storage failure continues, auto-index triggered, auto-index no password,+ intra-batch duplicates (duplicate_in_batch + uploaded filename),+ per-file SAVEPOINT isolation (new doc + existing doc),+ intra-batch PDF upgrade path, failed-first does not block twin- get_collection_documents: collection not found, index size formatting (B/KB/MB)"""@@ -49,14 +52,13 @@ class TestUploadToCollection:"""Tests for the upload_to_collection route."""def test_upload_rolls_back_per_failed_file_so_batch_survives(self, app):- """A per-file DB failure must roll back the shared request session so+ """A per-file DB failure must roll back only that file's SAVEPOINT sothe next file in the batch — and the post-loop commit — don't cascadeinto PendingRollbackError and 500 the whole upload.Mocked session can't reproduce the real cascade (it never enters- PendingRollbackError), so this pins the fix is *wired*: rollback runs- once per failed file. Without ``safe_rollback`` in the except, rollback- is never called and this fails.+ PendingRollbackError), so this pins the fix is *wired*: begin_nested+ + sp.rollback run once per failed file."""mock_coll = Mock()mock_coll.id = "coll-1"@@ -92,8 +94,353 @@ class TestUploadToCollection:assert rdata["success"] is Trueassert len(rdata["uploaded"]) == 0assert len(rdata["errors"]) == 2- # The fix: each failed file rolled the shared session back.- assert db_session.rollback.call_count == 2+ # The fix: each failed file created a savepoint and rolled it back.+ assert db_session.begin_nested.call_count == 2+ assert len(db_session._savepoints) == 2+ for sp in db_session._savepoints:+ sp.rollback.assert_called_once()+ sp.commit.assert_not_called()++ def test_upload_savepoint_rollback_failure_does_not_crash_batch(self, app):+ """When sp.rollback() itself raises (e.g. broken connection during rollback),+ the error is trapped, errors.append/logging have already executed, and the+ batch returns 200 with per-file errors rather than crashing with 500."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ db_session = _make_db_session()+ call_count = {"n": 0}++ def query_side_effect(model):+ call_count["n"] += 1+ if call_count["n"] == 1:+ return _build_mock_query(first_result=mock_coll)+ raise RuntimeError("simulated DB query failure")++ db_session.query = Mock(side_effect=query_side_effect)++ # Make savepoint rollback raise while sp.is_active remains True+ def _failing_begin_nested():+ sp = Mock()+ sp.is_active = True+ sp.commit = Mock()+ sp.rollback = Mock(+ side_effect=RuntimeError("connection dead during rollback")+ )+ db_session._savepoints.append(sp)+ return sp++ db_session.begin_nested = Mock(side_effect=_failing_begin_nested)+ mock_opt_logger = Mock()+ mock_opt = Mock(return_value=mock_opt_logger)+ with _auth_client(+ app,+ mock_db_session=db_session,+ extra_patches=[patch(f"{MODULE}.logger.opt", mock_opt)],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={+ "files": [+ (BytesIO(b"file one"), "a.txt"),+ (BytesIO(b"file two"), "b.txt"),+ ]+ },+ content_type="multipart/form-data",+ )++ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert len(rdata["uploaded"]) == 0+ assert len(rdata["errors"]) == 2+ assert all(+ "Failed to upload file" in e["error"] for e in rdata["errors"]+ )+ db_session.commit.assert_called_once()+ # Verify that rollback failure warning was logged with exception info for each file+ assert mock_opt.call_count == 2+ for call in mock_opt.call_args_list:+ assert call.kwargs.get("exception") is True+ assert mock_opt_logger.warning.call_count == 2+ warn_messages = [+ call.args[0] for call in mock_opt_logger.warning.call_args_list+ ]+ assert any(+ "Failed to rollback savepoint for a.txt" in msg+ for msg in warn_messages+ )+ assert any(+ "Failed to rollback savepoint for b.txt" in msg+ for msg in warn_messages+ )++ def test_upload_mixed_batch_survives_savepoint_rollback_failure(self, app):+ """When an earlier file succeeds and a subsequent file's sp.rollback() raises,+ the earlier file's committed insert is preserved, the failing file is recorded+ in errors with exception-preserving warning log, an intra-batch twin of the+ first file is correctly recognized as duplicate_in_batch, and the batch returns 200."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"+ mock_source = Mock()+ mock_source.id = "src-sp"++ db_session = _make_db_session()+ collection_queried = {"v": False}++ def query_side_effect(model):+ from local_deep_research.database.models.library import (+ Collection,+ SourceType,+ )++ q = _build_mock_query()+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection and not collection_queried["v"]:+ collection_queried["v"] = True+ q.first.return_value = mock_coll+ elif model is SourceType:+ q.first.return_value = mock_source+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ def fake_extract(content, ext, filename):+ if filename == "ErrorFile.txt":+ raise RuntimeError("Simulated processing error on second file")+ return f"Extracted text for {filename}"++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ call_idx = {"n": 0}++ def _custom_begin_nested():+ idx = call_idx["n"]+ call_idx["n"] += 1+ sp = Mock()+ sp.is_active = True+ sp.commit = Mock()+ if idx == 1:+ sp.rollback = Mock(+ side_effect=RuntimeError("connection dead during rollback")+ )+ else:+ sp.rollback = Mock()+ db_session._savepoints.append(sp)+ return sp++ db_session.begin_nested = Mock(side_effect=_custom_begin_nested)+ mock_opt_logger = Mock()+ mock_opt = Mock(return_value=mock_opt_logger)++ shared_bytes = b"identical bytes for First and Third"++ with _auth_client(+ app,+ mock_db_session=db_session,+ settings_overrides={"research_library.upload_pdf_storage": "none"},+ extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ side_effect=fake_extract,+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ patch(f"{MODULE}.logger.opt", mock_opt),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={+ "files": [+ (BytesIO(shared_bytes), "First.txt"),+ (BytesIO(b"error content"), "ErrorFile.txt"),+ (BytesIO(shared_bytes), "Third.txt"),+ ]+ },+ content_type="multipart/form-data",+ )++ rdata = resp.get_json()+ assert resp.status_code == 200+ assert rdata["success"] is True+ assert len(rdata["errors"]) == 1+ assert rdata["errors"][0]["filename"] == "ErrorFile.txt"+ assert "Failed to upload file" in rdata["errors"][0]["error"]++ by_name = {f["filename"]: f for f in rdata["uploaded"]}+ assert "First.txt" in by_name+ assert by_name["First.txt"]["status"] == "uploaded"+ assert "Third.txt" in by_name+ assert by_name["Third.txt"]["status"] == "duplicate_in_batch"++ # Verify savepoint commits and rollback attempts+ assert len(db_session._savepoints) == 3+ db_session._savepoints[0].commit.assert_called_once()+ db_session._savepoints[0].rollback.assert_not_called()+ db_session._savepoints[1].rollback.assert_called_once()+ db_session._savepoints[1].commit.assert_not_called()+ db_session._savepoints[2].commit.assert_called_once()+ db_session._savepoints[2].rollback.assert_not_called()++ # Verify outer transaction commit was called+ db_session.commit.assert_called_once()++ # Verify warning log with exception info for the failing file+ assert mock_opt.called+ assert any(+ call.kwargs.get("exception") is True+ for call in mock_opt.call_args_list+ )+ assert any(+ "Failed to rollback savepoint for ErrorFile.txt" in call.args[0]+ for call in mock_opt_logger.warning.call_args_list+ )++ def test_upload_inactive_savepoint_still_rolls_back(self, app):+ """When an exception occurs for a file and the savepoint is inactive+ (e.g. sp.is_active is False after a failed flush), sp.rollback() is still+ called to reset the session."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ db_session = _make_db_session()+ call_count = {"n": 0}++ def query_side_effect(model):+ call_count["n"] += 1+ if call_count["n"] == 1:+ return _build_mock_query(first_result=mock_coll)+ raise RuntimeError("simulated DB query failure")++ db_session.query = Mock(side_effect=query_side_effect)++ # Mock savepoint with is_active = False+ def _inactive_begin_nested():+ sp = Mock()+ sp.is_active = False+ sp.commit = Mock()+ sp.rollback = Mock()+ db_session._savepoints.append(sp)+ return sp++ db_session.begin_nested = Mock(side_effect=_inactive_begin_nested)++ with _auth_client(app, mock_db_session=db_session) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={+ "files": [+ (BytesIO(b"file one"), "a.txt"),+ ]+ },+ content_type="multipart/form-data",+ )++ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert len(rdata["uploaded"]) == 0+ assert len(rdata["errors"]) == 1+ assert "Failed to upload file" in rdata["errors"][0]["error"]+ # sp.rollback should be called even when sp.is_active was False+ assert len(db_session._savepoints) == 1+ db_session._savepoints[0].rollback.assert_called_once()+ db_session.commit.assert_called_once()++ def test_upload_begin_nested_failure_isolates_failing_file(self, app):+ """When begin_nested() raises for one file in a batch, it is caught as a+ per-file error; previous successful uploads survive and the batch returns 200."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"+ mock_source = Mock()+ mock_source.id = "src-bn"++ db_session = _make_db_session()+ bn_count = {"n": 0}++ def _conditional_begin_nested():+ bn_count["n"] += 1+ if bn_count["n"] == 1:+ sp = Mock()+ sp.is_active = True+ sp.commit = Mock()+ sp.rollback = Mock()+ db_session._savepoints.append(sp)+ return sp+ raise RuntimeError("begin_nested failed on file 2")++ db_session.begin_nested = Mock(side_effect=_conditional_begin_nested)++ def query_side_effect(model):+ from local_deep_research.database.models.library import (+ Collection,+ SourceType,+ )++ q = _build_mock_query()+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection:+ q.first.return_value = mock_coll+ elif model is SourceType:+ q.first.return_value = mock_source+ return q++ db_session.query = Mock(side_effect=query_side_effect)+ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ settings_overrides={"research_library.upload_pdf_storage": "none"},+ extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ return_value="text",+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={+ "files": [+ (BytesIO(b"file one content"), "file1.txt"),+ (BytesIO(b"file two content"), "file2.txt"),+ ]+ },+ content_type="multipart/form-data",+ )++ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert len(rdata["uploaded"]) == 1+ assert rdata["uploaded"][0]["filename"] == "file1.txt"+ assert rdata["uploaded"][0]["status"] == "uploaded"+ assert len(rdata["errors"]) == 1+ assert rdata["errors"][0]["filename"] == "file2.txt"+ assert rdata["errors"][0]["error"] == "Failed to upload file"+ db_session.commit.assert_called_once()def test_upload_no_files_key(self, app):"""POST with no 'files' key in the request returns 400."""@@ -177,8 +524,16 @@ class TestUploadToCollection:"File too large" in e.get("error", "") for e in data["errors"])- def test_upload_empty_files_list(self, app):- """File with empty filename is silently skipped; response is success with 0 uploaded."""+ def test_upload_soft_validation_savepoint_commit_failure_does_not_double_report(+ self, app+ ):+ """When a soft-validation failure occurs (e.g. oversized file) and sp.commit()+ raises an exception, the file is caught by the per-file exception handler+ and reported exactly once in errors (no duplicate error entries)."""+ from local_deep_research.security.file_upload_validator import (+ FileUploadValidator,+ )+mock_coll = Mock()mock_coll.id = "coll-1"@@ -186,33 +541,177 @@ class TestUploadToCollection:q = _build_mock_query(first_result=mock_coll)db_session.query = Mock(return_value=q)+ def _failing_commit_begin_nested():+ sp = Mock()+ sp.is_active = True+ sp.commit = Mock(side_effect=RuntimeError("commit release failed"))+ sp.rollback = Mock()+ db_session._savepoints.append(sp)+ return sp++ db_session.begin_nested = Mock(side_effect=_failing_commit_begin_nested)++ with patch.object(FileUploadValidator, "MAX_FILE_SIZE", 100):+ with _auth_client(+ app,+ mock_db_session=db_session,+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={+ "files": (BytesIO(b"x" * 200), "big.txt"),+ },+ content_type="multipart/form-data",+ )++ assert resp.status_code == 200+ data = resp.get_json()+ assert data["success"] is True+ assert len(data["errors"]) == 1+ assert data["errors"][0]["filename"] == "big.txt"+ assert "Failed to upload file" in data["errors"][0]["error"]++ def test_upload_success_path_savepoint_commit_failure_suppresses_publication(+ self, app+ ):+ """When sp.commit() raises after writes on a new document success path,+ the file is caught by the per-file exception handler, reported in errors+ (not in uploaded), and not registered in seen_hashes so subsequent identical+ files are not falsely flagged as duplicate_in_batch."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"+ mock_source = Mock()+ mock_source.id = "src-sp"++ db_session = _make_db_session()+ collection_queried = {"v": False}++ def query_side_effect(model):+ from local_deep_research.database.models.library import (+ Collection,+ SourceType,+ )++ q = _build_mock_query()+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection and not collection_queried["v"]:+ collection_queried["v"] = True+ q.first.return_value = mock_coll+ elif model is SourceType:+ q.first.return_value = mock_source+ return q++ db_session.query = Mock(side_effect=query_side_effect)+mock_password_store = Mock()mock_password_store.get_session_password.return_value = None+ # First file's sp.commit() fails; second file (same bytes) sp.commit() succeeds+ call_idx = {"n": 0}++ def _custom_begin_nested():+ idx = call_idx["n"]+ call_idx["n"] += 1+ sp = Mock()+ sp.is_active = True+ if idx == 0:+ sp.commit = Mock(+ side_effect=RuntimeError(+ "savepoint commit failed for file 1"+ )+ )+ else:+ sp.commit = Mock()+ sp.rollback = Mock()+ db_session._savepoints.append(sp)+ return sp++ db_session.begin_nested = Mock(side_effect=_custom_begin_nested)+ shared_bytes = b"same content for file 1 and 2"+with _auth_client(app,mock_db_session=db_session,+ settings_overrides={"research_library.upload_pdf_storage": "none"},extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ return_value="Extracted text",+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),patch(f"{_DB_PASS}.session_password_store", mock_password_store),],) as (client, ctx):- # Send a file with no filename (empty string filename is treated as "no filename")resp = client.post("/library/api/collections/coll-1/upload",- data={"files": (BytesIO(b""), "")},+ data={+ "files": [+ (BytesIO(shared_bytes), "File1.txt"),+ (BytesIO(shared_bytes), "File2.txt"),+ ]+ },content_type="multipart/form-data",)- assert resp.status_code == 200+rdata = resp.get_json()+ assert resp.status_code == 200assert rdata["success"] is True- assert rdata["summary"]["successful"] == 0- def test_upload_collection_not_found(self, app):- """Returns 404 when the collection does not exist in the DB."""- db_session = _make_db_session()- q = _build_mock_query(first_result=None)+ # File1 failed at sp.commit(), so it appears in errors and NOT in uploaded+ assert len(rdata["errors"]) == 1+ assert rdata["errors"][0]["filename"] == "File1.txt"+ assert "Failed to upload file" in rdata["errors"][0]["error"]++ # File2 was processed as a fresh upload (status 'uploaded', NOT 'duplicate_in_batch')+ # because File1 was not added to seen_hashes+ assert len(rdata["uploaded"]) == 1+ assert rdata["uploaded"][0]["filename"] == "File2.txt"+ assert rdata["uploaded"][0]["status"] == "uploaded"++ def test_upload_empty_files_list(self, app):+ """File with empty filename is silently skipped; response is success with 0 uploaded."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ db_session = _make_db_session()+ q = _build_mock_query(first_result=mock_coll)+ db_session.query = Mock(return_value=q)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ extra_patches=[+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ # Send a file with no filename (empty string filename is treated as "no filename")+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={"files": (BytesIO(b""), "")},+ content_type="multipart/form-data",+ )+ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert rdata["summary"]["successful"] == 0++ def test_upload_collection_not_found(self, app):+ """Returns 404 when the collection does not exist in the DB."""+ db_session = _make_db_session()+ q = _build_mock_query(first_result=None)db_session.query = Mock(return_value=q)with _auth_client(app, mock_db_session=db_session) as (client, ctx):@@ -227,7 +726,8 @@ class TestUploadToCollection:assert "Collection not found" in data["error"]def test_upload_existing_doc_already_in_collection(self, app):- """Existing doc that is already in the collection → status 'already_in_collection'."""+ """Existing doc already in collection: first file is 'already_in_collection',+ second identical file in same request is 'duplicate_in_batch'."""mock_coll = Mock()mock_coll.id = "coll-1"@@ -246,11 +746,191 @@ class TestUploadToCollection:if call_count["n"] == 1:q.first.return_value = mock_coll # Collection lookupelif call_count["n"] == 2:- q.first.return_value = existing_doc # Document hash lookup+ q.first.return_value = (+ existing_doc # Document hash lookup (file 1)+ )elif call_count["n"] == 3:q.first.return_value = (- existing_link # DocumentCollection lookup+ existing_link # DocumentCollection lookup (file 1))+ # File 2 hits seen_hashes, so no Document query is executed+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ shared_bytes = b"pdf content for both files"++ with _auth_client(+ app,+ mock_db_session=db_session,+ extra_patches=[+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={+ "files": [+ (BytesIO(shared_bytes), "report.pdf"),+ (BytesIO(shared_bytes), "report_copy.pdf"),+ ]+ },+ content_type="multipart/form-data",+ )+ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert len(rdata["uploaded"]) == 2+ by_name = {f["filename"]: f for f in rdata["uploaded"]}+ assert "report.pdf" in by_name+ assert by_name["report.pdf"]["status"] == "already_in_collection"+ assert by_name["report.pdf"]["pdf_upgraded"] is False+ assert "report_copy.pdf" in by_name+ assert by_name["report_copy.pdf"]["status"] == "duplicate_in_batch"+ assert by_name["report_copy.pdf"]["pdf_upgraded"] is False++ def test_upload_existing_doc_add_to_collection(self, app):+ """Existing doc not yet in collection → status 'added_to_collection'."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ existing_doc = Mock()+ existing_doc.id = "doc-xyz"+ existing_doc.filename = "paper.txt"++ db_session = _make_db_session()+ call_count = {"n": 0}++ def query_side_effect(model):+ call_count["n"] += 1+ q = _build_mock_query()+ if call_count["n"] == 1:+ q.first.return_value = mock_coll # Collection+ elif call_count["n"] == 2:+ q.first.return_value = existing_doc # Existing doc by hash+ elif call_count["n"] == 3:+ q.first.return_value = None # Not yet in collection+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ extra_patches=[+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={"files": (BytesIO(b"text data"), "paper.txt")},+ content_type="multipart/form-data",+ )+ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert rdata["uploaded"][0]["status"] == "added_to_collection"+ assert rdata["uploaded"][0]["pdf_upgraded"] is False+ # Confirm the link was added to session+ db_session.add.assert_called()++ def test_upload_existing_doc_pdf_upgrade(self, app):+ """Existing doc already in collection with pdf_upgrade=True → status 'pdf_upgraded'."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ existing_doc = Mock()+ existing_doc.id = "doc-pdf"+ existing_doc.filename = "scan.pdf"++ existing_link = Mock() # already in collection++ db_session = _make_db_session()+ call_count = {"n": 0}++ def query_side_effect(model):+ call_count["n"] += 1+ q = _build_mock_query()+ if call_count["n"] == 1:+ q.first.return_value = mock_coll+ elif call_count["n"] == 2:+ q.first.return_value = existing_doc+ elif call_count["n"] == 3:+ q.first.return_value = existing_link # already linked+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ mock_pdf_manager = Mock()+ mock_pdf_manager.upgrade_to_pdf.return_value = True # upgrade happened++ with _auth_client(+ app,+ mock_db_session=db_session,+ settings_overrides={+ "research_library.upload_pdf_storage": "database"+ },+ extra_patches=[+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ patch(+ "local_deep_research.research_library.services.pdf_storage_manager.PDFStorageManager",+ return_value=mock_pdf_manager,+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={"files": (BytesIO(b"%PDF-content"), "scan.pdf")},+ content_type="multipart/form-data",+ )+ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert rdata["uploaded"][0]["status"] == "pdf_upgraded"+ assert rdata["uploaded"][0]["pdf_upgraded"] is True++ def test_upload_existing_doc_pdf_upgrade_failure_swallowed_and_logged(+ self, app+ ):+ """When pdf_storage_manager.upgrade_to_pdf raises for an existing library document,+ _try_pdf_upgrade catches the error and returns False so the file upload still succeeds+ (pdf_upgraded=False) without failing the whole batch."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ existing_doc = Mock()+ existing_doc.id = "doc-pdf-fail"+ existing_doc.filename = "scan.pdf"++ existing_link = Mock() # already in collection++ db_session = _make_db_session()+ call_count = {"n": 0}++ def query_side_effect(model):+ call_count["n"] += 1+ q = _build_mock_query()+ if call_count["n"] == 1:+ q.first.return_value = mock_coll+ elif call_count["n"] == 2:+ q.first.return_value = existing_doc+ elif call_count["n"] == 3:+ q.first.return_value = existing_link # already linkedreturn qdb_session.query = Mock(side_effect=query_side_effect)@@ -258,59 +938,641 @@ class TestUploadToCollection:mock_password_store = Mock()mock_password_store.get_session_password.return_value = None+ mock_pdf_manager = Mock()+ mock_pdf_manager.upgrade_to_pdf.side_effect = RuntimeError(+ "Corrupt PDF data"+ )+with _auth_client(app,mock_db_session=db_session,+ settings_overrides={+ "research_library.upload_pdf_storage": "database"+ },extra_patches=[patch(f"{_DB_PASS}.session_password_store", mock_password_store),+ patch(+ "local_deep_research.research_library.services.pdf_storage_manager.PDFStorageManager",+ return_value=mock_pdf_manager,+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={+ "files": (+ BytesIO(b"%PDF-1.4 header and content"),+ "scan.pdf",+ ),+ "pdf_storage": "database",+ },+ content_type="multipart/form-data",+ )++ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert len(rdata["uploaded"]) == 1+ assert rdata["uploaded"][0]["status"] == "already_in_collection"+ assert rdata["uploaded"][0]["pdf_upgraded"] is False+ assert len(rdata["errors"]) == 0+ mock_pdf_manager.upgrade_to_pdf.assert_called_once()+ db_session.commit.assert_called_once()++ def test_upload_new_doc_unsupported_extension(self, app):+ """File with unsupported extension → error entry, not in uploaded list."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ db_session = _make_db_session()+ call_count = {"n": 0}++ def query_side_effect(model):+ call_count["n"] += 1+ q = _build_mock_query()+ if call_count["n"] == 1:+ q.first.return_value = mock_coll # Collection found+ elif call_count["n"] == 2:+ q.first.return_value = None # No existing doc by hash+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=False+ ),+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={"files": (BytesIO(b"data"), "file.xyz")},+ content_type="multipart/form-data",+ )+ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert rdata["summary"]["successful"] == 0+ assert len(rdata["errors"]) == 1+ assert "Unsupported format" in rdata["errors"][0]["error"]++ def test_upload_new_doc_no_text_extracted(self, app):+ """File that produces empty extracted text → error entry."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ db_session = _make_db_session()+ call_count = {"n": 0}++ def query_side_effect(model):+ call_count["n"] += 1+ q = _build_mock_query()+ if call_count["n"] == 1:+ q.first.return_value = mock_coll+ elif call_count["n"] == 2:+ q.first.return_value = None # No existing doc+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes", return_value=""+ ),+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={"files": (BytesIO(b"\x00\x01\x02"), "binary.pdf")},+ content_type="multipart/form-data",+ )+ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert rdata["summary"]["successful"] == 0+ assert len(rdata["errors"]) == 1+ assert "Could not extract text" in rdata["errors"][0]["error"]++ def test_upload_new_doc_success_text_only(self, app):+ """New document upload with pdf_storage='none' succeeds; status is 'uploaded'."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ mock_source = Mock()+ mock_source.id = "src-001"++ db_session = _make_db_session()+ call_count = {"n": 0}++ def query_side_effect(model):+ call_count["n"] += 1+ q = _build_mock_query()+ if call_count["n"] == 1:+ q.first.return_value = mock_coll # Collection+ elif call_count["n"] == 2:+ q.first.return_value = None # No existing doc+ elif call_count["n"] == 3:+ q.first.return_value = mock_source # SourceType exists+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ settings_overrides={"research_library.upload_pdf_storage": "none"},+ extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ return_value="Extracted document text",+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={"files": (BytesIO(b"some text content"), "doc.txt")},+ content_type="multipart/form-data",+ )+ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert len(rdata["uploaded"]) == 1+ assert rdata["uploaded"][0]["status"] == "uploaded"+ assert rdata["uploaded"][0]["pdf_stored"] is False+ assert rdata["summary"]["successful"] == 1+ assert rdata["summary"]["failed"] == 0++ def test_upload_intra_batch_duplicate_reports_distinct_status_and_filename(+ self, app+ ):+ """Regression test for the '3 books already in collection' bug.++ When two files in the same upload request have identical bytes,+ the first should be ``uploaded`` and the second should be+ ``duplicate_in_batch`` — NOT ``already_in_collection`` — and each+ entry must carry the filename of the file the user actually+ selected, not the existing/earlier-twin document's filename.+ Previously both entries carried the first occurrence's filename+ under the ``already_in_collection`` status, which made the+ warning show the same filename twice (once as uploaded, once as+ skipped) and confused users about which file was actually added.+ """+ mock_coll = Mock()+ mock_coll.id = "coll-1"++ mock_source = Mock()+ mock_source.id = "src-dup"++ # Two files in the batch share the same bytes → same hash. The+ # second occurrence in the loop would (without the fix) find the+ # Document the first occurrence just flushed and label it+ # ``already_in_collection``.+ same_content = b"identical payload for both files"++ db_session = _make_db_session()+ collection_queried = {"v": False}++ def query_side_effect(model):+ from local_deep_research.database.models.library import (+ Collection,+ SourceType,+ )++ q = _build_mock_query()+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection and not collection_queried["v"]:+ collection_queried["v"] = True+ q.first.return_value = mock_coll+ elif model is SourceType:+ q.first.return_value = mock_source+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ settings_overrides={"research_library.upload_pdf_storage": "none"},+ extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ return_value="Extracted text",+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={+ "files": [+ (BytesIO(same_content), "Foo.txt"),+ (BytesIO(same_content), "Foo (1).txt"),+ ]+ },+ content_type="multipart/form-data",+ )+ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ # Both files appear in the response (the second as a duplicate).+ assert len(rdata["uploaded"]) == 2+ by_name = {f["filename"]: f for f in rdata["uploaded"]}++ # First occurrence wins, reported under its OWN filename.+ first = by_name["Foo.txt"]+ assert first["status"] == "uploaded"+ assert "duplicate_of_id" not in first+ assert "id" in first++ # Second occurrence is the intra-batch duplicate and reports+ # under its OWN filename (the user's "Foo (1).txt", sanitised+ # to "Foo_1.txt" by sanitize_filename), not the first+ # occurrence's filename. This is the bug fix.+ second = by_name["Foo_1.txt"]+ assert second["status"] == "duplicate_in_batch"+ assert second["filename"] == "Foo_1.txt"+ assert "duplicate_of_id" not in second+ assert second["id"] == first["id"]++ # Filenames are distinct — the user can tell which file was kept+ # and which was dropped. Pre-fix both entries were "Foo.txt".+ assert first["filename"] != second["filename"]++ def test_upload_three_pairs_of_duplicates_all_dropped_cleanly(self, app):+ """Three intra-batch duplicate pairs in one request: each pair+ produces one ``uploaded`` and one ``duplicate_in_batch`` entry,+ none labeled ``already_in_collection``. Mirrors the real-world+ scenario where the user picked 3 originals + 3 ' (1)' copies in+ the file dialog at once."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"+ mock_source = Mock()+ mock_source.id = "src-triple"++ db_session = _make_db_session()+ collection_queried = {"v": False}++ def query_side_effect(model):+ from local_deep_research.database.models.library import (+ Collection,+ SourceType,+ )++ q = _build_mock_query()+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection and not collection_queried["v"]:+ collection_queried["v"] = True+ q.first.return_value = mock_coll+ elif model is SourceType:+ q.first.return_value = mock_source+ # DocumentCollection (ensure_in_collection) and Document+ # (hash lookup) both default to None above.+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ files = []+ # sanitize_filename turns spaces and parens into underscores, so+ # "A (1).txt" → "A_1.txt" by the time it reaches uploaded_files.+ # Each pair shares bytes so they hash to the same value.+ pair_payloads = {+ "A": b"bytes for A and A copy",+ "B": b"bytes for B and B copy",+ "C": b"bytes for C and C copy",+ }+ for original, dup in (+ ("A.txt", "A (1).txt"),+ ("B.txt", "B (1).txt"),+ ("C.txt", "C (1).txt"),+ ):+ payload = pair_payloads[original[0]]+ files.append((BytesIO(payload), original))+ files.append((BytesIO(payload), dup))++ with _auth_client(+ app,+ mock_db_session=db_session,+ settings_overrides={"research_library.upload_pdf_storage": "none"},+ extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes", return_value="x"+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={"files": files},+ content_type="multipart/form-data",+ )+ rdata = resp.get_json()+ assert resp.status_code == 200+ assert rdata["success"] is True++ by_name = {f["filename"]: f for f in rdata["uploaded"]}+ # Each original wins under its own filename.+ for original in ("A.txt", "B.txt", "C.txt"):+ assert original in by_name, f"{original} missing from response"+ assert by_name[original]["status"] == "uploaded"+ # Each (1) copy is the intra-batch duplicate, reported under+ # the sanitized (1) filename — never the original's filename.+ for dup_name, raw_name in (+ ("A_1.txt", "A (1).txt"),+ ("B_1.txt", "B (1).txt"),+ ("C_1.txt", "C (1).txt"),+ ):+ assert dup_name in by_name, f"{raw_name} missing from response"+ assert by_name[dup_name]["status"] == "duplicate_in_batch"+ assert by_name[dup_name]["filename"] == dup_name++ # Total accounting matches what the user picked.+ assert len(rdata["uploaded"]) == 6+ assert len(rdata["errors"]) == 0++ def test_upload_existing_doc_reports_uploaded_filename_not_db_filename(+ self, app+ ):+ """When the hash matches a pre-existing library doc, the response+ must echo the filename the user uploaded, not the existing doc's+ filename. Pre-fix the response showed ``existing_doc.filename``,+ so an upload of ``Renamed.pdf`` whose bytes matched an existing+ ``Original.pdf`` reported ``Original.pdf`` — making the warning+ unreadable when the same hash was in the user's batch from a+ previous upload with a different filename."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"+ mock_source = Mock()+ mock_source.id = "src-existing"++ existing_doc = Mock()+ existing_doc.id = "doc-existing"+ existing_doc.filename = "Original.pdf" # the OLD name in the library++ # existing_link stays None: the route treats no DocumentCollection+ # row as "not yet in this collection" → "added_to_collection".++ db_session = _make_db_session()+ collection_queried = {"v": False}++ def query_side_effect(model):+ from local_deep_research.database.models.library import (+ Collection,+ Document,+ )++ q = _build_mock_query()+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection and not collection_queried["v"]:+ collection_queried["v"] = True+ q.first.return_value = mock_coll+ elif model is Document:+ q.first.return_value = existing_doc # hash matches+ # DocumentCollection lookup defaults to None (no existing+ # link), which routes the request into the+ # ``added_to_collection`` branch.+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=db_session,+ settings_overrides={"research_library.upload_pdf_storage": "none"},+ extra_patches=[+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ "/library/api/collections/coll-1/upload",+ data={+ "files": (+ BytesIO(b"%PDF-1.4 same bytes"),+ "Renamed.pdf",+ ),+ },+ content_type="multipart/form-data",+ )+ rdata = resp.get_json()+ assert resp.status_code == 200+ assert rdata["success"] is True+ assert len(rdata["uploaded"]) == 1+ entry = rdata["uploaded"][0]+ assert entry["status"] == "added_to_collection"+ # The user uploaded ``Renamed.pdf`` and that's what should appear.+ # Pre-fix this would be ``Original.pdf``.+ assert entry["filename"] == "Renamed.pdf"+ assert entry["id"] == "doc-existing"++ def test_upload_failed_first_occurrence_does_not_block_second(self, app):+ """If the FIRST file in a batch fails (e.g. extraction returns+ empty text), the second file with the same bytes should be+ processed normally rather than being mis-labelled as a+ duplicate_in_batch of a file that never made it into the+ library. Otherwise one transient failure would silently drop+ both copies of a user's content."""+ mock_coll = Mock()+ mock_coll.id = "coll-1"+ mock_source = Mock()+ mock_source.id = "src-fail"++ db_session = _make_db_session()+ collection_queried = {"v": False}++ def query_side_effect(model):+ from local_deep_research.database.models.library import (+ Collection,+ SourceType,+ )++ q = _build_mock_query()+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection and not collection_queried["v"]:+ collection_queried["v"] = True+ q.first.return_value = mock_coll+ elif model is SourceType:+ q.first.return_value = mock_source+ return q++ db_session.query = Mock(side_effect=query_side_effect)++ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ # First call returns empty (failure); second returns text.+ extract_results = iter(["", "recovered text"])++ def fake_extract(*args, **kwargs):+ return next(extract_results)++ with _auth_client(+ app,+ mock_db_session=db_session,+ settings_overrides={"research_library.upload_pdf_storage": "none"},+ extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ side_effect=fake_extract,+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store+ ),],) as (client, ctx):resp = client.post("/library/api/collections/coll-1/upload",- data={"files": (BytesIO(b"pdf content"), "report.pdf")},+ data={+ "files": [+ (BytesIO(b"shared bytes"), "First.txt"),+ (BytesIO(b"shared bytes"), "Second.txt"),+ ]+ },content_type="multipart/form-data",)- assert resp.status_code == 200rdata = resp.get_json()- assert rdata["success"] is True- assert len(rdata["uploaded"]) == 1- assert rdata["uploaded"][0]["status"] == "already_in_collection"- assert rdata["uploaded"][0]["pdf_upgraded"] is False-- def test_upload_existing_doc_add_to_collection(self, app):- """Existing doc not yet in collection → status 'added_to_collection'."""+ assert resp.status_code == 200+ # First file failed extraction → in errors. Second file was+ # uploaded normally (NOT labelled duplicate_in_batch, because+ # the first file never made it into seen_hashes).+ assert any("Could not extract" in e["error"] for e in rdata["errors"])+ assert any(f["filename"] == "First.txt" for f in rdata["errors"])+ uploaded_names = {f["filename"]: f for f in rdata["uploaded"]}+ assert "Second.txt" in uploaded_names+ assert uploaded_names["Second.txt"]["status"] == "uploaded"+ # Soft failure (empty extract) commits the savepoint; success commits too.+ assert db_session.begin_nested.call_count == 2+ assert len(db_session._savepoints) == 2+ for sp in db_session._savepoints:+ sp.commit.assert_called_once()+ sp.rollback.assert_not_called()++ def test_upload_savepoint_isolates_failing_file_new_doc(self, app):+ """Per-file savepoints ensure that if a middle file fails and rolls back,+ earlier successful file inserts remain in the transaction and seen_hashes+ remains consistent, so a third file with identical bytes is reported as+ duplicate_in_batch rather than losing the first file's insert."""mock_coll = Mock()mock_coll.id = "coll-1"-- existing_doc = Mock()- existing_doc.id = "doc-xyz"- existing_doc.filename = "paper.txt"+ mock_source = Mock()+ mock_source.id = "src-sp"db_session = _make_db_session()- call_count = {"n": 0}+ collection_queried = {"v": False}def query_side_effect(model):- call_count["n"] += 1+ from local_deep_research.database.models.library import (+ Collection,+ SourceType,+ )+q = _build_mock_query()- if call_count["n"] == 1:- q.first.return_value = mock_coll # Collection- elif call_count["n"] == 2:- q.first.return_value = existing_doc # Existing doc by hash- elif call_count["n"] == 3:- q.first.return_value = None # Not yet in collection+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection and not collection_queried["v"]:+ collection_queried["v"] = True+ q.first.return_value = mock_coll+ elif model is SourceType:+ q.first.return_value = mock_sourcereturn qdb_session.query = Mock(side_effect=query_side_effect)+ def fake_extract(content, ext, filename):+ if filename == "ErrorFile.txt":+ raise RuntimeError("Simulated DB error on second file")+ return f"Extracted text for {filename}"+mock_password_store = Mock()mock_password_store.get_session_password.return_value = None+ shared_bytes = b"identical bytes for First and Third"+with _auth_client(app,mock_db_session=db_session,+ settings_overrides={"research_library.upload_pdf_storage": "none"},extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ side_effect=fake_extract,+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),patch(f"{_DB_PASS}.session_password_store", mock_password_store),@@ -318,105 +1580,288 @@ class TestUploadToCollection:) as (client, ctx):resp = client.post("/library/api/collections/coll-1/upload",- data={"files": (BytesIO(b"text data"), "paper.txt")},+ data={+ "files": [+ (BytesIO(shared_bytes), "First.txt"),+ (BytesIO(b"error content"), "ErrorFile.txt"),+ (BytesIO(shared_bytes), "Third.txt"),+ ]+ },content_type="multipart/form-data",)- assert resp.status_code == 200- rdata = resp.get_json()- assert rdata["success"] is True- assert rdata["uploaded"][0]["status"] == "added_to_collection"- assert rdata["uploaded"][0]["pdf_upgraded"] is False- # Confirm the link was added to session- db_session.add.assert_called()- def test_upload_existing_doc_pdf_upgrade(self, app):- """Existing doc already in collection with pdf_upgrade=True → status 'pdf_upgraded'."""+ rdata = resp.get_json()+ assert resp.status_code == 200+ assert any(e["filename"] == "ErrorFile.txt" for e in rdata["errors"])++ by_name = {f["filename"]: f for f in rdata["uploaded"]}+ assert "First.txt" in by_name+ assert by_name["First.txt"]["status"] == "uploaded"+ assert "Third.txt" in by_name+ assert by_name["Third.txt"]["status"] == "duplicate_in_batch"++ # First success commits; middle exception rolls back; third+ # (duplicate) commits its empty SAVEPOINT.+ assert db_session.begin_nested.call_count == 3+ assert len(db_session._savepoints) == 3+ db_session._savepoints[0].commit.assert_called_once()+ db_session._savepoints[0].rollback.assert_not_called()+ db_session._savepoints[1].rollback.assert_called_once()+ db_session._savepoints[1].commit.assert_not_called()+ db_session._savepoints[2].commit.assert_called_once()+ db_session._savepoints[2].rollback.assert_not_called()++ def test_upload_savepoint_isolates_failing_file_existing_doc(self, app):+ """Per-file savepoints ensure that if a middle file fails, an earlier file's link+ to an existing document is preserved and subsequent identical uploads are reported+ as duplicate_in_batch."""mock_coll = Mock()mock_coll.id = "coll-1"-- existing_doc = Mock()- existing_doc.id = "doc-pdf"- existing_doc.filename = "scan.pdf"-- existing_link = Mock() # already in collection+ mock_source = Mock()+ mock_source.id = "src-sp-existing"+ mock_existing_doc = Mock()+ mock_existing_doc.id = "doc-pre-existing"+ mock_existing_doc.filename = "OriginalInDB.txt"db_session = _make_db_session()- call_count = {"n": 0}+ shared_bytes = b"pre existing doc content"+ import hashlib++ shared_hash = hashlib.sha256(shared_bytes).hexdigest()def query_side_effect(model):- call_count["n"] += 1+ from local_deep_research.database.models.library import (+ Collection,+ Document,+ SourceType,+ )+q = _build_mock_query()- if call_count["n"] == 1:+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection:q.first.return_value = mock_coll- elif call_count["n"] == 2:- q.first.return_value = existing_doc- elif call_count["n"] == 3:- q.first.return_value = existing_link # already linked+ elif model is Document:+ # Return existing doc only for the shared_bytes hash+ def filter_by_side_effect(**kwargs):+ fq = _build_mock_query()+ if kwargs.get("document_hash") == shared_hash:+ fq.first.return_value = mock_existing_doc+ else:+ fq.first.return_value = None+ return fq++ q.filter_by = Mock(side_effect=filter_by_side_effect)+ elif model is SourceType:+ q.first.return_value = mock_sourcereturn qdb_session.query = Mock(side_effect=query_side_effect)+ def fake_extract(content, ext, filename):+ if filename == "ErrorFile.txt":+ raise RuntimeError("Simulated flush error")+ return f"Extracted text for {filename}"+mock_password_store = Mock()mock_password_store.get_session_password.return_value = None- mock_pdf_manager = Mock()- mock_pdf_manager.upgrade_to_pdf.return_value = True # upgrade happened-with _auth_client(app,mock_db_session=db_session,- settings_overrides={- "research_library.upload_pdf_storage": "database"- },+ settings_overrides={"research_library.upload_pdf_storage": "none"},extra_patches=[patch(- f"{_DB_PASS}.session_password_store", mock_password_store+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True),patch(- "local_deep_research.research_library.services.pdf_storage_manager.PDFStorageManager",- return_value=mock_pdf_manager,+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ side_effect=fake_extract,+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),+ patch(+ f"{_DB_PASS}.session_password_store", mock_password_store),],) as (client, ctx):resp = client.post("/library/api/collections/coll-1/upload",- data={"files": (BytesIO(b"%PDF-content"), "scan.pdf")},+ data={+ "files": [+ (BytesIO(shared_bytes), "First.txt"),+ (BytesIO(b"error content"), "ErrorFile.txt"),+ (BytesIO(shared_bytes), "Third.txt"),+ ]+ },content_type="multipart/form-data",)- assert resp.status_code == 200+rdata = resp.get_json()- assert rdata["success"] is True- assert rdata["uploaded"][0]["status"] == "pdf_upgraded"- assert rdata["uploaded"][0]["pdf_upgraded"] is True+ assert resp.status_code == 200+ assert any(e["filename"] == "ErrorFile.txt" for e in rdata["errors"])++ by_name = {f["filename"]: f for f in rdata["uploaded"]}+ assert "First.txt" in by_name+ assert by_name["First.txt"]["status"] == "added_to_collection"+ assert "Third.txt" in by_name+ assert by_name["Third.txt"]["status"] == "duplicate_in_batch"++ assert db_session.begin_nested.call_count == 3+ assert len(db_session._savepoints) == 3+ db_session._savepoints[0].commit.assert_called_once()+ db_session._savepoints[1].rollback.assert_called_once()+ db_session._savepoints[2].commit.assert_called_once()++ def test_upload_real_session_flush_error_isolation(+ self, app, library_session, mock_collection, mock_upload_source_type+ ):+ """On a real SQLAlchemy session, a flush error inside begin_nested()+ deactivates the savepoint (sp.is_active becomes False) and marks the+ Session as requiring an explicit rollback. Rolling back the savepoint+ without checking sp.is_active resets the session so subsequent files+ and the final commit succeed, and previous successes remain durable.+ """+ import uuid+ from sqlalchemy import event+ from local_deep_research.database.models.library import Document++ def on_before_insert(mapper, connection, target):+ if target.filename == "file2.txt":+ # Insert a colliding hash directly into SQLite table so flush() hits a real IntegrityError+ connection.execute(+ Document.__table__.insert().values(+ id=str(uuid.uuid4()),+ source_type_id=mock_upload_source_type.id,+ document_hash=target.document_hash,+ file_size=len(b"content 2"),+ file_type="txt",+ text_content="colliding row in db",+ )+ )- def test_upload_new_doc_unsupported_extension(self, app):- """File with unsupported extension → error entry, not in uploaded list."""+ event.listen(Document, "before_insert", on_before_insert)+ try:+ mock_password_store = Mock()+ mock_password_store.get_session_password.return_value = None++ with _auth_client(+ app,+ mock_db_session=library_session,+ settings_overrides={+ "research_library.upload_pdf_storage": "none"+ },+ extra_patches=[+ patch(+ f"{_DOC_LOADERS}.is_extension_supported",+ return_value=True,+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ side_effect=lambda content, ext, fn: f"Text for {fn}",+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates",+ side_effect=lambda x: x,+ ),+ patch(+ f"{_DB_PASS}.session_password_store",+ mock_password_store,+ ),+ ],+ ) as (client, ctx):+ resp = client.post(+ f"/library/api/collections/{mock_collection.id}/upload",+ data={+ "files": [+ (BytesIO(b"content 1"), "file1.txt"),+ (BytesIO(b"content 2"), "file2.txt"),+ (BytesIO(b"content 3"), "file3.txt"),+ ]+ },+ content_type="multipart/form-data",+ )++ assert resp.status_code == 200+ rdata = resp.get_json()+ assert rdata["success"] is True+ assert len(rdata["uploaded"]) == 2+ uploaded_names = {f["filename"]: f for f in rdata["uploaded"]}+ assert "file1.txt" in uploaded_names+ assert uploaded_names["file1.txt"]["status"] == "uploaded"+ assert "file3.txt" in uploaded_names+ assert uploaded_names["file3.txt"]["status"] == "uploaded"+ assert len(rdata["errors"]) == 1+ assert rdata["errors"][0]["filename"] == "file2.txt"+ assert "Failed to upload file" in rdata["errors"][0]["error"]++ # Verify durability in the real database after commit+ persisted = (+ library_session.query(Document)+ .filter(Document.filename.in_(["file1.txt", "file3.txt"]))+ .all()+ )+ persisted_names = {d.filename for d in persisted}+ assert persisted_names == {"file1.txt", "file3.txt"}+ finally:+ event.remove(Document, "before_insert", on_before_insert)++ def test_upload_intra_batch_pdf_upgrade_path(self, app):+ """When identical bytes are uploaded first under a non-PDF filename (stored text-only)+ and later as a .pdf with database PDF storage enabled, the second file upgrades+ the stored document to PDF storage and reports pdf_upgraded=True."""mock_coll = Mock()mock_coll.id = "coll-1"+ mock_source = Mock()+ mock_source.id = "src-pdf-up"db_session = _make_db_session()- call_count = {"n": 0}def query_side_effect(model):- call_count["n"] += 1+ from local_deep_research.database.models.library import (+ Collection,+ SourceType,+ )+q = _build_mock_query()- if call_count["n"] == 1:- q.first.return_value = mock_coll # Collection found- elif call_count["n"] == 2:- q.first.return_value = None # No existing doc by hash+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection:+ q.first.return_value = mock_coll+ elif model is SourceType:+ q.first.return_value = mock_sourcereturn qdb_session.query = Mock(side_effect=query_side_effect)+ pdf_bytes = b"%PDF-1.4 header and content"+ mock_mgr = Mock()+ mock_mgr.upgrade_to_pdf.return_value = True+mock_password_store = Mock()mock_password_store.get_session_password.return_value = Nonewith _auth_client(app,mock_db_session=db_session,+ settings_overrides={+ "research_library.upload_pdf_storage": "database"+ },extra_patches=[patch(- f"{_DOC_LOADERS}.is_extension_supported", return_value=False+ f"{_DOC_LOADERS}.is_extension_supported", return_value=True+ ),+ patch(+ f"{_DOC_LOADERS}.extract_text_from_bytes",+ return_value="Extracted PDF text",+ ),+ patch(+ f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x+ ),+ patch(+ "local_deep_research.research_library.services.pdf_storage_manager.PDFStorageManager",+ return_value=mock_mgr,),patch(f"{_DB_PASS}.session_password_store", mock_password_store@@ -425,47 +1870,97 @@ class TestUploadToCollection:) as (client, ctx):resp = client.post("/library/api/collections/coll-1/upload",- data={"files": (BytesIO(b"data"), "file.xyz")},+ data={+ "files": [+ (BytesIO(pdf_bytes), "sample.txt"),+ (BytesIO(pdf_bytes), "sample.pdf"),+ ],+ "pdf_storage": "database",+ },content_type="multipart/form-data",)- assert resp.status_code == 200- rdata = resp.get_json()- assert rdata["success"] is True- assert rdata["summary"]["successful"] == 0- assert len(rdata["errors"]) == 1- assert "Unsupported format" in rdata["errors"][0]["error"]- def test_upload_new_doc_no_text_extracted(self, app):- """File that produces empty extracted text → error entry."""+ rdata = resp.get_json()+ assert resp.status_code == 200+ by_name = {f["filename"]: f for f in rdata["uploaded"]}+ assert "sample.txt" in by_name+ assert by_name["sample.txt"]["status"] == "uploaded"+ assert "sample.pdf" in by_name+ assert by_name["sample.pdf"]["status"] == "duplicate_in_batch"+ assert by_name["sample.pdf"]["pdf_upgraded"] is True+ mock_mgr.upgrade_to_pdf.assert_called_once()+ # Upgrade target must be the Document created for the first file.+ call_kwargs = mock_mgr.upgrade_to_pdf.call_args.kwargs+ assert call_kwargs["pdf_content"] == pdf_bytes+ assert call_kwargs["session"] is db_session+ assert call_kwargs["document"] is not None+ # Both files release their SAVEPOINTs via commit.+ assert len(db_session._savepoints) == 2+ for sp in db_session._savepoints:+ sp.commit.assert_called_once()+ sp.rollback.assert_not_called()++ def test_upload_intra_batch_pdf_upgrade_with_pre_existing_doc_twin(+ self, app+ ):+ """When identical bytes match a pre-existing library document and a second+ file in the batch is a .pdf, the pre-existing document is upgraded to PDF+ and the second file reports duplicate_in_batch with pdf_upgraded=True."""mock_coll = Mock()mock_coll.id = "coll-1"+ mock_existing_doc = Mock()+ mock_existing_doc.id = "doc-pre-existing-pdf"+ mock_existing_doc.filename = "original.txt"+db_session = _make_db_session()- call_count = {"n": 0}+ pdf_bytes = b"%PDF-1.5 pre-existing doc content"+ import hashlib++ shared_hash = hashlib.sha256(pdf_bytes).hexdigest()def query_side_effect(model):- call_count["n"] += 1+ from local_deep_research.database.models.library import (+ Collection,+ Document,+ )+q = _build_mock_query()- if call_count["n"] == 1:+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection:q.first.return_value = mock_coll- elif call_count["n"] == 2:- q.first.return_value = None # No existing doc+ elif model is Document:++ def filter_by_side_effect(**kwargs):+ fq = _build_mock_query()+ if kwargs.get("document_hash") == shared_hash:+ fq.first.return_value = mock_existing_doc+ else:+ fq.first.return_value = None+ return fq++ q.filter_by = Mock(side_effect=filter_by_side_effect)return qdb_session.query = Mock(side_effect=query_side_effect)+ mock_mgr = Mock()+ mock_mgr.upgrade_to_pdf.side_effect = [False, True]+mock_password_store = Mock()mock_password_store.get_session_password.return_value = Nonewith _auth_client(app,mock_db_session=db_session,+ settings_overrides={+ "research_library.upload_pdf_storage": "database"+ },extra_patches=[patch(- f"{_DOC_LOADERS}.is_extension_supported", return_value=True- ),- patch(- f"{_DOC_LOADERS}.extract_text_from_bytes", return_value=""+ "local_deep_research.research_library.services.pdf_storage_manager.PDFStorageManager",+ return_value=mock_mgr,),patch(f"{_DB_PASS}.session_password_store", mock_password_store@@ -474,58 +1969,87 @@ class TestUploadToCollection:) as (client, ctx):resp = client.post("/library/api/collections/coll-1/upload",- data={"files": (BytesIO(b"\x00\x01\x02"), "binary.pdf")},+ data={+ "files": [+ (BytesIO(pdf_bytes), "first_existing.txt"),+ (BytesIO(pdf_bytes), "second_upgrade.pdf"),+ ],+ "pdf_storage": "database",+ },content_type="multipart/form-data",)- assert resp.status_code == 200- rdata = resp.get_json()- assert rdata["success"] is True- assert rdata["summary"]["successful"] == 0- assert len(rdata["errors"]) == 1- assert "Could not extract text" in rdata["errors"][0]["error"]- def test_upload_new_doc_success_text_only(self, app):- """New document upload with pdf_storage='none' succeeds; status is 'uploaded'."""+ rdata = resp.get_json()+ assert resp.status_code == 200+ by_name = {f["filename"]: f for f in rdata["uploaded"]}+ assert "first_existing.txt" in by_name+ assert by_name["first_existing.txt"]["status"] == "added_to_collection"+ assert by_name["first_existing.txt"]["pdf_upgraded"] is False+ assert "second_upgrade.pdf" in by_name+ assert by_name["second_upgrade.pdf"]["status"] == "duplicate_in_batch"+ assert by_name["second_upgrade.pdf"]["pdf_upgraded"] is True+ assert mock_mgr.upgrade_to_pdf.call_count == 2++ def test_upload_intra_batch_pdf_upgrade_failure_swallowed_and_logged(+ self, app+ ):+ """When pdf_storage_manager.upgrade_to_pdf raises during an intra-batch duplicate+ upgrade attempt, the error is caught and the second file is reported as+ duplicate_in_batch with pdf_upgraded=False rather than failing the batch."""mock_coll = Mock()mock_coll.id = "coll-1"-mock_source = Mock()- mock_source.id = "src-001"+ mock_source.id = "src-pdf-up-fail"db_session = _make_db_session()- call_count = {"n": 0}def query_side_effect(model):- call_count["n"] += 1+ from local_deep_research.database.models.library import (+ Collection,+ SourceType,+ )+q = _build_mock_query()- if call_count["n"] == 1:- q.first.return_value = mock_coll # Collection- elif call_count["n"] == 2:- q.first.return_value = None # No existing doc- elif call_count["n"] == 3:- q.first.return_value = mock_source # SourceType exists+ q.scalar.return_value = None+ q.first.return_value = None+ if model is Collection:+ q.first.return_value = mock_coll+ elif model is SourceType:+ q.first.return_value = mock_sourcereturn qdb_session.query = Mock(side_effect=query_side_effect)+ pdf_bytes = b"%PDF-1.4 header and content"+ mock_mgr = Mock()+ mock_mgr.upgrade_to_pdf.side_effect = RuntimeError(+ "Upgrade storage failed"+ )+mock_password_store = Mock()mock_password_store.get_session_password.return_value = Nonewith _auth_client(app,mock_db_session=db_session,- settings_overrides={"research_library.upload_pdf_storage": "none"},+ settings_overrides={+ "research_library.upload_pdf_storage": "database"+ },extra_patches=[patch(f"{_DOC_LOADERS}.is_extension_supported", return_value=True),patch(f"{_DOC_LOADERS}.extract_text_from_bytes",- return_value="Extracted document text",+ return_value="Extracted PDF text",),patch(f"{_TEXT_PROC}.remove_surrogates", side_effect=lambda x: x),+ patch(+ "local_deep_research.research_library.services.pdf_storage_manager.PDFStorageManager",+ return_value=mock_mgr,+ ),patch(f"{_DB_PASS}.session_password_store", mock_password_store),@@ -533,17 +2057,30 @@ class TestUploadToCollection:) as (client, ctx):resp = client.post("/library/api/collections/coll-1/upload",- data={"files": (BytesIO(b"some text content"), "doc.txt")},+ data={+ "files": [+ (BytesIO(pdf_bytes), "sample.txt"),+ (BytesIO(pdf_bytes), "sample.pdf"),+ ],+ "pdf_storage": "database",+ },content_type="multipart/form-data",)- assert resp.status_code == 200+rdata = resp.get_json()- assert rdata["success"] is True- assert len(rdata["uploaded"]) == 1- assert rdata["uploaded"][0]["status"] == "uploaded"- assert rdata["uploaded"][0]["pdf_stored"] is False- assert rdata["summary"]["successful"] == 1- assert rdata["summary"]["failed"] == 0+ assert resp.status_code == 200+ by_name = {f["filename"]: f for f in rdata["uploaded"]}+ assert "sample.txt" in by_name+ assert by_name["sample.txt"]["status"] == "uploaded"+ assert "sample.pdf" in by_name+ assert by_name["sample.pdf"]["status"] == "duplicate_in_batch"+ assert by_name["sample.pdf"]["pdf_upgraded"] is False+ assert len(rdata["errors"]) == 0+ mock_mgr.upgrade_to_pdf.assert_called_once()+ assert len(db_session._savepoints) == 2+ for sp in db_session._savepoints:+ sp.commit.assert_called_once()+ sp.rollback.assert_not_called()def test_upload_new_doc_success_with_pdf_db(self, app):"""New PDF upload with pdf_storage='database' stores the PDF and reports pdf_stored=True."""