OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
feat: disable langflow ingestion via UI (#1623)
Lucas Oliveira6a94df78d572
diff --git a/frontend/app/api/mutations/useUpdateSettingsMutation.ts b/frontend/app/api/mutations/useUpdateSettingsMutation.tsindex 318c7b784..1cd1377a0 100644--- a/frontend/app/api/mutations/useUpdateSettingsMutation.ts+++ b/frontend/app/api/mutations/useUpdateSettingsMutation.ts@@ -18,6 +18,7 @@ export interface UpdateSettingsRequest {table_structure?: boolean;ocr?: boolean;picture_descriptions?: boolean;+ disable_ingest_with_langflow?: boolean;embedding_model?: string;embedding_provider?: string;diff --git a/frontend/app/api/queries/useGetConversationsQuery.ts b/frontend/app/api/queries/useGetConversationsQuery.tsindex 20d375052..c8b4f4a0f 100644--- a/frontend/app/api/queries/useGetConversationsQuery.ts+++ b/frontend/app/api/queries/useGetConversationsQuery.ts@@ -48,7 +48,10 @@ export interface ConversationHistoryResponse {export const useGetConversationsQuery = (endpoint: EndpointType,refreshTrigger?: number,- options?: Omit<UseQueryOptions, "queryKey" | "queryFn">,+ options?: Omit<+ UseQueryOptions<ChatConversation[], Error, ChatConversation[]>,+ "queryKey" | "queryFn"+ >,) => {const queryClient = useQueryClient();const { isOnboardingComplete } = useChat();diff --git a/frontend/app/api/queries/useGetNudgesQuery.ts b/frontend/app/api/queries/useGetNudgesQuery.tsindex 4fc2163b5..6afbc897b 100644--- a/frontend/app/api/queries/useGetNudgesQuery.ts+++ b/frontend/app/api/queries/useGetNudgesQuery.ts@@ -25,7 +25,10 @@ export interface NudgeQueryParams {export const useGetNudgesQuery = (params: NudgeQueryParams | null = {},- options?: Omit<UseQueryOptions, "queryKey" | "queryFn">,+ options?: Omit<+ UseQueryOptions<Nudge[], Error, Nudge[]>,+ "queryKey" | "queryFn"+ >,) => {const { chatId, filters, limit, scoreThreshold } = params ?? {};const queryClient = useQueryClient();diff --git a/frontend/app/api/queries/useGetSettingsQuery.ts b/frontend/app/api/queries/useGetSettingsQuery.tsindex 1485749c2..bdb08c4cf 100644--- a/frontend/app/api/queries/useGetSettingsQuery.ts+++ b/frontend/app/api/queries/useGetSettingsQuery.ts@@ -18,6 +18,7 @@ export interface KnowledgeSettings {table_structure?: boolean;ocr?: boolean;picture_descriptions?: boolean;+ disable_ingest_with_langflow?: boolean;}export interface ProviderSettings {diff --git a/frontend/app/settings/_components/ingest-settings-section.tsx b/frontend/app/settings/_components/ingest-settings-section.tsxindex 0d27850ed..6d83fe921 100644--- a/frontend/app/settings/_components/ingest-settings-section.tsx+++ b/frontend/app/settings/_components/ingest-settings-section.tsx@@ -46,6 +46,8 @@ export function IngestSettingsSection() {const [ocr, setOcr] = useState<boolean>(false);const [pictureDescriptions, setPictureDescriptions] =useState<boolean>(false);+ const [disableIngestWithLangflow, setDisableIngestWithLangflow] =+ useState<boolean>(false);const { data: settings = {} } = useGetSettingsQuery({enabled: isAuthenticated || isNoAuthMode,@@ -146,13 +148,22 @@ export function IngestSettingsSection() {setPictureDescriptions(settings.knowledge.picture_descriptions);}, [settings.knowledge?.picture_descriptions]);+ useEffect(() => {+ if (settings.knowledge?.disable_ingest_with_langflow !== undefined)+ setDisableIngestWithLangflow(+ settings.knowledge.disable_ingest_with_langflow,+ );+ }, [settings.knowledge?.disable_ingest_with_langflow]);+const k = settings.knowledge;const knowledgeIngestDirty =chunkSize !== (k?.chunk_size ?? chunkSize) ||chunkOverlap !== (k?.chunk_overlap ?? chunkOverlap) ||tableStructure !== (k?.table_structure ?? tableStructure) ||ocr !== (k?.ocr ?? ocr) ||- pictureDescriptions !== (k?.picture_descriptions ?? pictureDescriptions);+ pictureDescriptions !== (k?.picture_descriptions ?? pictureDescriptions) ||+ disableIngestWithLangflow !==+ (k?.disable_ingest_with_langflow ?? disableIngestWithLangflow);const handleEmbeddingModelChange = (newModel: string, provider?: string) => {if (newModel && provider) {@@ -195,6 +206,7 @@ export function IngestSettingsSection() {table_structure: tableStructure,ocr,picture_descriptions: pictureDescriptions,+ disable_ingest_with_langflow: disableIngestWithLangflow,},{ onSuccess: () => setChunkValidationError(null) },);@@ -238,6 +250,7 @@ export function IngestSettingsSection() {setTableStructure(DEFAULT_KNOWLEDGE_SETTINGS.table_structure);setOcr(DEFAULT_KNOWLEDGE_SETTINGS.ocr);setPictureDescriptions(DEFAULT_KNOWLEDGE_SETTINGS.picture_descriptions);+ setDisableIngestWithLangflow(false);setChunkValidationError(null);closeDialog();})@@ -429,6 +442,25 @@ export function IngestSettingsSection() {</div></div><div>+ <div className="flex items-center justify-between py-3 border-b border-border">+ <div className="flex-1">+ <Label+ htmlFor="disable-ingest-with-langflow"+ className="text-base font-medium cursor-pointer pb-3"+ >+ Disable Langflow Ingestion+ </Label>+ <div className="text-sm text-muted-foreground">+ Bypass Langflow for document ingestion and use traditional+ processing.+ </div>+ </div>+ <Switch+ id="disable-ingest-with-langflow"+ checked={disableIngestWithLangflow}+ onCheckedChange={setDisableIngestWithLangflow}+ />+ </div><div className="flex items-center justify-between py-3 border-b border-border"><div className="flex-1"><Labeldiff --git a/scripts/setup-e2e.sh b/scripts/setup-e2e.shindex 7c91ba8d8..33eb2dbc3 100755--- a/scripts/setup-e2e.sh+++ b/scripts/setup-e2e.sh@@ -84,7 +84,7 @@ doneecho "Waiting for Backend (via proxy)..."ELAPSED=0-until curl -s http://localhost:8000/health >/dev/null; do+until [ "$(curl -s http://localhost:8000/search/health -o /dev/null -w "%{http_code}")" -eq 200 ]; dosleep 5ELAPSED=$((ELAPSED + 5))if [ $ELAPSED -ge $TIMEOUT ]; then@@ -95,4 +95,16 @@ until curl -s http://localhost:8000/health >/dev/null; doecho "Waiting for Backend... (${ELAPSED}s/${TIMEOUT}s)"done+echo "Waiting for OpenSearch security configuration to be applied..."+ELAPSED=0+until ${CONTAINER_RUNTIME} logs os 2>&1 | grep -q "Security configuration applied successfully" || [ $ELAPSED -ge 60 ]; do+ sleep 2+ ELAPSED=$((ELAPSED + 2))+done+if [ $ELAPSED -ge 60 ]; then+ echo "WARNING: OpenSearch security configuration wait timed out (60s)"+else+ echo "OpenSearch security configuration applied successfully"+fi+echo "Infrastructure Ready!"diff --git a/src/api/health.py b/src/api/health.pyindex 42278447f..31d697556 100644--- a/src/api/health.py+++ b/src/api/health.py@@ -17,7 +17,7 @@ async def health_check(request: Request):return JSONResponse({"status": "ok"}, status_code=200)-async def opensearch_health_ready(request):+async def opensearch_health_ready(request: Request):"""Readiness probe: verifies OpenSearch dependency is reachable."""from config.settings import IBM_AUTH_ENABLED, OPENSEARCH_URLdiff --git a/src/api/router.py b/src/api/router.pyindex 3ddd309c1..b92f2c9b0 100644--- a/src/api/router.py+++ b/src/api/router.py@@ -1,13 +1,12 @@"""Router endpoints that automatically route based on configuration settings."""import json-import osimport tempfilefrom fastapi import Depends, File, Form, UploadFilefrom fastapi.responses import JSONResponse-from config.settings import DISABLE_INGEST_WITH_LANGFLOW+from config.settings import get_openrag_configfrom dependencies import (get_current_user,get_document_service,@@ -40,21 +39,22 @@ async def upload_ingest_router(- If DISABLE_INGEST_WITH_LANGFLOW is True: uses traditional OpenRAG upload- If DISABLE_INGEST_WITH_LANGFLOW is False (default): uses Langflow upload-ingest via task service"""+ disable_ingest_with_langflow = get_openrag_config().knowledge.disable_ingest_with_langflowlogger.debug("Router upload_ingest endpoint called",- disable_langflow_ingest=DISABLE_INGEST_WITH_LANGFLOW,+ disable_langflow_ingest=disable_ingest_with_langflow,)- if DISABLE_INGEST_WITH_LANGFLOW:- logger.debug("Routing to traditional OpenRAG upload")- # Route to traditional upload — just take the first file- from api.upload import upload as traditional_upload_fn-- return await traditional_upload_fn(- file=file[0] if file else None,- document_service=document_service,+ if disable_ingest_with_langflow:+ logger.debug("Routing to traditional OpenRAG upload via task service")+ return await _traditional_upload_ingest_task(+ upload_files=file,+ replace_duplicates=replace_duplicates.lower() == "true",+ create_filter=create_filter.lower() == "true",session_manager=session_manager,+ task_service=task_service,user=user,+ settings_json=settings_json,)logger.debug("Routing to Langflow upload-ingest pipeline via task service")@@ -72,6 +72,96 @@ async def upload_ingest_router()+async def _traditional_upload_ingest_task(+ upload_files: list[UploadFile],+ replace_duplicates: bool,+ create_filter: bool,+ session_manager,+ task_service,+ user: User,+ settings_json: str | None = None,+):+ """Task-based traditional upload and ingest for single/multiple files"""+ try:+ if not upload_files:+ return JSONResponse({"error": "Missing files"}, status_code=400)++ settings = None+ if settings_json:+ try:+ settings = json.loads(settings_json)+ except json.JSONDecodeError as e:+ return JSONResponse({"error": f"Invalid settings JSON: {e}"}, status_code=400)++ user_id = user.user_id+ user_name = user.name+ user_email = user.email+ jwt_token = user.jwt_token++ temp_file_paths = []+ original_filenames = []++ try:+ for upload_file in upload_files:+ content = await upload_file.read()+ original_filenames.append(upload_file.filename)+ # Generate unique temp file to avoid collisions+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".tmp")+ temp_path = temp_file.name+ temp_file.close()+ with open(temp_path, "wb") as f:+ f.write(content)+ temp_file_paths.append(temp_path)++ file_path_to_original_filename = dict(+ zip(temp_file_paths, original_filenames, strict=True)+ )++ # Ensure the search index exists before creating the upload task+ from api.documents import _ensure_index_exists++ await _ensure_index_exists(jwt_token)++ task_id = await task_service.create_upload_task(+ user_id=user_id,+ file_paths=temp_file_paths,+ jwt_token=jwt_token,+ owner_name=user_name,+ owner_email=user_email,+ original_filenames=file_path_to_original_filename,+ replace_duplicates=replace_duplicates,+ settings=settings,+ )++ return JSONResponse(+ {+ "task_id": task_id,+ "message": f"Upload task created for {len(upload_files)} file(s)",+ "file_count": len(upload_files),+ "create_filter": create_filter,+ "filename": original_filenames[0] if len(original_filenames) == 1 else None,+ },+ status_code=202,+ )++ except Exception:+ from utils.file_utils import safe_unlink++ for temp_path in temp_file_paths:+ safe_unlink(temp_path)+ raise++ except Exception as e:+ logger.error("Task-based traditional upload_ingest failed", error=str(e))+ import traceback++ logger.error("Full traceback", traceback=traceback.format_exc())+ error_msg = str(e)+ if "AuthenticationException" in error_msg or "access denied" in error_msg.lower():+ return JSONResponse({"error": "Access denied"}, status_code=403)+ return JSONResponse({"error": "An internal error has occurred."}, status_code=500)++async def _langflow_upload_ingest_task(upload_files: list[UploadFile],session_id,@@ -113,13 +203,13 @@ async def _langflow_upload_ingest_task(original_filenames = []try:- temp_dir = tempfile.gettempdir()-for upload_file in upload_files:content = await upload_file.read()original_filenames.append(upload_file.filename)- safe_filename = upload_file.filename.replace(" ", "_").replace("/", "_")- temp_path = os.path.join(temp_dir, safe_filename)+ # Generate unique temp file to avoid collisions+ temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".tmp")+ temp_path = temp_file.name+ temp_file.close()with open(temp_path, "wb") as f:f.write(content)temp_file_paths.append(temp_path)diff --git a/src/api/settings/endpoints.py b/src/api/settings/endpoints.pyindex 4bb4eb29a..b8000a360 100644--- a/src/api/settings/endpoints.py+++ b/src/api/settings/endpoints.py@@ -211,6 +211,7 @@ async def get_settings(ocr=knowledge_config.ocr,picture_descriptions=knowledge_config.picture_descriptions,index_name=knowledge_config.index_name,+ disable_ingest_with_langflow=knowledge_config.disable_ingest_with_langflow,),agent=AgentConfig(llm_model=agent_config.llm_model,@@ -461,6 +462,15 @@ async def update_settings(except Exception as e:logger.error(f"Failed to update docling settings in flow: {str(e)}")+ if body.disable_ingest_with_langflow is not None:+ current_config.knowledge.disable_ingest_with_langflow = (+ body.disable_ingest_with_langflow+ )+ config_updated = True+ logger.info(+ f"Disable Langflow ingestion changed to {body.disable_ingest_with_langflow}"+ )+if body.chunk_size is not None:effective_overlap = (body.chunk_overlapdiff --git a/src/api/settings/models.py b/src/api/settings/models.pyindex b19d82c72..851c93da2 100644--- a/src/api/settings/models.py+++ b/src/api/settings/models.py@@ -21,6 +21,7 @@ class SettingsUpdateBody(BaseModel):table_structure: bool | None = Noneocr: bool | None = Nonepicture_descriptions: bool | None = None+ disable_ingest_with_langflow: bool | None = Noneembedding_model: str | None = Field(None, min_length=1)embedding_provider: str | None = Field(None, pattern="^(openai|watsonx|ollama)$")index_name: str | None = Field(None, min_length=1)@@ -128,6 +129,7 @@ class KnowledgeConfig(BaseModel):ocr: bool | Nonepicture_descriptions: bool | Noneindex_name: str | None+ disable_ingest_with_langflow: bool | Noneclass AgentConfig(BaseModel):diff --git a/src/app/container.py b/src/app/container.pyindex 694640645..be0a43083 100644--- a/src/app/container.py+++ b/src/app/container.py@@ -87,6 +87,7 @@ async def initialize_services():ingestion_timeout=INGESTION_TIMEOUT,docling_service=clients.docling_service,docling_polling_service=docling_polling_service,+ session_manager=session_manager,)flows_service = FlowsService()chat_service = ChatService(flows_service=flows_service)diff --git a/src/config/config_manager.py b/src/config/config_manager.pyindex 4a11e10bc..1d7281160 100644--- a/src/config/config_manager.py+++ b/src/config/config_manager.py@@ -1,10 +1,12 @@"""Configuration management for OpenRAG."""import os-import yaml+from dataclasses import asdict, dataclass, fieldfrom pathlib import Path-from typing import Dict, Any, Optional-from dataclasses import dataclass, asdict, field+from typing import Any, Optional++import yaml+from utils.logging_config import get_loggerlogger = get_logger(__name__)@@ -13,6 +15,7 @@ logger = get_logger(__name__)@dataclassclass OpenAIConfig:"""OpenAI provider configuration."""+api_key: str = ""configured: bool = False@@ -20,6 +23,7 @@ class OpenAIConfig:@dataclassclass AnthropicConfig:"""Anthropic provider configuration."""+api_key: str = ""configured: bool = False@@ -27,6 +31,7 @@ class AnthropicConfig:@dataclassclass WatsonXConfig:"""IBM WatsonX provider configuration."""+api_key: str = ""endpoint: str = ""project_id: str = ""@@ -36,6 +41,7 @@ class WatsonXConfig:@dataclassclass OllamaConfig:"""Ollama provider configuration."""+endpoint: str = ""resolved_endpoint: str = ""configured: bool = False@@ -44,6 +50,7 @@ class OllamaConfig:@dataclassclass ProvidersConfig:"""All provider configurations."""+openai: OpenAIConfiganthropic: AnthropicConfigwatsonx: WatsonXConfig@@ -80,6 +87,7 @@ class KnowledgeConfig:ocr: bool = Falsepicture_descriptions: bool = Falseindex_name: str = "documents" # OpenSearch index name+ disable_ingest_with_langflow: bool = False@dataclass@@ -88,7 +96,7 @@ class AgentConfig:llm_model: str = ""llm_provider: str = "openai" # Which provider to use for LLM- system_prompt: str = "You are the OpenRAG Agent. You answer questions using retrieval, reasoning, and tool use.\nYou have access to several tools. Your job is to determine **which tool to use and when**.\n### Available Tools\n- OpenSearch Retrieval Tool:\n Use this to search the indexed knowledge base. Use when the user asks about product details, internal concepts, processes, architecture, documentation, roadmaps, or anything that may be stored in the index.\n- Conversation History:\n Use this to maintain continuity when the user is referring to previous turns. \n Do not treat history as a factual source.\n- Conversation File Context:\n Use this when the user asks about a document they uploaded or refers directly to its contents.\n- URL Ingestion Tool:\n Use this **only** when the user explicitly asks you to read, summarize, or analyze the content of a URL.\n Do not ingest URLs automatically.\n- Calculator / Expression Evaluation Tool:\n Use this when the user asks to compare numbers, compute estimates, calculate totals, analyze pricing, or answer any question requiring mathematics or quantitative reasoning.\n If the answer requires arithmetic, call the calculator tool rather than calculating internally.\n### Retrieval Decision Rules\nUse OpenSearch **whenever**:\n1. The question may be answered from internal or indexed data.\n2. The user references team names, product names, release plans, configurations, requirements, or official information.\n3. The user needs a factual, grounded answer.\nDo **not** use retrieval if:\n- The question is purely creative (e.g., storytelling, analogies) or personal preference.\n- The user simply wants text reformatted or rewritten from what is already present in the conversation.\nWhen uncertain → **Retrieve.** Retrieval is low risk and improves grounding.\n### URL Ingestion Rules\nOnly ingest URLs when the user explicitly says:\n- \"Read this link\"\n- \"Summarize this webpage\"\n- \"What does this site say?\"\n- \"Ingest this URL\"\nIf unclear → ask a clarifying question.\n### Calculator Usage Rules\nUse the calculator when:\n- Performing arithmetic\n- Estimating totals\n- Comparing values\n- Modeling cost, time, effort, scale, or projections\nDo not perform math internally. **Call the calculator tool instead.**\n### Answer Construction Rules\n1. When asked: \"What is OpenRAG\", answer the following:\n\"OpenRAG is an open-source package for building agentic RAG systems. It supports integration with a wide range of orchestration tools, vector databases, and LLM providers. OpenRAG connects and amplifies three popular, proven open-source projects into one powerful platform:\n**Langflow** – Langflow is a powerful tool to build and deploy AI agents and MCP servers [Read more](https://www.langflow.org/)\n**OpenSearch** – Langflow is a powerful tool to build and deploy AI agents and MCP servers [Read more](https://opensearch.org/)\n**Docling** – Langflow is a powerful tool to build and deploy AI agents and MCP servers [Read more](https://www.docling.ai/)\"\n2. Synthesize retrieved or ingested content in your own words.\n3. Support factual claims with citations in the format:\n (Source: <document_name_or_id>)\n4. If no supporting evidence is found:\n Say: \"No relevant supporting sources were found for that request.\"\n5. Never invent facts or hallucinate details.\n6. Be concise, direct, and confident. \n7. Do not reveal internal chain-of-thought."+ system_prompt: str = 'You are the OpenRAG Agent. You answer questions using retrieval, reasoning, and tool use.\nYou have access to several tools. Your job is to determine **which tool to use and when**.\n### Available Tools\n- OpenSearch Retrieval Tool:\n Use this to search the indexed knowledge base. Use when the user asks about product details, internal concepts, processes, architecture, documentation, roadmaps, or anything that may be stored in the index.\n- Conversation History:\n Use this to maintain continuity when the user is referring to previous turns. \n Do not treat history as a factual source.\n- Conversation File Context:\n Use this when the user asks about a document they uploaded or refers directly to its contents.\n- URL Ingestion Tool:\n Use this **only** when the user explicitly asks you to read, summarize, or analyze the content of a URL.\n Do not ingest URLs automatically.\n- Calculator / Expression Evaluation Tool:\n Use this when the user asks to compare numbers, compute estimates, calculate totals, analyze pricing, or answer any question requiring mathematics or quantitative reasoning.\n If the answer requires arithmetic, call the calculator tool rather than calculating internally.\n### Retrieval Decision Rules\nUse OpenSearch **whenever**:\n1. The question may be answered from internal or indexed data.\n2. The user references team names, product names, release plans, configurations, requirements, or official information.\n3. The user needs a factual, grounded answer.\nDo **not** use retrieval if:\n- The question is purely creative (e.g., storytelling, analogies) or personal preference.\n- The user simply wants text reformatted or rewritten from what is already present in the conversation.\nWhen uncertain → **Retrieve.** Retrieval is low risk and improves grounding.\n### URL Ingestion Rules\nOnly ingest URLs when the user explicitly says:\n- "Read this link"\n- "Summarize this webpage"\n- "What does this site say?"\n- "Ingest this URL"\nIf unclear → ask a clarifying question.\n### Calculator Usage Rules\nUse the calculator when:\n- Performing arithmetic\n- Estimating totals\n- Comparing values\n- Modeling cost, time, effort, scale, or projections\nDo not perform math internally. **Call the calculator tool instead.**\n### Answer Construction Rules\n1. When asked: "What is OpenRAG", answer the following:\n"OpenRAG is an open-source package for building agentic RAG systems. It supports integration with a wide range of orchestration tools, vector databases, and LLM providers. OpenRAG connects and amplifies three popular, proven open-source projects into one powerful platform:\n**Langflow** – Langflow is a powerful tool to build and deploy AI agents and MCP servers [Read more](https://www.langflow.org/)\n**OpenSearch** – OpenSearch is a community-driven, open source search and analytics suite [Read more](https://opensearch.org/)\n**Docling** – Docling is a tool for document ingestion and semantic search [Read more](https://www.docling.ai/)"\n2. Synthesize retrieved or ingested content in your own words.\n3. Support factual claims with citations in the format:\n (Source: <document_name_or_id>)\n4. If no supporting evidence is found:\n Say: "No relevant supporting sources were found for that request."\n5. Never invent facts or hallucinate details.\n6. Be concise, direct, and confident. \n7. Do not reveal internal chain-of-thought.'@dataclass@@ -96,14 +104,14 @@ class OnboardingState:"""Onboarding state configuration."""current_step: int = 0- assistant_message: Optional[Dict[str, Any]] = field(default=None)- selected_nudge: Optional[str] = field(default=None)- card_steps: Optional[Dict[str, Any]] = field(default=None)- upload_steps: Optional[Dict[str, Any]] = field(default=None)- openrag_docs_filter_id: Optional[str] = field(default=None)- user_doc_filter_id: Optional[str] = field(default=None)- openrag_docs_ingested_version: Optional[str] = field(default=None)- openrag_docs_remote_signature: Optional[str] = field(default=None)+ assistant_message: dict[str, Any] | None = field(default=None)+ selected_nudge: str | None = field(default=None)+ card_steps: dict[str, Any] | None = field(default=None)+ upload_steps: dict[str, Any] | None = field(default=None)+ openrag_docs_filter_id: str | None = field(default=None)+ user_doc_filter_id: str | None = field(default=None)+ openrag_docs_ingested_version: str | None = field(default=None)+ openrag_docs_remote_signature: str | None = field(default=None)@dataclass@@ -117,19 +125,19 @@ class OpenRAGConfig:edited: bool = False # Track if manually edited@classmethod- def from_dict(cls, data: Dict[str, Any]) -> "OpenRAGConfig":+ def from_dict(cls, data: dict[str, Any]) -> "OpenRAGConfig":"""Create config from dictionary."""providers_data = data.get("providers", {})-+# Import inside to avoid circular dependencies if anyfrom utils.encryption import decrypt_secret-+def _decrypt_provider(p_data: dict) -> dict:new_data = dict(p_data)if "api_key" in new_data:new_data["api_key"] = decrypt_secret(new_data["api_key"])return new_data-+return cls(providers=ProvidersConfig(openai=OpenAIConfig(**_decrypt_provider(providers_data.get("openai", {}))),@@ -143,7 +151,7 @@ class OpenRAGConfig:edited=data.get("edited", False),)- def to_dict(self) -> Dict[str, Any]:+ def to_dict(self) -> dict[str, Any]:"""Convert config to dictionary."""return asdict(self)@@ -159,7 +167,7 @@ class OpenRAGConfig:class ConfigManager:"""Manages OpenRAG configuration from multiple sources."""- def __init__(self, config_file: Optional[str] = None):+ def __init__(self, config_file: str | None = None):"""Initialize configuration manager.Args:@@ -169,10 +177,9 @@ class ConfigManager:self.config_file = Path(config_file)else:from config.paths import get_config_file_path- self.config_file = Path(get_config_file_path())- self._config: Optional[OpenRAGConfig] = None-+ self.config_file = Path(get_config_file_path())+ self._config: OpenRAGConfig | None = Nonedef load_config(self) -> OpenRAGConfig:"""Load configuration from environment variables and config file.@@ -186,7 +193,7 @@ class ConfigManager:return self._config# Start with defaults- config_data = {+ config_data: dict[str, Any] = {"providers": {"openai": {},"anthropic": {},@@ -197,14 +204,14 @@ class ConfigManager:"agent": {},"onboarding": {},}-+needs_encryption_upgrade = Falsefrom utils.encryption import get_master_secret# Load from config file if it existsif self.config_file.exists():try:- with open(self.config_file, "r") as f:+ with open(self.config_file) as f:file_config = yaml.safe_load(f) or {}# Merge file config@@ -213,7 +220,11 @@ class ConfigManager:if provider in file_config["providers"]:provider_data = file_config["providers"][provider]# Check if api_key is unencrypted and we have a key- if "api_key" in provider_data and isinstance(provider_data["api_key"], str) and provider_data["api_key"]:+ if (+ "api_key" in provider_data+ and isinstance(provider_data["api_key"], str)+ and provider_data["api_key"]+ ):if get_master_secret() is not None:needs_encryption_upgrade = Trueconfig_data["providers"][provider].update(provider_data)@@ -244,7 +255,7 @@ class ConfigManager:return self._configdef _load_env_overrides(- self, config_data: Dict[str, Any], temp_config: Optional["OpenRAGConfig"] = None+ self, config_data: dict[str, Any], temp_config: Optional["OpenRAGConfig"] = None) -> None:"""Load environment variable overrides, respecting edited flag."""@@ -294,6 +305,10 @@ class ConfigManager:config_data["knowledge"]["picture_descriptions"] = os.getenv("PICTURE_DESCRIPTIONS_ENABLED").lower() in ("true", "1", "yes")+ if os.getenv("DISABLE_INGEST_WITH_LANGFLOW") is not None:+ config_data["knowledge"]["disable_ingest_with_langflow"] = os.getenv(+ "DISABLE_INGEST_WITH_LANGFLOW", "false"+ ).lower() in ("true", "1", "yes")# Agent settingsif os.getenv("LLM_MODEL"):@@ -314,7 +329,9 @@ class ConfigManager:self._config = Nonereturn self.load_config()- def save_config_file(self, config: Optional[OpenRAGConfig] = None, preserve_edited: bool = False) -> bool:+ def save_config_file(+ self, config: OpenRAGConfig | None = None, preserve_edited: bool = False+ ) -> bool:"""Save configuration to file.Args:@@ -336,11 +353,12 @@ class ConfigManager:self.config_file.parent.mkdir(parents=True, exist_ok=True)config_dict = config.to_dict()-+# Encrypt provider API keys before savingfrom utils.encryption import encrypt_secret+providers = config_dict.get("providers", {})- for provider_name, provider_config in providers.items():+ for _provider_name, provider_config in providers.items():if "api_key" in provider_config:provider_config["api_key"] = encrypt_secret(provider_config["api_key"])@@ -367,14 +385,14 @@ class ConfigManager:"""try:config = self.get_config()-+# Update only the provided fieldsfor key, value in kwargs.items():if hasattr(config.onboarding, key):setattr(config.onboarding, key, value)else:logger.warning(f"Unknown onboarding field: {key}")-+# Save the updated configreturn self.save_config_file(config)except Exception as e:diff --git a/src/config/settings.py b/src/config/settings.pyindex 6e9e4f4d9..0a30be010 100644--- a/src/config/settings.py+++ b/src/config/settings.py@@ -1210,7 +1210,9 @@ def get_agent_config():def get_embedding_model() -> str:"""Return the currently configured embedding model."""return get_openrag_config().knowledge.embedding_model or (- OPENAI_DEFAULT_EMBEDDING_MODEL if DISABLE_INGEST_WITH_LANGFLOW else ""+ OPENAI_DEFAULT_EMBEDDING_MODEL+ if get_openrag_config().knowledge.disable_ingest_with_langflow+ else "")diff --git a/src/connectors/service.py b/src/connectors/service.pyindex 88eb4aff5..838176738 100644--- a/src/connectors/service.py+++ b/src/connectors/service.py@@ -191,11 +191,15 @@ class ConnectorService:owner_user_id, jwt_token)- # Update ACL if changed (hash-based skip optimization)+ # Update ACL if changed (hash-based skip optimization).+ # Match both document_id and connector_file_id: non-Langflow connector+ # chunks store the connector id in connector_file_id (document_id holds the+ # content hash), while Langflow chunks store it in document_id.acl_result = await update_document_acl(document_id=document.id,acl=document.acl,opensearch_client=opensearch_client,+ id_fields=("document_id", "connector_file_id"),)# Log ACL update result@@ -214,7 +218,18 @@ class ConnectorService:await opensearch_client.update_by_query(index=self.index_name,body={- "query": {"term": {"document_id": document.id}},+ # Match both fields: non-Langflow chunks carry the connector id+ # in connector_file_id (document_id is the content hash),+ # Langflow chunks carry it in document_id.+ "query": {+ "bool": {+ "should": [+ {"term": {"document_id": document.id}},+ {"term": {"connector_file_id": document.id}},+ ],+ "minimum_should_match": 1,+ }+ },"script": {"source": """ctx._source.source_url = params.source_url;diff --git a/src/models/processors.py b/src/models/processors.pyindex e12081bd1..c86fce45c 100644--- a/src/models/processors.py+++ b/src/models/processors.py@@ -202,7 +202,7 @@ class TaskProcessor:chunk_size: int = None,chunk_overlap: int = None,is_sample_data: bool = False,- acl: "DocumentACL" = None,+ acl: "DocumentACL | None" = None,connector_file_id: str | None = None,):"""@@ -368,15 +368,19 @@ class TaskProcessor:if connector_file_id:chunk_doc["connector_file_id"] = connector_file_id- # Set owner and ACL fields+ # Set owner and ACL fields.+ # owner is always the syncing/uploading user (matching the Langflow+ # pipeline, which indexes owner from the OWNER global var = user id).+ # acl.owner (e.g. the SharePoint file's author) is intentionally NOT+ # used here — read access comes from allowed_users/allowed_groups + DLS,+ # while owner gates deletion and "my documents" ownership.+ chunk_doc["owner"] = owner_user_idif acl:- # Use ACL data if provided (from connector)- chunk_doc["owner"] = acl.owner if acl.owner else owner_user_id+ # Use ACL access lists if provided (from connector)chunk_doc["allowed_users"] = acl.allowed_userschunk_doc["allowed_groups"] = acl.allowed_groupselse:- # Fallback to owner_user_id if no ACL (local uploads)- chunk_doc["owner"] = owner_user_id+ # No ACL providedchunk_doc["allowed_users"] = []chunk_doc["allowed_groups"] = []@@ -435,6 +439,9 @@ class DocumentFileProcessor(TaskProcessor):is_sample_data: bool = False,connector_type: str = "local",docling_service=None,+ replace_duplicates: bool = False,+ session_manager=None,+ settings: dict | None = None,):super().__init__(document_service,@@ -448,6 +455,13 @@ class DocumentFileProcessor(TaskProcessor):self.owner_email = owner_emailself.is_sample_data = is_sample_dataself.connector_type = connector_type+ self.replace_duplicates = replace_duplicates+ self.session_manager = session_manager or (+ document_service.session_manager if document_service else None+ )+ self.settings = settings+ if self.session_manager is None:+ raise ValueError("session_manager is required for DocumentFileProcessor")async def process_item(self, upload_task: UploadTask, item: str, file_task: FileTask) -> None:"""Process a regular file path using consolidated methods"""@@ -455,6 +469,41 @@ class DocumentFileProcessor(TaskProcessor):file_task.updated_at = time.time()try:+ # Use the ORIGINAL filename stored in file_task (not the transformed temp path)+ # This ensures we check/store the original filename with spaces, etc.+ original_filename = file_task.filename or os.path.basename(item)++ # Check if document with same filename already exists+ if self.session_manager is None:+ raise ValueError("session_manager is required to get OpenSearch client")+ opensearch_client = self.session_manager.get_user_opensearch_client(+ self.owner_user_id, self.jwt_token+ )++ filename_exists = await self.check_filename_exists(original_filename, opensearch_client)++ if filename_exists and not self.replace_duplicates:+ # Duplicate exists and user hasn't confirmed replacement+ file_task.status = TaskStatus.FAILED+ file_task.error = f"File with name '{original_filename}' already exists"+ file_task.updated_at = time.time()+ upload_task.failed_files += 1+ return+ elif filename_exists and self.replace_duplicates:+ # Delete existing document before uploading new one+ logger.info(f"Replacing existing document: {original_filename}")+ await self.delete_document_by_filename(original_filename, opensearch_client)+ # Refresh index to make deletion visible before processing+ from config.settings import get_index_name++ try:+ await opensearch_client.indices.refresh(index=get_index_name())+ except Exception as refresh_error:+ logger.warning(+ "Failed to refresh index after delete",+ error=str(refresh_error),+ )+# Compute hashfile_hash = hash_id(item)@@ -464,18 +513,51 @@ class DocumentFileProcessor(TaskProcessor):except Exception:file_size = 0+ # Parse ACL from settings if present+ from connectors.base import DocumentACL++ acl = None+ if self.settings and (+ self.settings.get("allowed_users") is not None+ or self.settings.get("allowed_groups") is not None+ ):+ acl = DocumentACL(+ owner=self.owner_user_id,+ allowed_users=self.settings.get("allowed_users", []),+ allowed_groups=self.settings.get("allowed_groups", []),+ )++ standard_kwargs: dict[str, Any] = {}+ if self.settings:+ s = self.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 processingresult = await self.process_document_standard(file_path=item,file_hash=file_hash,owner_user_id=self.owner_user_id,- original_filename=os.path.basename(item),+ original_filename=original_filename,jwt_token=self.jwt_token,owner_name=self.owner_name,owner_email=self.owner_email,file_size=file_size,connector_type=self.connector_type,is_sample_data=self.is_sample_data,+ acl=acl,+ **standard_kwargs,)file_task.status = TaskStatus.COMPLETED@@ -628,7 +710,10 @@ class ConnectorFileProcessor(TaskProcessor):from config.settings import DISABLE_INGEST_WITH_LANGFLOW- if not DISABLE_INGEST_WITH_LANGFLOW:+ if (+ not DISABLE_INGEST_WITH_LANGFLOW+ and self.connector_service.langflow_service is not None+ ):# Delete existing chunks for this document before Langflow re-ingestiontry:from utils.opensearch_delete import (@@ -695,7 +780,9 @@ class ConnectorFileProcessor(TaskProcessor):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,+ docling_polling_service=self.connector_service.task_service.docling_polling_service+ if self.connector_service.task_service+ else None,file_task=file_task,document_id=document.id,source_url=document.source_url,@@ -905,6 +992,16 @@ class LangflowFileProcessor(TaskProcessor):# Delete existing document before uploading new onelogger.info(f"Replacing existing document: {original_filename}")await self.delete_document_by_filename(original_filename, opensearch_client)+ # Refresh index to make deletion visible before processing+ from config.settings import get_index_name++ try:+ await opensearch_client.indices.refresh(index=get_index_name())+ except Exception as refresh_error:+ logger.warning(+ "Failed to refresh index after delete",+ error=str(refresh_error),+ )# Read file content for processingwith open(item, "rb") as f:diff --git a/src/models/tasks.py b/src/models/tasks.pyindex 49eff03a5..7dde4bee5 100644--- a/src/models/tasks.py+++ b/src/models/tasks.py@@ -52,12 +52,12 @@ class FileTask:retry_count: int = 0created_at: float = field(default_factory=time.time)updated_at: float = field(default_factory=time.time)+ filename: str | None = None # Original filename for display# Two-phase ingestion fields. Only meaningful for processors that submit# files to Docling Serve and then trigger Langflow (i.e. LangflowFileProcessor).docling_task_id: str | None = Nonedocling_status: DoclingPhaseStatus = DoclingPhaseStatus.PENDINGphase: IngestionPhase = IngestionPhase.DOCLING- filename: str | None = None # Original filename for display@propertydef duration_seconds(self) -> float:@@ -80,6 +80,7 @@ class UploadTask:updated_at: float = field(default_factory=time.time)processor: TaskProcessor | None = field(default=None, repr=False)background_task: asyncio.Task[None] | None = field(default=None, repr=False)+ temp_file_paths: list[str] | None = field(default=None, repr=False)_sequence_number: int = field(init=False, repr=False)def __post_init__(self):diff --git a/src/services/default_docs_service.py b/src/services/default_docs_service.pyindex 304440abd..2b5774e7e 100644--- a/src/services/default_docs_service.py+++ b/src/services/default_docs_service.py@@ -21,7 +21,6 @@ from config.settings import (DEFAULT_DOCS_CRAWL_DEPTH,DEFAULT_DOCS_INGEST_SOURCE,DEFAULT_DOCS_URL,- DISABLE_INGEST_WITH_LANGFLOW,LANGFLOW_URL_INGEST_FLOW_ID,config_manager,get_index_name,@@ -67,7 +66,7 @@ async def ingest_openrag_docs_when_ready(await TelemetryClient.send_event(Category.DOCUMENT_INGESTION, MessageId.ORB_DOC_DEFAULT_URL_START)- if DISABLE_INGEST_WITH_LANGFLOW:+ if get_openrag_config().knowledge.disable_ingest_with_langflow:task_id = await _ingest_default_documents_url(document_service=document_service,models_service=models_service,@@ -111,7 +110,7 @@ async def ingest_default_documents_when_ready(try:logger.info("Ingesting default documents when ready",- disable_langflow_ingest=DISABLE_INGEST_WITH_LANGFLOW,+ disable_langflow_ingest=get_openrag_config().knowledge.disable_ingest_with_langflow,ingest_source=DEFAULT_DOCS_INGEST_SOURCE,)await TelemetryClient.send_event(@@ -144,7 +143,7 @@ async def ingest_default_documents_when_ready(if not file_paths:raise FileNotFoundError(f"No default documents found in {base_dir}")- if DISABLE_INGEST_WITH_LANGFLOW:+ if get_openrag_config().knowledge.disable_ingest_with_langflow:new_task_id = await _ingest_default_documents_openrag(document_service,models_service,@@ -233,6 +232,7 @@ async def _ingest_default_documents_langflow(replace_duplicates=True,connector_type=connector_type,existing_task_id=existing_task_id,+ temp_file_paths=[],)logger.info(@@ -540,7 +540,7 @@ async def refresh_default_openrag_docs(logger.info("Skipping OpenRAG docs refresh: URL ingestion is not active",ingest_source=DEFAULT_DOCS_INGEST_SOURCE,- disable_langflow_ingest=DISABLE_INGEST_WITH_LANGFLOW,+ disable_langflow_ingest=get_openrag_config().knowledge.disable_ingest_with_langflow,has_url_ingest_flow_id=bool(LANGFLOW_URL_INGEST_FLOW_ID),has_docs_url=bool(DEFAULT_DOCS_URL),)diff --git a/src/services/flows_service.py b/src/services/flows_service.pyindex a034371e1..8b5f5b789 100644--- a/src/services/flows_service.py+++ b/src/services/flows_service.py@@ -1,23 +1,25 @@+import asyncio+import json+import os+from datetime import datetime+from typing import Any++from cachetools import LRUCache+from config.settings import (AGENT_COMPONENT_DISPLAY_NAME,- DISABLE_INGEST_WITH_LANGFLOW,- LANGFLOW_URL_INGEST_FLOW_ID,- NUDGES_FLOW_ID,- LANGFLOW_URL,LANGFLOW_CHAT_FLOW_ID,LANGFLOW_INGEST_FLOW_ID,+ LANGFLOW_URL,+ LANGFLOW_URL_INGEST_FLOW_ID,+ NUDGES_FLOW_ID,OPENAI_EMBEDDING_COMPONENT_DISPLAY_NAME,OPENAI_LLM_COMPONENT_DISPLAY_NAME,clients,get_openrag_config,)-import json-import os-from datetime import datetimefrom utils.logging_config import get_logger-from utils.telemetry import TelemetryClient, Category, MessageId-import asyncio-from cachetools import LRUCache+from utils.telemetry import Category, MessageId, TelemetryClientlogger = get_logger(__name__)@@ -26,15 +28,23 @@ class FlowsService:async def resolve_ollama_url(self, endpoint: str, force_refresh: bool = False) -> str:"""Find the correct Ollama URL by probing candidates via Langflow's validate-provider API."""from config.config_manager import config_manager+config = config_manager.get_config()- from utils.container_utils import is_localhost_url, replace_localhost_patterns, get_container_host, transform_localhost_url+ from utils.container_utils import (+ get_container_host,+ is_localhost_url,+ replace_localhost_patterns,+ transform_localhost_url,+ )# If not forcing, check if we already have a resolved endpoint for this original endpointif not force_refresh and config.providers.ollama.resolved_endpoint:# We only use the cached one if the original endpoint is still a localhost oneif is_localhost_url(endpoint):- logger.debug(f"Using cached resolved Ollama URL: {config.providers.ollama.resolved_endpoint}")+ logger.debug(+ f"Using cached resolved Ollama URL: {config.providers.ollama.resolved_endpoint}"+ )return config.providers.ollama.resolved_endpointif not is_localhost_url(endpoint):@@ -53,8 +63,9 @@ class FlowsService:logger.debug(f"Probing Ollama candidate via Langflow: {test_url}")try:response = await clients.langflow_request(- "POST", "/api/v1/models/validate-provider",- json={"provider": "Ollama", "variables": {"OLLAMA_BASE_URL": test_url}}+ "POST",+ "/api/v1/models/validate-provider",+ json={"provider": "Ollama", "variables": {"OLLAMA_BASE_URL": test_url}},)if response.status_code in (200, 201) and response.json().get("valid"):logger.info(f"Resolved Ollama URL via Langflow: {test_url}")@@ -98,11 +109,13 @@ class FlowsService:def _get_flows_directory(self):"""Get the flows directory path"""from config.paths import get_flows_path+return get_flows_path()def _get_backup_directory(self):"""Get the backup directory path"""from config.paths import get_flows_backup_path+backup_dir = get_flows_backup_path()os.makedirs(backup_dir, exist_ok=True)return backup_dir@@ -207,7 +220,7 @@ class FlowsService:"flow_type": flow_type,"flow_id": flow_id,"error": f"HTTP {response.status_code}",- }+ },}current_flow = response.json()@@ -228,13 +241,13 @@ class FlowsService:"flow_type": flow_type,"flow_id": flow_id,"reason": "locked_without_backups",- }+ },}# Check if we need to backup (only if changed)if only_if_changed and has_backups:try:- with open(latest_backup_path, "r") as f:+ with open(latest_backup_path) as f:latest_backup = json.load(f)# Compare flows@@ -248,7 +261,7 @@ class FlowsService:"flow_type": flow_type,"flow_id": flow_id,"reason": "unchanged",- }+ },}except Exception as e:logger.warning(@@ -264,7 +277,7 @@ class FlowsService:"flow_type": flow_type,"flow_id": flow_id,"backup_path": backup_path,- }+ },}else:return {@@ -273,19 +286,17 @@ class FlowsService:"flow_type": flow_type,"flow_id": flow_id,"error": "Backup returned None",- }+ },}except Exception as e:- logger.error(- f"Failed to backup {flow_type} flow (ID: {flow_id}): {str(e)}"- )+ logger.error(f"Failed to backup {flow_type} flow (ID: {flow_id}): {str(e)}")return {"type": "failed","data": {"flow_type": flow_type,"flow_id": flow_id,"error": str(e),- }+ },}tasks = [backup_single_flow(ft, fi) for ft, fi in flow_configs]@@ -307,9 +318,13 @@ class FlowsService:# Send telemetry eventif backup_results["failed"]:- await TelemetryClient.send_event(Category.FLOW_OPERATIONS, MessageId.ORB_FLOW_BACKUP_FAILED)+ await TelemetryClient.send_event(+ Category.FLOW_OPERATIONS, MessageId.ORB_FLOW_BACKUP_FAILED+ )else:- await TelemetryClient.send_event(Category.FLOW_OPERATIONS, MessageId.ORB_FLOW_BACKUP_COMPLETE)+ await TelemetryClient.send_event(+ Category.FLOW_OPERATIONS, MessageId.ORB_FLOW_BACKUP_COMPLETE+ )return backup_results@@ -399,7 +414,7 @@ class FlowsService:file_path = os.path.join(flows_dir, filename)try:- with open(file_path, "r") as f:+ with open(file_path) as f:flow_data = json.load(f)# Check if this file contains the flow we're looking for@@ -456,15 +471,15 @@ class FlowsService:# Load flow JSON filetry:- with open(flow_path, "r") as f:+ with open(flow_path) as f:flow_data = json.load(f)logger.info(f"Successfully loaded flow data for {flow_type} from {os.path.basename(flow_path)}")except json.JSONDecodeError as e:- raise ValueError(f"Invalid JSON in flow file {flow_path}: {e}")- except FileNotFoundError:- raise ValueError(f"Flow file not found: {flow_path}")+ raise ValueError(f"Invalid JSON in flow file {flow_path}: {e}") from e+ except FileNotFoundError as e:+ raise ValueError(f"Flow file not found: {flow_path}") from e# Make PATCH request to Langflow API to update the flow using shared clienttry:@@ -473,7 +488,6 @@ class FlowsService:)if response.status_code == 200:- result = response.json()logger.info(f"Successfully reset {flow_type} flow",flow_id=flow_id,@@ -495,7 +509,7 @@ class FlowsService:{"name": flow_type, "flow_id": flow_id},config.agent.llm_provider.lower(),llm_model=config.agent.llm_model,- force_llm_update=True+ force_llm_update=True,)# Update all configured embedding providers@@ -509,12 +523,16 @@ class FlowsService:current_emb_provider = config.knowledge.embedding_provider.lower()for provider in embedding_providers:- model = config.knowledge.embedding_model if provider == current_emb_provider else None+ model = (+ config.knowledge.embedding_model+ if provider == current_emb_provider+ else None+ )await self._update_provider_components({"name": flow_type, "flow_id": flow_id},provider,embedding_model=model,- force_embedding_update=True+ force_embedding_update=True,)if update_result.get("success"):@@ -607,7 +625,9 @@ class FlowsService:return "Anthropic"return "OpenAI"- async def _update_flow_field(self, flow_id: str, field_name: str, field_value: str, node_display_name: str = None):+ async def _update_flow_field(+ self, flow_id: str, field_name: str, field_value: Any, node_display_name: str = None+ ):"""Generic helper function to update any field in any Langflow component.@@ -625,9 +645,7 @@ class FlowsService:response = await clients.langflow_request("GET", f"/api/v1/flows/{flow_id}")if response.status_code != 200:- raise Exception(- f"Failed to get flow: HTTP {response.status_code} - {response.text}"- )+ raise Exception(f"Failed to get flow: HTTP {response.status_code} - {response.text}")flow_data = response.json()@@ -645,9 +663,22 @@ class FlowsService:# Update the field value directly in the existing nodetemplate = target_node.get("data", {}).get("node", {}).get("template", {})if template.get(field_name):- flow_data["data"]["nodes"][target_node_index]["data"]["node"]["template"][field_name]["value"] = field_value- if "options" in flow_data["data"]["nodes"][target_node_index]["data"]["node"]["template"][field_name] and field_value not in flow_data["data"]["nodes"][target_node_index]["data"]["node"]["template"][field_name]["options"]:- flow_data["data"]["nodes"][target_node_index]["data"]["node"]["template"][field_name]["options"].append(field_value)+ flow_data["data"]["nodes"][target_node_index]["data"]["node"]["template"][field_name][+ "value"+ ] = field_value+ if (+ "options"+ in flow_data["data"]["nodes"][target_node_index]["data"]["node"]["template"][+ field_name+ ]+ and field_value+ not in flow_data["data"]["nodes"][target_node_index]["data"]["node"]["template"][+ field_name+ ]["options"]+ ):+ flow_data["data"]["nodes"][target_node_index]["data"]["node"]["template"][+ field_name+ ]["options"].append(field_value)else:identifier = node_display_nameraise Exception(f"{field_name} field not found in {identifier} component")@@ -670,8 +701,9 @@ class FlowsService:# Determine target component IDs based on providertarget_llm_id = self._get_provider_component_ids(provider)[1]- await self._update_flow_field(LANGFLOW_CHAT_FLOW_ID, "model_name", model_name,- node_display_name=target_llm_id)+ await self._update_flow_field(+ LANGFLOW_CHAT_FLOW_ID, "model_name", model_name, node_display_name=target_llm_id+ )async def update_chat_flow_system_prompt(self, system_prompt: str, provider: str):"""Helper function to update the system prompt in the chat flow"""@@ -681,8 +713,9 @@ class FlowsService:# Determine target component IDs based on providertarget_agent_id = self._get_provider_component_ids(provider)[1]- await self._update_flow_field(LANGFLOW_CHAT_FLOW_ID, "system_prompt", system_prompt,- node_display_name=target_agent_id)+ await self._update_flow_field(+ LANGFLOW_CHAT_FLOW_ID, "system_prompt", system_prompt, node_display_name=target_agent_id+ )async def update_flow_docling_preset(self, preset: str, preset_config: dict):"""Helper function to update docling preset in the ingest flow"""@@ -690,8 +723,13 @@ class FlowsService:raise ValueError("LANGFLOW_INGEST_FLOW_ID is not configured")from config.settings import DOCLING_COMPONENT_DISPLAY_NAME- await self._update_flow_field(LANGFLOW_INGEST_FLOW_ID, "docling_serve_opts", preset_config,- node_display_name=DOCLING_COMPONENT_DISPLAY_NAME)++ await self._update_flow_field(+ LANGFLOW_INGEST_FLOW_ID,+ "docling_serve_opts",+ preset_config,+ node_display_name=DOCLING_COMPONENT_DISPLAY_NAME,+ )async def update_ingest_flow_chunk_size(self, chunk_size: int):"""Helper function to update chunk size in the ingest flow"""@@ -723,8 +761,9 @@ class FlowsService:# Determine target component IDs based on providertarget_embedding_id = self._get_provider_component_ids(provider)[0]- await self._update_flow_field(LANGFLOW_INGEST_FLOW_ID, "model", embedding_model,- node_display_name=target_embedding_id)+ await self._update_flow_field(+ LANGFLOW_INGEST_FLOW_ID, "model", embedding_model, node_display_name=target_embedding_id+ )def _replace_node_in_flow(self, flow_data, old_display_name, new_node):"""Replace a node in the flow data"""@@ -741,12 +780,7 @@ class FlowsService:Keeps structural elements: nodes (types, display names, templates), edges (connections).Removes: IDs, timestamps, positions, etc. but keeps template structure."""- normalized = {- "data": {- "nodes": [],- "edges": []- }- }+ normalized = {"data": {"nodes": [], "edges": []}}# Normalize nodes - keep structural info including templatesnodes = flow_data.get("data", {}).get("nodes", [])@@ -764,7 +798,7 @@ class FlowsService:"base_classes": node_template.get("base_classes", []),"template": node_template.get("template", {}), # Include template structure}- }+ },}normalized["data"]["nodes"].append(normalized_node)@@ -790,7 +824,9 @@ class FlowsService:# Get flow from Langflow APIresponse = await clients.langflow_request("GET", f"/api/v1/flows/{flow_id}")if response.status_code != 200:- logger.warning(f"Failed to get flow {flow_id} from Langflow: HTTP {response.status_code}")+ logger.warning(+ f"Failed to get flow {flow_id} from Langflow: HTTP {response.status_code}"+ )return Falselangflow_flow = response.json()@@ -801,7 +837,7 @@ class FlowsService:logger.warning(f"Flow file not found for flow ID: {flow_id}")return False- with open(flow_path, "r") as f:+ with open(flow_path) as f:file_flow = json.load(f)# Normalize both flows for comparison@@ -812,20 +848,29 @@ class FlowsService:# Sort nodes and edges for consistent comparisonnormalized_langflow["data"]["nodes"] = sorted(normalized_langflow["data"]["nodes"],- key=lambda x: (x.get("id", ""), x.get("type", ""))+ key=lambda x: (x.get("id", ""), x.get("type", "")),)normalized_file["data"]["nodes"] = sorted(- normalized_file["data"]["nodes"],- key=lambda x: (x.get("id", ""), x.get("type", ""))+ normalized_file["data"]["nodes"], key=lambda x: (x.get("id", ""), x.get("type", "")))normalized_langflow["data"]["edges"] = sorted(normalized_langflow["data"]["edges"],- key=lambda x: (x.get("source", ""), x.get("target", ""), x.get("sourceHandle", ""), x.get("targetHandle", ""))+ key=lambda x: (+ x.get("source", ""),+ x.get("target", ""),+ x.get("sourceHandle", ""),+ x.get("targetHandle", ""),+ ),)normalized_file["data"]["edges"] = sorted(normalized_file["data"]["edges"],- key=lambda x: (x.get("source", ""), x.get("target", ""), x.get("sourceHandle", ""), x.get("targetHandle", ""))+ key=lambda x: (+ x.get("source", ""),+ x.get("target", ""),+ x.get("sourceHandle", ""),+ x.get("targetHandle", ""),+ ),)# Compare entire normalized structures@@ -861,9 +906,7 @@ class FlowsService:if not flow_id:return Nonetry:- response = await clients.langflow_request(- "GET", f"/api/v1/flows/{flow_id}"- )+ response = await clients.langflow_request("GET", f"/api/v1/flows/{flow_id}")if response.status_code == 200:logger.info(f"Flow {flow_type} (ID: {flow_id}) already exists, skipping creation"@@ -884,7 +927,7 @@ class FlowsService:)return None- with open(flow_path, "r") as f:+ with open(flow_path) as f:flow_data = json.load(f)response = await clients.langflow_request(@@ -902,9 +945,7 @@ class FlowsService:)return Noneexcept Exception as e:- logger.error(- f"Error ensuring {flow_type} flow (ID: {flow_id}) exists: {e}"- )+ logger.error(f"Error ensuring {flow_type} flow (ID: {flow_id}) exists: {e}")return Nonetasks = [ensure_single_flow_exists(ft, fi) for ft, fi in flow_configs]@@ -992,7 +1033,7 @@ class FlowsService:# Process all flows simultaneouslyraw_results = await asyncio.gather(*tasks, return_exceptions=True)- results = []+ results: list[Any] = []for i, result in enumerate(raw_results):if isinstance(result, Exception):flow_name = flow_configs[i]["name"]@@ -1009,8 +1050,6 @@ class FlowsService:logger.error(f"Error in change_langflow_model_value: {str(e)}")return {"success": False, "error": str(e)}--async def _update_provider_components(self,config,@@ -1044,26 +1083,40 @@ class FlowsService:return None# Update embedding component- if not DISABLE_INGEST_WITH_LANGFLOW and (embedding_model or force_embedding_update):+ if not get_openrag_config().knowledge.disable_ingest_with_langflow and (+ embedding_model or force_embedding_update+ ):# Get all embedding nodes in the flow- embedding_nodes = self._find_nodes_in_flow(flow_data, display_name=OPENAI_EMBEDDING_COMPONENT_DISPLAY_NAME)- logger.info(f"Found {len(embedding_nodes)} embedding nodes in flow {flow_name} with display name '{OPENAI_EMBEDDING_COMPONENT_DISPLAY_NAME}'")+ embedding_nodes = self._find_nodes_in_flow(+ flow_data, display_name=OPENAI_EMBEDDING_COMPONENT_DISPLAY_NAME+ )+ logger.info(+ f"Found {len(embedding_nodes)} embedding nodes in flow {flow_name} with display name '{OPENAI_EMBEDDING_COMPONENT_DISPLAY_NAME}'"+ )# Count configured embedding-enabled providersconfig_obj = get_openrag_config()configured_providers = []- if config_obj.providers.openai.configured: configured_providers.append("openai")- if config_obj.providers.watsonx.configured: configured_providers.append("watsonx")- if config_obj.providers.ollama.configured: configured_providers.append("ollama")+ if config_obj.providers.openai.configured:+ configured_providers.append("openai")+ if config_obj.providers.watsonx.configured:+ configured_providers.append("watsonx")+ if config_obj.providers.ollama.configured:+ configured_providers.append("ollama")# Ensure current provider is in the list for counting purposes if it's being configured- if provider in ["openai", "watsonx", "ollama"] and provider not in configured_providers:+ if (+ provider in ["openai", "watsonx", "ollama"]+ and provider not in configured_providers+ ):configured_providers.append(provider)all_possible = ["openai", "watsonx", "ollama"]configured_providers = [p for p in all_possible if p in configured_providers]provider_count = len(configured_providers)- logger.info(f"Configured embedding providers: {configured_providers} (count: {provider_count})")+ logger.info(+ f"Configured embedding providers: {configured_providers} (count: {provider_count})"+ )# 1. Check if any node is already this provider - always update those firstmatched_nodes = []@@ -1073,41 +1126,84 @@ class FlowsService:matched_nodes.append((node, idx))if matched_nodes:- logger.info(f"Found {len(matched_nodes)} nodes already configured for provider '{provider}'")- for node, idx in matched_nodes:- node_tasks.append(wrap_node_update(node, provider, embedding_model, f"embedding model: {embedding_model} (updated existing {provider} node)"))+ logger.info(+ f"Found {len(matched_nodes)} nodes already configured for provider '{provider}'"+ )+ for node, _idx in matched_nodes:+ node_tasks.append(+ wrap_node_update(+ node,+ provider,+ embedding_model,+ f"embedding model: {embedding_model} (updated existing {provider} node)",+ )+ )else:# 2. No existing node matched, use slot-based logictry:p_index = configured_providers.index(provider)- logger.info(f"Using slot-based logic for provider '{provider}' (p_index: {p_index}, total configured: {provider_count})")+ logger.info(+ f"Using slot-based logic for provider '{provider}' (p_index: {p_index}, total configured: {provider_count})"+ )if provider_count == 1:# Single provider mode: update all available nodes (up to 3)- logger.info(f"Single provider mode: updating all available embedding nodes (available: {len(embedding_nodes)})")+ logger.info(+ f"Single provider mode: updating all available embedding nodes (available: {len(embedding_nodes)})"+ )for i in range(min(3, len(embedding_nodes))):node, idx = embedding_nodes[i]- node_tasks.append(wrap_node_update(node, provider, embedding_model, f"embedding model: {embedding_model} (set node {i+1})"))+ node_tasks.append(+ wrap_node_update(+ node,+ provider,+ embedding_model,+ f"embedding model: {embedding_model} (set node {i + 1})",+ )+ )else:# Multiple providers: each gets one slot based on its list indexif p_index < len(embedding_nodes):node, idx = embedding_nodes[p_index]- logger.info(f"Multiple provider mode: assigning provider '{provider}' to node slot {p_index} (node {p_index+1})")- node_tasks.append(wrap_node_update(node, provider, embedding_model, f"embedding model: {embedding_model} (set node {p_index+1})"))+ logger.info(+ f"Multiple provider mode: assigning provider '{provider}' to node slot {p_index} (node {p_index + 1})"+ )+ node_tasks.append(+ wrap_node_update(+ node,+ provider,+ embedding_model,+ f"embedding model: {embedding_model} (set node {p_index + 1})",+ )+ )else:- logger.info(f"Provider index {p_index} exceeds available embedding nodes ({len(embedding_nodes)}) - skipping automatic assignment")+ logger.info(+ f"Provider index {p_index} exceeds available embedding nodes ({len(embedding_nodes)}) - skipping automatic assignment"+ )except ValueError:- logger.warning(f"Current provider '{provider}' not found in configured providers list: {configured_providers}")+ logger.warning(+ f"Current provider '{provider}' not found in configured providers list: {configured_providers}"+ )# Update LLM component (if exists in this flow)if llm_model or force_llm_update:- llm_node, _ = self._find_node_in_flow(flow_data, display_name=OPENAI_LLM_COMPONENT_DISPLAY_NAME)+ llm_node, _ = self._find_node_in_flow(+ flow_data, display_name=OPENAI_LLM_COMPONENT_DISPLAY_NAME+ )if llm_node:- node_tasks.append(wrap_node_update(llm_node, provider, llm_model, f"llm model: {llm_model}"))-- agent_node, _ = self._find_node_in_flow(flow_data, display_name=AGENT_COMPONENT_DISPLAY_NAME)+ node_tasks.append(+ wrap_node_update(llm_node, provider, llm_model, f"llm model: {llm_model}")+ )++ agent_node, _ = self._find_node_in_flow(+ flow_data, display_name=AGENT_COMPONENT_DISPLAY_NAME+ )if agent_node:- node_tasks.append(wrap_node_update(agent_node, provider, llm_model, f"agent model: {llm_model}"))+ node_tasks.append(+ wrap_node_update(+ agent_node, provider, llm_model, f"agent model: {llm_model}"+ )+ )# Execute all node updates simultaneouslyif node_tasks:@@ -1142,7 +1238,7 @@ class FlowsService:"flow_id": flow_id,}- async def _update_component_langflow(self, template, model: str):+ async def _update_component_langflow(self, template, model: Any):# Call custom_component/update endpoint to get updated template# Only call if code field exists (custom components should have code)if "code" in template and "value" in template["code"]:@@ -1200,26 +1296,35 @@ class FlowsService:# Enable the model in Langflow firstawait self._enable_model_in_langflow(provider_name, model_value)# Update template via Langflow API to get latest options- template = await self._update_component_langflow(template, template["model"]["value"]) or template+ template = (+ await self._update_component_langflow(template, template["model"]["value"])+ or template+ )component_node["data"]["node"]["template"] = template# Find the specific model option for the providerif model_value:model_options = [- item for item in template["model"].get("options", [])+ item+ for item in template["model"].get("options", [])if item.get("provider") == provider_name and item.get("name") == model_value]else:# If no specific model provided, pick the first available one for this providermodel_options = [- item for item in template["model"].get("options", [])+ item+ for item in template["model"].get("options", [])if item.get("provider") == provider_name][:1]if model_options:- logger.info(f"Using first available model '{model_options[0].get('name')}' for provider {provider_name}")+ logger.info(+ f"Using first available model '{model_options[0].get('name')}' for provider {provider_name}"+ )if not model_options:- logger.warning(f"Model {model_value or 'ANY'} not found for provider {provider_name}")+ logger.warning(+ f"Model {model_value or 'ANY'} not found for provider {provider_name}"+ )return Falsetemplate["model"]["value"] = model_options@@ -1271,12 +1376,18 @@ class FlowsService:enabled_data = Noneasync with self._enabled_models_lock:# Check if cache is still valid- if (self._enabled_models_cache and self._enabled_models_cache_time and- (datetime.now() - self._enabled_models_cache_time).total_seconds() < self._enabled_models_cache_ttl):+ if (+ self._enabled_models_cache+ and self._enabled_models_cache_time+ and (datetime.now() - self._enabled_models_cache_time).total_seconds()+ < self._enabled_models_cache_ttl+ ):enabled_data = self._enabled_models_cacheelse:# Cache miss or stale, fetch from Langflow- get_response = await clients.langflow_request("GET", "/api/v1/models/enabled_models")+ get_response = await clients.langflow_request(+ "GET", "/api/v1/models/enabled_models"+ )if get_response.status_code == 200:enabled_data = get_response.json().get("enabled_models", {})self._enabled_models_cache = enabled_data@@ -1286,21 +1397,21 @@ class FlowsService:if enabled_data:provider_models = enabled_data.get(provider_name, {})if provider_models.get(model_value) is True:- logger.info(f"Model {model_value} for provider {provider_name} is already enabled. Skipping.")+ logger.info(+ f"Model {model_value} for provider {provider_name} is already enabled. Skipping."+ )return False- enable_payload = [{- "provider": provider_name,- "model_id": model_value,- "enabled": True- }]+ enable_payload = [{"provider": provider_name, "model_id": model_value, "enabled": True}]response = await clients.langflow_request("POST", "/api/v1/models/enabled_models", json=enable_payload)if response.status_code == 200:- logger.info(f"Successfully enabled model {model_value} for provider {provider_name}")+ logger.info(+ f"Successfully enabled model {model_value} for provider {provider_name}"+ )async with self._enabled_models_lock:self._enabled_models_cache = Nonereturn True@@ -1317,13 +1428,14 @@ class FlowsService:def _get_provider_component_ids(self, provider: str):"""Helper to get component display names for various providers."""from config.settings import (+ OLLAMA_EMBEDDING_COMPONENT_DISPLAY_NAME,+ OLLAMA_LLM_COMPONENT_DISPLAY_NAME,OPENAI_EMBEDDING_COMPONENT_DISPLAY_NAME,OPENAI_LLM_COMPONENT_DISPLAY_NAME,WATSONX_EMBEDDING_COMPONENT_DISPLAY_NAME,WATSONX_LLM_COMPONENT_DISPLAY_NAME,- OLLAMA_EMBEDDING_COMPONENT_DISPLAY_NAME,- OLLAMA_LLM_COMPONENT_DISPLAY_NAME,)+if provider == "openai":return (OPENAI_EMBEDDING_COMPONENT_DISPLAY_NAME, OPENAI_LLM_COMPONENT_DISPLAY_NAME)elif provider == "watsonx":diff --git a/src/services/startup_orchestrator.py b/src/services/startup_orchestrator.pyindex 6a3a94ad8..6b3eef162 100644--- a/src/services/startup_orchestrator.py+++ b/src/services/startup_orchestrator.py@@ -7,7 +7,6 @@ server URLs, and reapplies user settings if Langflow flows were reset."""from config.settings import (- DISABLE_INGEST_WITH_LANGFLOW,FETCH_OPENRAG_DOCS_AT_STARTUP,OPENRAG_BOOTSTRAP_OS_SECURITY_ON_STARTUP,OPENRAG_SKIP_OS_SECURITY_SETUP,@@ -94,7 +93,7 @@ async def startup_tasks(services):error=str(e),)- if DISABLE_INGEST_WITH_LANGFLOW:+ if get_openrag_config().knowledge.disable_ingest_with_langflow:await _ensure_opensearch_index()# Ensure that the OpenSearch index exists if onboarding was already completeddiff --git a/src/services/task_service.py b/src/services/task_service.pyindex 48a590a87..4935a9220 100644--- a/src/services/task_service.py+++ b/src/services/task_service.py@@ -136,10 +136,12 @@ class TaskService:ingestion_timeout=3600,docling_service=None,docling_polling_service=None,+ session_manager=None,):self.document_service = document_serviceself.models_service = models_serviceself.docling_service = docling_service+ self.session_manager = session_manager# Backend-side Docling polling coordinator. Injected by the container# so LangflowFileProcessor receives it from the established DI chain# rather than constructing it inline. None disables the two-phase@@ -226,6 +228,9 @@ class TaskService:jwt_token: str = None,owner_name: str = None,owner_email: str = None,+ original_filenames: dict | None = None,+ replace_duplicates: bool = False,+ settings: dict | None = None,) -> str:"""Create a new upload task for bulk file processing"""# Use default DocumentFileProcessor with user context@@ -239,8 +244,17 @@ class TaskService:owner_name=owner_name,owner_email=owner_email,docling_service=self.docling_service,+ replace_duplicates=replace_duplicates,+ session_manager=self.session_manager,+ settings=settings,+ )+ return await self.create_custom_task(+ user_id,+ file_paths,+ processor,+ original_filenames=original_filenames,+ temp_file_paths=file_paths,)- return await self.create_custom_task(user_id, file_paths, processor)async def create_langflow_upload_task(self,@@ -258,6 +272,7 @@ class TaskService:replace_duplicates: bool = False,connector_type: str = "local",existing_task_id: str = None,+ temp_file_paths: list | None = None,) -> str:"""Create a new upload task for Langflow file processing with upload and ingest"""# Use LangflowFileProcessor with user context@@ -278,7 +293,12 @@ class TaskService:docling_polling_service=self.docling_polling_service,)return await self.create_custom_task(- user_id, file_paths, processor, original_filenames, existing_task_id=existing_task_id+ user_id,+ file_paths,+ processor,+ original_filenames,+ existing_task_id=existing_task_id,+ temp_file_paths=temp_file_paths if temp_file_paths is not None else file_paths,)async def create_langflow_url_upload_task(@@ -323,6 +343,7 @@ class TaskService:processor,original_filenames: dict | None = None,existing_task_id: str = None,+ temp_file_paths: list | None = None,) -> str:"""Create a new task with custom processor for any type of items"""import os@@ -363,6 +384,12 @@ class TaskService:self.task_store[store_user_id] = {}self.task_store[store_user_id][task_id] = upload_task+ # Store temp file paths for cleanup after processing+ if temp_file_paths:+ if upload_task.temp_file_paths is None:+ upload_task.temp_file_paths = []+ upload_task.temp_file_paths.extend(temp_file_paths)+# Start background processingbackground_task = asyncio.create_task(self.background_custom_processor(store_user_id, task_id, items, processor)@@ -567,6 +594,21 @@ class TaskService:upload_task.status = TaskStatus.COMPLETEDupload_task.updated_at = time.time()+ # Clean up temp files after all processing is complete+ if hasattr(upload_task, "temp_file_paths") and upload_task.temp_file_paths:+ from utils.file_utils import safe_unlink++ for temp_path in upload_task.temp_file_paths:+ try:+ safe_unlink(temp_path)+ logger.debug("Cleaned up temp file", temp_path=temp_path)+ except Exception as cleanup_error:+ logger.warning(+ "Failed to clean up temp file after processing",+ temp_path=temp_path,+ error=str(cleanup_error),+ )+status: str = "FAILED"if upload_task.failed_files == 0:diff --git a/src/session_manager.py b/src/session_manager.pyindex a57a52928..faf553e25 100644--- a/src/session_manager.py+++ b/src/session_manager.py@@ -2,7 +2,7 @@ import osimport timefrom dataclasses import dataclassfrom datetime import datetime, timedelta-from typing import Any, Union+from typing import Anyimport httpximport jwt@@ -313,7 +313,7 @@ class SessionManager:if IBM_AUTH_ENABLED and jwt_token:return jwt_token- if jwt_token is not None:+ if jwt_token is not None and isinstance(jwt_token, str) and jwt_token.strip():return jwt_token# No token — create onediff --git a/src/utils/acl_utils.py b/src/utils/acl_utils.pyindex 5ffa56f31..13d79e79c 100644--- a/src/utils/acl_utils.py+++ b/src/utils/acl_utils.py@@ -5,10 +5,11 @@ This module provides hash-based ACL change detection and bulk update operationsto minimize write amplification when ACLs change."""+import asyncioimport hashlibimport json-import asyncio-from typing import Dict, List, Tuple, Optional+from typing import Any+from src.connectors.base import DocumentACLfrom utils.logging_config import get_logger@@ -30,15 +31,32 @@ def compute_acl_hash(acl: DocumentACL) -> str:"allowed_users": sorted(acl.allowed_users),"allowed_groups": sorted(acl.allowed_groups),}- return hashlib.sha256(- json.dumps(acl_data, sort_keys=True).encode()- ).hexdigest()+ return hashlib.sha256(json.dumps(acl_data, sort_keys=True).encode()).hexdigest()+++def _build_id_query(document_id: str, id_fields: tuple[str, ...]) -> dict:+ """Build an OpenSearch query matching ``document_id`` against one or more fields.++ Non-Langflow connector chunks store the connector source id in+ ``connector_file_id`` while ``document_id`` holds the content hash, whereas+ Langflow chunks and local uploads store the id in ``document_id``. Matching+ multiple fields lets a single id reliably target chunks from either pipeline.+ """+ if len(id_fields) == 1:+ return {"term": {id_fields[0]: document_id}}+ return {+ "bool": {+ "should": [{"term": {field: document_id}} for field in id_fields],+ "minimum_should_match": 1,+ }+ }async def should_update_acl(document_id: str,new_acl: DocumentACL,- opensearch_client+ opensearch_client,+ id_fields: tuple[str, ...] = ("document_id",),) -> bool:"""Check if ACL has changed by querying one chunk and comparing hashes.@@ -59,14 +77,14 @@ async def should_update_acl(response = await opensearch_client.search(index="documents",body={- "query": {"term": {"document_id": document_id}},+ "query": _build_id_query(document_id, id_fields),"size": 1,"_source": ["owner","allowed_users","allowed_groups",- ]- }+ ],+ },)if not response["hits"]["hits"]:@@ -96,24 +114,34 @@ async def should_update_acl(async def update_document_acl(document_id: str,acl: DocumentACL,- opensearch_client-) -> Dict[str, any]:+ opensearch_client,+ id_fields: tuple[str, ...] = ("document_id",),+) -> dict[str, Any]:"""Update ACL for all chunks of a document.Uses hash-based skip optimization: queries one chunk to check if ACL changed,only updates if changed. When updating, uses bulk update_by_query for efficiency.+ Only the access lists (``allowed_users``/``allowed_groups``) are updated — the+ ``owner`` field is intentionally left untouched so an ACL re-sync never+ reassigns document ownership (owner is set once at ingest to the syncing user).+Args:document_id: Document identifieracl: New ACL to applyopensearch_client: OpenSearch client instance+ id_fields: Chunk fields to match ``document_id`` against. Defaults to+ ``("document_id",)``; pass ``("document_id", "connector_file_id")`` for+ connector chunks where the connector id lives in ``connector_file_id``.Returns:Dict with status ("unchanged" or "updated") and chunks_updated count"""# Check if ACL changed (queries one chunk)- should_update = await should_update_acl(document_id, acl, opensearch_client)+ should_update = await should_update_acl(+ document_id, acl, opensearch_client, id_fields=id_fields+ )if not should_update:return {"status": "unchanged", "chunks_updated": 0}@@ -123,26 +151,21 @@ async def update_document_acl(response = await opensearch_client.update_by_query(index="documents",body={- "query": {"term": {"document_id": document_id}},+ "query": _build_id_query(document_id, id_fields),"script": {"source": """- ctx._source.owner = params.owner;ctx._source.allowed_users = params.allowed_users;ctx._source.allowed_groups = params.allowed_groups;""","params": {- "owner": acl.owner,"allowed_users": acl.allowed_users,"allowed_groups": acl.allowed_groups,- }- }- }+ },+ },+ },)- return {- "status": "updated",- "chunks_updated": response.get("updated", 0)- }+ return {"status": "updated", "chunks_updated": response.get("updated", 0)}except Exception as e:logger.error("[OPENSEARCH] ACL update failed", document_id=document_id, error=str(e))@@ -150,9 +173,10 @@ async def update_document_acl(async def batch_update_acls(- acl_updates: List[Tuple[str, DocumentACL]],- opensearch_client-) -> Dict[str, any]:+ acl_updates: list[tuple[str, DocumentACL]],+ opensearch_client,+ id_fields: tuple[str, ...] = ("document_id",),+) -> dict[str, Any]:"""Batch update ACLs for multiple documents.@@ -161,9 +185,14 @@ async def batch_update_acls(- Skip unchanged ACLs (95%+ of webhook notifications)- Parallel bulk updates for changed ACLs+ Only ``allowed_users``/``allowed_groups`` are updated; ``owner`` is left+ untouched (see :func:`update_document_acl`).+Args:acl_updates: List of (document_id, acl) tuplesopensearch_client: OpenSearch client instance+ id_fields: Chunk fields to match the id against (see+ :func:`update_document_acl`).Returns:Dict with status, documents_updated count, and chunks_updated count@@ -173,7 +202,7 @@ async def batch_update_acls(# Filter to only changed ACLs (parallel chunk queries)check_tasks = [- should_update_acl(doc_id, acl, opensearch_client)+ should_update_acl(doc_id, acl, opensearch_client, id_fields=id_fields)for doc_id, acl in acl_updates]should_update_flags = await asyncio.gather(*check_tasks)@@ -181,7 +210,7 @@ async def batch_update_acls(# Filter to documents with changed ACLschanged = [(doc_id, acl)- for (doc_id, acl), should_update in zip(acl_updates, should_update_flags)+ for (doc_id, acl), should_update in zip(acl_updates, should_update_flags, strict=True)if should_update]@@ -190,7 +219,7 @@ async def batch_update_acls("status": "no_changes","documents_updated": 0,"chunks_updated": 0,- "skipped": len(acl_updates)+ "skipped": len(acl_updates),}# Bulk update chunks for each document (parallelized)@@ -198,20 +227,18 @@ async def batch_update_acls(opensearch_client.update_by_query(index="documents",body={- "query": {"term": {"document_id": doc_id}},+ "query": _build_id_query(doc_id, id_fields),"script": {"source": """- ctx._source.owner = params.owner;ctx._source.allowed_users = params.allowed_users;ctx._source.allowed_groups = params.allowed_groups;""","params": {- "owner": acl.owner,"allowed_users": acl.allowed_users,"allowed_groups": acl.allowed_groups,- }- }- }+ },+ },+ },)for doc_id, acl in changed]@@ -222,8 +249,8 @@ async def batch_update_acls(# Count successful updatestotal_chunks_updated = 0errors = []- for i, result in enumerate(results):- if isinstance(result, Exception):+ for result in results:+ if isinstance(result, BaseException):errors.append(str(result))else:total_chunks_updated += result.get("updated", 0)@@ -233,13 +260,8 @@ async def batch_update_acls("documents_updated": len(changed) - len(errors),"chunks_updated": total_chunks_updated,"skipped": len(acl_updates) - len(changed),- "errors": errors if errors else None+ "errors": errors if errors else None,}except Exception as e:- return {- "status": "error",- "documents_updated": 0,- "chunks_updated": 0,- "error": str(e)- }+ return {"status": "error", "documents_updated": 0, "chunks_updated": 0, "error": str(e)}diff --git a/tests/integration/core/test_api_endpoints.py b/tests/integration/core/test_api_endpoints.pyindex 37b0258a8..9444739d7 100644--- a/tests/integration/core/test_api_endpoints.py+++ b/tests/integration/core/test_api_endpoints.py@@ -226,20 +226,14 @@ async def test_upload_and_search_endpoint(tmp_path: Path, disable_langflow_inges}upload_resp = await client.post("/router/upload_ingest", files=files)body = upload_resp.json()- assert upload_resp.status_code in (201, 202), upload_resp.text+ assert upload_resp.status_code == 202, upload_resp.text- # Handle different response formats based on whether Langflow is used- if disable_langflow_ingest:- # Traditional OpenRAG response (201)- assert body.get("status") in {"indexed", "unchanged"}- assert isinstance(body.get("id"), str)- else:- # Langflow task response (202)- task_id = body.get("task_id")- assert isinstance(task_id, str)- assert body.get("file_count") == 1- # Wait for task completion before searching- await _wait_for_task_completion(client, task_id)+ # Traditional OpenRAG and Langflow upload both use task-based ingestion (202)+ task_id = body.get("task_id")+ assert isinstance(task_id, str)+ assert body.get("file_count") == 1+ # Wait for task completion before searching+ await _wait_for_task_completion(client, task_id)# Poll search for the specific content until it's indexedasync def _wait_for_indexed(timeout_s: float = 30.0):@@ -701,14 +695,9 @@ async def test_router_upload_ingest_traditional(tmp_path: Path, disable_langflowdata = resp.json()print(f"data: {data}")- if disable_langflow_ingest:- assert resp.status_code == 201 or resp.status_code == 202, resp.text- assert data.get("status") in {"indexed", "unchanged"}- assert isinstance(data.get("id"), str)- else:- assert resp.status_code == 201 or resp.status_code == 202, resp.text- assert isinstance(data.get("task_id"), str)- assert data.get("file_count") == 1+ assert resp.status_code == 202, resp.text+ assert isinstance(data.get("task_id"), str)+ assert data.get("file_count") == 1finally:from config.settings import clientsdiff --git a/tests/unit/config/test_disable_ingest_setting.py b/tests/unit/config/test_disable_ingest_setting.pynew file mode 100644index 000000000..a0a3bb0ac--- /dev/null+++ b/tests/unit/config/test_disable_ingest_setting.py@@ -0,0 +1,117 @@+"""Unit tests for the disable_ingest_with_langflow configuration setting."""++import tempfile+from pathlib import Path++import pytest++from config.config_manager import ConfigManager+++def test_disable_ingest_default(monkeypatch):+ """Verify that disable_ingest_with_langflow defaults to False when no env var is present."""+ monkeypatch.delenv("DISABLE_INGEST_WITH_LANGFLOW", raising=False)+ with tempfile.TemporaryDirectory() as tmp:+ cfg_file = Path(tmp) / "config.yaml"+ cm = ConfigManager(config_file=str(cfg_file))+ config = cm.load_config()+ assert config.knowledge.disable_ingest_with_langflow is False+++def test_disable_ingest_env_override(monkeypatch):+ """Verify that DISABLE_INGEST_WITH_LANGFLOW env var sets the default value of the setting."""+ monkeypatch.setenv("DISABLE_INGEST_WITH_LANGFLOW", "true")+ with tempfile.TemporaryDirectory() as tmp:+ cfg_file = Path(tmp) / "config.yaml"+ cm = ConfigManager(config_file=str(cfg_file))+ config = cm.load_config()+ assert config.knowledge.disable_ingest_with_langflow is True++ monkeypatch.setenv("DISABLE_INGEST_WITH_LANGFLOW", "1")+ with tempfile.TemporaryDirectory() as tmp:+ cfg_file = Path(tmp) / "config.yaml"+ cm = ConfigManager(config_file=str(cfg_file))+ config = cm.load_config()+ assert config.knowledge.disable_ingest_with_langflow is True++ monkeypatch.setenv("DISABLE_INGEST_WITH_LANGFLOW", "false")+ with tempfile.TemporaryDirectory() as tmp:+ cfg_file = Path(tmp) / "config.yaml"+ cm = ConfigManager(config_file=str(cfg_file))+ config = cm.load_config()+ assert config.knowledge.disable_ingest_with_langflow is False+++def test_disable_ingest_preserves_on_save(monkeypatch):+ """Verify that manual updates are persisted to yaml file and not overridden by env var on subsequent loads."""+ monkeypatch.setenv("DISABLE_INGEST_WITH_LANGFLOW", "false")+ with tempfile.TemporaryDirectory() as tmp:+ cfg_file = Path(tmp) / "config.yaml"+ cm = ConfigManager(config_file=str(cfg_file))+ config = cm.load_config()+ assert config.knowledge.disable_ingest_with_langflow is False++ # Manually edit it to True+ config.knowledge.disable_ingest_with_langflow = True+ config.edited = True+ cm.save_config_file(config)++ # Reload configuration+ cm2 = ConfigManager(config_file=str(cfg_file))+ config2 = cm2.load_config()+ assert config2.knowledge.disable_ingest_with_langflow is True++ # Even if environment variable is set to False, once edited=True, the setting is preserved+ monkeypatch.setenv("DISABLE_INGEST_WITH_LANGFLOW", "false")+ config3 = cm2.load_config()+ assert config3.knowledge.disable_ingest_with_langflow is True+++async def test_traditional_upload_ingest_task(monkeypatch):+ """Verify that traditional ingestion invokes task_service.create_upload_task and returns 202."""+ from unittest.mock import AsyncMock, MagicMock++ from fastapi import UploadFile++ from api.router import _traditional_upload_ingest_task+ from session_manager import User++ mock_file = MagicMock(spec=UploadFile)+ mock_file.filename = "test_document.txt"+ mock_file.read = AsyncMock(return_value=b"Dummy content for traditional upload test")++ mock_task_service = MagicMock()+ mock_task_service.create_upload_task = AsyncMock(return_value="traditional-task-123")++ mock_session_manager = MagicMock()++ mock_user = MagicMock(spec=User)+ mock_user.user_id = "test-user-id"+ mock_user.name = "Test User"+ mock_user.email = "[email protected]"+ mock_user.jwt_token = "mock-jwt-token"++ # Mock _ensure_index_exists to avoid calling opensearch+ mock_ensure_index = AsyncMock()+ monkeypatch.setattr("api.documents._ensure_index_exists", mock_ensure_index)++ response = await _traditional_upload_ingest_task(+ upload_files=[mock_file],+ replace_duplicates=True,+ create_filter=False,+ session_manager=mock_session_manager,+ task_service=mock_task_service,+ user=mock_user,+ )++ assert response.status_code == 202+ import json++ data = json.loads(response.body.decode())+ assert data["task_id"] == "traditional-task-123"+ assert data["file_count"] == 1+ assert data["filename"] == "test_document.txt"++ mock_task_service.create_upload_task.assert_called_once()+ mock_ensure_index.assert_called_once_with("mock-jwt-token")diff --git a/tests/unit/connectors/test_langflow_connector_txt_to_md.py b/tests/unit/connectors/test_langflow_connector_txt_to_md.pyindex fb99096c4..f57a7acd9 100644--- a/tests/unit/connectors/test_langflow_connector_txt_to_md.py+++ b/tests/unit/connectors/test_langflow_connector_txt_to_md.py@@ -4,8 +4,8 @@ path.Background: Langflow's docling component fails on text/plain. Theuser-upload path already applies a .txt -> .md rename (commit f6b9fe0).This test pins that the connector path-(`LangflowConnectorService.process_connector_document`) applies the same-rule, so a SharePoint .txt reaches Langflow as .md / text/markdown — not+(`ConnectorService.process_connector_document`) applies the same rule, so+a SharePoint .txt reaches Langflow as .md / text/markdown — notthe unhandled text/plain shape that previously broke ingestion.This test drives the production code path; if the rename is ever removeddiff --git a/tests/unit/connectors/test_update_connector_metadata_filename.py b/tests/unit/connectors/test_update_connector_metadata_filename.pyindex 14cbccaa2..a98f375f9 100644--- a/tests/unit/connectors/test_update_connector_metadata_filename.py+++ b/tests/unit/connectors/test_update_connector_metadata_filename.py@@ -79,8 +79,19 @@ async def test_update_includes_filename_in_script_and_params(monkeypatch):"the new name written through to indexed chunks")assert params["filename"] == "Report-FY26.docx"- # Sanity: scope is by document_id (the stable connector ID).- assert body["query"] == {"term": {"document_id": "graph-item-id-stable"}}+ # Scope matches the stable connector ID against BOTH document_id (Langflow+ # chunks) and connector_file_id (non-Langflow chunks, whose document_id is+ # the content hash). Without the connector_file_id clause, non-Langflow+ # chunks never get source_url/filename/timestamps re-applied.+ assert body["query"] == {+ "bool": {+ "should": [+ {"term": {"document_id": "graph-item-id-stable"}},+ {"term": {"connector_file_id": "graph-item-id-stable"}},+ ],+ "minimum_should_match": 1,+ }+ }@pytest.mark.asynciodiff --git a/tests/unit/test_traditional_duplicate_handling.py b/tests/unit/test_traditional_duplicate_handling.pynew file mode 100644index 000000000..50f94f601--- /dev/null+++ b/tests/unit/test_traditional_duplicate_handling.py@@ -0,0 +1,94 @@+"""Unit tests for duplicate filename handling in DocumentFileProcessor."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from models.processors import DocumentFileProcessor+from models.tasks import FileTask, TaskStatus, UploadTask+++async def test_traditional_processor_duplicate_exists_no_replace():+ """Verify that if a duplicate file exists and replace_duplicates is False, processing fails."""+ mock_doc_service = MagicMock()+ mock_models_service = MagicMock()+ mock_session_manager = MagicMock()++ processor = DocumentFileProcessor(+ document_service=mock_doc_service,+ models_service=mock_models_service,+ owner_user_id="user-123",+ jwt_token="mock-token",+ replace_duplicates=False,+ session_manager=mock_session_manager,+ )++ # Assert that session_manager was set correctly on the processor+ assert processor.session_manager == mock_session_manager++ # Mock base class methods directly on the instance to ensure perfect isolation+ processor.check_filename_exists = AsyncMock(return_value=True)+ processor.delete_document_by_filename = AsyncMock()++ upload_task = UploadTask(task_id="task-123", total_files=1)+ file_task = FileTask(file_path="/tmp/test.txt", filename="test.txt")++ await processor.process_item(upload_task, "/tmp/test.txt", file_task)++ assert file_task.status == TaskStatus.FAILED+ assert "already exists" in file_task.error+ assert upload_task.failed_files == 1+ assert upload_task.successful_files == 0++ processor.check_filename_exists.assert_called_once()+ processor.delete_document_by_filename.assert_not_called()+ mock_session_manager.get_user_opensearch_client.assert_called_once_with(+ "user-123", "mock-token"+ )+++async def test_traditional_processor_duplicate_exists_with_replace():+ """Verify that if a duplicate file exists and replace_duplicates is True, the old document is deleted and ingestion succeeds."""+ mock_doc_service = MagicMock()+ mock_models_service = MagicMock()+ mock_session_manager = MagicMock()++ processor = DocumentFileProcessor(+ document_service=mock_doc_service,+ models_service=mock_models_service,+ owner_user_id="user-123",+ jwt_token="mock-token",+ replace_duplicates=True,+ session_manager=mock_session_manager,+ )++ # Assert that session_manager was set correctly on the processor+ assert processor.session_manager == mock_session_manager++ # Mock base class methods directly on the instance to ensure perfect isolation+ processor.check_filename_exists = AsyncMock(return_value=True)+ processor.delete_document_by_filename = AsyncMock()+ processor.process_document_standard = AsyncMock(return_value={"status": "indexed"})++ upload_task = UploadTask(task_id="task-123", total_files=1)+ file_task = FileTask(file_path="/tmp/test.txt", filename="test.txt")++ with (+ patch("os.path.getsize", return_value=1234),+ patch("models.processors.hash_id", return_value="dummy-hash"),+ ):+ await processor.process_item(upload_task, "/tmp/test.txt", file_task)++ assert file_task.status == TaskStatus.COMPLETED+ assert file_task.error is None+ assert upload_task.failed_files == 0+ assert upload_task.successful_files == 1++ processor.check_filename_exists.assert_called_once()+ processor.delete_document_by_filename.assert_called_once()+ processor.process_document_standard.assert_called_once()+ mock_session_manager.get_user_opensearch_client.assert_called_once_with(+ "user-123", "mock-token"+ )diff --git a/tests/unit/test_traditional_settings_handling.py b/tests/unit/test_traditional_settings_handling.pynew file mode 100644index 000000000..966ada04c--- /dev/null+++ b/tests/unit/test_traditional_settings_handling.py@@ -0,0 +1,101 @@+"""Unit tests for settings handling in DocumentFileProcessor."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from models.processors import DocumentFileProcessor+from models.tasks import FileTask, UploadTask+++async def test_traditional_processor_settings_propagation():+ """Verify that settings like chunkSize, chunkOverlap, and embeddingModel are propagated correctly."""+ mock_doc_service = MagicMock()+ mock_models_service = MagicMock()+ mock_session_manager = MagicMock()++ settings = {+ "chunkSize": 500,+ "chunkOverlap": 50,+ "embeddingModel": "custom-embedding-model",+ "allowed_users": ["user-1"],+ "allowed_groups": ["group-1"],+ }++ processor = DocumentFileProcessor(+ document_service=mock_doc_service,+ models_service=mock_models_service,+ owner_user_id="user-123",+ jwt_token="mock-token",+ replace_duplicates=False,+ session_manager=mock_session_manager,+ settings=settings,+ )++ processor.check_filename_exists = AsyncMock(return_value=False)+ processor.process_document_standard = AsyncMock(return_value={"status": "indexed"})++ upload_task = UploadTask(task_id="task-123", total_files=1)+ file_task = FileTask(file_path="/tmp/test.txt", filename="test.txt")++ with (+ patch("os.path.getsize", return_value=1234),+ patch("models.processors.hash_id", return_value="dummy-hash"),+ ):+ await processor.process_item(upload_task, "/tmp/test.txt", file_task)++ # Verify standard kwargs passed to process_document_standard+ processor.process_document_standard.assert_called_once()+ kwargs = processor.process_document_standard.call_args.kwargs++ assert kwargs["chunk_size"] == 500+ assert kwargs["chunk_overlap"] == 50+ assert kwargs["embedding_model"] == "custom-embedding-model"+ assert kwargs["acl"] is not None+ assert kwargs["acl"].allowed_users == ["user-1"]+ assert kwargs["acl"].allowed_groups == ["group-1"]+++async def test_traditional_processor_invalid_settings_fallback():+ """Verify that invalid integer settings or empty strings are safely ignored or default handling is used."""+ mock_doc_service = MagicMock()+ mock_models_service = MagicMock()+ mock_session_manager = MagicMock()++ settings = {+ "chunkSize": "invalid-int",+ "chunkOverlap": None,+ "embeddingModel": " ", # spaces only+ }++ processor = DocumentFileProcessor(+ document_service=mock_doc_service,+ models_service=mock_models_service,+ owner_user_id="user-123",+ jwt_token="mock-token",+ replace_duplicates=False,+ session_manager=mock_session_manager,+ settings=settings,+ )++ processor.check_filename_exists = AsyncMock(return_value=False)+ processor.process_document_standard = AsyncMock(return_value={"status": "indexed"})++ upload_task = UploadTask(task_id="task-123", total_files=1)+ file_task = FileTask(file_path="/tmp/test.txt", filename="test.txt")++ with (+ patch("os.path.getsize", return_value=1234),+ patch("models.processors.hash_id", return_value="dummy-hash"),+ ):+ await processor.process_item(upload_task, "/tmp/test.txt", file_task)++ processor.process_document_standard.assert_called_once()+ kwargs = processor.process_document_standard.call_args.kwargs++ # Should not have passed these to process_document_standard or they fell back to default+ assert "chunk_size" not in kwargs+ assert "chunk_overlap" not in kwargs+ assert "embedding_model" not in kwargs