RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(rag): keep search queries and page text out of connector logs (#18582)
Brian Sparker9c98f186000b
diff --git a/rag/utils/querit_conn.py b/rag/utils/querit_conn.pyindex 030aae58b4..4cc5eb3d28 100644--- a/rag/utils/querit_conn.py+++ b/rag/utils/querit_conn.py@@ -76,14 +76,17 @@ class Querit:})return normalized_results+ except requests.HTTPError as error:+ status = error.response.status_code if error.response is not None else "unknown"+ logger.error("Querit search failed: HTTP %s", status)+ return []except (requests.RequestException, TypeError, ValueError) as error:- logger.error("Querit search failed: %s", _safe_error_message(error, self.api_key))+ logger.error("Querit search failed: %s", type(error).__name__)return []def retrieve_chunks(self, question: str) -> dict[str, list]:chunks = []doc_aggs = []- logger.info("[Querit]Q: %s", question)for result in self.search(question):chunk_id = get_uuid()chunks.append(@@ -112,14 +115,10 @@ class Querit:"url": result["url"],})- logger.info("[Querit]R: %s...", result["content"][:128])+ # Counts only: the query and the retrieved page text are user data.+ logger.info("Querit search returned %d chunks", len(chunks))return {"chunks": chunks, "doc_aggs": doc_aggs}def _querit_text(value: Any) -> str:return "" if value is None else str(value)---def _safe_error_message(error: Exception, api_key: str) -> str:- message = str(error) or error.__class__.__name__- return message.replace(api_key, "[REDACTED]") if api_key else messagediff --git a/rag/utils/serply_conn.py b/rag/utils/serply_conn.pyindex 92949f182b..cb72d5034b 100644--- a/rag/utils/serply_conn.py+++ b/rag/utils/serply_conn.py@@ -74,8 +74,14 @@ class Serply:})return normalized_results+ except requests.HTTPError as error:+ # requests builds the HTTPError message from the response URL, and+ # the query is a URL parameter here, so the message must not be logged.+ status = error.response.status_code if error.response is not None else "unknown"+ logger.error("Serply search failed: HTTP %s", status)+ return []except (requests.RequestException, TypeError, ValueError) as error:- logger.error("Serply search failed: %s", _safe_error_message(error, self.api_key))+ logger.error("Serply search failed: %s", type(error).__name__)return []def retrieve_chunks(self, question: str) -> dict[str, list]:@@ -116,8 +122,3 @@ class Serply:def _serply_text(value: Any) -> str:return "" if value is None else str(value)---def _safe_error_message(error: Exception, api_key: str) -> str:- message = str(error) or error.__class__.__name__- return message.replace(api_key, "[REDACTED]") if api_key else messagediff --git a/rag/utils/tavily_conn.py b/rag/utils/tavily_conn.pyindex 33d265a050..a638eec59d 100644--- a/rag/utils/tavily_conn.py+++ b/rag/utils/tavily_conn.py@@ -18,6 +18,8 @@ from tavily import TavilyClientfrom common.misc_utils import get_uuidfrom rag.nlp import rag_tokenizer+logger = logging.getLogger(__name__)+class Tavily:def __init__(self, api_key: str):@@ -28,14 +30,16 @@ class Tavily:response = self.tavily_client.search(query=query, search_depth="advanced", max_results=6)return [{"url": res["url"], "title": res["title"], "content": res["content"], "score": res["score"]} for res in response["results"]]except Exception as e:- logging.exception(e)+ # Log the exception type only. Unlike its sibling connectors this+ # path has no redaction at all, and the client's exception text is+ # not under our control, so nothing from it is logged.+ logger.error("Tavily search failed: %s", type(e).__name__)return []def retrieve_chunks(self, question):chunks = []aggs = []- logging.info("[Tavily]Q: " + question)for r in self.search(question):id = get_uuid()chunks.append(@@ -57,5 +61,6 @@ class Tavily:})aggs.append({"doc_name": r["title"], "doc_id": id, "count": 1, "url": r["url"]})- logging.info("[Tavily]R: " + r["content"][:128] + "...")+ # Counts only: the query and the retrieved page text are user data.+ logger.info("Tavily search returned %d chunks", len(chunks))return {"chunks": chunks, "doc_aggs": aggs}diff --git a/test/unit_test/rag/utils/test_querit_conn.py b/test/unit_test/rag/utils/test_querit_conn.pyindex 40224a4778..0fd40c0bdd 100644--- a/test/unit_test/rag/utils/test_querit_conn.py+++ b/test/unit_test/rag/utils/test_querit_conn.py@@ -111,13 +111,60 @@ def test_querit_retrieve_chunks_returns_ragflow_reference_shape(monkeypatch):]-def test_querit_search_redacts_api_key_from_failures(monkeypatch, caplog):+def test_querit_search_keeps_the_key_out_of_failure_logs(monkeypatch, caplog):class _FailedResponse:def raise_for_status(self):raise ValueError("request failed with querit-secret")monkeypatch.setattr(querit_conn.requests, "post", lambda *_args, **_kwargs: _FailedResponse())- assert querit_conn.Querit("querit-secret").search("RAGFlow") == []+ with caplog.at_level("ERROR"):+ assert querit_conn.Querit("querit-secret").search("RAGFlow") == []+assert "querit-secret" not in caplog.text- assert "[REDACTED]" in caplog.text+ # Only the exception type survives into the log.+ assert "ValueError" in caplog.text+++def test_querit_search_logs_only_the_status_on_http_errors(monkeypatch, caplog):+ class _ErrorResponse:+ status_code = 402+ url = "https://api.querit.ai/v1/search"++ def raise_for_status(self):+ raise querit_conn.requests.HTTPError(+ f"402 Client Error: Payment Required for url: {self.url}",+ response=self,+ )++ monkeypatch.setattr(querit_conn.requests, "post", lambda *_args, **_kwargs: _ErrorResponse())++ with caplog.at_level("ERROR"):+ assert querit_conn.Querit("querit-secret").search("my private query") == []++ assert "my private query" not in caplog.text+ assert "querit-secret" not in caplog.text+ assert "402" in caplog.text+++def test_querit_retrieve_chunks_never_logs_the_query_or_page_text(monkeypatch, caplog):+ monkeypatch.setattr(+ querit_conn.Querit,+ "search",+ lambda self, question: [+ {+ "url": "https://example.com/a",+ "title": "A",+ "content": "secret page body text",+ "score": 1.0,+ }+ ],+ )++ with caplog.at_level("INFO"):+ retrieved = querit_conn.Querit("k").retrieve_chunks("my private query")++ assert len(retrieved["chunks"]) == 1+ assert "my private query" not in caplog.text+ assert "secret page body text" not in caplog.text+ assert "1" in caplog.textdiff --git a/test/unit_test/rag/utils/test_serply_conn.py b/test/unit_test/rag/utils/test_serply_conn.pyindex 5f79c0c547..fc42fc699e 100644--- a/test/unit_test/rag/utils/test_serply_conn.py+++ b/test/unit_test/rag/utils/test_serply_conn.py@@ -132,13 +132,40 @@ def test_serply_retrieve_chunks_returns_ragflow_reference_shape(monkeypatch):]-def test_serply_search_redacts_api_key_from_failures(monkeypatch, caplog):+def test_serply_search_keeps_the_key_out_of_failure_logs(monkeypatch, caplog):class _FailedResponse:def raise_for_status(self):raise ValueError("request failed with serply-secret")monkeypatch.setattr(serply_conn.requests, "get", lambda *_args, **_kwargs: _FailedResponse())- assert serply_conn.Serply("serply-secret").search("RAGFlow") == []+ with caplog.at_level("ERROR"):+ assert serply_conn.Serply("serply-secret").search("RAGFlow") == []++ assert "serply-secret" not in caplog.text+ assert "ValueError" in caplog.text+++def test_serply_search_never_logs_the_query_from_the_request_url(monkeypatch, caplog):+ """Serply passes the query as a URL parameter, so the requests error+ message contains it."""++ class _ErrorResponse:+ status_code = 429+ url = "https://api.serply.io/v1/search/?q=my%20private%20query&num=6"++ def raise_for_status(self):+ raise serply_conn.requests.HTTPError(+ f"429 Client Error: Too Many Requests for url: {self.url}",+ response=self,+ )++ monkeypatch.setattr(serply_conn.requests, "get", lambda *_args, **_kwargs: _ErrorResponse())++ with caplog.at_level("ERROR"):+ assert serply_conn.Serply("serply-secret").search("my private query") == []++ assert "my private query" not in caplog.text+ assert "my%20private%20query" not in caplog.textassert "serply-secret" not in caplog.text- assert "[REDACTED]" in caplog.text+ assert "429" in caplog.textdiff --git a/test/unit_test/rag/utils/test_tavily_conn.py b/test/unit_test/rag/utils/test_tavily_conn.pynew file mode 100644index 0000000000..c6376e1005--- /dev/null+++ b/test/unit_test/rag/utils/test_tavily_conn.py@@ -0,0 +1,78 @@+#+# Copyright 2026 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.+#++from rag.utils import tavily_conn+++class _StubClient:+ def __init__(self, results=None, error=None):+ self._results = results or []+ self._error = error++ def search(self, **_kwargs):+ if self._error is not None:+ raise self._error+ return {"results": self._results}+++def _tavily(client) -> tavily_conn.Tavily:+ instance = tavily_conn.Tavily.__new__(tavily_conn.Tavily)+ instance.tavily_client = client+ return instance+++def test_tavily_search_logs_only_the_exception_type(monkeypatch, caplog):+ """The client's exception can carry both the query and the API key."""+ error = RuntimeError("401 for https://api.tavily.com/search?q=my%20private%20query key=tvly-secret")++ with caplog.at_level("ERROR"):+ assert _tavily(_StubClient(error=error)).search("my private query") == []++ assert "my%20private%20query" not in caplog.text+ assert "tvly-secret" not in caplog.text+ assert "RuntimeError" in caplog.text+++def test_tavily_retrieve_chunks_never_logs_the_query_or_page_text(caplog):+ results = [+ {+ "url": "https://example.com/ragflow",+ "title": "RAGFlow",+ "content": "secret page body text",+ "score": 0.9,+ }+ ]++ with caplog.at_level("INFO"):+ retrieved = _tavily(_StubClient(results=results)).retrieve_chunks("my private query")++ assert len(retrieved["chunks"]) == 1+ assert retrieved["chunks"][0]["url"] == "https://example.com/ragflow"+ assert "my private query" not in caplog.text+ assert "secret page body text" not in caplog.text+++def test_tavily_retrieve_chunks_still_returns_the_reference_shape(caplog):+ results = [+ {"url": "https://example.com/a", "title": "A", "content": "body a", "score": 0.5},+ {"url": "https://example.com/b", "title": "B", "content": "body b", "score": 0.4},+ ]++ retrieved = _tavily(_StubClient(results=results)).retrieve_chunks("q")++ assert [c["url"] for c in retrieved["chunks"]] == ["https://example.com/a", "https://example.com/b"]+ assert [a["doc_name"] for a in retrieved["doc_aggs"]] == ["A", "B"]+ assert retrieved["chunks"][0]["similarity"] == 0.5