Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(config): read boolean env flags so that off means off (#19689)

Lukascaf16653ab4f
diff --git a/common/connection_utils.py b/common/connection_utils.py
index 48327a1879..be48146956 100644
--- a/common/connection_utils.py
+++ b/common/connection_utils.py
@@ -14,7 +14,6 @@
# limitations under the License.
#
-import os
import queue
import threading
from typing import Any, Callable, Coroutine, Optional, Type, Union
@@ -22,6 +21,7 @@ import asyncio
from functools import wraps
from quart import make_response, jsonify
from common.constants import RetCode
+from common.misc_utils import env_flag
TimeoutException = Union[Type[BaseException], BaseException]
OnTimeoutCallback = Union[Callable[..., Any], Coroutine[Any, Any, Any]]
@@ -49,7 +49,7 @@ def timeout(seconds: float | int | str = None, attempts: int = 2, *, exception:
for a in range(attempts):
try:
- if os.environ.get("ENABLE_TIMEOUT_ASSERTION"):
+ if env_flag("ENABLE_TIMEOUT_ASSERTION", False):
result = result_queue.get(timeout=seconds)
else:
result = result_queue.get()
@@ -67,7 +67,7 @@ def timeout(seconds: float | int | str = None, attempts: int = 2, *, exception:
for a in range(attempts):
try:
- if os.environ.get("ENABLE_TIMEOUT_ASSERTION"):
+ if env_flag("ENABLE_TIMEOUT_ASSERTION", False):
return await asyncio.wait_for(func(*args, **kwargs), timeout=seconds)
else:
return await func(*args, **kwargs)
diff --git a/common/misc_utils.py b/common/misc_utils.py
index 9decef3c83..12f626ba10 100644
--- a/common/misc_utils.py
+++ b/common/misc_utils.py
@@ -33,6 +33,20 @@ logger = logging.getLogger(__name__)
_LONG_TIME_THREAD_POOL_EXECUTOR = ThreadPoolExecutor(max_workers=int(os.getenv("LONG_TIME_THREAD_POOL_WORKERS", "1")), thread_name_prefix="long-time")
+def env_flag(name: str, default: bool) -> bool:
+ """Read a boolean environment variable the way the rest of the codebase does.
+
+ Unset keeps the documented default. Anything else is matched against the
+ truthy vocabulary used elsewhere in this file and in common/data_source, so
+ a switch written as "off" or "disabled" turns the feature off instead of
+ being read as its opposite.
+ """
+ raw = os.environ.get(name)
+ if raw is None:
+ return default
+ return raw.strip().lower() in ("1", "true", "yes", "on")
+
+
def get_uuid():
return uuid.uuid1().hex
diff --git a/common/settings.py b/common/settings.py
index faebc1cecc..6bbd606704 100644
--- a/common/settings.py
+++ b/common/settings.py
@@ -23,7 +23,7 @@ from datetime import date
from common.constants import RAG_FLOW_SERVICE_NAME
from common.file_utils import get_project_base_directory
from common.config_utils import get_base_config, decrypt_database_config
-from common.misc_utils import pip_install_torch
+from common.misc_utils import env_flag, pip_install_torch
from common.constants import SVR_QUEUE_NAME, Storage
import rag.utils
@@ -326,8 +326,7 @@ def init_settings():
pass
global OAUTH_AUTO_REGISTER
- env_val = os.environ.get("OAUTH_AUTO_REGISTER", "").lower()
- OAUTH_AUTO_REGISTER = env_val not in ("0", "false", "no")
+ OAUTH_AUTO_REGISTER = env_flag("OAUTH_AUTO_REGISTER", True)
global DISABLE_PASSWORD_LOGIN
try:
diff --git a/docker/.env b/docker/.env
index 32fd1bf262..c9db7f4d25 100644
--- a/docker/.env
+++ b/docker/.env
@@ -485,6 +485,10 @@ LLM_POOL_RATE_LIMIT_RETRY_MAX_DELAY=30.0
#Option to disable login form for SSO
DISABLE_PASSWORD_LOGIN=false
+# Option to allow OAuth/OIDC just-in-time user provisioning. Independent of
+# REGISTER_ENABLED: set to false to require that an OAuth/OIDC user already exists.
+OAUTH_AUTO_REGISTER=true
+
# -----------------------------------------------------------------------------
# DeepDoc (in-process)
# -----------------------------------------------------------------------------
diff --git a/docs/administrator/configurations/configurations.md b/docs/administrator/configurations/configurations.md
index f1d5d75973..6e3ee3d473 100644
--- a/docs/administrator/configurations/configurations.md
+++ b/docs/administrator/configurations/configurations.md
@@ -143,8 +143,8 @@ If you cannot download the RAGFlow Docker image, try the following mirrors.
- `0`: Disable user registration.
- `OAUTH_AUTO_REGISTER`
- - `true`: (Default) Allow new users to be provisioned on OAuth/OIDC login.
- - `false`: Require OAuth/OIDC users to already exist. This is independent of `REGISTER_ENABLED`.
+ - `true`: (Default) Allow new users to be provisioned on OAuth/OIDC login. Also accepts `1`, `yes`, `on`.
+ - Any other value, `false` included: require OAuth/OIDC users to already exist. This is independent of `REGISTER_ENABLED`.
## Service Configuration
diff --git a/rag/graphrag/entity_resolution.py b/rag/graphrag/entity_resolution.py
index 0b900464fc..74135cb6ac 100644
--- a/rag/graphrag/entity_resolution.py
+++ b/rag/graphrag/entity_resolution.py
@@ -16,7 +16,6 @@
import asyncio
import logging
import itertools
-import os
import re
from dataclasses import dataclass
from typing import Any, Awaitable, Callable
@@ -33,6 +32,7 @@ from rag.llm.chat_model import Base as CompletionLLM
from rag.graphrag.utils import perform_variable_replacements, chat_limiter, GraphChange
from api.db.services.task_service import has_canceled
from common.exceptions import TaskCanceledException
+from common.misc_utils import env_flag
DEFAULT_RECORD_DELIMITER = "##"
@@ -127,7 +127,7 @@ class EntityResolution(Extractor):
remain_candidates_to_resolve -= len(candidate_batch[1])
callback(msg=f"Replayed {len(candidate_batch[1])} resolved pairs from checkpoint, {remain_candidates_to_resolve} remain.")
return
- enable_timeout_assertion = os.environ.get("ENABLE_TIMEOUT_ASSERTION")
+ enable_timeout_assertion = env_flag("ENABLE_TIMEOUT_ASSERTION", False)
timeout_sec = 280 if enable_timeout_assertion else 1_000_000_000
try:
@@ -214,7 +214,7 @@ class EntityResolution(Extractor):
text = perform_variable_replacements(self._resolution_prompt, variables=variables)
logging.info(f"Created resolution prompt {len(text)} bytes for {len(candidate_resolution_i[1])} entity pairs of type {candidate_resolution_i[0]}")
async with chat_limiter:
- timeout_seconds = 280 if os.environ.get("ENABLE_TIMEOUT_ASSERTION") else 1000000000
+ timeout_seconds = 280 if env_flag("ENABLE_TIMEOUT_ASSERTION", False) else 1000000000
try:
response = await asyncio.wait_for(
self._async_chat(text, [{"role": "user", "content": "Output:"}], {}, task_id),
diff --git a/rag/graphrag/general/community_reports_extractor.py b/rag/graphrag/general/community_reports_extractor.py
index 57f1759e16..501786966a 100644
--- a/rag/graphrag/general/community_reports_extractor.py
+++ b/rag/graphrag/general/community_reports_extractor.py
@@ -10,7 +10,6 @@ Reference:
import asyncio
import logging
import json
-import os
import re
from typing import Any, Awaitable, Callable
from dataclasses import dataclass
@@ -19,6 +18,7 @@ import pandas as pd
from api.db.services.task_service import has_canceled
from common.exceptions import TaskCanceledException
+from common.misc_utils import env_flag
from rag.graphrag.general import leiden
from rag.graphrag.general.community_report_prompt import COMMUNITY_REPORT_PROMPT
from rag.graphrag.general.extractor import Extractor
@@ -63,7 +63,7 @@ class CommunityReportsExtractor(Extractor):
checkpoints: dict[str, Any] | None = None,
save_checkpoint: Callable[[str, Any], Awaitable[bool]] | None = None,
):
- enable_timeout_assertion = os.environ.get("ENABLE_TIMEOUT_ASSERTION")
+ enable_timeout_assertion = env_flag("ENABLE_TIMEOUT_ASSERTION", False)
for node_degree in graph.degree:
graph.nodes[str(node_degree[0])]["rank"] = int(node_degree[1])
diff --git a/rag/graphrag/utils.py b/rag/graphrag/utils.py
index 5c584af901..42b2251825 100644
--- a/rag/graphrag/utils.py
+++ b/rag/graphrag/utils.py
@@ -1,7 +1,7 @@
# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License
-from common.misc_utils import thread_pool_exec
+from common.misc_utils import env_flag, thread_pool_exec
"""
Reference:
@@ -63,7 +63,7 @@ async def insert_chunks_bounded(chunks, tenant_id, kb_id, *, callback=None, labe
"""
if not chunks:
return
- enable_timeout_assertion = os.environ.get("ENABLE_TIMEOUT_ASSERTION")
+ enable_timeout_assertion = env_flag("ENABLE_TIMEOUT_ASSERTION", False)
sem = asyncio.Semaphore(_INSERT_CONCURRENCY)
total = len(chunks)
progress = {"done": 0, "next_report": 100}
@@ -414,7 +414,7 @@ def chunk_id(chunk):
async def graph_node_to_chunk(kb_id, embd_mdl, ent_name, meta, chunks, nhop_neighbors=None):
"""Convert a graph node (entity) to an embeddable chunk and append it to *chunks*."""
global chat_limiter
- enable_timeout_assertion = os.environ.get("ENABLE_TIMEOUT_ASSERTION")
+ enable_timeout_assertion = env_flag("ENABLE_TIMEOUT_ASSERTION", False)
chunk = {
"id": get_uuid(),
"important_kwd": [ent_name],
@@ -471,7 +471,7 @@ async def get_relation(tenant_id, kb_id, from_ent_name, to_ent_name, size=1):
async def graph_edge_to_chunk(kb_id, embd_mdl, from_ent_name, to_ent_name, meta, chunks):
"""Convert a graph edge (relation) to an embeddable chunk and append it to *chunks*."""
- enable_timeout_assertion = os.environ.get("ENABLE_TIMEOUT_ASSERTION")
+ enable_timeout_assertion = env_flag("ENABLE_TIMEOUT_ASSERTION", False)
chunk = {
"id": get_uuid(),
"from_entity_kwd": from_ent_name,
@@ -604,7 +604,7 @@ async def set_graph(tenant_id: str, kb_id: str, embd_mdl, graph: nx.Graph, chang
len(_uncached_node_names),
)
if _uncached_node_names:
- _enable_ta = os.environ.get("ENABLE_TIMEOUT_ASSERTION")
+ _enable_ta = env_flag("ENABLE_TIMEOUT_ASSERTION", False)
_timeout = 3 if _enable_ta else 30000000
for _i in range(0, len(_uncached_node_names), _INSERT_BULK_SIZE):
_batch = _uncached_node_names[_i : _i + _INSERT_BULK_SIZE]
@@ -657,7 +657,7 @@ async def set_graph(tenant_id: str, kb_id: str, embd_mdl, graph: nx.Graph, chang
if _uncached_edge_items:
_edge_keys = [f"{f}->{t}" for f, t, _ in _uncached_edge_items]
_edge_texts = [f"{f}->{t}: {a['description']}" for f, t, a in _uncached_edge_items]
- _enable_ta = os.environ.get("ENABLE_TIMEOUT_ASSERTION")
+ _enable_ta = env_flag("ENABLE_TIMEOUT_ASSERTION", False)
_timeout = 3 if _enable_ta else 30000000
for _i in range(0, len(_edge_texts), _INSERT_BULK_SIZE):
_btexts = _edge_texts[_i : _i + _INSERT_BULK_SIZE]
diff --git a/test/unit_test/common/test_env_flag.py b/test/unit_test/common/test_env_flag.py
new file mode 100644
index 0000000000..35489f54c9
--- /dev/null
+++ b/test/unit_test/common/test_env_flag.py
@@ -0,0 +1,74 @@
+#
+# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Test cases for env_flag in common.misc_utils."""
+
+import pytest
+
+from common.misc_utils import env_flag
+
+
+class TestEnvFlag:
+ def test_unset_keeps_the_documented_default(self, monkeypatch):
+ monkeypatch.delenv("SOME_FLAG", raising=False)
+ assert env_flag("SOME_FLAG", True) is True
+ assert env_flag("SOME_FLAG", False) is False
+
+ @pytest.mark.parametrize("raw", ["1", "true", "TRUE", "True", "yes", "YES", "on", "ON", " true "])
+ def test_truthy_vocabulary(self, monkeypatch, raw):
+ monkeypatch.setenv("SOME_FLAG", raw)
+ assert env_flag("SOME_FLAG", False) is True
+
+ @pytest.mark.parametrize("raw", ["0", "false", "FALSE", "no", "NO", " false ", ""])
+ def test_falsy_vocabulary(self, monkeypatch, raw):
+ monkeypatch.setenv("SOME_FLAG", raw)
+ assert env_flag("SOME_FLAG", True) is False
+
+ @pytest.mark.parametrize("raw", ["off", "OFF", "disabled", "none", "n", "0.0"])
+ def test_an_unrecognized_value_turns_a_default_on_flag_off(self, monkeypatch, raw):
+ """The reason this helper exists.
+
+ A deny-list parse (`value not in ("0", "false", "no")`) reads every one of
+ these as enabled, so an administrator who writes `off` gets the opposite of
+ what they asked for. For a switch that decides whether a stranger arriving
+ over OAuth is provisioned an account, that is the wrong direction to guess in.
+ """
+ monkeypatch.setenv("SOME_FLAG", raw)
+ assert env_flag("SOME_FLAG", True) is False
+
+ def test_surrounding_whitespace_is_not_a_different_value(self, monkeypatch):
+ monkeypatch.setenv("SOME_FLAG", " false\n")
+ assert env_flag("SOME_FLAG", True) is False
+
+
+class TestTimeoutAssertionFlag:
+ """`ENABLE_TIMEOUT_ASSERTION` is documented as enabling *or disabling* the
+ parsing-task timeout, but every read was a bare presence check, so writing
+ `false` armed a 280-second timeout instead of the effectively unbounded one.
+ """
+
+ @pytest.mark.parametrize("raw", ["false", "0", "no", "off", " false "])
+ def test_a_disabled_value_disables_it(self, monkeypatch, raw):
+ monkeypatch.setenv("ENABLE_TIMEOUT_ASSERTION", raw)
+ assert env_flag("ENABLE_TIMEOUT_ASSERTION", False) is False
+
+ @pytest.mark.parametrize("raw", ["1", "true", "yes", "on"])
+ def test_an_enabled_value_still_enables_it(self, monkeypatch, raw):
+ monkeypatch.setenv("ENABLE_TIMEOUT_ASSERTION", raw)
+ assert env_flag("ENABLE_TIMEOUT_ASSERTION", False) is True
+
+ def test_unset_leaves_it_off(self, monkeypatch):
+ monkeypatch.delenv("ENABLE_TIMEOUT_ASSERTION", raising=False)
+ assert env_flag("ENABLE_TIMEOUT_ASSERTION", False) is False
diff --git a/test/unit_test/common/test_oauth_auto_register_settings.py b/test/unit_test/common/test_oauth_auto_register_settings.py
new file mode 100644
index 0000000000..ce01b4c875
--- /dev/null
+++ b/test/unit_test/common/test_oauth_auto_register_settings.py
@@ -0,0 +1,138 @@
+#
+# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""`OAUTH_AUTO_REGISTER` as `init_settings()` actually resolves it.
+
+`test_env_flag` covers the parser in isolation. This covers the one line that
+binds the parser to the environment variable, so a renamed variable, a flipped
+default or a helper that stops being called is caught at the boundary the
+deployment documentation describes.
+
+Importing `common.settings` pulls in every document store, message store and
+blob storage client, so those modules are replaced by inert stubs first, the
+same way `test_gaussdb_settings` does it.
+"""
+
+import importlib
+import sys
+import types
+
+import pytest
+
+
+class _Stub:
+ """Stands in for any client `init_settings()` constructs.
+
+ Calling it or reading an attribute yields the stub again, so none of the
+ storage or index clients need a purpose-built fake here.
+ """
+
+ def __call__(self, *args, **kwargs):
+ return self
+
+ def __getattr__(self, name):
+ return self
+
+
+_STUB = _Stub()
+
+
+class _StubModule(types.ModuleType):
+ def __getattr__(self, name):
+ return _STUB
+
+
+_STUBBED_MODULES = (
+ "rag.utils.es_conn",
+ "rag.utils.infinity_conn",
+ "rag.utils.ob_conn",
+ "rag.utils.opensearch_conn",
+ "rag.utils.gaussdb_conn",
+ "rag.utils.azure_sas_conn",
+ "rag.utils.azure_spn_conn",
+ "rag.utils.gcs_conn",
+ "rag.utils.minio_conn",
+ "rag.utils.opendal_conn",
+ "rag.utils.redis_conn",
+ "rag.utils.s3_conn",
+ "rag.utils.oss_conn",
+ "rag.nlp",
+ "rag.graphrag",
+ "rag.graphrag.search",
+ "memory.utils.es_conn",
+ "memory.utils.infinity_conn",
+ "memory.utils.ob_conn",
+ "memory.utils.gaussdb_conn",
+)
+
+
+def settings(monkeypatch):
+ importlib.import_module("rag.utils")
+ importlib.import_module("memory.utils")
+
+ for name in _STUBBED_MODULES:
+ stub = _StubModule(name)
+ monkeypatch.setitem(sys.modules, name, stub)
+ parent_name, _, child_name = name.rpartition(".")
+ parent = sys.modules.get(parent_name)
+ if parent is not None:
+ monkeypatch.setattr(parent, child_name, stub, raising=False)
+
+ import common
+
+ # Import machinery assigns a freshly imported submodule to
+ # ``common.settings`` on the parent package. Restoring only
+ # ``sys.modules["common.settings"]`` leaves that parent attribute pointing
+ # at this test's stub-backed module and contaminates later tests.
+ monkeypatch.setattr(common, "settings", getattr(common, "settings", None), raising=False)
+ # ``delitem`` records nothing when the key is absent, so the stub-backed
+ # module imported below would outlive the test. ``setitem`` always records
+ # the previous state, and teardown then removes or restores the entry.
+ monkeypatch.setitem(sys.modules, "common.settings", None)
+ del sys.modules["common.settings"]
+ return importlib.import_module("common.settings")
+
+
+def test_unset_provisions_oauth_arrivals(settings, monkeypatch):
+ monkeypatch.delenv("OAUTH_AUTO_REGISTER", raising=False)
+
+ settings.init_settings()
+
+ assert settings.OAUTH_AUTO_REGISTER is True
+
+
[email protected]("raw", ["1", "true", "TRUE", "yes", "on", " true "])
+def test_an_enabled_value_keeps_auto_registration_on(settings, monkeypatch, raw):
+ monkeypatch.setenv("OAUTH_AUTO_REGISTER", raw)
+
+ settings.init_settings()
+
+ assert settings.OAUTH_AUTO_REGISTER is True
+
+
[email protected]("raw", ["0", "false", "FALSE", "no", "off", "disabled", ""])
+def test_anything_else_turns_auto_registration_off(settings, monkeypatch, raw):
+ """`off` and `disabled` are the values this pull request changes.
+
+ The previous deny-list parse recognized only `0`, `false` and `no`, so an
+ administrator who wrote `off` kept provisioning accounts for every stranger
+ who arrived over OAuth.
+ """
+ monkeypatch.setenv("OAUTH_AUTO_REGISTER", raw)
+
+ settings.init_settings()
+
+ assert settings.OAUTH_AUTO_REGISTER is False
diff --git a/test/unit_test/rag/graphrag/test_graphrag_extractors.py b/test/unit_test/rag/graphrag/test_graphrag_extractors.py
index 3361e9fbbe..dce0afe817 100644
--- a/test/unit_test/rag/graphrag/test_graphrag_extractors.py
+++ b/test/unit_test/rag/graphrag/test_graphrag_extractors.py
@@ -15,6 +15,7 @@
#
import asyncio
+import types
from types import SimpleNamespace
import networkx as nx
@@ -29,6 +30,21 @@ def _build_llm_stub():
return SimpleNamespace(llm_name="test-llm", max_length=4096)
+class _RecordingAsyncio(types.ModuleType):
+ """`asyncio` as a module sees it, with the timeouts handed to `wait_for` recorded."""
+
+ def __init__(self):
+ super().__init__("asyncio")
+ self.timeouts = []
+
+ def __getattr__(self, name):
+ return getattr(asyncio, name)
+
+ def wait_for(self, awaitable, timeout):
+ self.timeouts.append(timeout)
+ return asyncio.wait_for(awaitable, timeout)
+
+
class TestGraphExtractor:
@pytest.mark.p2
@pytest.mark.asyncio
@@ -91,3 +107,52 @@ class TestCommunityReportsExtractor:
assert len(result.structured_output) == 1
assert result.structured_output[0]["title"] == "Community"
+
+
+class TestCommunityReportsTimeoutFlag:
+ """`ENABLE_TIMEOUT_ASSERTION` decides the per-report LLM timeout.
+
+ It was read with `os.environ.get`, so any non-empty value, `false` and `0`
+ included, armed the 180 s timeout.
+ """
+
+ async def _report_timeouts(self, monkeypatch, raw):
+ extractor = CommunityReportsExtractor(_build_llm_stub())
+ graph = nx.Graph()
+ graph.add_node("A", description="alpha")
+ graph.add_node("B", description="beta")
+ graph.add_edge("A", "B", description="related")
+ if raw is None:
+ monkeypatch.delenv("ENABLE_TIMEOUT_ASSERTION", raising=False)
+ else:
+ monkeypatch.setenv("ENABLE_TIMEOUT_ASSERTION", raw)
+
+ async def fast_async_chat(*_args, **_kwargs):
+ return '{"title":"Community","summary":"Summary","findings":[],"rating":1.0,"rating_explanation":"Clear"}'
+
+ recording = _RecordingAsyncio()
+ monkeypatch.setattr(community_reports_module, "asyncio", recording)
+ monkeypatch.setattr(
+ community_reports_module.leiden,
+ "run",
+ lambda *_args, **_kwargs: {0: {"0": {"weight": 1.0, "nodes": ["A", "B"]}}},
+ )
+ monkeypatch.setattr(community_reports_module, "add_community_info2graph", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(extractor, "_async_chat", fast_async_chat)
+
+ await extractor(graph)
+ return recording.timeouts
+
+ @pytest.mark.p2
+ @pytest.mark.parametrize("raw", ["false", "0", "off", "no", ""])
+ async def test_a_disabling_value_leaves_the_report_untimed(self, monkeypatch, raw):
+ assert await self._report_timeouts(monkeypatch, raw) == [1000000000]
+
+ @pytest.mark.p2
+ async def test_an_unset_flag_leaves_the_report_untimed(self, monkeypatch):
+ assert await self._report_timeouts(monkeypatch, None) == [1000000000]
+
+ @pytest.mark.p2
+ @pytest.mark.parametrize("raw", ["1", "true", "on"])
+ async def test_an_enabling_value_times_the_report(self, monkeypatch, raw):
+ assert await self._report_timeouts(monkeypatch, raw) == [180]
diff --git a/test/unit_test/rag/graphrag/test_graphrag_utils.py b/test/unit_test/rag/graphrag/test_graphrag_utils.py
index 06ee172b89..9deaf8a276 100644
--- a/test/unit_test/rag/graphrag/test_graphrag_utils.py
+++ b/test/unit_test/rag/graphrag/test_graphrag_utils.py
@@ -14,7 +14,9 @@
# limitations under the License.
#
+import asyncio
import json
+import types
from types import SimpleNamespace
import networkx as nx
@@ -638,3 +640,71 @@ class TestFlatUniqList:
arr = [{"k": [1, 2]}, {"k": 3}]
result = flat_uniq_list(arr, "k")
assert set(result) == {1, 2, 3}
+
+
+class _RecordingAsyncio(types.ModuleType):
+ """`asyncio` as a module sees it, with the timeouts handed to `wait_for` recorded."""
+
+ def __init__(self):
+ super().__init__("asyncio")
+ self.timeouts = []
+
+ def __getattr__(self, name):
+ return getattr(asyncio, name)
+
+ def wait_for(self, awaitable, timeout):
+ self.timeouts.append(timeout)
+ return asyncio.wait_for(awaitable, timeout)
+
+
+class _StopAfterPrewarm(Exception):
+ pass
+
+
+class TestSetGraphPrewarmTimeoutFlag:
+ """`ENABLE_TIMEOUT_ASSERTION` decides the timeout of both embedding pre-warms.
+
+ `set_graph` read it with `os.environ.get`, so `false` or `0` armed the
+ 3 s timeout on every node and edge batch.
+ """
+
+ async def _prewarm_timeouts(self, monkeypatch, raw):
+ graph = nx.Graph(source_id=["doc1"])
+ graph.add_node("A", source_id=["doc1"])
+ graph.add_node("B", source_id=["doc1"])
+ graph.add_edge("A", "B", description="related")
+ change = GraphChange(added_updated_nodes={"A", "B"}, added_updated_edges={("A", "B")})
+ if raw is None:
+ monkeypatch.delenv("ENABLE_TIMEOUT_ASSERTION", raising=False)
+ else:
+ monkeypatch.setenv("ENABLE_TIMEOUT_ASSERTION", raw)
+
+ async def no_chunk(*_args, **_kwargs):
+ return None
+
+ async def stop(*_args, **_kwargs):
+ # Both pre-warms have run by the time the edge chunks are built.
+ raise _StopAfterPrewarm
+
+ recording = _RecordingAsyncio()
+ monkeypatch.setattr(graphrag_utils, "asyncio", recording)
+ monkeypatch.setattr(graphrag_utils, "_batch_embed_cache_misses", lambda _llm, keys: [True] * len(keys))
+ monkeypatch.setattr(graphrag_utils, "_write_embed_cache_batch", lambda *_args: None)
+ monkeypatch.setattr(graphrag_utils, "graph_node_to_chunk", no_chunk)
+ monkeypatch.setattr(graphrag_utils, "graph_edge_to_chunk", stop)
+ embd_mdl = SimpleNamespace(llm_name="m", encode=lambda texts: (np.zeros((len(texts), 2)), 0))
+
+ with pytest.raises(_StopAfterPrewarm):
+ await graphrag_utils.set_graph("tenant", "kb", embd_mdl, graph, change, callback=None)
+ return recording.timeouts
+
+ @pytest.mark.parametrize("raw", ["false", "0", "off", "no", ""])
+ async def test_a_disabling_value_leaves_both_prewarms_untimed(self, monkeypatch, raw):
+ assert await self._prewarm_timeouts(monkeypatch, raw) == [30000000, 30000000]
+
+ async def test_an_unset_flag_leaves_both_prewarms_untimed(self, monkeypatch):
+ assert await self._prewarm_timeouts(monkeypatch, None) == [30000000, 30000000]
+
+ @pytest.mark.parametrize("raw", ["1", "true", "on"])
+ async def test_an_enabling_value_times_both_prewarms(self, monkeypatch, raw):
+ assert await self._prewarm_timeouts(monkeypatch, raw) == [3, 3]