Skip to content

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

Python

fix: unify connector ingestion pipelines and consolidate service layer (#1695)

Lucas Oliveira2ac03730b64c
diff --git a/src/api/connector_router.py b/src/api/connector_router.py
deleted file mode 100644
index e8bf8228e..000000000
--- a/src/api/connector_router.py
+++ /dev/null
@@ -1,84 +0,0 @@
-"""Connector router that automatically routes based on configuration settings."""
-
-from config.settings import DISABLE_INGEST_WITH_LANGFLOW
-from utils.logging_config import get_logger
-
-logger = get_logger(__name__)
-
-
-class ConnectorRouter:
- """
- Router that automatically chooses between LangflowConnectorService and ConnectorService
- based on the DISABLE_INGEST_WITH_LANGFLOW configuration.
-
- - If DISABLE_INGEST_WITH_LANGFLOW is False (default): uses LangflowConnectorService
- - If DISABLE_INGEST_WITH_LANGFLOW is True: uses traditional ConnectorService
- """
-
- def __init__(self, langflow_connector_service, openrag_connector_service):
- self.langflow_connector_service = langflow_connector_service
- self.openrag_connector_service = openrag_connector_service
- logger.debug(
- "ConnectorRouter initialized",
- disable_langflow_ingest=DISABLE_INGEST_WITH_LANGFLOW,
- )
-
- def get_active_service(self):
- """Get the currently active connector service based on configuration."""
- if DISABLE_INGEST_WITH_LANGFLOW:
- logger.debug("Using traditional OpenRAG connector service")
- return self.openrag_connector_service
- else:
- logger.debug("Using Langflow connector service")
- return self.langflow_connector_service
-
- # Proxy all connector service methods to the active service
-
- async def initialize(self):
- """Initialize the active connector service."""
- # Initialize OpenSearch index if using traditional OpenRAG connector service
-
- return await self.get_active_service().initialize()
-
- @property
- def connection_manager(self):
- """Get the connection manager from the active service."""
- return self.get_active_service().connection_manager
-
- async def get_connector(self, connection_id: str):
- """Get a connector instance from the active service."""
- return await self.get_active_service().get_connector(connection_id)
-
- async def sync_specific_files(
- self,
- connection_id: str,
- user_id: str,
- file_list: list,
- jwt_token: str = None,
- file_infos: list = None,
- ingest_settings: dict = None,
- replace_duplicates: bool = False,
- ):
- """Sync specific files using the active service."""
- return await self.get_active_service().sync_specific_files(
- connection_id,
- user_id,
- file_list,
- jwt_token,
- file_infos=file_infos,
- ingest_settings=ingest_settings,
- replace_duplicates=replace_duplicates,
- )
-
- def __getattr__(self, name):
- """
- Proxy any other method calls to the active service.
- This ensures compatibility with any methods we might have missed.
- """
- active_service = self.get_active_service()
- if hasattr(active_service, name):
- return getattr(active_service, name)
- else:
- raise AttributeError(
- f"'{type(active_service).__name__}' object has no attribute '{name}'"
- )
diff --git a/src/app/container.py b/src/app/container.py
index 1f20d4f4a..694640645 100644
--- a/src/app/container.py
+++ b/src/app/container.py
@@ -3,7 +3,6 @@
Returns a dict consumed by routes (via FastAPI Depends) and the lifespan hook.
"""
-from api.connector_router import ConnectorRouter
from config.settings import (
ENABLE_BACKEND_DOCLING_POLLING,
INGESTION_TIMEOUT,
@@ -15,7 +14,6 @@ from config.settings import (
get_index_name,
is_no_auth_mode,
)
-from connectors.langflow_connector_service import LangflowConnectorService
from connectors.service import ConnectorService
from services.api_key_service import APIKeyService
from services.auth_service import AuthService
@@ -100,13 +98,7 @@ async def initialize_services():
)
langflow_mcp_service = LangflowMCPService()
- langflow_connector_service = LangflowConnectorService(
- task_service=task_service,
- session_manager=session_manager,
- flows_service=flows_service,
- docling_service=clients.docling_service,
- )
- openrag_connector_service = ConnectorService(
+ connector_service = ConnectorService(
patched_async_client=clients,
embed_model=get_embedding_model(),
index_name=get_index_name(),
@@ -115,11 +107,8 @@ async def initialize_services():
models_service=models_service,
document_service=document_service,
docling_service=clients.docling_service,
- )
-
- connector_service = ConnectorRouter(
- langflow_connector_service=langflow_connector_service,
- openrag_connector_service=openrag_connector_service,
+ flows_service=flows_service,
+ langflow_service=langflow_file_service,
)
auth_service = AuthService(
diff --git a/src/connectors/langflow_connector_service.py b/src/connectors/langflow_connector_service.py
deleted file mode 100644
index 8214f2a63..000000000
--- a/src/connectors/langflow_connector_service.py
+++ /dev/null
@@ -1,457 +0,0 @@
-from typing import Any
-
-# Create custom processor for connector files using Langflow
-from models.processors import LangflowConnectorFileProcessor
-from services.langflow_file_service import LangflowFileService
-from utils.file_utils import (
- clean_connector_filename,
- get_file_extension,
- langflow_safe_filename_and_mimetype,
-)
-from utils.logging_config import get_logger
-
-from .base import BaseConnector, ConnectorDocument
-from .connection_manager import ConnectionManager
-
-logger = get_logger(__name__)
-
-
-class LangflowConnectorService:
- """Service to manage connector documents and process them via Langflow"""
-
- def __init__(
- self,
- task_service=None,
- session_manager=None,
- flows_service=None,
- docling_service=None,
- ):
- self.task_service = task_service
- self.session_manager = session_manager
- self.docling_service = docling_service
- self.connection_manager = ConnectionManager()
- self.langflow_service = LangflowFileService(
- flows_service=flows_service, docling_service=docling_service
- )
-
- async def initialize(self):
- """Initialize the service by loading existing connections"""
- await self.connection_manager.load_connections()
-
- async def get_connector(self, connection_id: str) -> BaseConnector | None:
- """Get a connector by connection ID"""
- return await self.connection_manager.get_connector(connection_id)
-
- async def process_connector_document(
- self,
- document: ConnectorDocument,
- owner_user_id: str,
- connector_type: str,
- jwt_token: str = None,
- owner_name: str = None,
- owner_email: str = None,
- ingest_settings: dict[str, Any] | None = None,
- ) -> dict[str, Any]:
- """Process a document from a connector using LangflowFileService pattern"""
-
- logger.debug(
- "Processing connector document via Langflow",
- document_id=document.id,
- filename=document.filename,
- )
-
- import os
-
- from utils.file_utils import auto_cleanup_tempfile
-
- suffix = os.path.splitext(document.filename)[1]
- if not suffix:
- suffix = get_file_extension(document.mimetype)
-
- # Create temporary file from document content
- with auto_cleanup_tempfile(suffix=suffix) as tmp_path:
- # Write document content to temp file
- with open(tmp_path, "wb") as f:
- f.write(document.content)
-
- # Step 1: Upload file to Langflow
- logger.debug("Uploading file to Langflow", filename=document.filename)
- content = document.content
-
- # Clean filename and ensure we don't add a double extension
- processed_filename = clean_connector_filename(document.filename, document.mimetype)
- # Langflow's docling chokes on text/plain — rename .txt -> .md.
- processed_filename, processed_mimetype = langflow_safe_filename_and_mimetype(
- processed_filename, document.mimetype
- )
-
- file_tuple = (
- processed_filename,
- content,
- processed_mimetype,
- )
-
- # Step 0: Delete existing chunks for this file before re-ingesting.
- # Match on document_id (the stable connector item ID, e.g. the
- # SharePoint Graph item id) — NOT on filename. On a rename, the
- # `processed_filename` here is the NEW name while OpenSearch chunks
- # still carry the OLD name, so a filename-keyed delete misses them
- # and the re-ingest leaves duplicate chunks (same document_id, two
- # different filenames). Also use enumerate-then-delete-by-id rather
- # than delete_by_query, which is silently no-opped under DLS.
- if self.session_manager:
- from config.settings import get_index_name
- from utils.opensearch_delete import (
- collect_visible_document_ids,
- delete_document_ids,
- )
-
- opensearch_client = self.session_manager.get_user_opensearch_client(
- owner_user_id, jwt_token
- )
- try:
- chunk_ids = await collect_visible_document_ids(
- opensearch_client,
- index=get_index_name(),
- query={"term": {"document_id": document.id}},
- )
- deleted_count = await delete_document_ids(
- opensearch_client,
- index=get_index_name(),
- document_ids=chunk_ids,
- refresh=True,
- )
- logger.info(
- "Deleted existing chunks before re-ingestion",
- document_id=document.id,
- filename=processed_filename,
- deleted_count=deleted_count,
- )
- except Exception as delete_err:
- logger.warning(
- "Failed to delete existing chunks before re-ingestion",
- document_id=document.id,
- filename=processed_filename,
- error=str(delete_err),
- )
-
- langflow_file_id = None # Initialize to track if upload succeeded
- try:
- upload_result = await self.langflow_service.upload_user_file(file_tuple, jwt_token)
- langflow_file_id = upload_result["id"]
- langflow_file_path = upload_result["path"]
-
- logger.debug(
- "File uploaded to Langflow",
- file_id=langflow_file_id,
- path=langflow_file_path,
- )
-
- # Step 2: Run ingestion flow with the uploaded file
- logger.debug("Running Langflow ingestion flow", file_path=langflow_file_path)
-
- connector_tweak_settings = None
- if isinstance(ingest_settings, dict):
- connector_tweak_settings = dict(ingest_settings)
- # Model selection is injected via selected_embedding_model header override.
- # Avoid hard-coding provider-specific embedding component tweak IDs here.
- connector_tweak_settings.pop("embeddingModel", None)
-
- tweaks = LangflowFileService.merge_ui_ingest_settings_into_tweaks(
- {}, connector_tweak_settings
- )
-
- # Extract ACL information from the connector document, if available
- allowed_users: list[str] = []
- allowed_groups: list[str] = []
- if getattr(document, "acl", None) is not None:
- try:
- allowed_users = document.acl.allowed_users or []
- allowed_groups = document.acl.allowed_groups or []
- except AttributeError:
- # If ACL shape is different or missing fields, fall back to empty lists
- allowed_users = []
- allowed_groups = []
-
- ingestion_result = await self.langflow_service.run_ingestion_flow(
- file_paths=[langflow_file_path],
- file_tuples=[file_tuple],
- jwt_token=jwt_token,
- tweaks=tweaks,
- owner=owner_user_id,
- owner_name=owner_name,
- owner_email=owner_email,
- connector_type=connector_type,
- document_id=document.id,
- source_url=document.source_url,
- allowed_users=allowed_users,
- allowed_groups=allowed_groups,
- selected_embedding_model=(
- ingest_settings.get("embeddingModel")
- if isinstance(ingest_settings, dict)
- else None
- ),
- )
-
- logger.debug("Ingestion flow completed", result=ingestion_result)
-
- # Step 3: Delete the file from Langflow
- logger.debug("Deleting file from Langflow", file_id=langflow_file_id)
- await self.langflow_service.delete_user_file(langflow_file_id)
- logger.debug("File deleted from Langflow", file_id=langflow_file_id)
-
- return {
- "status": "indexed",
- "filename": document.filename,
- "source_url": document.source_url,
- "document_id": document.id,
- "connector_type": connector_type,
- "langflow_result": ingestion_result,
- }
-
- except Exception as e:
- logger.error(
- "Failed to process connector document via Langflow",
- document_id=document.id,
- error=str(e),
- )
- # Try to clean up Langflow file if upload succeeded but processing failed
- if langflow_file_id is not None:
- try:
- await self.langflow_service.delete_user_file(langflow_file_id)
- logger.debug(
- "Cleaned up Langflow file after error",
- file_id=langflow_file_id,
- )
- except Exception as cleanup_error:
- logger.warning(
- "Failed to cleanup Langflow file",
- file_id=langflow_file_id,
- error=str(cleanup_error),
- )
- raise
-
- async def sync_connector_files(
- self,
- connection_id: str,
- user_id: str,
- max_files: int = None,
- jwt_token: str = None,
- filename_filter: set = None,
- replace_duplicates: bool = False,
- ) -> str:
- """Sync files from a connector connection using Langflow processing"""
- if not self.task_service:
- raise ValueError(
- "TaskService not available - connector sync requires task service dependency"
- )
-
- logger.debug(
- "Starting Langflow-based sync for connection",
- connection_id=connection_id,
- max_files=max_files,
- )
-
- connector = await self.get_connector(connection_id)
- if not connector:
- raise ValueError(f"Connection '{connection_id}' not found or not authenticated")
-
- logger.debug("Got connector", authenticated=connector.is_authenticated)
-
- if not connector.is_authenticated:
- raise ValueError(f"Connection '{connection_id}' not authenticated")
-
- # Collect files to process (limited by max_files)
- files_to_process: list[dict[str, Any]] = []
- page_token = None
-
- # Calculate page size to minimize API calls
- page_size = min(max_files or 100, 1000) if max_files else 100
-
- while True:
- # List files from connector with limit
- logger.debug("Calling list_files", page_size=page_size, page_token=page_token)
- file_list = await connector.list_files(page_token, max_files=page_size)
- logger.debug("Got files from connector", file_count=len(file_list.get("files", [])))
- files = file_list["files"]
-
- if not files:
- break
-
- for file_info in files:
- if max_files and len(files_to_process) >= max_files:
- break
- if filename_filter is not None:
- file_name = file_info.get("name", "")
- if file_name not in filename_filter:
- logger.debug("Skipping file not in filter", filename=file_name)
- continue
- files_to_process.append(file_info)
-
- # Stop if we have enough files or no more pages
- if (max_files and len(files_to_process) >= max_files) or not file_list.get(
- "nextPageToken"
- ):
- break
-
- page_token = file_list.get("nextPageToken")
-
- # Get user information
- user = self.session_manager.get_user(user_id) if self.session_manager else None
- owner_name = user.name if user else None
- owner_email = user.email if user else None
-
- processor = LangflowConnectorFileProcessor(
- self,
- connection_id,
- files_to_process,
- user_id,
- jwt_token=jwt_token,
- owner_name=owner_name,
- owner_email=owner_email,
- replace_duplicates=replace_duplicates,
- )
-
- # Use file IDs as items
- file_ids = [file_info["id"] for file_info in files_to_process]
- original_filenames = {
- file_info["id"]: clean_connector_filename(
- file_info["name"], file_info.get("mimeType") or file_info.get("mimetype")
- )
- for file_info in files_to_process
- if "name" in file_info
- }
-
- # Create custom task using TaskService
- task_id = await self.task_service.create_custom_task(
- user_id, file_ids, processor, original_filenames=original_filenames
- )
-
- return task_id
-
- async def sync_specific_files(
- self,
- connection_id: str,
- user_id: str,
- file_ids: list[str],
- jwt_token: str = None,
- file_infos: list[dict[str, Any]] = None,
- ingest_settings: dict[str, Any] | None = None,
- replace_duplicates: bool = False,
- ) -> str:
- """
- Sync specific files by their IDs using Langflow processing.
- Automatically expands folders to their contents.
-
- Args:
- connection_id: The connection ID
- user_id: The user ID
- file_ids: List of file IDs to sync
- jwt_token: Optional JWT token for authentication
- file_infos: Optional list of file info dicts with {id, name, mimeType, downloadUrl, size}
- When provided, download URLs can be used directly without Graph API calls.
- """
- if not self.task_service:
- raise ValueError(
- "TaskService not available - connector sync requires task service dependency"
- )
-
- connector = await self.get_connector(connection_id)
- if not connector:
- raise ValueError(f"Connection '{connection_id}' not found or not authenticated")
-
- if not connector.is_authenticated:
- raise ValueError(f"Connection '{connection_id}' not authenticated")
-
- if not file_ids:
- raise ValueError("No file IDs provided")
-
- # Get user information
- user = self.session_manager.get_user(user_id) if self.session_manager else None
- owner_name = user.name if user else None
- owner_email = user.email if user else None
-
- # If file_infos provided, cache them in the connector for later use
- # This allows get_file_content to use download URLs directly
- if file_infos and hasattr(connector, "set_file_infos"):
- connector.set_file_infos(file_infos)
- logger.info(f"Cached {len(file_infos)} file infos with download URLs in connector")
-
- # Temporarily set file_ids in the connector's config so list_files() can use them
- # Store the original values to restore later
- cfg = getattr(connector, "cfg", None)
- original_file_ids = None
- original_folder_ids = None
-
- if cfg is not None:
- original_file_ids = getattr(cfg, "file_ids", None)
- original_folder_ids = getattr(cfg, "folder_ids", None)
-
- expanded_file_ids = file_ids # Default to original IDs
-
- # Only attempt folder expansion for connectors that use cfg-based filtering
- # (Google Drive, OneDrive, SharePoint). Connectors without a cfg attribute
- # (e.g. IBM COS) receive pre-filtered file IDs and must NOT call list_files()
- # here — doing so would re-list all files from all buckets, overwriting the
- # carefully selected IDs passed in.
- if cfg is not None:
- try:
- cfg.file_ids = file_ids
- cfg.folder_ids = None
-
- # Expand file IDs — folders become their individual file contents
- result = await connector.list_files()
- expanded_file_ids = [f["id"] for f in result.get("files", [])]
-
- if not expanded_file_ids:
- logger.warning(
- f"No files found after expanding file_ids. "
- f"Original IDs: {file_ids}. This may indicate all IDs were folders "
- f"with no contents, or files that were filtered out."
- )
- # If we have file_infos with download URLs, use original file_ids
- # (OneDrive sharing IDs can't be expanded but can be downloaded directly)
- if file_infos:
- logger.info("Using original file IDs with cached download URLs")
- expanded_file_ids = file_ids
- else:
- raise ValueError("No files to sync after expanding folders")
-
- except Exception as e:
- logger.error(f"Failed to expand file_ids via list_files(): {e}")
- # Fallback to original file_ids if expansion fails
- expanded_file_ids = file_ids
- finally:
- cfg.file_ids = original_file_ids
- cfg.folder_ids = original_folder_ids
-
- processor = LangflowConnectorFileProcessor(
- self,
- connection_id,
- expanded_file_ids,
- user_id,
- jwt_token=jwt_token,
- owner_name=owner_name,
- owner_email=owner_email,
- ingest_settings=ingest_settings,
- replace_duplicates=replace_duplicates,
- )
-
- # Create custom task using TaskService
- original_filenames = {}
- if file_infos:
- original_filenames = {
- f["id"]: clean_connector_filename(f["name"], f.get("mimeType") or f.get("mimetype"))
- for f in file_infos
- if "id" in f and "name" in f
- }
-
- task_id = await self.task_service.create_custom_task(
- user_id, expanded_file_ids, processor, original_filenames=original_filenames
- )
-
- return task_id
-
- async def _get_connector(self, connection_id: str) -> BaseConnector | None:
- """Get a connector by connection ID (alias for get_connector)"""
- return await self.get_connector(connection_id)
diff --git a/src/connectors/service.py b/src/connectors/service.py
index 9e887a677..88eb4aff5 100644
--- a/src/connectors/service.py
+++ b/src/connectors/service.py
@@ -14,14 +14,16 @@ class ConnectorService:
def __init__(
self,
- patched_async_client,
- embed_model: str,
- index_name: str,
+ patched_async_client=None,
+ embed_model: str = "",
+ index_name: str = "",
task_service=None,
session_manager=None,
models_service=None,
document_service=None,
docling_service=None,
+ flows_service=None,
+ langflow_service=None,
):
self.clients = patched_async_client
self.embed_model = embed_model
@@ -32,6 +34,8 @@ class ConnectorService:
self.models_service = models_service
self.document_service = document_service
self.docling_service = docling_service
+ self.flows_service = flows_service
+ self.langflow_service = langflow_service
async def initialize(self):
"""Initialize the service by loading existing connections"""
@@ -49,69 +53,126 @@ class ConnectorService:
jwt_token: str = None,
owner_name: str = None,
owner_email: str = None,
+ ingest_settings: dict[str, Any] | None = None,
) -> dict[str, Any]:
- """Process a document from a connector using existing processing pipeline"""
-
- # Create temporary file from document content
- import os
-
- from utils.file_utils import auto_cleanup_tempfile
+ """Process a document from a connector using active processing pipeline"""
- suffix = os.path.splitext(document.filename)[1]
- if not suffix:
- suffix = get_file_extension(document.mimetype)
+ from config.settings import DISABLE_INGEST_WITH_LANGFLOW
- with auto_cleanup_tempfile(suffix=suffix) as tmp_path:
- # Write document content to temp file
- with open(tmp_path, "wb") as f:
- f.write(document.content)
+ if not DISABLE_INGEST_WITH_LANGFLOW and self.langflow_service is not None:
+ # Process via Langflow pipeline
+ from utils.file_utils import langflow_safe_filename_and_mimetype
- logger.info(
- "[CONNECTOR] Processing document",
- document_id=document.id,
- connector_type=connector_type,
- filename=document.filename,
+ langflow_filename, processed_mimetype = langflow_safe_filename_and_mimetype(
+ document.filename, document.mimetype
)
-
- # Process using consolidated processing pipeline
- from models.processors import TaskProcessor
-
- processor = TaskProcessor(
- document_service=self.document_service,
- models_service=self.models_service,
- docling_service=self.docling_service,
+ file_tuple = (langflow_filename, document.content, processed_mimetype)
+
+ allowed_users = []
+ allowed_groups = []
+ if document.acl:
+ try:
+ allowed_users = document.acl.allowed_users or []
+ allowed_groups = document.acl.allowed_groups or []
+ except AttributeError:
+ pass
+
+ connector_tweak_settings = None
+ if isinstance(ingest_settings, dict):
+ connector_tweak_settings = dict(ingest_settings)
+ connector_tweak_settings.pop("embeddingModel", None)
+
+ tweaks = self.langflow_service.merge_ui_ingest_settings_into_tweaks(
+ {}, connector_tweak_settings
)
- result = await processor.process_document_standard(
- file_path=tmp_path,
- file_hash=document.id, # Use connector document ID as hash
- owner_user_id=owner_user_id,
- original_filename=document.filename, # Pass the original Google Doc title
+
+ result = await self.langflow_service.upload_and_ingest_file(
+ file_tuple=file_tuple,
+ session_id=None,
+ tweaks=tweaks,
+ settings=ingest_settings,
jwt_token=jwt_token,
+ owner=owner_user_id,
owner_name=owner_name,
owner_email=owner_email,
- file_size=len(document.content) if document.content else 0,
connector_type=connector_type,
- acl=document.acl,
- )
-
- logger.info(
- "[CONNECTOR] Document processed",
+ docling_polling_service=self.task_service.docling_polling_service
+ if self.task_service
+ else None,
document_id=document.id,
- status=result.get("status"),
+ source_url=document.source_url,
+ allowed_users=allowed_users,
+ allowed_groups=allowed_groups,
)
-
- # If successfully indexed or already exists, update the indexed documents with connector metadata
- if result["status"] in ["indexed", "unchanged"]:
- # Update all chunks with connector-specific metadata
- await self._update_connector_metadata(
- document, owner_user_id, connector_type, jwt_token
- )
-
return {
- **result,
+ "status": "indexed",
"filename": document.filename,
"source_url": document.source_url,
+ "document_id": document.id,
+ "connector_type": connector_type,
+ "langflow_result": result,
}
+ else:
+ # Create temporary file from document content
+ import os
+
+ from utils.file_utils import auto_cleanup_tempfile
+
+ suffix = os.path.splitext(document.filename)[1]
+ if not suffix:
+ suffix = get_file_extension(document.mimetype)
+
+ with auto_cleanup_tempfile(suffix=suffix) as tmp_path:
+ # Write document content to temp file
+ with open(tmp_path, "wb") as f:
+ f.write(document.content)
+
+ logger.info(
+ "[CONNECTOR] Processing document",
+ document_id=document.id,
+ connector_type=connector_type,
+ filename=document.filename,
+ )
+
+ # Process using consolidated processing pipeline
+ from models.processors import TaskProcessor
+
+ processor = TaskProcessor(
+ document_service=self.document_service,
+ models_service=self.models_service,
+ docling_service=self.docling_service,
+ )
+ result = await processor.process_document_standard(
+ file_path=tmp_path,
+ file_hash=document.id, # Use connector document ID as hash
+ owner_user_id=owner_user_id,
+ original_filename=document.filename, # Pass the original Google Doc title
+ jwt_token=jwt_token,
+ owner_name=owner_name,
+ owner_email=owner_email,
+ file_size=len(document.content) if document.content else 0,
+ connector_type=connector_type,
+ acl=document.acl,
+ )
+
+ logger.info(
+ "[CONNECTOR] Document processed",
+ document_id=document.id,
+ status=result.get("status"),
+ )
+
+ # If successfully indexed or already exists, update the indexed documents with connector metadata
+ if result["status"] in ["indexed", "unchanged"]:
+ # Update all chunks with connector-specific metadata
+ await self._update_connector_metadata(
+ document, owner_user_id, connector_type, jwt_token
+ )
+
+ return {
+ **result,
+ "filename": document.filename,
+ "source_url": document.source_url,
+ }
async def _update_connector_metadata(
self,
@@ -386,15 +447,15 @@ class ConnectorService:
connector.cfg.file_ids = file_ids
connector.cfg.folder_ids = None
- # Get the expanded list of file IDs (folders will be expanded to their contents)
- # This uses the connector's list_files() which calls _iter_selected_items()
- result = await connector.list_files()
- expanded_files = result.get("files", [])
- expanded_file_ids = [f["id"] for f in expanded_files]
+ # Get the expanded list of file IDs (folders will be expanded to their contents)
+ # This uses the connector's list_files() which calls _iter_selected_items()
+ result = await connector.list_files()
+ expanded_files = result.get("files", [])
+ expanded_file_ids = [f["id"] for f in expanded_files]
- # Save the expanded files info so we can set correct names in the task UI
- for f in expanded_files:
- expanded_files_info.append(f)
+ # Save the expanded files info so we can set correct names in the task UI
+ for f in expanded_files:
+ expanded_files_info.append(f)
if not expanded_file_ids:
logger.warning(
diff --git a/src/models/processors.py b/src/models/processors.py
index 384f0ec05..4d4a06093 100644
--- a/src/models/processors.py
+++ b/src/models/processors.py
@@ -53,8 +53,16 @@ class TaskProcessor:
for attempt in range(max_retries):
try:
- exists = await opensearch_client.exists(index=get_index_name(), id=file_hash)
- return exists
+ response = await opensearch_client.search(
+ index=get_index_name(),
+ body={
+ "size": 1,
+ "_source": False,
+ "query": {"term": {"document_id": file_hash}},
+ },
+ )
+ hits = response.get("hits", {}).get("hits", [])
+ return bool(hits)
except (TimeoutError, Exception) as e:
if attempt == max_retries - 1:
logger.error(
@@ -519,7 +527,7 @@ class ConnectorFileProcessor(TaskProcessor):
self.replace_duplicates = replace_duplicates
async def process_item(self, upload_task: UploadTask, item: str, file_task: FileTask) -> None:
- """Process a connector file using consolidated methods"""
+ """Process a connector file using unified methods"""
file_task.status = TaskStatus.RUNNING
file_task.updated_at = time.time()
@@ -603,8 +611,7 @@ class ConnectorFileProcessor(TaskProcessor):
return
await self.delete_document_by_filename(document.filename, opensearch_client)
- # Create temporary file from document content import os
-
+ # Create temporary file from document content
suffix = os.path.splitext(document.filename)[1]
if not suffix:
suffix = get_file_extension(document.mimetype)
@@ -616,205 +623,136 @@ class ConnectorFileProcessor(TaskProcessor):
# Compute hash
file_hash = hash_id(tmp_path)
- standard_kwargs: dict[str, Any] = {}
- if isinstance(self.ingest_settings, dict):
- s = self.ingest_settings
- em = s.get("embeddingModel")
- if isinstance(em, str) and em.strip():
- standard_kwargs["embedding_model"] = em.strip()
- for ui_key, param in (
- ("chunkSize", "chunk_size"),
- ("chunkOverlap", "chunk_overlap"),
- ):
- raw = s.get(ui_key)
- if raw is not None:
- try:
- standard_kwargs[param] = int(raw)
- except (TypeError, ValueError):
- pass
-
- # Use consolidated standard processing
- result = await self.process_document_standard(
- file_path=tmp_path,
- file_hash=file_hash,
- owner_user_id=self.user_id,
- original_filename=document.filename,
- jwt_token=self.jwt_token,
- owner_name=self.owner_name,
- owner_email=self.owner_email,
- file_size=len(document.content),
- connector_type=connection.connector_type,
- acl=document.acl,
- connector_file_id=document.id,
- **standard_kwargs,
- )
-
- # Add connector-specific metadata
- result.update(
- {
- "source_url": document.source_url,
- "document_id": document.id,
- }
- )
-
- file_task.status = TaskStatus.COMPLETED
- file_task.result = result
- file_task.updated_at = time.time()
- upload_task.successful_files += 1
-
- except Exception as e:
- file_task.status = TaskStatus.FAILED
- file_task.error = str(e)
- file_task.updated_at = time.time()
- upload_task.failed_files += 1
- raise
-
-
-class LangflowConnectorFileProcessor(TaskProcessor):
- """Processor for connector file uploads using Langflow"""
-
- def __init__(
- self,
- langflow_connector_service,
- connection_id: str,
- files_to_process: list,
- user_id: str = None,
- jwt_token: str = None,
- owner_name: str = None,
- owner_email: str = None,
- ingest_settings: dict[str, Any] | None = None,
- replace_duplicates: bool = False,
- ):
- super().__init__(
- document_service=langflow_connector_service.task_service.document_service
- if langflow_connector_service.task_service
- else None,
- models_service=langflow_connector_service.task_service.models_service
- if langflow_connector_service.task_service
- else None,
- docling_service=langflow_connector_service.docling_service,
- )
- self.langflow_connector_service = langflow_connector_service
- self.connection_id = connection_id
- self.files_to_process = files_to_process
- self.user_id = user_id
- self.jwt_token = jwt_token
- self.owner_name = owner_name
- self.owner_email = owner_email
- self.ingest_settings = ingest_settings
- self.replace_duplicates = replace_duplicates
-
- async def process_item(self, upload_task: UploadTask, item: str, file_task: FileTask) -> None:
- """Process a connector file using LangflowConnectorService"""
- file_task.status = TaskStatus.RUNNING
- file_task.updated_at = time.time()
-
- try:
- file_id = item # item is the connector file ID
+ if await self.check_document_exists(file_hash, opensearch_client):
+ file_task.status = TaskStatus.COMPLETED
+ file_task.result = {"status": "unchanged", "id": file_hash}
+ file_task.updated_at = time.time()
+ upload_task.successful_files += 1
+ return
- # Get the connector and connection info
- connector = await self.langflow_connector_service.get_connector(self.connection_id)
- connection = await self.langflow_connector_service.connection_manager.get_connection(
- self.connection_id
- )
- if not connector or not connection:
- raise ValueError(f"Connection '{self.connection_id}' not found")
+ from config.settings import DISABLE_INGEST_WITH_LANGFLOW
- # Get file content from connector
- try:
- document = await connector.get_file_content(file_id)
- except (FileNotFoundError, ValueError) as e:
- msg = str(e).lower()
- if "not found" in msg or "404" in msg:
- # File gone at source — remove indexed chunks by document_id
- # (= connector file_id) so it stops appearing in search/chat.
- # Filename rename (e.g. .txt → .md) is irrelevant here.
- deleted_chunks = 0
+ if not DISABLE_INGEST_WITH_LANGFLOW:
+ # Delete existing chunks for this document before Langflow re-ingestion
try:
- from api.documents import delete_chunks_by_document_ids
+ from utils.opensearch_delete import (
+ collect_visible_document_ids,
+ delete_document_ids,
+ )
- opensearch_client = self.langflow_connector_service.session_manager.get_user_opensearch_client(
- self.user_id, self.jwt_token
+ chunk_ids = await collect_visible_document_ids(
+ opensearch_client,
+ index=get_index_name(),
+ query={"term": {"document_id": document.id}},
)
- deleted_chunks = await delete_chunks_by_document_ids(
- [file_id], opensearch_client, get_index_name()
+ deleted_count = await delete_document_ids(
+ opensearch_client,
+ index=get_index_name(),
+ document_ids=chunk_ids,
+ refresh=True,
)
- except Exception as cleanup_err:
- logger.error(
- "Failed to clean up chunks for deleted source file",
- file_id=file_id,
- connection_id=self.connection_id,
- error=str(cleanup_err),
+ logger.info(
+ "Deleted existing chunks before Langflow re-ingestion",
+ document_id=document.id,
+ deleted_count=deleted_count,
+ )
+ except Exception as delete_err:
+ logger.warning(
+ "Failed to delete existing chunks before Langflow re-ingestion",
+ document_id=document.id,
+ error=str(delete_err),
)
- logger.warning(
- "File no longer exists at source — removed from index",
- file_id=file_id,
- connection_id=self.connection_id,
- deleted_chunks=deleted_chunks,
- error=str(e),
+ # Ingest via unified Langflow pipeline (two-phase Docling + Langflow run)
+ langflow_filename, processed_mimetype = langflow_safe_filename_and_mimetype(
+ document.filename, document.mimetype
+ )
+ file_tuple = (langflow_filename, document.content, processed_mimetype)
+
+ # Extract ACL information
+ allowed_users: list[str] = []
+ allowed_groups: list[str] = []
+ if document.acl:
+ try:
+ allowed_users = document.acl.allowed_users or []
+ allowed_groups = document.acl.allowed_groups or []
+ except AttributeError:
+ pass
+
+ # Prepare tweaks
+ connector_tweak_settings = None
+ if isinstance(self.ingest_settings, dict):
+ connector_tweak_settings = dict(self.ingest_settings)
+ connector_tweak_settings.pop("embeddingModel", None)
+
+ tweaks = self.connector_service.langflow_service.merge_ui_ingest_settings_into_tweaks(
+ {}, connector_tweak_settings
)
- file_task.status = TaskStatus.SKIPPED
- file_task.result = {
- "status": "skipped",
- "reason": "deleted_at_source",
- "deleted_chunks": deleted_chunks,
- }
- file_task.updated_at = time.time()
- upload_task.successful_files += 1
- return
- raise
-
- # Update filename in task once we have it from the connector
- file_task.filename = clean_connector_filename(document.filename, document.mimetype)
-
- if not self.user_id:
- raise ValueError("user_id not provided to LangflowConnectorFileProcessor")
-
- opensearch_client = (
- self.langflow_connector_service.session_manager.get_user_opensearch_client(
- self.user_id, self.jwt_token
- )
- )
- if await self.check_filename_exists(document.filename, opensearch_client):
- if not self.replace_duplicates:
- file_task.status = TaskStatus.FAILED
- file_task.error = f"File with name '{document.filename}' already exists"
- file_task.updated_at = time.time()
- upload_task.failed_files += 1
- return
- await self.delete_document_by_filename(document.filename, opensearch_client)
-
- # Create temporary file and compute hash to check for duplicates import os
-
- suffix = os.path.splitext(document.filename)[1]
- if not suffix:
- suffix = get_file_extension(document.mimetype)
- with auto_cleanup_tempfile(suffix=suffix) as tmp_path:
- # Write content to temp file
- with open(tmp_path, "wb") as f:
- f.write(document.content)
- # Compute hash and check if already exists
- file_hash = hash_id(tmp_path)
+ result = await self.connector_service.langflow_service.upload_and_ingest_file(
+ file_tuple=file_tuple,
+ session_id=None,
+ tweaks=tweaks,
+ settings=self.ingest_settings,
+ jwt_token=self.jwt_token,
+ owner=self.user_id,
+ owner_name=self.owner_name,
+ owner_email=self.owner_email,
+ connector_type=connection.connector_type,
+ docling_polling_service=self.connector_service.task_service.docling_polling_service,
+ file_task=file_task,
+ document_id=document.id,
+ source_url=document.source_url,
+ allowed_users=allowed_users,
+ allowed_groups=allowed_groups,
+ )
+ else:
+ # Standard OpenRAG processing pipeline (process_document_standard)
+ standard_kwargs: dict[str, Any] = {}
+ if isinstance(self.ingest_settings, dict):
+ s = self.ingest_settings
+ em = s.get("embeddingModel")
+ if isinstance(em, str) and em.strip():
+ standard_kwargs["embedding_model"] = em.strip()
+ for ui_key, param in (
+ ("chunkSize", "chunk_size"),
+ ("chunkOverlap", "chunk_overlap"),
+ ):
+ raw = s.get(ui_key)
+ if raw is not None:
+ try:
+ standard_kwargs[param] = int(raw)
+ except (TypeError, ValueError):
+ pass
+
+ result = await self.process_document_standard(
+ file_path=tmp_path,
+ file_hash=file_hash,
+ owner_user_id=self.user_id,
+ original_filename=document.filename,
+ jwt_token=self.jwt_token,
+ owner_name=self.owner_name,
+ owner_email=self.owner_email,
+ file_size=len(document.content),
+ connector_type=connection.connector_type,
+ acl=document.acl,
+ connector_file_id=document.id,
+ **standard_kwargs,
+ )
- if await self.check_document_exists(file_hash, opensearch_client):
- file_task.status = TaskStatus.COMPLETED
- file_task.result = {"status": "unchanged", "id": file_hash}
- file_task.updated_at = time.time()
- upload_task.successful_files += 1
- return
+ # Update indexed chunks with connector-specific metadata
+ if result["status"] in ["indexed", "unchanged"]:
+ await self.connector_service._update_connector_metadata(
+ document, self.user_id, connection.connector_type, self.jwt_token
+ )
- # Process using Langflow pipeline
- result = await self.langflow_connector_service.process_connector_document(
- document,
- self.user_id,
- connection.connector_type,
- jwt_token=self.jwt_token,
- owner_name=self.owner_name,
- owner_email=self.owner_email,
- ingest_settings=self.ingest_settings,
- )
+ # Add connector-specific metadata
+ result.update(
+ {
+ "source_url": document.source_url,
+ "document_id": document.id,
+ }
+ )
file_task.status = TaskStatus.COMPLETED
file_task.result = result
diff --git a/src/services/langflow_file_service.py b/src/services/langflow_file_service.py
index c2ca4ae01..a6b68745c 100644
--- a/src/services/langflow_file_service.py
+++ b/src/services/langflow_file_service.py
@@ -562,6 +562,10 @@ class LangflowFileService:
connector_type: str | None = None,
docling_polling_service: Any | None = None,
file_task: Any | None = None,
+ document_id: str | None = None,
+ source_url: str | None = None,
+ allowed_users: list[str] | None = None,
+ allowed_groups: list[str] | None = None,
) -> dict[str, Any]:
"""
Two-phase Docling upload + Langflow ingest operation.
@@ -679,6 +683,10 @@ class LangflowFileService:
owner_email=owner_email,
connector_type=connector_type,
docling_task_id=task_id,
+ document_id=document_id,
+ source_url=source_url,
+ allowed_users=allowed_users,
+ allowed_groups=allowed_groups,
)
total_duration = round(time.time() - total_start_time, 2)
logger.info(f"[LF] Ingestion completed successfully in {total_duration}s")
diff --git a/tests/unit/connectors/test_langflow_connector_txt_to_md.py b/tests/unit/connectors/test_langflow_connector_txt_to_md.py
index cb267aff5..fb99096c4 100644
--- a/tests/unit/connectors/test_langflow_connector_txt_to_md.py
+++ b/tests/unit/connectors/test_langflow_connector_txt_to_md.py
@@ -26,38 +26,19 @@ if str(SRC) not in sys.path:
def _make_service():
- """Build a LangflowConnectorService with the surface
- process_connector_document touches stubbed:
- - session_manager (only needed if pre-delete fires; we let it run as
- a no-op against a mocked OpenSearch client).
- - langflow_service.upload_user_file / run_ingestion_flow / delete_user_file.
+ """Build a ConnectorService with the surface
+ process_connector_document touches stubbed.
"""
- from connectors.langflow_connector_service import LangflowConnectorService
+ from connectors.service import ConnectorService
- service = LangflowConnectorService.__new__(LangflowConnectorService)
+ service = ConnectorService.__new__(ConnectorService)
- # OpenSearch mock for the pre-delete step (collect+delete). Empty result
- # so the pre-delete is a no-op; the test isn't about that path.
- opensearch_client = AsyncMock()
- opensearch_client.search = AsyncMock(return_value={"_scroll_id": None, "hits": {"hits": []}})
- opensearch_client.delete = AsyncMock(return_value={"result": "deleted"})
-
- session_manager = MagicMock()
- session_manager.get_user_opensearch_client = MagicMock(return_value=opensearch_client)
-
- service.session_manager = session_manager
- service.docling_service = MagicMock()
- service.connection_manager = MagicMock()
-
- # Mock Langflow service — the surface we're asserting against is its
- # upload_user_file (the file_tuple it receives).
+ # Mock Langflow service
langflow_service = MagicMock()
- langflow_service.upload_user_file = AsyncMock(
- return_value={"id": "lf-file-id", "path": "/lf/path/file"}
- )
- langflow_service.run_ingestion_flow = AsyncMock(return_value={"status": "ok"})
- langflow_service.delete_user_file = AsyncMock()
+ langflow_service.upload_and_ingest_file = AsyncMock(return_value={"status": "ok"})
+ langflow_service.merge_ui_ingest_settings_into_tweaks = MagicMock(return_value={})
service.langflow_service = langflow_service
+ service.task_service = None
return service, langflow_service
@@ -81,12 +62,10 @@ def _make_document(filename: str, mimetype: str, content: bytes = b"hello world"
@pytest.mark.asyncio
async def test_sharepoint_txt_is_uploaded_to_langflow_as_md():
"""A connector document with mimetype text/plain must reach Langflow's
- upload_user_file with a .md filename and text/markdown mimetype."""
+ upload_and_ingest_file with a .md filename and text/markdown mimetype."""
service, langflow_service = _make_service()
document = _make_document(filename="notes.txt", mimetype="text/plain")
- # auto_cleanup_tempfile is a context manager that yields a real path;
- # let it run normally — it just creates a temp file we won't use.
await service.process_connector_document(
document=document,
owner_user_id="alice",
@@ -94,8 +73,9 @@ async def test_sharepoint_txt_is_uploaded_to_langflow_as_md():
jwt_token="jwt",
)
- langflow_service.upload_user_file.assert_awaited_once()
- (file_tuple, _jwt) = langflow_service.upload_user_file.await_args.args
+ langflow_service.upload_and_ingest_file.assert_awaited_once()
+ kwargs = langflow_service.upload_and_ingest_file.await_args.kwargs
+ file_tuple = kwargs.get("file_tuple")
filename, content, mimetype = file_tuple
assert filename.endswith(".md"), (
@@ -125,7 +105,9 @@ async def test_sharepoint_pdf_passes_through_untouched():
jwt_token="jwt",
)
- (file_tuple, _jwt) = langflow_service.upload_user_file.await_args.args
+ langflow_service.upload_and_ingest_file.assert_awaited_once()
+ kwargs = langflow_service.upload_and_ingest_file.await_args.kwargs
+ file_tuple = kwargs.get("file_tuple")
filename, _content, mimetype = file_tuple
assert filename == "report.pdf"
assert mimetype == "application/pdf"
diff --git a/tests/unit/test_connector_processor_filename_dedupe.py b/tests/unit/test_connector_processor_filename_dedupe.py
index a866939e5..a269a721a 100644
--- a/tests/unit/test_connector_processor_filename_dedupe.py
+++ b/tests/unit/test_connector_processor_filename_dedupe.py
@@ -12,7 +12,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from connectors.base import ConnectorDocument, DocumentACL
-from models.processors import ConnectorFileProcessor, LangflowConnectorFileProcessor
+from models.processors import ConnectorFileProcessor
from models.tasks import FileTask, TaskStatus, UploadTask
@@ -47,6 +47,7 @@ def _build_connector_processor(replace_duplicates: bool) -> ConnectorFileProcess
document_service.session_manager = MagicMock()
document_service.session_manager.get_user_opensearch_client = MagicMock()
connector_service = MagicMock()
+ connector_service._update_connector_metadata = AsyncMock()
return ConnectorFileProcessor(
connector_service=connector_service,
connection_id="conn-1",
@@ -63,10 +64,20 @@ def _wire_connector_processor(
processor: ConnectorFileProcessor,
document: ConnectorDocument,
filename_exists: bool,
+ hash_exists: bool = False,
):
opensearch_client = AsyncMock()
- opensearch_client.search = AsyncMock(return_value=_make_search_response(filename_exists))
+
+ async def mock_search(index, body, **kwargs):
+ query_str = str(body)
+ if "document_id" in query_str:
+ return _make_search_response(hash_exists)
+ else:
+ return _make_search_response(filename_exists)
+
+ opensearch_client.search = mock_search
opensearch_client.delete_by_query = AsyncMock(return_value={"deleted": 3})
+ opensearch_client.delete = AsyncMock(return_value={"result": "deleted"})
opensearch_client.exists = AsyncMock(return_value=False)
processor.document_service.session_manager.get_user_opensearch_client.return_value = (
opensearch_client
@@ -85,7 +96,8 @@ def _wire_connector_processor(
@pytest.mark.asyncio
-async def test_connector_processor_fails_when_filename_exists_and_replace_false():
+async def test_connector_processor_fails_when_filename_exists_and_replace_false(monkeypatch):
+ monkeypatch.setattr("config.settings.DISABLE_INGEST_WITH_LANGFLOW", True)
processor = _build_connector_processor(replace_duplicates=False)
document = _make_document()
opensearch_client = _wire_connector_processor(processor, document, filename_exists=True)
@@ -105,7 +117,8 @@ async def test_connector_processor_fails_when_filename_exists_and_replace_false(
@pytest.mark.asyncio
-async def test_connector_processor_deletes_then_ingests_when_replace_true():
+async def test_connector_processor_deletes_then_ingests_when_replace_true(monkeypatch):
+ monkeypatch.setattr("config.settings.DISABLE_INGEST_WITH_LANGFLOW", True)
processor = _build_connector_processor(replace_duplicates=True)
document = _make_document()
opensearch_client = _wire_connector_processor(processor, document, filename_exists=True)
@@ -129,12 +142,13 @@ async def test_connector_processor_deletes_then_ingests_when_replace_true():
@pytest.mark.asyncio
-async def test_connector_processor_deletes_chunks_when_source_returns_404():
+async def test_connector_processor_deletes_chunks_when_source_returns_404(monkeypatch):
"""When the source connector reports the file is gone (404), the processor
must remove the already-indexed chunks queried by connector_file_id — NOT
document_id. Chunks are indexed with document_id=file_hash (SHA of content)
which differs from file_id, so querying document_id would find nothing.
"""
+ monkeypatch.setattr("config.settings.DISABLE_INGEST_WITH_LANGFLOW", True)
processor = _build_connector_processor(replace_duplicates=False)
opensearch_client = AsyncMock()
@@ -181,7 +195,8 @@ async def test_connector_processor_deletes_chunks_when_source_returns_404():
@pytest.mark.asyncio
-async def test_connector_processor_proceeds_when_filename_absent():
+async def test_connector_processor_proceeds_when_filename_absent(monkeypatch):
+ monkeypatch.setattr("config.settings.DISABLE_INGEST_WITH_LANGFLOW", True)
processor = _build_connector_processor(replace_duplicates=False)
document = _make_document()
opensearch_client = _wire_connector_processor(processor, document, filename_exists=False)
@@ -203,55 +218,61 @@ async def test_connector_processor_proceeds_when_filename_absent():
def _build_langflow_processor(
replace_duplicates: bool,
-) -> LangflowConnectorFileProcessor:
+) -> ConnectorFileProcessor:
+ processor = _build_connector_processor(replace_duplicates)
+
langflow_service = MagicMock()
- langflow_service.task_service = MagicMock()
- langflow_service.task_service.document_service = MagicMock()
- langflow_service.task_service.models_service = MagicMock()
- langflow_service.docling_service = MagicMock()
- langflow_service.session_manager = MagicMock()
- langflow_service.session_manager.get_user_opensearch_client = MagicMock()
- langflow_service.process_connector_document = AsyncMock(
+ langflow_service.upload_and_ingest_file = AsyncMock(
return_value={"status": "indexed", "id": "hash-1"}
)
- return LangflowConnectorFileProcessor(
- langflow_connector_service=langflow_service,
- connection_id="conn-1",
- files_to_process=["file-id-1"],
- user_id="user-1",
- jwt_token="jwt",
- replace_duplicates=replace_duplicates,
- )
+ langflow_service.merge_ui_ingest_settings_into_tweaks = MagicMock(return_value={})
+
+ processor.connector_service.langflow_service = langflow_service
+ processor.connector_service.task_service = MagicMock()
+ processor.connector_service.task_service.docling_polling_service = MagicMock()
+
+ return processor
def _wire_langflow_processor(
- processor: LangflowConnectorFileProcessor,
+ processor: ConnectorFileProcessor,
document: ConnectorDocument,
filename_exists: bool,
hash_exists: bool = False,
):
opensearch_client = AsyncMock()
- opensearch_client.search = AsyncMock(return_value=_make_search_response(filename_exists))
+
+ async def mock_search(index, body, **kwargs):
+ query_str = str(body)
+ if "document_id" in query_str:
+ return _make_search_response(hash_exists)
+ else:
+ return _make_search_response(filename_exists)
+
+ opensearch_client.search = mock_search
opensearch_client.delete_by_query = AsyncMock(return_value={"deleted": 2})
+ opensearch_client.delete = AsyncMock(return_value={"result": "deleted"})
opensearch_client.exists = AsyncMock(return_value=hash_exists)
- processor.langflow_connector_service.session_manager.get_user_opensearch_client.return_value = (
+
+ processor.document_service.session_manager.get_user_opensearch_client.return_value = (
opensearch_client
)
connector = MagicMock()
connector.get_file_content = AsyncMock(return_value=document)
- processor.langflow_connector_service.get_connector = AsyncMock(return_value=connector)
+ processor.connector_service.get_connector = AsyncMock(return_value=connector)
connection = MagicMock()
connection.connector_type = "sharepoint"
- processor.langflow_connector_service.connection_manager = MagicMock()
- processor.langflow_connector_service.connection_manager.get_connection = AsyncMock(
+ processor.connector_service.connection_manager = MagicMock()
+ processor.connector_service.connection_manager.get_connection = AsyncMock(
return_value=connection
)
return opensearch_client
@pytest.mark.asyncio
-async def test_langflow_connector_processor_fails_on_filename_collision():
+async def test_langflow_connector_processor_fails_on_filename_collision(monkeypatch):
+ monkeypatch.setattr("config.settings.DISABLE_INGEST_WITH_LANGFLOW", False)
processor = _build_langflow_processor(replace_duplicates=False)
document = _make_document()
opensearch_client = _wire_langflow_processor(processor, document, filename_exists=True)
@@ -264,12 +285,13 @@ async def test_langflow_connector_processor_fails_on_filename_collision():
assert file_task.status == TaskStatus.FAILED
assert "already exists" in (file_task.error or "")
assert upload_task.failed_files == 1
- processor.langflow_connector_service.process_connector_document.assert_not_called()
+ processor.connector_service.langflow_service.upload_and_ingest_file.assert_not_called()
opensearch_client.delete_by_query.assert_not_called()
@pytest.mark.asyncio
-async def test_langflow_connector_processor_overwrites_when_replace_true():
+async def test_langflow_connector_processor_overwrites_when_replace_true(monkeypatch):
+ monkeypatch.setattr("config.settings.DISABLE_INGEST_WITH_LANGFLOW", False)
processor = _build_langflow_processor(replace_duplicates=True)
document = _make_document()
opensearch_client = _wire_langflow_processor(processor, document, filename_exists=True)
@@ -281,16 +303,17 @@ async def test_langflow_connector_processor_overwrites_when_replace_true():
assert file_task.status == TaskStatus.COMPLETED
opensearch_client.delete_by_query.assert_awaited()
- processor.langflow_connector_service.process_connector_document.assert_awaited_once()
+ processor.connector_service.langflow_service.upload_and_ingest_file.assert_awaited_once()
@pytest.mark.asyncio
-async def test_langflow_connector_processor_deletes_chunks_when_source_returns_404():
+async def test_langflow_connector_processor_deletes_chunks_when_source_returns_404(monkeypatch):
"""When the source connector reports the file is gone (404), the Langflow
processor must remove the already-indexed chunks instead of surfacing
'File not found: <id>' as a task error. Regression test for SharePoint
webhook-triggered sync of a deleted source file.
"""
+ monkeypatch.setattr("config.settings.DISABLE_INGEST_WITH_LANGFLOW", False)
processor = _build_langflow_processor(replace_duplicates=False)
opensearch_client = AsyncMock()
@@ -298,19 +321,20 @@ async def test_langflow_connector_processor_deletes_chunks_when_source_returns_4
return_value={"hits": {"hits": [{"_id": "chunk-1"}]}, "_scroll_id": None}
)
opensearch_client.delete = AsyncMock(return_value={"result": "deleted"})
- processor.langflow_connector_service.session_manager.get_user_opensearch_client.return_value = (
+ processor.document_service.session_manager.get_user_opensearch_client.return_value = (
opensearch_client
)
connector = MagicMock()
- connector.get_file_content = AsyncMock(
- side_effect=ValueError("File not found: 01BYMO7NCRKVAJFSPPABBKQXS4PPDHBVUY")
+ connector.get_file_content = MagicMock()
+ connector.get_file_content.side_effect = ValueError(
+ "File not found: 01BYMO7NCRKVAJFSPPABBKQXS4PPDHBVUY"
)
- processor.langflow_connector_service.get_connector = AsyncMock(return_value=connector)
+ processor.connector_service.get_connector = AsyncMock(return_value=connector)
connection = MagicMock()
connection.connector_type = "sharepoint"
- processor.langflow_connector_service.connection_manager = MagicMock()
- processor.langflow_connector_service.connection_manager.get_connection = AsyncMock(
+ processor.connector_service.connection_manager = MagicMock()
+ processor.connector_service.connection_manager.get_connection = AsyncMock(
return_value=connection
)
@@ -325,14 +349,15 @@ async def test_langflow_connector_processor_deletes_chunks_when_source_returns_4
assert file_task.error is None
assert upload_task.successful_files == 1
assert upload_task.failed_files == 0
- processor.langflow_connector_service.process_connector_document.assert_not_called()
+ processor.connector_service.langflow_service.upload_and_ingest_file.assert_not_called()
opensearch_client.delete.assert_awaited_once()
@pytest.mark.asyncio
-async def test_langflow_connector_processor_hash_unchanged_path_preserved():
+async def test_langflow_connector_processor_hash_unchanged_path_preserved(monkeypatch):
"""When the filename is new but the byte hash already exists, the file
is reported as 'unchanged' — same as before this change."""
+ monkeypatch.setattr("config.settings.DISABLE_INGEST_WITH_LANGFLOW", False)
processor = _build_langflow_processor(replace_duplicates=False)
document = _make_document()
_wire_langflow_processor(processor, document, filename_exists=False, hash_exists=True)
@@ -344,4 +369,4 @@ async def test_langflow_connector_processor_hash_unchanged_path_preserved():
assert file_task.status == TaskStatus.COMPLETED
assert (file_task.result or {}).get("status") == "unchanged"
- processor.langflow_connector_service.process_connector_document.assert_not_called()
+ processor.connector_service.langflow_service.upload_and_ingest_file.assert_not_called()
diff --git a/tests/unit/test_processors_clear_stale_chunks.py b/tests/unit/test_processors_clear_stale_chunks.py
index 6136e8df0..f1daac461 100644
--- a/tests/unit/test_processors_clear_stale_chunks.py
+++ b/tests/unit/test_processors_clear_stale_chunks.py
@@ -127,7 +127,9 @@ async def test_stale_chunks_cleared_before_reindex(monkeypatch):
async def _search(**kw):
op_order.append(("search", kw))
- return {"_scroll_id": None, "hits": {"hits": [{"_id": cid} for cid in stale_chunk_ids]}}
+ if "scroll" in kw:
+ return {"_scroll_id": None, "hits": {"hits": [{"_id": cid} for cid in stale_chunk_ids]}}
+ return {"hits": {"hits": []}}
async def _delete(**kw):
op_order.append(("delete", kw))