OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
fix: added modified time as tag on langflow flows so that updated versions are always prompted to upgrade (#2524) (#2551)
Lucas Oliveira24d42cbf616a
diff --git a/.env.example b/.env.exampleindex 1d05f965f..9e7543169 100644--- a/.env.example+++ b/.env.example@@ -420,8 +420,6 @@ LANGFLOW_NEW_USER_IS_ACTIVE=FalseLANGFLOW_ENABLE_SUPERUSER_CLI=False# Disable custom component creation in LangflowLANGFLOW_ALLOW_CUSTOM_COMPONENTS=false-# Path to the component index JSON file-LANGFLOW_COMPONENTS_INDEX_PATH=/app/flows/component_index.json# ─────────────────────────────────────────────────────────────────────────────# Langflow Container Variablesdiff --git a/Dockerfile.backend b/Dockerfile.backendindex 98180d1aa..71ffef205 100644--- a/Dockerfile.backend+++ b/Dockerfile.backend@@ -127,4 +127,4 @@ EXPOSE 8000EXPOSE 8100ENTRYPOINT ["/entrypoint.sh"]-CMD ["/app/.venv/bin/python", "src/main.py"]\ No newline at end of file+CMD ["/app/.venv/bin/python", "src/main.py"]diff --git a/Dockerfile.langflow b/Dockerfile.langflowindex 57b3c3802..d0b3544b2 100644--- a/Dockerfile.langflow+++ b/Dockerfile.langflow@@ -87,7 +87,6 @@ RUN pip install --no-cache-dir \COPY --from=lxml-build /wheels /tmp/lxml-wheelsRUN pip install --no-cache-dir --no-deps --force-reinstall /tmp/lxml-wheels/lxml-*.whl-COPY flows/ /app/flows/COPY custom_components/ /app/custom_components/# Switch to root so the entrypoint can correct bind-mount permissions atdiff --git a/docker-compose.yml b/docker-compose.ymlindex c3a7692ff..bd702ce9d 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -228,16 +228,12 @@ services:ports:- "${LANGFLOW_PORT:-7860}:7860"volumes:- - ${OPENRAG_FLOWS_PATH:-./flows}:/app/flows:U,z- ${LANGFLOW_DATA_PATH:-./langflow-data}:/app/langflow-data:U,z# Linux: Docker Engine does not auto-inject host.docker.internal; map it to the host gatewayextra_hosts:- "host.docker.internal:host-gateway"environment:- LANGFLOW_ALLOW_CUSTOM_COMPONENTS=${LANGFLOW_ALLOW_CUSTOM_COMPONENTS:-false}- # Prefer the bind-mounted index so `scripts/update_openrag_component_index.py`- # takes effect on `docker compose restart langflow` without an image rebuild.- - LANGFLOW_COMPONENTS_INDEX_PATH=/app/flows/component_index.json- LANGFUSE_SECRET_KEY=${LANGFUSE_SECRET_KEY:-}- LANGFUSE_PUBLIC_KEY=${LANGFUSE_PUBLIC_KEY:-}- LANGFUSE_BASE_URL=${LANGFUSE_BASE_URL:-}diff --git a/src/services/flows_service.py b/src/services/flows_service.pyindex d75976cc2..3ab0124a0 100644--- a/src/services/flows_service.py+++ b/src/services/flows_service.py@@ -1,7 +1,7 @@import asyncioimport jsonimport os-from datetime import UTC, datetime+from datetime import datetimefrom typing import Anyfrom cachetools import LRUCache@@ -25,6 +25,7 @@ from utils.telemetry import Category, MessageId, TelemetryClientlogger = get_logger(__name__)_UNSET = object()+_FLOW_FILE_MTIME_TAG_PREFIX = "openrag:file-mtime:"class FlowsService:@@ -559,6 +560,7 @@ class FlowsService:try:with open(flow_path) as f:flow_data = json.load(f)+ self._stamp_flow_with_file_mtime(flow_data, flow_path)logger.info(f"Successfully loaded flow data for {flow_type} from {os.path.basename(flow_path)}")@@ -569,10 +571,10 @@ class FlowsService:await self._unlock_flow(flow_id)- # Make PATCH request to Langflow API to update the flow using shared client+ # Replace the complete flow so the stamped source timestamp is persisted.try:response = await clients.langflow_request(- "PATCH",+ "PUT",f"/api/v1/flows/{flow_id}",json=flow_data,idempotent=True,@@ -889,7 +891,13 @@ class FlowsService:self, flow_type: str, flow_id: str, flow_data: dict[str, Any] | None = None) -> dict[str, Any] | None:"""- Check if a flow has a newer version on disk compared to Langflow.+ Check whether the source flow file is newer than the version stored in Langflow.++ The backend stamps each uploaded flow with an+ ``openrag:file-mtime:<nanoseconds>`` tag. Comparing the current file+ timestamp to that tag avoids relying on Langflow's unrelated+ ``updated_at`` value.+Returns flow update info dict if an update is available, None otherwise."""if not flow_id:@@ -897,7 +905,12 @@ class FlowsService:flow_path = self._find_flow_file_by_id(flow_id)if not flow_path or not os.path.exists(flow_path):return None- local_mtime = os.path.getmtime(flow_path)++ try:+ source_mtime = os.stat(flow_path).st_mtime_ns+ except OSError as error:+ logger.warning(f"Could not stat bundled flow {flow_path} for update check: {error}")+ return Noneif flow_data is None:try:@@ -909,20 +922,8 @@ class FlowsService:logger.error(f"Failed to fetch flow {flow_id} for update check: {e}")return None- langflow_updated_at_str = flow_data.get("updated_at")- langflow_mtime: float = 0.0- if langflow_updated_at_str:- if langflow_updated_at_str.endswith("Z"):- langflow_updated_at_str = langflow_updated_at_str[:-1] + "+00:00"- try:- dt = datetime.fromisoformat(langflow_updated_at_str)- if dt.tzinfo is None:- dt = dt.replace(tzinfo=UTC)- langflow_mtime = dt.timestamp()- except ValueError:- pass-- if local_mtime > langflow_mtime + 1.0:+ stored_mtime = self._get_flow_file_mtime_tag(flow_data)+ if stored_mtime is None or source_mtime > stored_mtime:is_locked = flow_data.get("locked", False)return {"flow_type": flow_type,@@ -931,6 +932,34 @@ class FlowsService:}return None+ @staticmethod+ def _stamp_flow_with_file_mtime(flow_data: dict[str, Any], flow_path: str) -> None:+ """Embed the source flow's modification timestamp into its Langflow tags."""+ tags = flow_data.get("tags")+ if tags is None:+ tags = []+ if not isinstance(tags, list) or not all(isinstance(tag, str) for tag in tags):+ raise ValueError(f"Flow {flow_data.get('id', '<unknown>')} has invalid tags")+ flow_data["tags"] = [+ *[tag for tag in tags if not tag.startswith(_FLOW_FILE_MTIME_TAG_PREFIX)],+ f"{_FLOW_FILE_MTIME_TAG_PREFIX}{os.stat(flow_path).st_mtime_ns}",+ ]++ @staticmethod+ def _get_flow_file_mtime_tag(flow_data: dict[str, Any]) -> int | None:+ """Return the source-file modification timestamp recorded on a Langflow flow."""+ tags = flow_data.get("tags")+ if not isinstance(tags, list):+ return None+ for tag in tags:+ if not isinstance(tag, str) or not tag.startswith(_FLOW_FILE_MTIME_TAG_PREFIX):+ continue+ try:+ return int(tag.removeprefix(_FLOW_FILE_MTIME_TAG_PREFIX))+ except ValueError:+ continue+ return None+async def ensure_flows_exist(self) -> set[str]:"""Ensure all configured flows exist in Langflow.@@ -983,6 +1012,7 @@ class FlowsService:with open(flow_path) as f:flow_data = json.load(f)+ self._stamp_flow_with_file_mtime(flow_data, flow_path)response = await clients.langflow_request("PUT", f"/api/v1/flows/{flow_id}", json=flow_datadiff --git a/tests/unit/services/test_flows_service_bulk_update.py b/tests/unit/services/test_flows_service_bulk_update.pyindex 78aff2ff9..6301684ed 100644--- a/tests/unit/services/test_flows_service_bulk_update.py+++ b/tests/unit/services/test_flows_service_bulk_update.py@@ -281,3 +281,150 @@ async def test_get_flows_updates_available_includes_all_flows():assert len(updates) == 4assert all(u["flow_type"] in ["nudges", "retrieval", "ingest", "url_ingest"] for u in updates)+++async def test_flow_update_uses_source_mtime_tag_not_langflow_updated_at(tmp_path):+ service = FlowsService()+ flow_path = tmp_path / "flow.json"+ flow_path.write_text('{"id": "flow-1", "tags": ["rag"]}', encoding="utf-8")+ source_mtime = flow_path.stat().st_mtime_ns++ with patch.object(service, "_find_flow_file_by_id", return_value=str(flow_path)):+ update = await service._check_flow_update(+ "retrieval",+ "flow-1",+ {+ "locked": True,+ "tags": [f"openrag:file-mtime:{source_mtime - 1}"],+ "updated_at": "2099-01-01T00:00:00Z",+ },+ )++ assert update == {"flow_type": "retrieval", "flow_id": "flow-1", "is_custom": False}+++async def test_flow_update_is_not_available_when_source_mtime_matches_tag(tmp_path):+ service = FlowsService()+ flow_path = tmp_path / "flow.json"+ flow_path.write_text('{"id": "flow-1", "tags": ["rag"]}', encoding="utf-8")+ source_mtime = flow_path.stat().st_mtime_ns++ with patch.object(service, "_find_flow_file_by_id", return_value=str(flow_path)):+ update = await service._check_flow_update(+ "retrieval",+ "flow-1",+ {+ "locked": False,+ "tags": [f"openrag:file-mtime:{source_mtime}"],+ "updated_at": "1970-01-01T00:00:00Z",+ },+ )++ assert update is None+++async def test_flow_update_does_not_upgrade_when_stored_mtime_is_newer(tmp_path):+ service = FlowsService()+ flow_path = tmp_path / "flow.json"+ flow_path.write_text('{"id": "flow-1", "tags": ["rag"]}', encoding="utf-8")+ source_mtime = flow_path.stat().st_mtime_ns++ with patch.object(service, "_find_flow_file_by_id", return_value=str(flow_path)):+ update = await service._check_flow_update(+ "retrieval", "flow-1", {"tags": [f"openrag:file-mtime:{source_mtime + 1}"]}+ )++ assert update is None+++async def test_flow_update_detects_stored_flow_without_a_mtime_tag(tmp_path):+ service = FlowsService()+ flow_path = tmp_path / "flow.json"+ flow_path.write_text('{"id": "flow-1", "tags": ["rag"]}', encoding="utf-8")++ with patch.object(service, "_find_flow_file_by_id", return_value=str(flow_path)):+ update = await service._check_flow_update(+ "retrieval", "flow-1", {"locked": False, "tags": ["rag"]}+ )++ assert update == {"flow_type": "retrieval", "flow_id": "flow-1", "is_custom": True}+++def test_stamp_flow_with_file_mtime_replaces_previous_mtime_tag(tmp_path):+ service = FlowsService()+ flow_path = tmp_path / "flow.json"+ flow_path.write_text('{"id": "flow-1", "tags": ["rag"]}', encoding="utf-8")+ flow_data = {+ "id": "flow-1",+ "tags": ["rag", "openrag:file-mtime:1", "openrag:file-mtime:2"],+ }++ service._stamp_flow_with_file_mtime(flow_data, str(flow_path))++ assert flow_data["tags"] == [+ "rag",+ f"openrag:file-mtime:{flow_path.stat().st_mtime_ns}",+ ]+++async def test_reset_stamps_flow_with_source_mtime(tmp_path, monkeypatch):+ service = FlowsService()+ flow_path = tmp_path / "flow.json"+ flow_path.write_text('{"id": "flow-1", "tags": ["rag"]}', encoding="utf-8")+ source_mtime = flow_path.stat().st_mtime_ns+ response = MagicMock(status_code=200)+ response.json.return_value = {}+ uploaded_flow: dict = {}++ async def request(method, url, json=None, **kwargs):+ assert method == "PUT"+ assert url == "/api/v1/flows/flow-1"+ uploaded_flow.update(json)+ return response++ monkeypatch.setattr("services.flows_service.LANGFLOW_URL", "http://langflow")+ with (+ patch.object(service, "_find_flow_file_by_id", return_value=str(flow_path)),+ patch.object(service, "_unlock_flow", AsyncMock()),+ patch.object(service, "_lock_flow", AsyncMock()),+ patch("services.flows_service.clients.langflow_request", side_effect=request),+ ):+ result = await service._reset_langflow_flow_locked("retrieval", "flow-1")++ assert result["success"] is True+ assert uploaded_flow["tags"] == ["rag", f"openrag:file-mtime:{source_mtime}"]+++async def test_ensure_flows_exist_stamps_created_flow_with_source_mtime(tmp_path, monkeypatch):+ service = FlowsService()+ flow_path = tmp_path / "flow.json"+ flow_path.write_text('{"id": "flow-1", "tags": ["rag"]}', encoding="utf-8")+ source_mtime = flow_path.stat().st_mtime_ns+ uploaded_flow: dict = {}++ async def request(method, url, json=None, **kwargs):+ if method == "GET":+ return MagicMock(status_code=404)+ assert method == "PUT"+ assert url == "/api/v1/flows/flow-1"+ uploaded_flow.update(json)+ return MagicMock(status_code=201)++ monkeypatch.setattr("services.flows_service.NUDGES_FLOW_ID", "flow-1")+ monkeypatch.setattr("services.flows_service.LANGFLOW_CHAT_FLOW_ID", "")+ monkeypatch.setattr("services.flows_service.LANGFLOW_INGEST_FLOW_ID", "")+ monkeypatch.setattr("services.flows_service.LANGFLOW_URL_INGEST_FLOW_ID", "")+ with (+ patch.object(service, "_find_flow_file_by_id", return_value=str(flow_path)),+ patch("services.flows_service.clients.langflow_request", side_effect=request),+ ):+ created = await service.ensure_flows_exist()++ assert created == {"nudges"}+ assert uploaded_flow["tags"] == ["rag", f"openrag:file-mtime:{source_mtime}"]diff --git a/tests/unit/test_openai_compatible_langflow_components.py b/tests/unit/test_openai_compatible_langflow_components.pyindex 130c5460e..a17b9bf02 100644--- a/tests/unit/test_openai_compatible_langflow_components.py+++ b/tests/unit/test_openai_compatible_langflow_components.py@@ -93,7 +93,6 @@ def test_langflow_image_installs_the_openrag_component_bundle():def test_docker_compose_seeds_openrag_llm_token_placeholder():compose = Path("docker-compose.yml").read_text(encoding="utf-8")- assert "LANGFLOW_COMPONENTS_INDEX_PATH=/app/flows/component_index.json" in composeassert "OPENRAG_LLM_TOKEN=None" in composeassert ("OPENRAG_LLM_TOKEN"