Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

fix: two files heading for one filename no longer merge into one document (#2406)

Rico Furtado6bce2f841017
diff --git a/src/models/processors.py b/src/models/processors.py
index 0c1026828..250e90aef 100644
--- a/src/models/processors.py
+++ b/src/models/processors.py
@@ -19,6 +19,7 @@ from utils.file_utils import (
get_filename_aliases,
langflow_safe_filename_and_mimetype,
)
+from utils.filename_claims import claim_holder, filename_claims
from utils.hash_utils import hash_id
from utils.logging_config import get_logger
from utils.opensearch_queries import build_owned_filename_query, build_replace_filename_query
@@ -31,6 +32,12 @@ DOCLING_PARSER_LABEL = "Docling Serve 1.20.0"
TEXT_PARSER_LABEL = "Text Parser"
DUPLICATE_FILENAME_WARNING = "A file with this name already exists."
+
+# Both outcomes finish the file the same way — SKIPPED, counted successful,
+# duplicate warning — but only "skip" means a document with this name is
+# actually indexed. "skip_in_flight" means another file in this batch is still
+# writing it, which is a different fact about the index.
+DUPLICATE_SKIP_ACTIONS = ("skip", "skip_in_flight")
DUPLICATE_CONTENT_WARNING = (
"Identical content already exists in the knowledge base under a different filename."
)
@@ -259,20 +266,41 @@ class TaskProcessor:
replace: bool,
owner_user_id: str | None,
shared: bool = False,
+ claim_holder: str | None = None,
allow_anonymous_delete: bool = True,
- ) -> Literal["proceed", "skip", "replaced"]:
+ ) -> Literal["proceed", "skip", "skip_in_flight", "replaced"]:
"""Single duplicate-filename policy shared by every processor.
Checks whether a document with this filename (or one of its aliases)
is already indexed and applies the caller's replace decision:
* ``"proceed"`` — no duplicate; continue ingestion.
- * ``"skip"`` — duplicate and ``replace`` is False; the caller
- should finish via ``mark_duplicate_skipped``.
+ * ``"skip"`` — a document with this name is indexed and
+ ``replace`` is False; the caller should finish via
+ ``mark_duplicate_skipped``.
+ * ``"skip_in_flight"`` — another file in this batch holds the name and
+ has not finished writing it. Finishes the same way,
+ but nothing is indexed under the name *yet*, so a
+ caller must not treat it as a statement about what
+ is in the index (see ``_reconcile_shared_owner``).
* ``"replaced"`` — duplicate and ``replace`` is True; the existing
chunks were deleted and the index refreshed, so
ingestion can continue.
+
+ ``claim_holder`` identifies this file's run (see ``utils.filename_claims``)
+ and holds the name for its duration, so a second file heading for the
+ same name inside the same batch resolves as a duplicate instead of
+ racing the index check. TaskService releases the claim when the file
+ reaches a terminal state. Callers that pass None get the OpenSearch
+ policy alone — every processor passes one.
"""
+ if claim_holder is not None and not filename_claims.claim(
+ claim_holder, filename, owner_user_id=owner_user_id, shared=shared
+ ):
+ # Another file in flight is already heading for this name; whichever
+ # of them lands first is the one this name belongs to.
+ return "skip_in_flight"
+
if not await self.check_filename_exists(filename, opensearch_client):
return "proceed"
if not replace:
@@ -304,6 +332,11 @@ class TaskProcessor:
)
return "replaced"
+ @staticmethod
+ def _claim_holder(upload_task: UploadTask, file_task: FileTask) -> str:
+ """Identity of this file's run, for the in-flight filename claim."""
+ return claim_holder(upload_task.task_id, file_task.file_path)
+
def mark_duplicate_skipped(self, upload_task: UploadTask, file_task: FileTask) -> None:
"""Uniform terminal state for a duplicate that was not replaced:
SKIPPED, counted toward successful files, with a warning the task view
@@ -818,8 +851,9 @@ class DocumentFileProcessor(TaskProcessor):
opensearch_client,
replace=self.replace_duplicates,
owner_user_id=self.owner_user_id,
+ claim_holder=self._claim_holder(upload_task, file_task),
)
- if duplicate_action == "skip":
+ if duplicate_action in DUPLICATE_SKIP_ACTIONS:
self.mark_duplicate_skipped(upload_task, file_task)
return
@@ -1019,10 +1053,16 @@ class ConnectorFileProcessor(TaskProcessor):
"""Update owner fields on already-indexed chunks for `filename` to match
the `shared` setting resolved for this file.
- Called on the duplicate/unchanged skip paths below, where a file's
- content and name haven't changed since a prior sync but the connector's
- "Make documents available to all users" setting may have been toggled
- since then. Without this, those chunks would keep whatever owner they
+ Called where the document indexed under this name is THIS file's own —
+ the unchanged-content path, and a skip against a real duplicate. Never
+ for a "skip_in_flight": there the name belongs to another file that is
+ still writing it, and this query matches by filename, so reconciling
+ would stamp this file's sharing answer onto that one's chunks.
+
+ On those paths the file's content and name haven't changed since a prior
+ sync, but the connector's "Make documents available to all users"
+ setting may have been toggled since. Without this, those chunks would
+ keep whatever owner they
got on their original ingest forever, since a byte-identical re-sync
never reaches resolve_shared_owner_fields(). Scoped to chunks owned by
this user — and to ownerless ones only under the same
@@ -1247,10 +1287,18 @@ class ConnectorFileProcessor(TaskProcessor):
replace=self.replace_duplicates,
owner_user_id=self.user_id,
shared=shared,
+ claim_holder=self._claim_holder(upload_task, file_task),
allow_anonymous_delete=self.allow_anonymous_delete,
)
- if duplicate_action == "skip":
- await self._reconcile_shared_owner(file_task.filename, shared)
+ if duplicate_action in DUPLICATE_SKIP_ACTIONS:
+ # Only for a real duplicate. The reconcile rewrites owner fields
+ # on every chunk with this filename, and "skip_in_flight" means
+ # the chunks under that name are being written right now by a
+ # DIFFERENT document, whose sharing state was resolved from its
+ # own file id and can differ from this one's. Reconciling then
+ # would stamp this file's answer onto another file's chunks.
+ if duplicate_action == "skip":
+ await self._reconcile_shared_owner(file_task.filename, shared)
self.mark_duplicate_skipped(upload_task, file_task)
return
@@ -1574,8 +1622,9 @@ class S3FileProcessor(TaskProcessor):
opensearch_client,
replace=self.replace_duplicates,
owner_user_id=self.owner_user_id,
+ claim_holder=self._claim_holder(upload_task, file_task),
)
- if duplicate_action == "skip":
+ if duplicate_action in DUPLICATE_SKIP_ACTIONS:
self.mark_duplicate_skipped(upload_task, file_task)
return
@@ -1681,8 +1730,9 @@ class LangflowFileProcessor(TaskProcessor):
opensearch_client,
replace=self.replace_duplicates,
owner_user_id=self.owner_user_id,
+ claim_holder=self._claim_holder(upload_task, file_task),
)
- if duplicate_action == "skip":
+ if duplicate_action in DUPLICATE_SKIP_ACTIONS:
self.mark_duplicate_skipped(upload_task, file_task)
return
diff --git a/src/services/task_service.py b/src/services/task_service.py
index e0b966d41..5f6c43386 100644
--- a/src/services/task_service.py
+++ b/src/services/task_service.py
@@ -17,6 +17,11 @@ from models.tasks import (
UploadTask,
)
from session_manager import AnonymousUser
+from utils.filename_claims import (
+ INFLIGHT_CLAIM_WINNER_FAILED_ERROR,
+ claim_holder,
+ filename_claims,
+)
from utils.gpu_detection import get_worker_count
from utils.logging_config import get_logger
from utils.telemetry import Category, MessageId, TelemetryClient
@@ -606,6 +611,76 @@ class TaskService:
return f"{hours}h {mins}m {secs}s"
+ def _find_upload_task(self, task_id: str) -> UploadTask | None:
+ """The task with this id, whichever user's store holds it.
+
+ A claim conflict is not confined to one task: the registry keys names by
+ ownership scope, not by task, so a file in one task can lose a name to a
+ file in another — two uploads in flight at once, or an upload racing a
+ connector sync.
+ """
+ for tasks in self.task_store.values():
+ found = tasks.get(task_id)
+ if found is not None:
+ return found
+ return None
+
+ async def _fail_files_stranded_by(self, refused_holders: set[str]) -> None:
+ """Fail the files that were skipped for a name this one never indexed.
+
+ The duplicate gate decides a losing file's outcome the moment it loses
+ the claim, before the winner has ingested anything. When the winner then
+ fails, nothing landed under that name, so the loser's "skipped, a file
+ with this name already exists" describes something that never happened —
+ and it is counted as a successful file, which is a document the user
+ never got. SKIPPED is also not a retry candidate (retry_failed_files
+ takes FAILED only), so nothing would ever recover it.
+
+ Failing it instead says what happened and puts it back within reach of a
+ retry, which re-runs the gate and resolves correctly either way: it
+ ingests if the name is genuinely free, and skips again as a duplicate if
+ something else holds it by then.
+
+ Each loser is corrected inside its own task, which may not be this one
+ and may already have finished. That stays consistent: processed_files is
+ untouched, one successful file becomes a failed one under that task's
+ lock, and a COMPLETED task carrying failures is the ordinary shape retry
+ operates on — it refuses only while a task is still RUNNING. The
+ completion event for such a task was emitted with the earlier counts,
+ which leaves a stale statistic behind rather than inconsistent state.
+ """
+ for holder in refused_holders:
+ loser_task_id, _, file_key = holder.partition(":")
+ if not file_key:
+ continue
+ owning_task = self._find_upload_task(loser_task_id)
+ if owning_task is None:
+ # Task already evicted from the store; nothing left to correct.
+ continue
+ stranded = owning_task.file_tasks.get(file_key)
+ if stranded is None or stranded.status != TaskStatus.SKIPPED:
+ continue
+ # Only the in-flight skip is ours to reverse; a file skipped against
+ # something already indexed is unaffected by this failure.
+ if (stranded.result or {}).get("reason") != "duplicate_filename":
+ continue
+
+ stranded.status = TaskStatus.FAILED
+ stranded.error = INFLIGHT_CLAIM_WINNER_FAILED_ERROR
+ stranded.result = None
+ stranded.updated_at = time.time()
+ async with self._get_task_lock(loser_task_id):
+ if owning_task.successful_files > 0:
+ owning_task.successful_files -= 1
+ owning_task.failed_files += 1
+ owning_task.updated_at = time.time()
+ logger.info(
+ "Reversed an in-flight duplicate skip after the ingesting file failed",
+ task_id=loser_task_id,
+ file_path=stranded.file_path,
+ filename=stranded.filename,
+ )
+
async def background_custom_processor(
self, user_id: str, task_id: str, items: list, processor=None
) -> None:
@@ -754,6 +829,13 @@ class TaskService:
)
finally:
+ # Hand back the filename this file held while in flight
+ # (utils.filename_claims), so the next task — or a retry
+ # of this one — can take it. Every file passes through
+ # here, including the ones that never claimed anything.
+ refused = filename_claims.release(claim_holder(task_id, item_key))
+ if refused and file_task.status == TaskStatus.FAILED:
+ await self._fail_files_stranded_by(refused)
file_task.updated_at = time.time()
# Only increment processed_files if the file reached a terminal state
# This prevents counter inconsistency on cancellation.
@@ -1152,6 +1234,19 @@ class TaskService:
"actionable_by": "USER_ACTIONABLE",
}
+ # Before the substring heuristics below, which would otherwise read this
+ # as a plain duplicate: the file was never ingested, and retrying is
+ # exactly the right move.
+ if error == INFLIGHT_CLAIM_WINNER_FAILED_ERROR:
+ return {
+ "component": "openrag",
+ "failure_phase": "unknown",
+ "user_facing_message": (
+ f"{INFLIGHT_CLAIM_WINNER_FAILED_ERROR} Retry to ingest it."
+ ),
+ "actionable_by": "RETRYABLE",
+ }
+
# Before any substring heuristic: an OpenSearch transport failure carries a
# JSON payload whose contents would otherwise match the file-corruption and
# "already exists" markers below.
@@ -1878,10 +1973,39 @@ class TaskService:
metadata = self._infer_failure_metadata(file_task)
return bool(metadata and metadata.get("actionable_by") == "RETRYABLE")
+ def _is_unsettled_claim_loser_temp(self, upload_task: UploadTask, temp_path: str) -> bool:
+ """True when a staged temp belongs to a file skipped for a name another
+ in-flight file still holds.
+
+ Such a skip is provisional: if the file holding the name fails, nothing
+ was indexed under it and _fail_files_stranded_by turns this file into a
+ retryable failure. That correction can land after this task has already
+ finished — the holder may belong to another task entirely — and a retry
+ then needs the staged source that cleanup would otherwise have deleted.
+
+ Retention is bounded the same way a retryable failure's is: whichever
+ way the holder ends, the temp is reclaimed when the task ages out of the
+ store (cleanup_old_tasks force-cleans what it evicts).
+ """
+ if not os.path.isabs(temp_path):
+ return False
+ file_task = self._file_task_for_temp_path(upload_task, temp_path)
+ if file_task is None or file_task.status != TaskStatus.SKIPPED:
+ return False
+ if (file_task.result or {}).get("reason") != "duplicate_filename":
+ return False
+ # Local uploads key file_tasks by the staged path, which is what the
+ # claim holder was built from.
+ return filename_claims.is_awaiting_outcome(
+ claim_holder(upload_task.task_id, file_task.file_path)
+ )
+
def _should_retain_upload_temp(self, upload_task: UploadTask, temp_path: str) -> bool:
"""Return True when an upload temp should be kept after processing."""
if self._is_retryable_local_upload_temp(upload_task, temp_path):
return True
+ if self._is_unsettled_claim_loser_temp(upload_task, temp_path):
+ return True
if (
os.path.isabs(temp_path)
and self._file_task_for_temp_path(upload_task, temp_path) is None
diff --git a/src/utils/filename_claims.py b/src/utils/filename_claims.py
new file mode 100644
index 000000000..b1d97e458
--- /dev/null
+++ b/src/utils/filename_claims.py
@@ -0,0 +1,188 @@
+"""In-flight claims on the filename a document is about to be indexed under.
+
+Duplicate detection asks OpenSearch whether a name is taken, which can only
+answer for what is already indexed. Files within a task are ingested
+concurrently (``TaskService`` runs them under a worker semaphore), so two files
+heading for the same name are both told "no" and both proceed:
+
+ * chunk ids are content-derived, so the two documents do not overwrite each
+ other — the index ends up with one filename whose chunks come from two
+ different files, and deleting "it" deletes both;
+ * with ``replace_duplicates`` on (the default for uploads) the later file
+ deletes the earlier one's chunks mid-flight instead, and the earlier file's
+ task still reports success.
+
+Neither is reachable by looking at the index, because at the moment each file
+checks, the other has not written yet. Claiming the name for the duration of
+one file's ingestion turns that race into an ordinary duplicate: the first file
+to claim proceeds, the rest take the existing "a file with this name already
+exists" skip.
+
+Claims cover every alias a name can be indexed under (``get_filename_aliases``),
+so ``notes.txt`` and ``notes.md`` in one batch contest the same claim, matching
+what the duplicate check and the delete path already treat as one name.
+
+Two writes contend when they could land on the same indexed document, which is
+the boundary ``build_replace_filename_query`` already draws for the delete a
+replace performs: a write collides with anything ownerless, and with anything
+owned by the same user. So a shared write contends with every other write for
+that name, while two users' private writes do not — neither can see the other's
+document, and their chunks are written under different ownership scopes
+(``DocumentIndexWriter._scoped_chunk_id``).
+
+In-process only. That is the same single-worker assumption the RBAC and
+identity caches already make (see AGENTS.md); with several workers, two files
+landing in different processes fall back to the pre-existing behaviour.
+"""
+
+from collections.abc import Iterable
+from dataclasses import dataclass
+
+from utils.file_utils import get_filename_aliases
+from utils.logging_config import get_logger
+
+logger = get_logger(__name__)
+
+
+# Error recorded on a file whose skip turned out to describe an ingestion that
+# never happened. Kept distinctive so failure classification can recognise it
+# without colliding with the corruption/duplicate substring heuristics.
+INFLIGHT_CLAIM_WINNER_FAILED_ERROR = (
+ "Another file with this name was ingesting at the same time and did not finish, "
+ "so this file was not ingested."
+)
+
+
+@dataclass(frozen=True)
+class _Claim:
+ """A name held by one in-flight file, and the layout it will be written in."""
+
+ holder: str
+ owner_user_id: str | None
+ shared: bool
+
+
+def _contends(claim: _Claim, owner_user_id: str | None, shared: bool) -> bool:
+ """Whether a write by this owner, in this layout, could land on `claim`'s
+ document.
+
+ An ownerless document is visible to the whole instance and is what every
+ user's duplicate check sees, so a shared write on either side makes the two
+ contend. Otherwise they contend only when the same user owns both: another
+ user's private document is invisible to the check and is written under a
+ different ownership scope, so it cannot be collided with.
+
+ A write with no owner at all is treated as shared, which is how it is
+ indexed.
+ """
+ if shared or not owner_user_id or claim.shared or not claim.owner_user_id:
+ return True
+ return claim.owner_user_id == owner_user_id
+
+
+class FilenameClaimRegistry:
+ """Which in-flight file holds which filename, per ownership scope.
+
+ Every method runs to completion without awaiting, so the event loop cannot
+ interleave two claims for the same name — the check and the take are one
+ step, which is the whole point of the registry.
+ """
+
+ def __init__(self) -> None:
+ # alias -> holder -> claim. Several holders can sit under one alias when
+ # they do not contend (two users' private writes of the same name).
+ self._claims: dict[str, dict[str, _Claim]] = {}
+ self._claimed_by: dict[str, set[str]] = {}
+ # Who was turned away while a holder had the name. The holder's outcome
+ # decides what their skip meant, so release() hands them back.
+ self._refused: dict[str, set[str]] = {}
+
+ def claim(self, holder: str, filename: str, *, owner_user_id: str | None, shared: bool) -> bool:
+ """Take `filename` and its aliases for `holder`, or report the name as
+ already in flight for a write this one would collide with.
+
+ Re-claiming what this holder already holds succeeds, so a retry of the
+ same file is never blocked by its own claim.
+ """
+ aliases = get_filename_aliases(filename)
+ if not aliases:
+ return True
+
+ for alias in aliases:
+ for existing in self._claims.get(alias, {}).values():
+ if existing.holder == holder:
+ continue
+ if not _contends(existing, owner_user_id, shared):
+ continue
+ logger.info(
+ "Filename already claimed by an in-flight ingestion",
+ filename=filename,
+ owner_user_id=owner_user_id,
+ shared=shared,
+ holder=holder,
+ held_by=existing.holder,
+ )
+ self._refused.setdefault(existing.holder, set()).add(holder)
+ return False
+
+ claim = _Claim(holder=holder, owner_user_id=owner_user_id, shared=shared)
+ for alias in aliases:
+ self._claims.setdefault(alias, {})[holder] = claim
+ self._claimed_by.setdefault(holder, set()).update(aliases)
+ return True
+
+ def release(self, holder: str) -> set[str]:
+ """Drop everything `holder` claimed and report who was turned away for it.
+
+ Safe to call for a holder that never claimed anything, which is the
+ common case (a file that failed before reaching the duplicate gate).
+
+ The refused holders come back because their outcome was decided on the
+ assumption that this one would index the name: if it did not, their skip
+ described something that never happened, and the caller has to say so.
+ """
+ for alias in self._claimed_by.pop(holder, ()):
+ holders = self._claims.get(alias)
+ if holders is None:
+ continue
+ holders.pop(holder, None)
+ if not holders:
+ del self._claims[alias]
+ return self._refused.pop(holder, set())
+
+ def is_awaiting_outcome(self, holder: str) -> bool:
+ """True while a name this holder was refused is still held by someone.
+
+ The refusal decided that file's outcome on the assumption the holder
+ would index the name. Until the holder reaches a terminal state that
+ assumption is unsettled, so anything staged for the refused file has to
+ stay put — it may yet be handed back for a retry.
+ """
+ return any(holder in refused for refused in self._refused.values())
+
+ def holder_for(self, filename: str, *, owner_user_id: str | None, shared: bool) -> str | None:
+ """The in-flight holder a write like this would contend with, if any."""
+ for alias in get_filename_aliases(filename):
+ for existing in self._claims.get(alias, {}).values():
+ if _contends(existing, owner_user_id, shared):
+ return existing.holder
+ return None
+
+ def clear(self) -> None:
+ self._claims.clear()
+ self._claimed_by.clear()
+ self._refused.clear()
+
+
+# One registry per process: ingestion is driven by the singleton TaskService.
+filename_claims = FilenameClaimRegistry()
+
+
+def claim_holder(task_id: str, file_key: str) -> str:
+ """Stable identity for one file's run within one task."""
+ return f"{task_id}:{file_key}"
+
+
+def release_claims(task_id: str, file_keys: Iterable[str]) -> None:
+ for file_key in file_keys:
+ filename_claims.release(claim_holder(task_id, file_key))
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index 643021b1a..dae6d701e 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -108,3 +108,23 @@ def pytest_collection_modifyitems(config, items):
"(renamed, deleted, or mistyped). Remove or fix these lines:\n "
+ "\n ".join(stale)
)
+
+
[email protected](autouse=True)
+def _reset_filename_claims():
+ """Per-test, drop in-flight filename claims.
+
+ In production TaskService releases a file's claim when it reaches a
+ terminal state, but tests drive `processor.process_item` directly and never
+ pass through that release — a leaked claim would make a later test's ingest
+ of the same filename resolve as a duplicate.
+ """
+ try:
+ from utils.filename_claims import filename_claims
+ except ImportError:
+ yield
+ return
+
+ filename_claims.clear()
+ yield
+ filename_claims.clear()
diff --git a/tests/unit/test_claim_winner_failure.py b/tests/unit/test_claim_winner_failure.py
new file mode 100644
index 000000000..33347c07f
--- /dev/null
+++ b/tests/unit/test_claim_winner_failure.py
@@ -0,0 +1,304 @@
+"""What happens to the loser of an in-flight filename claim when the winner fails.
+
+The duplicate gate decides a losing file's outcome the moment it loses the
+claim — before the winning file has ingested anything. If the winner then fails,
+nothing was indexed under that name, and the loser's "skipped, it already
+exists" is a document the user never got. Worse, SKIPPED is not a retry
+candidate (retry_failed_files takes FAILED only), so nothing recovers it.
+"""
+
+import asyncio
+import os
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from models.processors import DUPLICATE_SKIP_ACTIONS, TaskProcessor
+from models.tasks import TaskStatus
+from services.task_service import TaskService
+from utils.filename_claims import INFLIGHT_CLAIM_WINNER_FAILED_ERROR
+
+
+class _RacingProcessor(TaskProcessor):
+ """Two files heading for one name; the first to claim it can be made to fail.
+
+ Everything below the gate is stubbed — this is about the gate's bookkeeping,
+ not about ingestion.
+ """
+
+ def __init__(self, *, winner_fails: bool):
+ super().__init__()
+ self.winner_fails = winner_fails
+
+ async def check_filename_exists(self, filename, opensearch_client, **kwargs):
+ # Nothing indexed yet: the window where both files are told the name is free.
+ return False
+
+ async def process_item(self, upload_task, item, file_task):
+ action = await self.resolve_duplicate_filename(
+ file_task.filename,
+ AsyncMock(),
+ replace=False,
+ owner_user_id="user-1",
+ claim_holder=self._claim_holder(upload_task, file_task),
+ )
+ if action in DUPLICATE_SKIP_ACTIONS:
+ # Both skips finish a file the same way; only the reconcile in
+ # ConnectorFileProcessor tells them apart.
+ self.mark_duplicate_skipped(upload_task, file_task)
+ return
+
+ # Hold the claim long enough for the other file to lose it.
+ await asyncio.sleep(0)
+ if self.winner_fails:
+ # How a processor reports a failure: it owns the status and the
+ # counter (TaskService's handler says so explicitly).
+ file_task.status = TaskStatus.FAILED
+ file_task.error = "The file appears corrupted or invalid and cannot be processed."
+ upload_task.failed_files += 1
+ return
+
+ file_task.status = TaskStatus.COMPLETED
+ upload_task.successful_files += 1
+
+
+async def _run_pair(winner_fails: bool):
+ service = TaskService(document_service=Mock(), ingestion_timeout=5)
+ # Force real concurrency: with a single worker the files run one after the
+ # other and the second never loses an in-flight claim.
+ service._processing_semaphore = asyncio.Semaphore(4)
+
+ processor = _RacingProcessor(winner_fails=winner_fails)
+ items = ["/tmp/one/report.pdf", "/tmp/two/report.pdf"]
+ task_id = await service.create_custom_task(
+ "user-1",
+ items,
+ processor,
+ original_filenames=dict.fromkeys(items, "report.pdf"),
+ )
+ if service.background_tasks:
+ await asyncio.gather(*list(service.background_tasks), return_exceptions=True)
+
+ upload_task = service.task_store["user-1"][task_id]
+ return service, task_id, upload_task
+
+
+async def test_loser_is_failed_when_the_winner_fails():
+ """Nothing reached the index, so neither file may be reported as successful."""
+ _, _, upload_task = await _run_pair(winner_fails=True)
+
+ statuses = [t.status for t in upload_task.file_tasks.values()]
+ assert statuses == [TaskStatus.FAILED, TaskStatus.FAILED]
+ assert upload_task.successful_files == 0
+ assert upload_task.failed_files == 2
+
+
+async def test_a_failed_winner_leaves_the_loser_retryable():
+ """retry_failed_files only considers FAILED, so the loser has to land there
+ to be recoverable — and the retry re-runs the gate, which resolves correctly
+ either way."""
+ service, task_id, upload_task = await _run_pair(winner_fails=True)
+
+ loser = upload_task.file_tasks["/tmp/two/report.pdf"]
+ assert loser.status is TaskStatus.FAILED
+ metadata = service._infer_failure_metadata(loser)
+ assert metadata["actionable_by"] == "RETRYABLE"
+
+
+async def test_loser_stays_a_skipped_duplicate_when_the_winner_succeeds():
+ """The ordinary case is untouched: one document indexed, the other skipped as
+ a duplicate and counted successful."""
+ _, _, upload_task = await _run_pair(winner_fails=False)
+
+ statuses = {t.status for t in upload_task.file_tasks.values()}
+ assert statuses == {TaskStatus.COMPLETED, TaskStatus.SKIPPED}
+ assert upload_task.successful_files == 2
+ assert upload_task.failed_files == 0
+
+ skipped = next(t for t in upload_task.file_tasks.values() if t.status is TaskStatus.SKIPPED)
+ assert skipped.result["reason"] == "duplicate_filename"
+
+
+class _HeldClaimProcessor(TaskProcessor):
+ """Claims the name, then holds it until released — so a second task can lose
+ the race while this one is still in flight."""
+
+ def __init__(self, *, claimed: asyncio.Event, may_finish: asyncio.Event):
+ super().__init__()
+ self.claimed = claimed
+ self.may_finish = may_finish
+
+ async def check_filename_exists(self, filename, opensearch_client, **kwargs):
+ return False
+
+ async def process_item(self, upload_task, item, file_task):
+ action = await self.resolve_duplicate_filename(
+ file_task.filename,
+ AsyncMock(),
+ replace=False,
+ owner_user_id="user-1",
+ claim_holder=self._claim_holder(upload_task, file_task),
+ )
+ assert action == "proceed"
+ self.claimed.set()
+ await self.may_finish.wait()
+ file_task.status = TaskStatus.FAILED
+ file_task.error = "The file appears corrupted or invalid and cannot be processed."
+ upload_task.failed_files += 1
+
+
+class _LosingProcessor(TaskProcessor):
+ async def check_filename_exists(self, filename, opensearch_client, **kwargs):
+ return False
+
+ async def process_item(self, upload_task, item, file_task):
+ action = await self.resolve_duplicate_filename(
+ file_task.filename,
+ AsyncMock(),
+ replace=False,
+ owner_user_id="user-1",
+ claim_holder=self._claim_holder(upload_task, file_task),
+ )
+ assert action in DUPLICATE_SKIP_ACTIONS
+ self.mark_duplicate_skipped(upload_task, file_task)
+
+
+async def test_a_loser_in_another_task_is_recovered_too():
+ """Claims are keyed by name and ownership, not by task, so the file that
+ loses can belong to a different task — two uploads in flight, or an upload
+ racing a connector sync. It has to be recovered there, in its own task."""
+ service = TaskService(document_service=Mock(), ingestion_timeout=5)
+ service._processing_semaphore = asyncio.Semaphore(4)
+
+ claimed = asyncio.Event()
+ may_finish = asyncio.Event()
+
+ winner_task_id = await service.create_custom_task(
+ "user-1",
+ ["/tmp/winner/report.pdf"],
+ _HeldClaimProcessor(claimed=claimed, may_finish=may_finish),
+ original_filenames={"/tmp/winner/report.pdf": "report.pdf"},
+ )
+ await asyncio.wait_for(claimed.wait(), timeout=5)
+
+ # A separate task, started while the first still holds the name.
+ loser_task_id = await service.create_custom_task(
+ "user-1",
+ ["/tmp/loser/report.pdf"],
+ _LosingProcessor(),
+ original_filenames={"/tmp/loser/report.pdf": "report.pdf"},
+ )
+ loser_task = service.task_store["user-1"][loser_task_id]
+ while loser_task.processed_files < 1:
+ await asyncio.sleep(0)
+
+ # The loser is already finalized as a successful skip before the winner fails.
+ loser_file = loser_task.file_tasks["/tmp/loser/report.pdf"]
+ assert loser_file.status is TaskStatus.SKIPPED
+ assert loser_task.successful_files == 1
+
+ may_finish.set()
+ await asyncio.gather(*list(service.background_tasks), return_exceptions=True)
+
+ assert (
+ service.task_store["user-1"][winner_task_id].file_tasks["/tmp/winner/report.pdf"].status
+ is TaskStatus.FAILED
+ )
+
+ assert loser_file.status is TaskStatus.FAILED
+ assert loser_file.error == INFLIGHT_CLAIM_WINNER_FAILED_ERROR
+ assert loser_task.successful_files == 0
+ assert loser_task.failed_files == 1
+ # The loser's task finished before the reversal; its accounting stays whole.
+ assert loser_task.processed_files == loser_task.total_files
+
+
+async def test_a_cross_task_loser_keeps_its_staged_file(tmp_path):
+ """The loser's task finishes — and cleans up — while the winner is still in
+ flight. The staged source has to survive that, or the FAILED state the
+ reversal produces is one retry cannot act on: retry_failed_files rejects a
+ file whose source is gone as "source_file_missing".
+ """
+ service = TaskService(document_service=Mock(), ingestion_timeout=5)
+ service._processing_semaphore = asyncio.Semaphore(4)
+
+ claimed = asyncio.Event()
+ may_finish = asyncio.Event()
+
+ winner_path = tmp_path / "winner-report.pdf"
+ winner_path.write_bytes(b"%PDF-winner")
+ loser_path = tmp_path / "loser-report.pdf"
+ loser_path.write_bytes(b"%PDF-loser")
+
+ await service.create_custom_task(
+ "user-1",
+ [str(winner_path)],
+ _HeldClaimProcessor(claimed=claimed, may_finish=may_finish),
+ original_filenames={str(winner_path): "report.pdf"},
+ temp_file_paths=[str(winner_path)],
+ )
+ await asyncio.wait_for(claimed.wait(), timeout=5)
+
+ loser_task_id = await service.create_custom_task(
+ "user-1",
+ [str(loser_path)],
+ _LosingProcessor(),
+ original_filenames={str(loser_path): "report.pdf"},
+ temp_file_paths=[str(loser_path)],
+ )
+ loser_task = service.task_store["user-1"][loser_task_id]
+ while loser_task.status != TaskStatus.COMPLETED:
+ await asyncio.sleep(0)
+
+ # Its task has finished and run cleanup, with the outcome still unsettled.
+ assert loser_path.exists(), "staged source deleted before the winner resolved"
+
+ may_finish.set()
+ await asyncio.gather(*list(service.background_tasks), return_exceptions=True)
+
+ loser_file = loser_task.file_tasks[str(loser_path)]
+ assert loser_file.status is TaskStatus.FAILED
+ assert loser_path.exists(), "retry has nothing to read"
+ # What retry checks before re-queueing.
+ assert os.path.exists(loser_file.file_path)
+
+
+async def test_an_ordinary_duplicate_skip_still_cleans_up(tmp_path):
+ """Retention is only for the unsettled case — a file skipped against a
+ document that is already indexed keeps today's cleanup."""
+ service = TaskService(document_service=Mock(), ingestion_timeout=5)
+
+ staged = tmp_path / "report.pdf"
+ staged.write_bytes(b"%PDF-")
+
+ class _AlreadyIndexedProcessor(TaskProcessor):
+ async def check_filename_exists(self, filename, opensearch_client, **kwargs):
+ return True
+
+ async def process_item(self, upload_task, item, file_task):
+ action = await self.resolve_duplicate_filename(
+ file_task.filename,
+ AsyncMock(),
+ replace=False,
+ owner_user_id="user-1",
+ claim_holder=self._claim_holder(upload_task, file_task),
+ )
+ assert action in DUPLICATE_SKIP_ACTIONS
+ self.mark_duplicate_skipped(upload_task, file_task)
+
+ await service.create_custom_task(
+ "user-1",
+ [str(staged)],
+ _AlreadyIndexedProcessor(),
+ original_filenames={str(staged): "report.pdf"},
+ temp_file_paths=[str(staged)],
+ )
+ await asyncio.gather(*list(service.background_tasks), return_exceptions=True)
+
+ assert not staged.exists()
diff --git a/tests/unit/test_filename_claims.py b/tests/unit/test_filename_claims.py
new file mode 100644
index 000000000..7474c29e1
--- /dev/null
+++ b/tests/unit/test_filename_claims.py
@@ -0,0 +1,161 @@
+"""In-flight filename claims (utils.filename_claims).
+
+The duplicate gate asks OpenSearch whether a name is taken, which only sees
+what is already indexed. Files inside a task are ingested concurrently, so two
+files heading for the same name are both told "no". These cover the registry
+that makes the second one resolve as a duplicate instead.
+"""
+
+import pytest
+
+from utils.filename_claims import (
+ FilenameClaimRegistry,
+ claim_holder,
+ filename_claims,
+)
+
+
+def test_first_holder_wins_and_second_is_refused():
+ registry = FilenameClaimRegistry()
+
+ assert registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=False) is True
+ assert registry.claim("task-1:b", "report.pdf", owner_user_id="alice", shared=False) is False
+
+
+def test_release_frees_the_name():
+ registry = FilenameClaimRegistry()
+ registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=False)
+
+ registry.release("task-1:a")
+
+ assert registry.claim("task-1:b", "report.pdf", owner_user_id="alice", shared=False) is True
+
+
+def test_same_holder_can_reclaim_its_own_name():
+ """A retry of the same file must not be blocked by its own claim."""
+ registry = FilenameClaimRegistry()
+
+ assert registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=False) is True
+ assert registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=False) is True
+
+
+def test_aliases_contest_the_same_claim():
+ """notes.txt is indexed as notes.md by the legacy Langflow path, so the two
+ names are one name for duplicate purposes — here too."""
+ registry = FilenameClaimRegistry()
+
+ assert registry.claim("task-1:a", "notes.txt", owner_user_id="alice", shared=False) is True
+ assert registry.claim("task-1:b", "notes.md", owner_user_id="alice", shared=False) is False
+
+
+def test_other_owners_do_not_contest():
+ """Another user's private document with this name is not a duplicate, and
+ is invisible to the check that would find it."""
+ registry = FilenameClaimRegistry()
+
+ assert registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=False) is True
+ assert registry.claim("task-2:a", "report.pdf", owner_user_id="bob", shared=False) is True
+
+
+def test_a_shared_write_contends_with_the_same_user_s_private_write():
+ """The case the scope-string keying missed. A private write's duplicate
+ check sees ownerless documents, so the two can land on one name — on the
+ connector re-sync path each file resolves `shared` from its own indexed
+ state, so two files heading for one name can disagree."""
+ registry = FilenameClaimRegistry()
+
+ assert registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=True) is True
+ assert registry.claim("task-1:b", "report.pdf", owner_user_id="alice", shared=False) is False
+
+
+def test_a_private_write_contends_with_an_existing_shared_claim_of_another_user():
+ """An ownerless document is visible instance-wide, so it is what every
+ user's duplicate check sees."""
+ registry = FilenameClaimRegistry()
+
+ assert registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=True) is True
+ assert registry.claim("task-2:a", "report.pdf", owner_user_id="bob", shared=False) is False
+
+
+def test_two_shared_writes_contend():
+ registry = FilenameClaimRegistry()
+
+ assert registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=True) is True
+ assert registry.claim("task-2:a", "report.pdf", owner_user_id="bob", shared=True) is False
+
+
+def test_an_ownerless_write_is_treated_as_shared():
+ registry = FilenameClaimRegistry()
+
+ assert registry.claim("task-1:a", "report.pdf", owner_user_id=None, shared=False) is True
+ assert registry.claim("task-2:a", "report.pdf", owner_user_id="bob", shared=False) is False
+
+
+def test_release_of_an_unknown_holder_is_a_no_op():
+ """Most files never reach the duplicate gate's claim — failed downloads,
+ unsupported types — and TaskService releases for all of them."""
+ registry = FilenameClaimRegistry()
+
+ registry.release("task-1:never-claimed") # must not raise
+
+
+def test_blank_filename_claims_nothing():
+ registry = FilenameClaimRegistry()
+
+ assert registry.claim("task-1:a", "", owner_user_id="alice", shared=False) is True
+ assert registry.claim("task-1:b", "", owner_user_id="alice", shared=False) is True
+
+
+def test_releasing_one_holder_leaves_the_others_alone():
+ registry = FilenameClaimRegistry()
+ registry.claim("task-1:a", "a.pdf", owner_user_id="alice", shared=False)
+ registry.claim("task-1:b", "b.pdf", owner_user_id="alice", shared=False)
+
+ registry.release("task-1:a")
+
+ assert registry.holder_for("a.pdf", owner_user_id="alice", shared=False) is None
+ assert registry.holder_for("b.pdf", owner_user_id="alice", shared=False) == "task-1:b"
+
+
+def test_holder_identity_is_per_file_within_a_task():
+ assert claim_holder("task-1", "/tmp/a.pdf") != claim_holder("task-1", "/tmp/b.pdf")
+ assert claim_holder("task-1", "/tmp/a.pdf") != claim_holder("task-2", "/tmp/a.pdf")
+
+
+async def test_module_registry_is_clean_between_tests():
+ """The autouse fixture in conftest clears it; without that, a claim leaked
+ by a test driving process_item directly would skip a later test's file."""
+ assert filename_claims.holder_for("report.pdf", owner_user_id="alice", shared=False) is None
+
+
+def test_release_reports_who_was_turned_away():
+ """The holder's outcome decides what the refused files' skips meant, so the
+ registry has to remember them."""
+ registry = FilenameClaimRegistry()
+ registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=False)
+
+ assert registry.claim("task-1:b", "report.pdf", owner_user_id="alice", shared=False) is False
+ assert registry.claim("task-1:c", "report.pdf", owner_user_id="alice", shared=False) is False
+
+ assert registry.release("task-1:a") == {"task-1:b", "task-1:c"}
+
+
+def test_release_reports_nobody_when_no_one_was_refused():
+ registry = FilenameClaimRegistry()
+ registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=False)
+
+ assert registry.release("task-1:a") == set()
+
+
+def test_refusals_do_not_leak_to_the_next_holder():
+ """Whoever takes the name next starts with a clean slate — the previous
+ holder's losers were already accounted for."""
+ registry = FilenameClaimRegistry()
+ registry.claim("task-1:a", "report.pdf", owner_user_id="alice", shared=False)
+ registry.claim("task-1:b", "report.pdf", owner_user_id="alice", shared=False)
+ registry.release("task-1:a")
+
+ registry.claim("task-1:b", "report.pdf", owner_user_id="alice", shared=False)
+
+ assert registry.release("task-1:b") == set()
diff --git a/tests/unit/test_reconcile_shared_owner.py b/tests/unit/test_reconcile_shared_owner.py
index 99232a8c3..9b981cca1 100644
--- a/tests/unit/test_reconcile_shared_owner.py
+++ b/tests/unit/test_reconcile_shared_owner.py
@@ -7,12 +7,14 @@ resolve_shared_owner_fields() recompute is normally only reached on a fresh
index write.
"""
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
import config.settings as settings_module
from models.processors import ConnectorFileProcessor
+from models.tasks import FileTask, TaskStatus, UploadTask
+from utils.filename_claims import filename_claims
def _make_processor(*, shared: bool, user_id: str = "user-1"):
@@ -153,3 +155,85 @@ async def test_reconcile_of_a_shared_file_keeps_the_wider_scope():
query = write_client.update_by_query.await_args.kwargs["body"]["query"]
assert query == build_replace_filename_query("report.pdf", "user-1")
+
+
+def _connector_processor_for(filename: str, *, indexed: bool):
+ """A ConnectorFileProcessor wired far enough to reach the duplicate gate."""
+ from types import SimpleNamespace
+
+ processor = _make_processor(shared=False)
+ document = SimpleNamespace(
+ id="file-abc",
+ filename=filename,
+ mimetype="application/pdf",
+ content=b"%PDF-",
+ acl=None,
+ )
+ connector = AsyncMock()
+ connector.get_file_content = AsyncMock(return_value=document)
+ connector.CONNECTOR_TYPE = "ibm_cos"
+ connector_service = AsyncMock()
+ connector_service.get_connector = AsyncMock(return_value=connector)
+ connector_service.connection_manager.get_connection = AsyncMock(
+ return_value=SimpleNamespace(connector_type="ibm_cos")
+ )
+ processor.connector_service = connector_service
+ processor.document_service = MagicMock()
+ processor.session_manager = MagicMock()
+ processor.check_filename_exists = AsyncMock(return_value=indexed)
+ processor._reconcile_shared_owner = AsyncMock()
+ return processor
+
+
+async def test_losing_an_in_flight_claim_does_not_reconcile():
+ """The reconcile matches by filename, so running it for a claim loser would
+ rewrite owner fields on the chunks the WINNER is writing — a different
+ document, whose sharing state was resolved from its own file id and can
+ differ from this one's. Nothing is indexed under the name by this file, so
+ there is nothing of its own to reconcile.
+ """
+ processor = _connector_processor_for("report.pdf", indexed=False)
+ upload_task = UploadTask(task_id="task-1", total_files=2)
+ file_task = FileTask(file_path="cos::b/report.pdf", filename="report.pdf")
+
+ # Another file in this batch already holds the name.
+ filename_claims.claim("task-1:winner", "report.pdf", owner_user_id="user-1", shared=False)
+
+ await processor.process_item(upload_task, "cos::b/report.pdf", file_task)
+
+ assert file_task.status is TaskStatus.SKIPPED
+ assert file_task.result["reason"] == "duplicate_filename"
+ processor._reconcile_shared_owner.assert_not_awaited()
+
+
+async def test_a_real_duplicate_still_reconciles():
+ """The document indexed under this name IS this file's own, so the owner
+ fields still get brought in line with the connector's current setting."""
+ processor = _connector_processor_for("report.pdf", indexed=True)
+ upload_task = UploadTask(task_id="task-1", total_files=1)
+ file_task = FileTask(file_path="cos::b/report.pdf", filename="report.pdf")
+
+ await processor.process_item(upload_task, "cos::b/report.pdf", file_task)
+
+ assert file_task.status is TaskStatus.SKIPPED
+ processor._reconcile_shared_owner.assert_awaited_once()
+
+
+async def test_the_gate_reports_the_two_skips_apart():
+ """The indexed document under this name IS this file's own, so the caller
+ reconciles as before."""
+ processor = _make_processor(shared=False)
+ processor.check_filename_exists = AsyncMock(return_value=True)
+
+ action = await processor.resolve_duplicate_filename(
+ "report.pdf",
+ AsyncMock(),
+ replace=False,
+ owner_user_id="user-1",
+ claim_holder="task-1:only",
+ )
+
+ assert action == "skip"
diff --git a/tests/unit/test_same_name_files_in_one_batch.py b/tests/unit/test_same_name_files_in_one_batch.py
new file mode 100644
index 000000000..1895e4d87
--- /dev/null
+++ b/tests/unit/test_same_name_files_in_one_batch.py
@@ -0,0 +1,119 @@
+"""Two files heading for the same indexed filename, ingested at once.
+
+Files inside a task run concurrently under TaskService's worker semaphore, and
+the duplicate gate's question — "is this name already indexed?" — is answered
+by OpenSearch, which cannot see a file that has not been written yet. Two files
+named report.pdf (different folders in an upload, different keys under one
+bucket prefix, a Drive selection spanning folders) therefore both passed the
+gate, and their chunk ids are content-derived, so neither overwrote the other:
+one filename ended up holding two documents' chunks. With replace_duplicates on
+— the default for uploads — the later file deleted the earlier one's chunks
+instead, while the earlier file's task still reported success.
+
+The in-flight claim makes the second file resolve as an ordinary duplicate.
+"""
+
+import asyncio
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from models.processors import DUPLICATE_FILENAME_WARNING, DocumentFileProcessor
+from models.tasks import FileTask, TaskStatus, UploadTask
+
+
+def _processor(replace_duplicates: bool) -> DocumentFileProcessor:
+ processor = DocumentFileProcessor(
+ document_service=MagicMock(),
+ models_service=MagicMock(),
+ owner_user_id="user-123",
+ jwt_token="mock-token",
+ replace_duplicates=replace_duplicates,
+ session_manager=MagicMock(),
+ )
+ # The index is empty as far as either file can tell: this is the window
+ # where both of them are told the name is free.
+ processor.check_filename_exists = AsyncMock(return_value=False)
+ processor.delete_document_by_filename = AsyncMock(return_value=1)
+ processor.process_document_standard = AsyncMock(return_value={"status": "indexed"})
+ return processor
+
+
+async def _ingest_both_at_once(processor, upload_task, file_tasks):
+ with (
+ patch("os.path.getsize", return_value=1234),
+ patch("models.processors.hash_id", side_effect=lambda path: f"hash-{path}"),
+ ):
+ await asyncio.gather(
+ *(
+ processor.process_item(upload_task, file_task.file_path, file_task)
+ for file_task in file_tasks
+ )
+ )
+
+
+async def test_only_one_of_two_same_named_files_is_ingested():
+ processor = _processor(replace_duplicates=False)
+ upload_task = UploadTask(task_id="task-123", total_files=2)
+ first = FileTask(file_path="/tmp/one/report.pdf", filename="report.pdf")
+ second = FileTask(file_path="/tmp/two/report.pdf", filename="report.pdf")
+
+ await _ingest_both_at_once(processor, upload_task, [first, second])
+
+ assert {first.status, second.status} == {TaskStatus.COMPLETED, TaskStatus.SKIPPED}
+ # One document indexed, not two under one name.
+ processor.process_document_standard.assert_called_once()
+
+ skipped = first if first.status is TaskStatus.SKIPPED else second
+ assert skipped.result["reason"] == "duplicate_filename"
+ assert skipped.result["warning"] == DUPLICATE_FILENAME_WARNING
+ assert skipped.error is None
+ # A declined duplicate is a chosen outcome, not a failure.
+ assert upload_task.failed_files == 0
+ assert upload_task.successful_files == 2
+
+
+async def test_replace_duplicates_does_not_let_the_second_file_delete_the_first():
+ """With replace on, the loser used to delete the winner's freshly written
+ chunks and index itself over them."""
+ processor = _processor(replace_duplicates=True)
+ upload_task = UploadTask(task_id="task-123", total_files=2)
+ first = FileTask(file_path="/tmp/one/report.pdf", filename="report.pdf")
+ second = FileTask(file_path="/tmp/two/report.pdf", filename="report.pdf")
+
+ await _ingest_both_at_once(processor, upload_task, [first, second])
+
+ processor.process_document_standard.assert_called_once()
+ processor.delete_document_by_filename.assert_not_called()
+
+
+async def test_aliases_of_one_name_also_resolve_to_one_file():
+ """notes.txt is indexed as notes.md by the Langflow path, so the pair is one
+ name for duplicate purposes."""
+ processor = _processor(replace_duplicates=False)
+ upload_task = UploadTask(task_id="task-123", total_files=2)
+ txt = FileTask(file_path="/tmp/notes.txt", filename="notes.txt")
+ md = FileTask(file_path="/tmp/notes.md", filename="notes.md")
+
+ await _ingest_both_at_once(processor, upload_task, [txt, md])
+
+ processor.process_document_standard.assert_called_once()
+ assert {txt.status, md.status} == {TaskStatus.COMPLETED, TaskStatus.SKIPPED}
+
+
+async def test_differently_named_files_are_both_ingested():
+ """The claim must not serialize an ordinary batch."""
+ processor = _processor(replace_duplicates=False)
+ upload_task = UploadTask(task_id="task-123", total_files=2)
+ first = FileTask(file_path="/tmp/a.pdf", filename="a.pdf")
+ second = FileTask(file_path="/tmp/b.pdf", filename="b.pdf")
+
+ await _ingest_both_at_once(processor, upload_task, [first, second])
+
+ assert first.status is TaskStatus.COMPLETED
+ assert second.status is TaskStatus.COMPLETED
+ assert processor.process_document_standard.await_count == 2